mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
35
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6a463712a4 | ||
|
|
39158dec4b | ||
|
|
28ed22824f | ||
|
|
d10ccbedac | ||
|
|
55c4e6689b | ||
|
|
0c983566f6 | ||
|
|
68c3c759d5 | ||
|
|
ac5be43448 | ||
|
|
d24919c2c3 | ||
|
|
34a9aa9a48 | ||
|
|
ae321b3409 | ||
|
|
c2fb97cc81 | ||
|
|
aa27f55ab5 | ||
|
|
8f5d500459 | ||
|
|
f7562b6fd7 | ||
|
|
fdcbdd1646 | ||
|
|
2ef9c11cd3 | ||
|
|
46c84c21fe | ||
|
|
b1b372f1d6 | ||
|
|
907b7d5ce3 | ||
|
|
ddafaaa757 | ||
|
|
2c1cca7e99 | ||
|
|
c91d0cd5a3 | ||
|
|
84ed60a404 | ||
|
|
942d138fc1 | ||
|
|
dadc8717ff | ||
|
|
9423dcada7 | ||
|
|
2941c74051 | ||
|
|
cd00af84f3 | ||
|
|
951339a6d6 | ||
|
|
f5507c0959 | ||
|
|
60bba681d3 | ||
|
|
f868aadd8d | ||
|
|
b610d9bc23 | ||
|
|
69398a6703 |
No files matched your search
@@ -1,7 +1,7 @@
|
||||
{ pkgs, ... }:
|
||||
|
||||
let
|
||||
toolchain = pkgs.rust-bin.nightly."2026-04-11".default.override {
|
||||
toolchain = pkgs.rust-bin.nightly."2026-07-03".default.override {
|
||||
extensions = [
|
||||
"rust-src"
|
||||
"rust-analyzer"
|
||||
@@ -32,11 +32,12 @@ let
|
||||
(finalAttrs: {
|
||||
pname = "rustc_codegen_spirv";
|
||||
version = "0.10.0-alpha.1";
|
||||
src = pkgs.fetchCrate {
|
||||
inherit (finalAttrs) pname version;
|
||||
sha256 = "sha256-zJEpExkPgYzwo7fR4ge4GxJNj7H5yo4bJ4eTOw36+7c=";
|
||||
src = pkgs.fetchgit {
|
||||
url = "https://github.com/Rust-GPU/rust-gpu";
|
||||
rev = "2fff75a21a1909945ac85f5818843dd9960004d7";
|
||||
sha256 = "sha256-clUt4jUh4D9EmoXZFgur1RrMYob4X5jti2e2hvBnAx8=";
|
||||
};
|
||||
cargoHash = "sha256-J1rtbfGqrL2NJ7Bu2pYfDwCdUmnECB/kzxrpYluA0kY=";
|
||||
cargoHash = "sha256-9dGb+RDYpJKaIhkMPkZAx1M1VGE3gMfCD2T84i1VtV8=";
|
||||
cargoBuildFlags = [
|
||||
"-p"
|
||||
"rustc_codegen_spirv"
|
||||
|
||||
Generated
+163
-154
File diff suppressed because it is too large.
Load diff
+11
-6
@@ -53,7 +53,7 @@ default-members = [
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
rust-version = "1.88"
|
||||
rust-version = "1.98"
|
||||
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"
|
||||
rmp-serde = "1.3"
|
||||
postcard = { version = "1.1", default-features = false, features = ["use-std"] }
|
||||
serde_bytes = "0.11"
|
||||
serde-wasm-bindgen = "0.6"
|
||||
reqwest = { version = "0.13", features = ["blocking", "json"] }
|
||||
@@ -172,7 +172,6 @@ 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"] }
|
||||
@@ -182,10 +181,12 @@ color = "0.3"
|
||||
# Linebender ecosystem (END)
|
||||
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
|
||||
rand_chacha = "0.9"
|
||||
glam = { version = "0.32.1", default-features = false, features = [
|
||||
glam = { version = "0.33", default-features = false, features = [
|
||||
"nostd-libm",
|
||||
"scalar-math",
|
||||
"bytemuck",
|
||||
"debug-glam-assert",
|
||||
"all-types",
|
||||
] }
|
||||
base64 = "0.22"
|
||||
blake3 = "1.5"
|
||||
@@ -239,8 +240,12 @@ rfd = "0.17"
|
||||
open = "5.3"
|
||||
spin = "0.10"
|
||||
clap = "4.5"
|
||||
spirv-std = { version = "0.10.0-alpha.1", features = ["bytemuck"] }
|
||||
cargo-gpu-install = { version = "0.10.0-alpha.1", default-features = false }
|
||||
|
||||
# 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 }
|
||||
|
||||
qrcodegen = "1.8"
|
||||
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
|
||||
scraper = "0.25"
|
||||
|
||||
Generated
+1
-1
@@ -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
|
||||
Generated
+1
-1
@@ -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
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_Line truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"I64":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"I64":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_vaLine truncated
|
||||
Generated
+1
-1
@@ -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
@@ -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
@@ -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
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2Line truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpLine truncated
|
||||
Generated
+1
-1
@@ -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
|
||||
@@ -5,9 +5,15 @@ 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"
|
||||
|
||||
@@ -5,9 +5,15 @@ 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 }
|
||||
|
||||
|
||||
@@ -7,6 +7,9 @@ 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();
|
||||
|
||||
@@ -5,6 +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
|
||||
|
||||
|
||||
@@ -5,9 +5,15 @@ 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"
|
||||
|
||||
@@ -5,9 +5,15 @@ 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"]
|
||||
|
||||
@@ -5,9 +5,15 @@ 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"
|
||||
|
||||
+8
-15
@@ -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, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
|
||||
use crate::wrapper::{DesktopWrapper, FolderStore, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
|
||||
|
||||
pub(crate) struct App {
|
||||
render_state: Option<RenderState>,
|
||||
@@ -99,7 +99,13 @@ 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), dirs::app_autosave_documents_dir(), wgpu_context.clone(), 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,
|
||||
);
|
||||
|
||||
Self {
|
||||
render_state: None,
|
||||
@@ -307,19 +313,6 @@ 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);
|
||||
}
|
||||
|
||||
+4
-4
@@ -20,10 +20,10 @@ pub(crate) fn clear_dir(path: &PathBuf) {
|
||||
if let Err(e) = fs::remove_dir_all(&entry_path) {
|
||||
tracing::error!("Failed to remove directory at {:?}: {}", entry_path, e);
|
||||
}
|
||||
} else if entry_path.is_file() {
|
||||
if let Err(e) = fs::remove_file(&entry_path) {
|
||||
tracing::error!("Failed to remove file at {:?}: {}", entry_path, e);
|
||||
}
|
||||
} else if entry_path.is_file()
|
||||
&& let Err(e) = fs::remove_file(&entry_path)
|
||||
{
|
||||
tracing::error!("Failed to remove file at {:?}: {}", entry_path, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+50
-51
@@ -1,6 +1,9 @@
|
||||
use crate::wrapper::messages::{DocumentId, PersistedState};
|
||||
use crate::wrapper::messages::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,
|
||||
@@ -13,16 +16,13 @@ pub(crate) fn read_state() -> PersistedState {
|
||||
return PersistedState::default();
|
||||
}
|
||||
};
|
||||
let loaded = match ron::from_str(&data) {
|
||||
match ron::from_str(&data) {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to deserialize persistent data: {e}");
|
||||
return PersistedState::default();
|
||||
PersistedState::default()
|
||||
}
|
||||
};
|
||||
|
||||
garbage_collect_document_files(&loaded);
|
||||
loaded
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn write_state(state: PersistedState) {
|
||||
@@ -37,46 +37,6 @@ 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) {
|
||||
if 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 {
|
||||
@@ -85,8 +45,47 @@ fn state_file_path() -> std::path::PathBuf {
|
||||
path
|
||||
}
|
||||
|
||||
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
|
||||
// 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)
|
||||
}
|
||||
@@ -5,9 +5,15 @@ 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"]
|
||||
|
||||
@@ -5,9 +5,15 @@ 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,10 +44,6 @@ 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,18 +69,6 @@ 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);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ 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;
|
||||
@@ -32,7 +33,7 @@ pub struct DesktopWrapper {
|
||||
}
|
||||
|
||||
impl DesktopWrapper {
|
||||
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 {
|
||||
pub fn new(uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, document_store: Arc<dyn DocumentStore>, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self {
|
||||
#[cfg(target_os = "windows")]
|
||||
let host = Host::Windows;
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -43,7 +44,7 @@ impl DesktopWrapper {
|
||||
let application_io = PlatformApplicationIo::new_with_context(wgpu_context);
|
||||
|
||||
Self {
|
||||
editor: Editor::new(env, uuid_random_seed, resource_storage, Some(working_copy_root), application_io, schedule_wake),
|
||||
editor: Editor::new(env, uuid_random_seed, resource_storage, document_store, application_io, schedule_wake),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -44,10 +44,10 @@ impl<'a> DesktopWrapperMessageDispatcher<'a> {
|
||||
|
||||
pub(super) fn poll_node_graph_evaluation(&mut self) {
|
||||
let mut responses = VecDeque::new();
|
||||
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses) {
|
||||
if e != "No active document" {
|
||||
tracing::error!("Error poling node graph: {}", e);
|
||||
}
|
||||
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses)
|
||||
&& e != "No active document"
|
||||
{
|
||||
tracing::error!("Error polling node graph: {}", e);
|
||||
}
|
||||
while let Some(message) = responses.pop_front() {
|
||||
self.queue_editor_message(message);
|
||||
|
||||
@@ -44,13 +44,6 @@ pub enum DesktopFrontendMessage {
|
||||
enabled: bool,
|
||||
},
|
||||
UpdateOverlays(vello::Scene),
|
||||
PersistenceWriteDocument {
|
||||
id: DocumentId,
|
||||
document_serialized_content: String,
|
||||
},
|
||||
PersistenceDeleteDocument {
|
||||
id: DocumentId,
|
||||
},
|
||||
PersistenceWritePreferences {
|
||||
preferences: Preferences,
|
||||
},
|
||||
@@ -59,9 +52,6 @@ pub enum DesktopFrontendMessage {
|
||||
state: PersistedState,
|
||||
},
|
||||
PersistenceReadState,
|
||||
PersistenceReadDocument {
|
||||
id: DocumentId,
|
||||
},
|
||||
UpdateMenu {
|
||||
entries: Vec<MenuItem>,
|
||||
},
|
||||
@@ -92,7 +82,6 @@ pub enum DesktopWrapperMessage {
|
||||
PollNodeGraphEvaluation,
|
||||
UpdateMaximized { maximized: bool },
|
||||
UpdateFullscreen { fullscreen: bool },
|
||||
LoadDocumentContent { id: DocumentId, document: String },
|
||||
LoadPersistedState { state: PersistedState },
|
||||
LoadPreferences { preferences: Preferences },
|
||||
MenuEvent { id: String },
|
||||
|
||||
@@ -5,9 +5,15 @@ 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"]
|
||||
@@ -34,6 +40,7 @@ web-sys = { workspace = true, features = [
|
||||
"FileSystemFileHandle",
|
||||
"FileSystemGetFileOptions",
|
||||
"FileSystemGetDirectoryOptions",
|
||||
"FileSystemRemoveOptions",
|
||||
"FileSystemHandle",
|
||||
"FileSystemHandleKind",
|
||||
"FileSystemWritableFileStream",
|
||||
|
||||
@@ -6,6 +6,7 @@ use std::fs::{self, OpenOptions};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct FolderBackend {
|
||||
root: PathBuf,
|
||||
}
|
||||
|
||||
@@ -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::Mutex;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[derive(Default)]
|
||||
#[derive(Clone, Default)]
|
||||
pub struct MemoryBackend {
|
||||
files: Mutex<HashMap<String, Vec<u8>>>,
|
||||
files: Arc<Mutex<HashMap<String, Vec<u8>>>>,
|
||||
}
|
||||
|
||||
impl MemoryBackend {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
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;
|
||||
@@ -40,6 +41,33 @@ 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>>,
|
||||
}
|
||||
@@ -77,8 +105,6 @@ 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;
|
||||
}
|
||||
}
|
||||
@@ -239,12 +265,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 {
|
||||
log::error!("OPFS background write for {path} failed: {error:?}");
|
||||
report_write_error("write", &path, &error);
|
||||
}
|
||||
}
|
||||
Mutation::Append { path, bytes } => {
|
||||
if let Err(error) = append_file(&directory, &path, &bytes).await {
|
||||
log::error!("OPFS background append for {path} failed: {error:?}");
|
||||
report_write_error("append", &path, &error);
|
||||
}
|
||||
}
|
||||
Mutation::Delete { path } => {
|
||||
@@ -252,7 +278,7 @@ async fn drain_queue(inner: Arc<Mutex<Inner>>) {
|
||||
if let Err(error) = remove_file(&directory, &path).await
|
||||
&& !is_not_found(&error)
|
||||
{
|
||||
log::error!("OPFS background delete for {path} failed: {error:?}");
|
||||
report_write_error("delete", &path, &error);
|
||||
}
|
||||
}
|
||||
// A receive error on the waiter side just means the reader gave up; nothing to apply.
|
||||
@@ -263,16 +289,11 @@ 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 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()?;
|
||||
let mut current = opfs_root().await?;
|
||||
|
||||
for segment in directory_path.split('/').filter(|segment| !segment.is_empty()) {
|
||||
let options = FileSystemGetDirectoryOptions::new();
|
||||
@@ -283,6 +304,37 @@ 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();
|
||||
@@ -473,3 +525,7 @@ fn list_error(prefix: &str, error: JsValue) -> ContainerError {
|
||||
js_err(error)
|
||||
}
|
||||
}
|
||||
|
||||
fn js_err(error: JsValue) -> ContainerError {
|
||||
ContainerError::Backend(format!("{error:?}"))
|
||||
}
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
pub mod archive;
|
||||
pub mod backends;
|
||||
pub mod store;
|
||||
|
||||
pub enum ByteHolder {
|
||||
/// Bytes synthesized in memory (decompressed from an archive, produced by serialization).
|
||||
@@ -350,6 +351,7 @@ 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"))]
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
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 })
|
||||
}
|
||||
}
|
||||
@@ -176,3 +176,15 @@ 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"));
|
||||
}
|
||||
@@ -5,9 +5,15 @@ 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`
|
||||
@@ -27,7 +33,7 @@ graphene-resource = { workspace = true }
|
||||
core-types = { workspace = true, optional = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
rmp-serde = { workspace = true }
|
||||
postcard = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
thiserror = "2.0"
|
||||
log = { workspace = true }
|
||||
|
||||
@@ -8,18 +8,16 @@ pub enum Codec {
|
||||
Json,
|
||||
/// Newline-delimited compact JSON, one value per line.
|
||||
JsonLines,
|
||||
/// 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,
|
||||
/// 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,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum CodecError {
|
||||
#[error("MessagePack encode error: {0}")]
|
||||
MessagePackEncode(#[from] rmp_serde::encode::Error),
|
||||
#[error("MessagePack decode error: {0}")]
|
||||
MessagePackDecode(#[from] rmp_serde::decode::Error),
|
||||
#[error("postcard error: {0}")]
|
||||
Postcard(#[from] postcard::Error),
|
||||
#[error("JSON error: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
#[error("frame length {0} exceeds u32")]
|
||||
@@ -41,8 +39,8 @@ impl Codec {
|
||||
match self {
|
||||
Codec::Json => "json",
|
||||
Codec::JsonLines => "jsonl",
|
||||
Codec::MessagePack => "bin",
|
||||
Codec::MessagePackFrames => "frames",
|
||||
Codec::Postcard => "bin",
|
||||
Codec::PostcardFrames => "frames",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,15 +60,15 @@ impl Codec {
|
||||
output.push(b'\n');
|
||||
Ok(())
|
||||
}
|
||||
Codec::MessagePack => {
|
||||
Codec::Postcard => {
|
||||
if !output.is_empty() {
|
||||
return Err(CodecError::SingleValueAlreadyWritten);
|
||||
}
|
||||
rmp_serde::encode::write(output, value)?;
|
||||
postcard::to_io(value, &mut *output)?;
|
||||
Ok(())
|
||||
}
|
||||
Codec::MessagePackFrames => {
|
||||
let payload = rmp_serde::to_vec(value)?;
|
||||
Codec::PostcardFrames => {
|
||||
let payload = postcard::to_stdvec(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);
|
||||
@@ -91,11 +89,11 @@ impl Codec {
|
||||
remaining: bytes,
|
||||
_marker: std::marker::PhantomData,
|
||||
}),
|
||||
Codec::MessagePack => {
|
||||
let single = rmp_serde::from_slice::<T>(bytes).map_err(CodecError::from);
|
||||
Codec::Postcard => {
|
||||
let single = postcard::from_bytes::<T>(bytes).map_err(CodecError::from);
|
||||
Box::new(std::iter::once(single))
|
||||
}
|
||||
Codec::MessagePackFrames => Box::new(MessagePackFrameIter {
|
||||
Codec::PostcardFrames => Box::new(PostcardFrameIter {
|
||||
remaining: bytes,
|
||||
_marker: std::marker::PhantomData,
|
||||
}),
|
||||
@@ -153,12 +151,12 @@ impl<T: DeserializeOwned> Iterator for JsonLineIter<'_, T> {
|
||||
}
|
||||
}
|
||||
|
||||
struct MessagePackFrameIter<'a, T> {
|
||||
struct PostcardFrameIter<'a, T> {
|
||||
remaining: &'a [u8],
|
||||
_marker: std::marker::PhantomData<fn() -> T>,
|
||||
}
|
||||
|
||||
impl<T: DeserializeOwned> Iterator for MessagePackFrameIter<'_, T> {
|
||||
impl<T: DeserializeOwned> Iterator for PostcardFrameIter<'_, T> {
|
||||
type Item = Result<T, CodecError>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
@@ -183,7 +181,7 @@ impl<T: DeserializeOwned> Iterator for MessagePackFrameIter<'_, T> {
|
||||
let (frame, after) = tail.split_at(length);
|
||||
self.remaining = after;
|
||||
|
||||
Some(rmp_serde::from_slice(frame).map_err(CodecError::from))
|
||||
Some(postcard::from_bytes(frame).map_err(CodecError::from))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -224,31 +222,20 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn message_pack_round_trip_single() {
|
||||
fn postcard_round_trip_single() {
|
||||
let frame = Frame { id: 99, label: "blob".into() };
|
||||
let bytes = Codec::MessagePack.write_single(&frame).unwrap();
|
||||
let decoded: Frame = Codec::MessagePack.read_single(&bytes).unwrap();
|
||||
let bytes = Codec::Postcard.write_single(&frame).unwrap();
|
||||
let decoded: Frame = Codec::Postcard.read_single(&bytes).unwrap();
|
||||
assert_eq!(decoded, frame);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn message_pack_append_to_non_empty_errors() {
|
||||
fn postcard_append_to_non_empty_errors() {
|
||||
let mut buffer = vec![0xAB];
|
||||
let result = Codec::MessagePack.append(&mut buffer, &Frame { id: 1, label: "x".into() });
|
||||
let result = Codec::Postcard.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() }];
|
||||
@@ -263,13 +250,13 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn message_pack_frames_round_trip() {
|
||||
fn postcard_frames_round_trip() {
|
||||
let frames = frames();
|
||||
let mut buffer = Vec::new();
|
||||
for frame in &frames {
|
||||
Codec::MessagePackFrames.append(&mut buffer, frame).unwrap();
|
||||
Codec::PostcardFrames.append(&mut buffer, frame).unwrap();
|
||||
}
|
||||
let decoded: Vec<Frame> = Codec::MessagePackFrames.iter(&buffer).collect::<Result<_, _>>().unwrap();
|
||||
let decoded: Vec<Frame> = Codec::PostcardFrames.iter(&buffer).collect::<Result<_, _>>().unwrap();
|
||||
assert_eq!(decoded, frames);
|
||||
}
|
||||
|
||||
@@ -277,27 +264,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 message_pack_frames_detect_truncation() {
|
||||
fn postcard_frames_detect_truncation() {
|
||||
let mut buffer = Vec::new();
|
||||
Codec::MessagePackFrames.append(&mut buffer, &Frame { id: 7, label: "ok".into() }).unwrap();
|
||||
Codec::PostcardFrames.append(&mut buffer, &Frame { id: 7, label: "ok".into() }).unwrap();
|
||||
buffer.truncate(buffer.len() - 1);
|
||||
let last = Codec::MessagePackFrames.iter::<Frame>(&buffer).last().unwrap();
|
||||
let last = Codec::PostcardFrames.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 message_pack_frames_detect_truncated_length_prefix() {
|
||||
fn postcard_frames_detect_truncated_length_prefix() {
|
||||
let buffer = vec![0x00, 0x00];
|
||||
let last = Codec::MessagePackFrames.iter::<Frame>(&buffer).last().unwrap();
|
||||
let last = Codec::PostcardFrames.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::MessagePack, Codec::MessagePackFrames] {
|
||||
for codec in [Codec::Json, Codec::JsonLines, Codec::Postcard, Codec::PostcardFrames] {
|
||||
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:?}");
|
||||
@@ -315,12 +302,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn extensions_are_distinct() {
|
||||
let exts = [
|
||||
Codec::Json.extension(),
|
||||
Codec::JsonLines.extension(),
|
||||
Codec::MessagePack.extension(),
|
||||
Codec::MessagePackFrames.extension(),
|
||||
];
|
||||
let exts = [Codec::Json.extension(), Codec::JsonLines.extension(), Codec::Postcard.extension(), Codec::PostcardFrames.extension()];
|
||||
let unique: std::collections::HashSet<_> = exts.iter().collect();
|
||||
assert_eq!(unique.len(), exts.len(), "extensions collide: {exts:?}");
|
||||
}
|
||||
|
||||
@@ -35,6 +35,9 @@ 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 },
|
||||
|
||||
@@ -146,10 +146,14 @@ 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(),
|
||||
};
|
||||
|
||||
+49
-59
@@ -6,7 +6,6 @@
|
||||
//!
|
||||
//! 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"))]
|
||||
@@ -14,10 +13,10 @@ use std::path::Path;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
use document_container::backends::folder::FolderBackend;
|
||||
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
|
||||
use document_container::{AnyContainer, AsyncContainer, ByteHolder};
|
||||
#[cfg(feature = "conversion")]
|
||||
use document_graph_storage::{CommitError, NodeMetadataSource};
|
||||
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session};
|
||||
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session, UserId};
|
||||
#[cfg(feature = "conversion")]
|
||||
use graphene_resource::LoadResource;
|
||||
use graphene_resource::ResourceHash;
|
||||
@@ -49,30 +48,28 @@ 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. 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.
|
||||
/// 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.
|
||||
pub const DEFAULT_SESSION_CODEC: Codec = Codec::Json;
|
||||
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;
|
||||
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;
|
||||
|
||||
/// 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` / `create` / `export` are async, since they
|
||||
/// through the container's sync write surface. Only `open` / `export` are async, since they
|
||||
/// read.
|
||||
/// `Clone` shares the working-copy container (`Arc<AnyContainer>`) so a cloned handle reads and writes
|
||||
/// `Clone` shares the working-copy container (`AnyContainer` is a handle) 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: Arc<AnyContainer>,
|
||||
pub(crate) working: 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
|
||||
@@ -80,10 +77,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, serde_json::Value>,
|
||||
pub(crate) view_settings: std::collections::BTreeMap<String, document_graph_storage::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, serde_json::Value>>,
|
||||
pub(crate) network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, document_graph_storage::Value>>,
|
||||
}
|
||||
|
||||
/// Native folder-backed convenience constructors. On wasm the editor builds an OPFS-backed
|
||||
@@ -101,10 +98,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 async fn create(path: &Path, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
||||
pub 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).await
|
||||
Self::create_in(working, layout, peer, document_uuid, editor_version, stdlib_version)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,10 +121,14 @@ impl<L: Layout> Gdd<L> {
|
||||
/// Backend-agnostic open. Splits out so tests can supply a [`document_container::backends::memory::MemoryBackend`].
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::WrongFormat`] / [`Error::UnsupportedVersion`] if the manifest fails validation, plus
|
||||
/// the usual [`Error::Read`] / [`Error::Codec`] / [`Error::Crdt`] if a payload is malformed.
|
||||
/// [`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.
|
||||
pub async fn open_in(working: AnyContainer, layout: L) -> Result<Self, Error> {
|
||||
let manifest: Manifest = io::read_single(&working, layout.manifest_basename(), MANIFEST_CODEC).await?;
|
||||
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()),
|
||||
};
|
||||
validate_manifest(&manifest)?;
|
||||
let codecs = manifest.codecs;
|
||||
|
||||
@@ -140,18 +141,19 @@ 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, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
|
||||
Session::load(peer, user, 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, registry)?
|
||||
Session::bootstrap_from_registry(peer, user, registry)?
|
||||
}
|
||||
(false, _) => Session::replay_from_history(peer, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
|
||||
(false, _) => Session::replay_from_history(peer, user, 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.
|
||||
@@ -159,11 +161,15 @@ 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: Arc::new(working),
|
||||
working,
|
||||
layout,
|
||||
manifest,
|
||||
view_settings: session_state.view_settings,
|
||||
@@ -173,11 +179,15 @@ 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 async fn create_in(working: AnyContainer, layout: L, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
||||
pub 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, ..Default::default() };
|
||||
let session_state = SessionState {
|
||||
peer_id: peer,
|
||||
user_id: UserId(peer.0),
|
||||
..Default::default()
|
||||
};
|
||||
io::write_single(&working, layout.session_basename(), codecs.session, &session_state)?;
|
||||
|
||||
let session = Session::with_peer(peer);
|
||||
@@ -185,7 +195,7 @@ impl<L: Layout> Gdd<L> {
|
||||
|
||||
Ok(Self {
|
||||
session,
|
||||
working: Arc::new(working),
|
||||
working,
|
||||
layout,
|
||||
manifest,
|
||||
view_settings: std::collections::BTreeMap::new(),
|
||||
@@ -256,13 +266,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, serde_json::Value> {
|
||||
pub fn view_settings(&self) -> &std::collections::BTreeMap<String, document_graph_storage::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, serde_json::Value>> {
|
||||
pub fn network_view_settings(&self) -> &std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, document_graph_storage::Value>> {
|
||||
&self.network_view_settings
|
||||
}
|
||||
|
||||
@@ -285,31 +295,20 @@ 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) {
|
||||
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)
|
||||
(self.working, self.layout)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// 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.
|
||||
#[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 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 {
|
||||
for (id, hash) in self.session.all_declaration_resources() {
|
||||
let Some(hash) = hash else {
|
||||
log::error!("Declaration resource {id} has no resolved hash; cannot load ProtoNode");
|
||||
continue;
|
||||
};
|
||||
@@ -319,7 +318,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}"),
|
||||
}
|
||||
@@ -328,16 +327,7 @@ impl<L: Layout> Gdd<L> {
|
||||
declarations
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// Read the embedded legacy `.graphite` document, if present.
|
||||
pub async fn read_legacy_document(&self) -> Option<ByteHolder> {
|
||||
self.working.read(self.layout.legacy_path()).await.ok()
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
use document_container::AsyncContainer;
|
||||
#[cfg(feature = "conversion")]
|
||||
use document_graph_storage::NodeMetadataSource;
|
||||
use document_graph_storage::{HotOp, Rev, TimeStamp};
|
||||
use document_graph_storage::{HotOp, Rev, TimeStamp, Value};
|
||||
#[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.
|
||||
/// interaction. Returns the decoded declarations the snapshot references, for the caller's cache.
|
||||
///
|
||||
/// # 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<(), Error> {
|
||||
let (hot_ops, declaration_bytes) = self.session.stage_from_runtime(network, metadata, resources)?;
|
||||
) -> Result<document_graph_storage::Declarations, Error> {
|
||||
let (hot_ops, conversion) = self.session.stage_from_runtime(network, metadata, resources)?;
|
||||
|
||||
for hot_op in &hot_ops {
|
||||
self.append_hot_frame(hot_op)?;
|
||||
@@ -70,6 +70,29 @@ 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() {
|
||||
byte_store.store(bytes);
|
||||
}
|
||||
Ok(conversion.declarations)
|
||||
}
|
||||
|
||||
/// Stage ops the caller built from what the editor recorded, rather than deriving them by converting
|
||||
/// the whole document and diffing it against the working registry.
|
||||
///
|
||||
/// Otherwise identical to [`stage_runtime_snapshot`](Self::stage_runtime_snapshot): each op becomes a
|
||||
/// hot frame, and the proto-node declaration bytes go to the byte store.
|
||||
#[cfg(feature = "conversion")]
|
||||
pub fn stage_constructed_ops(
|
||||
&mut self,
|
||||
ops: Vec<document_graph_storage::RegistryDelta>,
|
||||
declaration_bytes: &document_graph_storage::from_runtime::DeclarationBytes,
|
||||
byte_store: &dyn ResourceStorage,
|
||||
) -> Result<(), Error> {
|
||||
let hot_ops = self.session.stage_computed_ops(ops)?;
|
||||
|
||||
for hot_op in &hot_ops {
|
||||
self.append_hot_frame(hot_op)?;
|
||||
}
|
||||
for bytes in declaration_bytes.values() {
|
||||
byte_store.store(bytes);
|
||||
}
|
||||
@@ -150,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: serde_json::Value) -> Result<(), Error> {
|
||||
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: Value) -> Result<(), Error> {
|
||||
if self.session.annotate_delta(rev, key, value) {
|
||||
self.rewrite_history()?;
|
||||
}
|
||||
@@ -171,10 +194,14 @@ 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(),
|
||||
};
|
||||
@@ -182,18 +209,16 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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`).
|
||||
/// 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.
|
||||
fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
|
||||
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.registry())?;
|
||||
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.retired_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, serde_json::Value>) -> Result<(), Error> {
|
||||
pub fn set_view_settings(&mut self, view_settings: std::collections::BTreeMap<String, document_graph_storage::Value>) -> Result<(), Error> {
|
||||
self.view_settings = view_settings;
|
||||
self.persist_session_state()
|
||||
}
|
||||
@@ -209,7 +234,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, serde_json::Value>>,
|
||||
network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, document_graph_storage::Value>>,
|
||||
) -> Result<(), Error> {
|
||||
self.network_view_settings = network_view_settings;
|
||||
self.persist_session_state()
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
|
||||
use graphene_resource::ResourceFuture;
|
||||
@@ -39,7 +38,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.as_ref() {
|
||||
if let AnyContainer::Folder(folder) = &self.working {
|
||||
let full = folder.root().join(&dest_path);
|
||||
if let Some(parent) = full.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(ContainerError::Io)?;
|
||||
@@ -102,7 +101,7 @@ impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ResourceProxy<T: Layout>(Arc<AnyContainer>, T);
|
||||
pub struct ResourceProxy<T: Layout>(AnyContainer, T);
|
||||
|
||||
impl<L: Layout + Send + Sync> LoadResource for ResourceProxy<L> {
|
||||
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//!
|
||||
//! Lives in `session.json`. Rewritten on retirement.
|
||||
|
||||
use document_graph_storage::{NetworkId, PeerId, Rev};
|
||||
use document_graph_storage::{HotSequence, NetworkId, PeerId, Rev, SettledHotOps, UserId, Value};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
@@ -15,13 +15,17 @@ 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, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(default)]
|
||||
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.)
|
||||
@@ -31,12 +35,24 @@ 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, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub view_settings: BTreeMap<String, serde_json::Value>,
|
||||
#[serde(default)]
|
||||
pub view_settings: BTreeMap<String, 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, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub network_view_settings: BTreeMap<NetworkId, BTreeMap<String, serde_json::Value>>,
|
||||
#[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,
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{Codec, Error, GddV1, GddV1Layout, Layout, Manifest, io, manifest};
|
||||
use document_graph_storage::{HotOp, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
|
||||
use document_graph_storage::{HotOp, HotSequence, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
|
||||
|
||||
fn empty_container() -> AnyContainer {
|
||||
AnyContainer::Memory(MemoryBackend::new())
|
||||
@@ -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()).await {
|
||||
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()) {
|
||||
Ok(gdd) => gdd,
|
||||
Err(error) => panic!("create_in failed: {error:?}"),
|
||||
};
|
||||
@@ -82,9 +82,7 @@ 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())
|
||||
.await
|
||||
.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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
assert_eq!(gdd.session().peer(), PeerId(13));
|
||||
|
||||
@@ -99,9 +97,7 @@ 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())
|
||||
.await
|
||||
.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()).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:?}"));
|
||||
@@ -116,9 +112,7 @@ 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())
|
||||
.await
|
||||
.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()).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.
|
||||
@@ -128,6 +122,7 @@ 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:?}"));
|
||||
|
||||
@@ -143,9 +138,7 @@ 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())
|
||||
.await
|
||||
.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()).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 {
|
||||
@@ -154,6 +147,7 @@ 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 {
|
||||
@@ -161,6 +155,7 @@ 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();
|
||||
@@ -189,9 +184,7 @@ 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())
|
||||
.await
|
||||
.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()).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 {
|
||||
@@ -200,6 +193,7 @@ 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:?}"));
|
||||
@@ -220,9 +214,7 @@ 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())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
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 dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("export");
|
||||
@@ -231,7 +223,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 MessagePack (`.bin`), manifest is JSON.
|
||||
// Payloads keep the working-copy codecs: registry is postcard (`.bin`), manifest is JSON.
|
||||
assert!(dest.join("registry.bin").exists());
|
||||
assert!(dest.join("manifest.json").exists());
|
||||
assert!(dest.join("session.json").exists());
|
||||
@@ -250,9 +242,7 @@ 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())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
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 dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("doc.gdd.zip");
|
||||
@@ -277,9 +267,7 @@ 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())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
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 dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("nope");
|
||||
@@ -302,9 +290,7 @@ 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())
|
||||
.await
|
||||
.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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"deadbeef cafe babe";
|
||||
let hash = ResourceHash::from(&payload[..]);
|
||||
@@ -334,9 +320,7 @@ 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())
|
||||
.await
|
||||
.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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"persistent bytes";
|
||||
let hash = ResourceHash::from(&payload[..]);
|
||||
@@ -365,9 +349,7 @@ 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())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// Source file outside the working copy.
|
||||
let payload = b"external resource bytes";
|
||||
@@ -391,9 +373,7 @@ 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())
|
||||
.await
|
||||
.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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"exported resource";
|
||||
let hash = ResourceHash::from(&payload[..]);
|
||||
@@ -416,14 +396,12 @@ fn export_carries_resources() {
|
||||
#[test]
|
||||
fn embed_all_resources_materializes_link_only_resource() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
use document_graph_storage::NoMetadata;
|
||||
use document_graph_storage::{NoMetadata, to_value};
|
||||
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())
|
||||
.await
|
||||
.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()).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.
|
||||
@@ -470,8 +448,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 = serde_json::to_value(DataSource::Embedded).unwrap();
|
||||
let url = serde_json::to_value(DataSource::Url("https://example.com/r.bin".parse().unwrap())).unwrap();
|
||||
let embedded = to_value(&DataSource::Embedded).unwrap();
|
||||
let url = 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");
|
||||
});
|
||||
@@ -488,9 +466,7 @@ 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())
|
||||
.await
|
||||
.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()).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";
|
||||
@@ -531,9 +507,7 @@ 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())
|
||||
.await
|
||||
.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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"hot resource bytes";
|
||||
let hash = graphene_resource::ResourceHash::from(&payload[..]);
|
||||
@@ -586,14 +560,12 @@ 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())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
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 codecs = gdd.manifest().codecs;
|
||||
assert_eq!(codecs.registry, Codec::MessagePack);
|
||||
assert_eq!(codecs.history, Codec::MessagePackFrames);
|
||||
assert_eq!(codecs.hot_log, Codec::MessagePackFrames);
|
||||
assert_eq!(codecs.registry, Codec::Postcard);
|
||||
assert_eq!(codecs.history, Codec::PostcardFrames);
|
||||
assert_eq!(codecs.hot_log, Codec::PostcardFrames);
|
||||
assert_eq!(codecs.session, Codec::Json);
|
||||
});
|
||||
}
|
||||
@@ -609,9 +581,7 @@ 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())
|
||||
.await
|
||||
.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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(core_types::uuid::NodeId(0), 0)],
|
||||
@@ -630,11 +600,19 @@ 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)), Some(&UserId(21)), "first commit registers the peer");
|
||||
assert_eq!(
|
||||
gdd.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
|
||||
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)), Some(&UserId(21)), "registration survives reopen");
|
||||
assert_eq!(
|
||||
reopened.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
|
||||
Some(UserId(21)),
|
||||
"registration survives reopen"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -645,9 +623,7 @@ 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())
|
||||
.await
|
||||
.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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let hot_op = HotOp {
|
||||
op: RegistryDelta::AddNetwork {
|
||||
@@ -655,12 +631,13 @@ 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 MessagePackFrames (.frames), manifest is always JSON.
|
||||
assert!(working.exists(&io::path_for(layout.hot_log_basename(), Codec::MessagePackFrames)).await);
|
||||
// Defaults: hot log is PostcardFrames (.frames), manifest is always JSON.
|
||||
assert!(working.exists(&io::path_for(layout.hot_log_basename(), Codec::PostcardFrames)).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:?}"));
|
||||
@@ -698,9 +675,7 @@ 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())
|
||||
.await
|
||||
.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()).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();
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
// 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);
|
||||
});
|
||||
}
|
||||
@@ -5,9 +5,15 @@ 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"]
|
||||
@@ -22,7 +28,7 @@ serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
blake3 = { workspace = true }
|
||||
rustc-hash = { workspace = true }
|
||||
rmp-serde = { workspace = true }
|
||||
postcard = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
graph-craft = { workspace = true, features = ["loading"] }
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::TimeStamp;
|
||||
use crate::{TimeStamp, Value, ValueError, from_value, to_value};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
@@ -8,33 +8,54 @@ 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 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.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Value {
|
||||
pub value: serde_json::Value,
|
||||
pub struct AttributeValue {
|
||||
pub value: Value,
|
||||
pub timestamp: TimeStamp,
|
||||
// No skipping: the registry is positional on disk.
|
||||
#[serde(default)]
|
||||
pub deleted: bool,
|
||||
}
|
||||
|
||||
impl Value {
|
||||
pub fn new(value: serde_json::Value, timestamp: TimeStamp) -> Self {
|
||||
Self { value, timestamp }
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type Attributes = BTreeMap<String, Value>;
|
||||
/// 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)
|
||||
}
|
||||
|
||||
/// Write helpers for `Attributes`.
|
||||
pub trait AttributesWrite {
|
||||
/// Inserts a JSON value under `key`.
|
||||
fn set(&mut self, key: &str, value: serde_json::Value, timestamp: TimeStamp);
|
||||
/// Inserts `value` under `key`.
|
||||
fn set(&mut self, key: &str, value: 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<(), serde_json::Error> {
|
||||
self.set(key, serde_json::to_value(value)?, timestamp);
|
||||
fn set_serialized<T: serde::Serialize>(&mut self, key: &str, value: &T, timestamp: TimeStamp) -> Result<(), ValueError> {
|
||||
self.set(key, 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<(), serde_json::Error> {
|
||||
fn set_if_not_default<T: serde::Serialize + PartialEq>(&mut self, key: &str, value: &T, default: &T, timestamp: TimeStamp) -> Result<(), ValueError> {
|
||||
if value != default {
|
||||
self.set_serialized(key, value, timestamp)?;
|
||||
}
|
||||
@@ -43,8 +64,8 @@ pub trait AttributesWrite {
|
||||
}
|
||||
|
||||
impl AttributesWrite for Attributes {
|
||||
fn set(&mut self, key: &str, value: serde_json::Value, timestamp: TimeStamp) {
|
||||
self.insert(key.to_string(), Value { value, timestamp });
|
||||
fn set(&mut self, key: &str, value: Value, timestamp: TimeStamp) {
|
||||
self.insert(key.to_string(), AttributeValue::new(value, timestamp));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,6 +87,6 @@ pub trait AttributesRead {
|
||||
|
||||
impl AttributesRead for Attributes {
|
||||
fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
|
||||
self.get(key).and_then(|v| serde_json::from_value(v.value.clone()).ok())
|
||||
self.get(key).filter(|v| !v.deleted).and_then(|v| from_value(&v.value).ok())
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,6 @@ pub mod node {
|
||||
pub mod session {
|
||||
pub mod network {
|
||||
pub const PREVIEWING: &str = "ui::previewing";
|
||||
|
||||
// TODO: Remove these graph ui nav-specific attributes
|
||||
pub const NAV_PTZ: &str = "ui::nav::ptz";
|
||||
pub const NAV_TRANSFORM: &str = "ui::nav::transform";
|
||||
@@ -60,6 +59,11 @@ pub mod network {
|
||||
/// serialized blob so its shape can evolve (e.g. dropping the `Type`) without a model change. The
|
||||
/// node references use stable storage IDs, resolved back to runtime-local IDs on conversion.
|
||||
pub const SCOPE_INJECTIONS: &str = "scope_injections";
|
||||
|
||||
/// Whole-vec LWW of the display order of the network's pinned nodes, as stable storage IDs.
|
||||
/// Concurrent reorders do not merge, but the pinned set is already shared, and a shared set with
|
||||
/// per-peer ordering would diverge with no way to reconcile.
|
||||
pub const PINNED_ORDER: &str = "ui::pinned_order";
|
||||
}
|
||||
|
||||
pub mod delta {
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
use crate::{Attributes, AttributesWrite, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev};
|
||||
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 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 (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.
|
||||
/// `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.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Delta {
|
||||
pub id: Rev,
|
||||
@@ -16,16 +18,22 @@ pub struct Delta {
|
||||
pub author: PeerId,
|
||||
pub timestamp: TimeStamp,
|
||||
pub kind: RegistryDelta,
|
||||
pub reverse: RegistryDelta,
|
||||
/// What every slot `kind` wrote held before it, stamps included, in write order. See [`Prior`].
|
||||
pub reverse: Vec<Prior>,
|
||||
/// 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, skip_serializing_if = "Attributes::is_empty")]
|
||||
#[serde(default)]
|
||||
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: RegistryDelta) -> Self {
|
||||
pub fn new(parent: Option<Rev>, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: Vec<Prior>) -> Self {
|
||||
let id = compute_rev(parent, author, timestamp, &kind);
|
||||
Self {
|
||||
id,
|
||||
@@ -35,6 +43,7 @@ impl Delta {
|
||||
kind,
|
||||
reverse,
|
||||
attributes: Attributes::default(),
|
||||
retired_at_ms: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,9 +61,10 @@ impl Delta {
|
||||
parent,
|
||||
author,
|
||||
timestamp,
|
||||
reverse: kind.clone(),
|
||||
reverse: Vec::new(),
|
||||
kind,
|
||||
attributes: Attributes::default(),
|
||||
retired_at_ms: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,11 +79,16 @@ 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, serde_json::Value::Bool(true), timestamp);
|
||||
self.attributes.set(attr::delta::INTERACTION_END, Value::Bool(true), timestamp);
|
||||
}
|
||||
|
||||
pub fn is_interaction_end(&self) -> bool {
|
||||
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == serde_json::Value::Bool(true))
|
||||
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)
|
||||
}
|
||||
|
||||
/// The content-addressed `Rev` this delta's identity fields hash to. Equals `id` for a delta built
|
||||
@@ -92,14 +107,13 @@ impl Delta {
|
||||
|
||||
/// Op payload. Timestamps live on the wrapping `Delta` — one per delta, applied to all LWW-eligible
|
||||
/// writes within. See `notes/document-format-collaboration.md`.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum RegistryDelta {
|
||||
AddNode {
|
||||
id: NodeId,
|
||||
node: Node,
|
||||
},
|
||||
/// `snapshot` lets the reverse `AddNode` rebuild without reading the (already-removed) node from
|
||||
/// the registry, mirroring `RemoveNetwork`.
|
||||
/// `snapshot` is the node as removed, which folds in like any write so a removal of a node never seen still lands.
|
||||
RemoveNode {
|
||||
id: NodeId,
|
||||
snapshot: Node,
|
||||
@@ -109,6 +123,25 @@ pub enum RegistryDelta {
|
||||
index: u32,
|
||||
new_input: NodeInput,
|
||||
},
|
||||
/// A node's whole input list, for a change to the number or order of its slots that the
|
||||
/// index-addressed `ChangeNodeInput` cannot express. Assigns rather than merging: concurrent
|
||||
/// per-slot edits are lost, which is inherent to the indices themselves moving.
|
||||
///
|
||||
/// Touches only the inputs, leaving the node's attributes and implementation alone, so it composes
|
||||
/// with attribute ops on the same node instead of reverting them.
|
||||
SetNodeInputs {
|
||||
id: NodeId,
|
||||
inputs: Vec<InputSlot>,
|
||||
},
|
||||
/// A node's implementation, for swapping what it computes without rebuilding the node.
|
||||
///
|
||||
/// Removing and re-adding the node would express the same change, but would also clear every
|
||||
/// attribute it carries, so restating them would clobber whatever a concurrent peer wrote to the
|
||||
/// node's name, lock or pin.
|
||||
SetNodeImplementation {
|
||||
id: NodeId,
|
||||
implementation: Implementation,
|
||||
},
|
||||
ChangeNodeAttribute {
|
||||
id: NodeId,
|
||||
delta: AttributeDelta,
|
||||
@@ -133,13 +166,12 @@ pub enum RegistryDelta {
|
||||
id: NetworkId,
|
||||
network: Network,
|
||||
},
|
||||
/// `snapshot` lets the reverse delta rebuild without re-walking history.
|
||||
/// `snapshot` is the network as removed; see [`RemoveNode`](Self::RemoveNode).
|
||||
RemoveNetwork {
|
||||
id: NetworkId,
|
||||
snapshot: Network,
|
||||
},
|
||||
/// Register a whole resource entry at once. Overwrites any existing entry for `id`; the reverse
|
||||
/// of `RemoveResource`, the way `AddNetwork` pairs with `RemoveNetwork`.
|
||||
/// Register a whole resource entry at once, the way `AddNetwork` pairs with `RemoveNetwork`.
|
||||
AddResource {
|
||||
id: ResourceId,
|
||||
entry: ResourceEntry,
|
||||
@@ -161,16 +193,15 @@ pub enum RegistryDelta {
|
||||
AddSource {
|
||||
id: ResourceId,
|
||||
key: SourceKey,
|
||||
source: serde_json::Value,
|
||||
source: Value,
|
||||
},
|
||||
/// Remove one entry from a resource's source chain. LWW against the entry's timestamp.
|
||||
RemoveSource {
|
||||
id: ResourceId,
|
||||
key: SourceKey,
|
||||
},
|
||||
/// 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.
|
||||
/// 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.
|
||||
RegisterPeer {
|
||||
peer: PeerId,
|
||||
user: UserId,
|
||||
@@ -185,42 +216,52 @@ 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(serde_json::Value),
|
||||
Other(Value),
|
||||
}
|
||||
|
||||
/// `value: None` means remove. The timestamp comes from the wrapping `Delta`.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AttributeDelta {
|
||||
pub key: String,
|
||||
pub value: Option<serde_json::Value>,
|
||||
pub value: Option<Value>,
|
||||
}
|
||||
|
||||
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) {
|
||||
/// 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) {
|
||||
let AttributeDelta { key, value } = delta;
|
||||
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);
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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.sources {
|
||||
for (key, _) in from.live_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.sources {
|
||||
for (key, to_source) in to.live_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 from.keys() {
|
||||
if !to.contains_key(key) {
|
||||
for (key, _) in crate::attributes::live(from) {
|
||||
if to.get(key).is_none_or(|value| value.deleted) {
|
||||
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 to {
|
||||
if from.get(key).is_none_or(|from_value| from_value.value != to_value.value) {
|
||||
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) {
|
||||
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};
|
||||
use crate::{Attributes, ExportSlot, Network, Node, NodeInput, TimeStamp, Value};
|
||||
|
||||
#[test]
|
||||
fn test_compute_deltas_empty() {
|
||||
@@ -287,6 +287,7 @@ mod tests {
|
||||
input: NodeInput::Import { index: 0 },
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
attributes: Attributes::new(),
|
||||
attributes_timestamp: TimeStamp::ORIGIN,
|
||||
});
|
||||
|
||||
let deltas = compute_deltas(&from, &to);
|
||||
@@ -304,11 +305,7 @@ 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", serde_json::json!(640.0), TimeStamp::ORIGIN);
|
||||
to.networks.get_mut(&NetworkId(0)).unwrap().attributes.set("ui::nav::width", Value::Float(640.), TimeStamp::ORIGIN);
|
||||
|
||||
let deltas = compute_deltas(&from, &to);
|
||||
assert_eq!(deltas.len(), 1, "a changed per-network attribute must emit one delta");
|
||||
@@ -341,9 +338,10 @@ mod tests {
|
||||
let stamp = |counter: u64| TimeStamp { counter, peer: crate::PeerId(0) };
|
||||
node.attributes.insert(
|
||||
"test".to_string(),
|
||||
crate::Value {
|
||||
value: serde_json::json!("old"),
|
||||
crate::AttributeValue {
|
||||
value: Value::Str("old".into()),
|
||||
timestamp: stamp(0),
|
||||
deleted: false,
|
||||
},
|
||||
);
|
||||
from.node_instances.insert(NodeId(42), node);
|
||||
@@ -351,9 +349,10 @@ mod tests {
|
||||
let mut to = from.clone();
|
||||
to.node_instances.get_mut(&NodeId(42)).unwrap().attributes.insert(
|
||||
"test".to_string(),
|
||||
crate::Value {
|
||||
value: serde_json::json!("new"),
|
||||
crate::AttributeValue {
|
||||
value: Value::Str("new".into()),
|
||||
timestamp: stamp(1),
|
||||
deleted: false,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -376,9 +375,10 @@ mod tests {
|
||||
let mut to = from.clone();
|
||||
to.attributes.insert(
|
||||
"doc::test_attribute".to_string(),
|
||||
crate::Value {
|
||||
value: serde_json::json!("value"),
|
||||
crate::AttributeValue {
|
||||
value: Value::Str("value".into()),
|
||||
timestamp: stamp(1),
|
||||
deleted: false,
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -1,23 +1,29 @@
|
||||
use std::collections::btree_map::Entry;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::hash::Hash;
|
||||
|
||||
use crate::{
|
||||
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,
|
||||
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,
|
||||
};
|
||||
|
||||
#[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, and what undo/redo force-apply against.
|
||||
/// reads and `registry()` observe.
|
||||
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, 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
|
||||
/// hot-polluted working state) and advances it. It equals the working registry whenever the hot log is
|
||||
/// empty.
|
||||
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>,
|
||||
@@ -28,97 +34,129 @@ pub struct Document {
|
||||
pub(crate) redo_stack: Vec<Rev>,
|
||||
pub(crate) clock: LamportClock,
|
||||
pub(crate) peer: PeerId,
|
||||
/// 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.
|
||||
/// 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.
|
||||
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 bytes = rmp_serde::to_vec(&(self.peer, self.next_node_counter)).expect("(PeerId, counter) must serialize");
|
||||
let digest = blake3::hash(&bytes);
|
||||
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 mut truncated = [0u8; 8];
|
||||
truncated.copy_from_slice(&digest.as_bytes()[..8]);
|
||||
NodeId(u64::from_le_bytes(truncated))
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
/// 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);
|
||||
}
|
||||
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)?;
|
||||
/// 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);
|
||||
self.hot_log.push(hot_op);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// Replay a hot op recovered from persisted state or received from a peer. Replaying one already
|
||||
/// reflected in the registry changes nothing.
|
||||
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(())
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// 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.
|
||||
pub fn apply_delta(&mut self, delta: Delta) -> Result<(), CrdtError> {
|
||||
for parent in delta.all_parents() {
|
||||
if !self.history.contains(parent) {
|
||||
@@ -138,296 +176,503 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
fn registry_ref(&self, target: RegistryTarget) -> &Registry {
|
||||
pub(crate) fn registry_ref(&self, target: RegistryTarget) -> &Registry {
|
||||
match target {
|
||||
RegistryTarget::Working => &self.working_registry,
|
||||
RegistryTarget::Snapshot => &self.retired_snapshot,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// A fresh local edit against the working registry; see [`ApplyMode::Live`].
|
||||
#[cfg(test)]
|
||||
pub(crate) fn apply_op(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
|
||||
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Live)
|
||||
}
|
||||
|
||||
/// 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 `>`.
|
||||
/// An op from a peer or from persisted state, against the working registry.
|
||||
pub(crate) fn apply_op_idempotent(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
|
||||
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Idempotent)
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
/// 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()`].
|
||||
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);
|
||||
|
||||
// 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 live = mode == ApplyMode::Live;
|
||||
|
||||
let registry = self.registry_mut(target);
|
||||
match op {
|
||||
RegistryDelta::AddNode { id, node } => {
|
||||
if registry.node_instances.contains_key(&id) {
|
||||
if idempotent {
|
||||
// Hot ops already created this node; skip rather than error.
|
||||
return Ok(());
|
||||
}
|
||||
if live && registry.node_instances.contains_key(&id) {
|
||||
return Err(CrdtError::NodeAlreadyExists(id));
|
||||
}
|
||||
registry.node_instances.insert(id, node);
|
||||
write_network(registry, node.network, timestamp, mode, |_| Ok(()))?;
|
||||
add(&mut registry.node_instances, &mut registry.removed_nodes, id, node, timestamp);
|
||||
}
|
||||
RegistryDelta::RemoveNode { id, .. } => {
|
||||
registry.node_instances.remove(&id);
|
||||
RegistryDelta::RemoveNode { id, snapshot } => {
|
||||
remove(&mut registry.node_instances, &mut registry.removed_nodes, id, snapshot, timestamp);
|
||||
}
|
||||
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::ChangeNodeInput { id, index, new_input } => {
|
||||
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
let input = node.inputs.get_mut(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
|
||||
if force || timestamp > input.timestamp {
|
||||
input.input = new_input;
|
||||
input.timestamp = timestamp;
|
||||
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(()))?;
|
||||
}
|
||||
}
|
||||
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 } => {
|
||||
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
apply_attribute_delta(delta, timestamp, force, &mut node.attributes);
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
apply_attribute_delta(delta, timestamp, &mut node.attributes, node.attributes_timestamp);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => {
|
||||
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);
|
||||
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(())
|
||||
})?;
|
||||
}
|
||||
RegistryDelta::SetNetworkExport { id, index, export } => {
|
||||
let net = registry.networks.get_mut(&id).ok_or(CrdtError::NetworkDoesNotExist(id))?;
|
||||
let slot_idx = index as usize;
|
||||
|
||||
if slot_idx >= net.exports.len() {
|
||||
if slot_idx >= MAX_EXPORT_SLOTS {
|
||||
return Err(CrdtError::ExportSlotOutOfBounds(index));
|
||||
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());
|
||||
}
|
||||
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;
|
||||
let existing = &mut net.exports[slot_idx];
|
||||
if timestamp > existing.timestamp {
|
||||
existing.target = export;
|
||||
existing.timestamp = timestamp;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
if let Some(referenced) = referenced {
|
||||
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
|
||||
}
|
||||
}
|
||||
RegistryDelta::AddNetwork { id, network: contents } => {
|
||||
if registry.networks.contains_key(&id) {
|
||||
if idempotent {
|
||||
return Ok(());
|
||||
}
|
||||
RegistryDelta::AddNetwork { id, network } => {
|
||||
if live && registry.networks.contains_key(&id) {
|
||||
return Err(CrdtError::NetworkAlreadyExists(id));
|
||||
}
|
||||
registry.networks.insert(id, contents);
|
||||
add(&mut registry.networks, &mut registry.removed_networks, id, network, timestamp);
|
||||
}
|
||||
RegistryDelta::RemoveNetwork { id, .. } => {
|
||||
registry.networks.remove(&id);
|
||||
RegistryDelta::RemoveNetwork { id, snapshot } => {
|
||||
remove(&mut registry.networks, &mut registry.removed_networks, id, snapshot, timestamp);
|
||||
}
|
||||
RegistryDelta::ChangeNetworkAttribute { id, delta } => {
|
||||
let net = registry.networks.get_mut(&id).ok_or(CrdtError::NetworkDoesNotExist(id))?;
|
||||
apply_attribute_delta(delta, timestamp, force, &mut net.attributes);
|
||||
write_network(registry, id, timestamp, mode, |net| {
|
||||
apply_attribute_delta(delta, timestamp, &mut net.attributes, net.attributes_timestamp);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
RegistryDelta::SetResourceHash { id, hash } => {
|
||||
let entry = registry.resources.entry(id).or_default();
|
||||
if force || timestamp > entry.hash_timestamp {
|
||||
entry.hash = hash;
|
||||
entry.hash_timestamp = timestamp;
|
||||
}
|
||||
upsert_resource(registry, id, timestamp, |entry| {
|
||||
if 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) }
|
||||
upsert_resource(registry, id, timestamp, |entry| {
|
||||
let value = SourceValue { source, timestamp, deleted: false };
|
||||
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);
|
||||
}
|
||||
}
|
||||
// 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 } => {
|
||||
registry.resources.insert(id, entry);
|
||||
add(&mut registry.resources, &mut registry.removed_resources, id, entry, timestamp);
|
||||
}
|
||||
RegistryDelta::RemoveResource { id, .. } => {
|
||||
registry.resources.remove(&id);
|
||||
RegistryDelta::RemoveResource { id, snapshot } => {
|
||||
remove(&mut registry.resources, &mut registry.removed_resources, id, snapshot, timestamp);
|
||||
}
|
||||
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::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 });
|
||||
}
|
||||
},
|
||||
}
|
||||
RegistryDelta::ChangeDocumentAttribute { delta } => {
|
||||
apply_attribute_delta(delta, timestamp, force, &mut registry.attributes);
|
||||
apply_attribute_delta(delta, timestamp, &mut registry.attributes, TimeStamp::ORIGIN);
|
||||
}
|
||||
// Merge is a structural sync point only; it mutates no registry state.
|
||||
RegistryDelta::Merge { .. } | RegistryDelta::Other(_) => {}
|
||||
RegistryDelta::Merge { .. } | RegistryDelta::EndTransaction | RegistryDelta::Other(_) => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)?;
|
||||
/// 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;
|
||||
}
|
||||
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)?;
|
||||
}
|
||||
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::ChangeNetworkAttribute { id: network, .. } => self.ensure_network_exists(target, *network)?,
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
*floor = (*floor).max(other_floor);
|
||||
}
|
||||
|
||||
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)?;
|
||||
/// 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;
|
||||
}
|
||||
newer.resize_with(index + 1, || InputSlot::unset(shape));
|
||||
}
|
||||
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)?;
|
||||
let slot = &mut newer[index];
|
||||
if incoming.timestamp > slot.timestamp {
|
||||
slot.input = incoming.input;
|
||||
slot.timestamp = incoming.timestamp;
|
||||
}
|
||||
Ok(())
|
||||
merge_attributes(&mut slot.attributes, &mut slot.attributes_timestamp, incoming.attributes, incoming.attributes_timestamp);
|
||||
}
|
||||
node.inputs = newer;
|
||||
node.inputs_timestamp = shape;
|
||||
}
|
||||
|
||||
/// 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::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, ®istry.attributes),
|
||||
},
|
||||
// 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),
|
||||
})
|
||||
/// 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,
|
||||
},
|
||||
);
|
||||
}
|
||||
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()
|
||||
},
|
||||
);
|
||||
}
|
||||
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
|
||||
@@ -439,13 +684,12 @@ pub(crate) enum RegistryTarget {
|
||||
Snapshot,
|
||||
}
|
||||
|
||||
/// How [`Document::apply_op_with`] resolves structural collisions and LWW timestamp ties.
|
||||
/// How [`Document::apply_op_with`] treats what it finds.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum ApplyMode {
|
||||
/// Fresh local/remote edit: structural ops error on duplicate/missing targets; LWW uses strict `>`.
|
||||
/// A fresh local edit: adding what exists, or writing to what was never seen, is an error, since a local
|
||||
/// edit cannot mean either.
|
||||
Live,
|
||||
/// Replay/retire: structural ops skip duplicate/missing targets; LWW still uses strict `>`.
|
||||
/// An op from a peer or from persisted state: every arm is a timestamp comparison.
|
||||
Idempotent,
|
||||
/// Silent-zone undo/redo rewind: structural ops are idempotent and LWW arms assign unconditionally.
|
||||
Force,
|
||||
}
|
||||
@@ -10,9 +10,12 @@ 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};
|
||||
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,
|
||||
};
|
||||
|
||||
fn map_serialization_error(key: &str) -> impl FnOnce(serde_json::Error) -> ConversionError + '_ {
|
||||
fn map_serialization_error(key: &str) -> impl FnOnce(ValueError) -> ConversionError + '_ {
|
||||
move |e| ConversionError::SerializationError(format!("{key}: {e:?}"))
|
||||
}
|
||||
|
||||
@@ -40,7 +43,7 @@ impl NodePath {
|
||||
}
|
||||
|
||||
fn to_global_id(&self, peer: PeerId) -> NodeId {
|
||||
let bytes = rmp_serde::to_vec(&(peer, self)).expect("NodePath must serialize");
|
||||
let bytes = postcard::to_stdvec(&(peer, self)).expect("NodePath must serialize");
|
||||
let digest = blake3::hash(&bytes);
|
||||
let mut truncated = [0u8; 8];
|
||||
truncated.copy_from_slice(&digest.as_bytes()[..8]);
|
||||
@@ -52,7 +55,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 = rmp_serde::to_vec(&("network", peer, self)).expect("NodePath must serialize");
|
||||
let bytes = postcard::to_stdvec(&("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]);
|
||||
@@ -60,6 +63,34 @@ impl NodePath {
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves a node's storage identity: the identity the metadata source holds for it where there is
|
||||
/// one, and a hash of its location otherwise. Every place a node is named goes through here, so a
|
||||
/// node's own registry key and every reference to it agree.
|
||||
///
|
||||
/// A held identity travels with the node, so moving it between networks keeps it. A hashed one is
|
||||
/// derived from the node's place in the tree, so it changes when the node moves; it stands in for a
|
||||
/// node no source names, such as one in a network that has never been stored.
|
||||
pub(crate) struct NodeIds<'a, M: NodeMetadataSource + ?Sized> {
|
||||
pub(crate) metadata: Option<&'a M>,
|
||||
pub(crate) metadata_path: &'a [RuntimeNodeId],
|
||||
pub(crate) peer: PeerId,
|
||||
}
|
||||
|
||||
impl<M: NodeMetadataSource + ?Sized> Clone for NodeIds<'_, M> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
impl<M: NodeMetadataSource + ?Sized> Copy for NodeIds<'_, M> {}
|
||||
|
||||
impl<M: NodeMetadataSource + ?Sized> NodeIds<'_, M> {
|
||||
fn resolve(&self, path: &NodePath, local_id: RuntimeNodeId) -> NodeId {
|
||||
self.metadata
|
||||
.and_then(|metadata| metadata.storage_node_id(self.metadata_path, local_id))
|
||||
.unwrap_or_else(|| path.to_global_id(self.peer))
|
||||
}
|
||||
}
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ConversionError {
|
||||
#[error("Failed to serialize value: {0}")]
|
||||
@@ -89,45 +120,29 @@ 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
|
||||
/// 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.
|
||||
/// 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).
|
||||
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>,
|
||||
}
|
||||
|
||||
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`].
|
||||
/// 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`].
|
||||
pub fn encode_declaration(proto: &ProtoNode) -> Result<Vec<u8>, 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())
|
||||
let value = to_value(proto).map_err(|error| error.to_string())?;
|
||||
postcard::to_stdvec(&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: 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())
|
||||
let value: Value = postcard::from_bytes(bytes).map_err(|error| error.to_string())?;
|
||||
from_value(&value).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
impl Registry {
|
||||
@@ -149,6 +164,7 @@ impl Registry {
|
||||
let mut ctx = ConversionContext {
|
||||
declaration_ids: HashMap::new(),
|
||||
declaration_bytes: HashMap::new(),
|
||||
declarations: HashMap::new(),
|
||||
network_ids: HashMap::new(),
|
||||
metadata,
|
||||
peer,
|
||||
@@ -167,6 +183,7 @@ impl Registry {
|
||||
Ok(RuntimeConversion {
|
||||
registry,
|
||||
declaration_bytes: ctx.declaration_bytes,
|
||||
declarations: ctx.declarations,
|
||||
network_ids: ctx.network_ids,
|
||||
})
|
||||
}
|
||||
@@ -175,40 +192,49 @@ 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 `serde_json::Value` so its on-disk shape can migrate freely. All
|
||||
/// stored type-erased as [`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() {
|
||||
if !referenced.contains(&id) {
|
||||
continue;
|
||||
}
|
||||
let Some(info) = resources.info(&id) else { continue };
|
||||
|
||||
let mut entry = crate::ResourceEntry {
|
||||
hash: info.hash.copied(),
|
||||
hash_timestamp: TimeStamp::ORIGIN,
|
||||
..Default::default()
|
||||
};
|
||||
for (position, source) in info.sources.iter().enumerate() {
|
||||
let key = crate::SourceKey {
|
||||
priority: crate::Priority::new(position as f64).expect("enumerate index is finite"),
|
||||
peer,
|
||||
};
|
||||
let body = serde_json::to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
|
||||
entry.set_source(
|
||||
key,
|
||||
crate::SourceValue {
|
||||
source: body,
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
},
|
||||
);
|
||||
if let Some(entry) = convert_resource_entry(resources, id, peer)? {
|
||||
registry.resources.insert(id, entry);
|
||||
}
|
||||
|
||||
registry.resources.insert(id, entry);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Snapshot one runtime resource into a storage entry, or `None` if the runtime has no such resource.
|
||||
pub fn convert_resource_entry(resources: &graphene_resource::ResourceRegistry, id: ResourceId, peer: PeerId) -> Result<Option<crate::ResourceEntry>, ConversionError> {
|
||||
let Some(info) = resources.info(&id) else { return Ok(None) };
|
||||
|
||||
let mut entry = crate::ResourceEntry {
|
||||
hash: info.hash.copied(),
|
||||
hash_timestamp: TimeStamp::ORIGIN,
|
||||
..Default::default()
|
||||
};
|
||||
for (position, source) in info.sources.iter().enumerate() {
|
||||
let key = crate::SourceKey {
|
||||
priority: crate::Priority::new(position as f64).expect("enumerate index is finite"),
|
||||
peer,
|
||||
};
|
||||
let body = 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(
|
||||
key,
|
||||
crate::SourceValue {
|
||||
source: body,
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
deleted: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Ok(Some(entry))
|
||||
}
|
||||
|
||||
/// Collect the `ResourceId`s referenced by `TaggedValue::Resource` inputs anywhere in the network
|
||||
/// (recursively through nested networks). These are the resources the document actually uses; the
|
||||
/// runtime cache may hold more (history-retained orphans) that shouldn't be snapshotted into storage.
|
||||
@@ -254,6 +280,8 @@ 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>,
|
||||
@@ -261,6 +289,20 @@ struct ConversionContext<'m, M: NodeMetadataSource + ?Sized> {
|
||||
peer: PeerId,
|
||||
}
|
||||
|
||||
impl<'m, M: NodeMetadataSource + ?Sized> ConversionContext<'m, M> {
|
||||
/// The identity resolver for nodes addressed inside the network at `metadata_path`.
|
||||
fn ids<'a>(&self, metadata_path: &'a [RuntimeNodeId]) -> NodeIds<'a, M>
|
||||
where
|
||||
'm: 'a,
|
||||
{
|
||||
NodeIds {
|
||||
metadata: Some(self.metadata),
|
||||
metadata_path,
|
||||
peer: self.peer,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_network<M: NodeMetadataSource + ?Sized>(
|
||||
node_network: &NodeNetwork,
|
||||
network_id: NetworkId,
|
||||
@@ -271,7 +313,7 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
|
||||
) -> Result<(), ConversionError> {
|
||||
for (runtime_node_id, doc_node) in &node_network.nodes {
|
||||
let node_path = child_path(parent_path, network_id, *runtime_node_id);
|
||||
let global_id = node_path.to_global_id(ctx.peer);
|
||||
let global_id = ctx.ids(metadata_path).resolve(&node_path, *runtime_node_id);
|
||||
|
||||
let location = NodeLocation {
|
||||
network_id,
|
||||
@@ -279,8 +321,8 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
|
||||
metadata_path,
|
||||
runtime_node_id: *runtime_node_id,
|
||||
};
|
||||
let mut node = convert_node(doc_node, location, registry, ctx)?;
|
||||
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(runtime_node_id.0), TimeStamp::ORIGIN);
|
||||
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);
|
||||
registry.node_instances.insert(global_id, node);
|
||||
}
|
||||
|
||||
@@ -289,17 +331,25 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
|
||||
.iter()
|
||||
.map(|export| {
|
||||
Ok(ExportSlot {
|
||||
target: Some(convert_input(export, parent_path, network_id, ctx.peer)?),
|
||||
target: Some(convert_input(export, parent_path, network_id, ctx.ids(metadata_path))?),
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>, ConversionError>>()?;
|
||||
|
||||
let mut attributes = crate::Attributes::new();
|
||||
write_ui_network_attributes(&mut attributes, ctx.metadata, metadata_path, TimeStamp::ORIGIN)?;
|
||||
write_scope_injections(&mut attributes, node_network, parent_path, network_id, ctx.peer, TimeStamp::ORIGIN)?;
|
||||
write_ui_network_attributes(&mut attributes, node_network, metadata_path, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
|
||||
write_scope_injections(&mut attributes, node_network, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
|
||||
|
||||
registry.networks.insert(network_id, Network { exports, attributes });
|
||||
registry.networks.insert(
|
||||
network_id,
|
||||
Network {
|
||||
presence: TimeStamp::ORIGIN,
|
||||
exports,
|
||||
attributes,
|
||||
attributes_timestamp: TimeStamp::ORIGIN,
|
||||
},
|
||||
);
|
||||
ctx.network_ids.insert(metadata_path.to_vec(), network_id);
|
||||
|
||||
Ok(())
|
||||
@@ -308,12 +358,12 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
|
||||
/// Serialize a network's `scope_injections` onto its attributes as one whole-map LWW blob, remapping
|
||||
/// each runtime-local node reference to its stable storage global ID so the reference survives a
|
||||
/// round trip even if runtime IDs are later reshuffled.
|
||||
fn write_scope_injections(
|
||||
fn write_scope_injections<M: NodeMetadataSource + ?Sized>(
|
||||
attributes: &mut crate::Attributes,
|
||||
node_network: &NodeNetwork,
|
||||
parent_path: Option<&NodePath>,
|
||||
network_id: NetworkId,
|
||||
peer: PeerId,
|
||||
ids: NodeIds<'_, M>,
|
||||
timestamp: TimeStamp,
|
||||
) -> Result<(), ConversionError> {
|
||||
if node_network.scope_injections.is_empty() {
|
||||
@@ -324,7 +374,7 @@ fn write_scope_injections(
|
||||
.scope_injections
|
||||
.iter()
|
||||
.map(|(key, (runtime_id, ty))| {
|
||||
let storage_id = child_path(parent_path, network_id, *runtime_id).to_global_id(peer);
|
||||
let storage_id = ids.resolve(&child_path(parent_path, network_id, *runtime_id), *runtime_id);
|
||||
(key.clone(), (storage_id, ty.clone()))
|
||||
})
|
||||
.collect();
|
||||
@@ -351,7 +401,13 @@ struct NodeLocation<'a> {
|
||||
runtime_node_id: RuntimeNodeId,
|
||||
}
|
||||
|
||||
fn convert_node<M: NodeMetadataSource + ?Sized>(doc_node: &DocumentNode, location: NodeLocation<'_>, registry: &mut Registry, ctx: &mut ConversionContext<'_, M>) -> Result<Node, ConversionError> {
|
||||
fn convert_node<M: NodeMetadataSource + ?Sized>(
|
||||
doc_node: &DocumentNode,
|
||||
location: NodeLocation<'_>,
|
||||
registry: &mut Registry,
|
||||
ctx: &mut ConversionContext<'_, M>,
|
||||
recurse: bool,
|
||||
) -> Result<Node, ConversionError> {
|
||||
let NodeLocation {
|
||||
network_id,
|
||||
parent_path,
|
||||
@@ -368,9 +424,10 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(doc_node: &DocumentNode, locatio
|
||||
write_ui_input_attributes(&mut input_attrs, ctx.metadata, metadata_path, runtime_node_id, input_index, timestamp)?;
|
||||
|
||||
inputs.push(InputSlot {
|
||||
input: convert_input(input, parent_path, network_id, ctx.peer)?,
|
||||
input: convert_input(input, parent_path, network_id, ctx.ids(metadata_path))?,
|
||||
timestamp,
|
||||
attributes: input_attrs,
|
||||
attributes_timestamp: timestamp,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -383,7 +440,7 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(doc_node: &DocumentNode, locatio
|
||||
} else {
|
||||
metadata_path
|
||||
};
|
||||
let implementation = convert_implementation(&doc_node.implementation, &node_path, child_metadata_path, registry, ctx)?;
|
||||
let implementation = convert_implementation(&doc_node.implementation, &node_path, child_metadata_path, registry, ctx, recurse)?;
|
||||
|
||||
// Defaults match `DocumentNode::default()`; `to_runtime` rehydrates absent keys from the same defaults.
|
||||
let mut attributes = crate::Attributes::new();
|
||||
@@ -403,13 +460,58 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(doc_node: &DocumentNode, locatio
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
/// The `call_argument` attribute write for a node, cleared when the value is the default that
|
||||
/// `to_runtime` rehydrates an absent key from. For staging paths that encode this field alone.
|
||||
pub fn encode_call_argument(call_argument: &core_types::Type) -> Result<crate::AttributeDelta, ConversionError> {
|
||||
encode_if_not_default(node::CALL_ARGUMENT, call_argument, &concrete!(Context))
|
||||
}
|
||||
|
||||
/// The `context_features` attribute write, cleared at its default like [`encode_call_argument`].
|
||||
pub fn encode_context_features(context_features: &ContextDependencies) -> Result<crate::AttributeDelta, ConversionError> {
|
||||
encode_if_not_default(node::CONTEXT_FEATURES, context_features, &ContextDependencies::default())
|
||||
}
|
||||
|
||||
fn encode_if_not_default<T: Serialize + PartialEq>(key: &str, value: &T, default: &T) -> Result<crate::AttributeDelta, ConversionError> {
|
||||
let value = if value == default { None } else { Some(to_value(value).map_err(map_serialization_error(key))?) };
|
||||
|
||||
Ok(crate::AttributeDelta { key: key.to_string(), value })
|
||||
}
|
||||
|
||||
/// Public form of the node ui-attribute encoding, for staging paths that encode single nodes.
|
||||
pub fn encode_node_ui_attributes<M: NodeMetadataSource + ?Sized>(
|
||||
attributes: &mut crate::Attributes,
|
||||
metadata: &M,
|
||||
metadata_path: &[RuntimeNodeId],
|
||||
runtime_node_id: RuntimeNodeId,
|
||||
timestamp: TimeStamp,
|
||||
) -> Result<(), ConversionError> {
|
||||
write_ui_attributes(attributes, metadata, metadata_path, runtime_node_id, timestamp)
|
||||
}
|
||||
|
||||
/// Public form of the per-input ui-attribute encoding, matching `encode_node_ui_attributes`.
|
||||
pub fn encode_input_ui_attributes<M: NodeMetadataSource + ?Sized>(
|
||||
attributes: &mut crate::Attributes,
|
||||
metadata: &M,
|
||||
metadata_path: &[RuntimeNodeId],
|
||||
runtime_node_id: RuntimeNodeId,
|
||||
input_index: usize,
|
||||
timestamp: TimeStamp,
|
||||
) -> Result<(), ConversionError> {
|
||||
write_ui_input_attributes(attributes, metadata, metadata_path, runtime_node_id, input_index, timestamp)
|
||||
}
|
||||
|
||||
fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
|
||||
attributes: &mut crate::Attributes,
|
||||
metadata: &M,
|
||||
@@ -430,14 +532,14 @@ fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
|
||||
(node::ui::PINNED, metadata.pinned(metadata_path, runtime_node_id)),
|
||||
] {
|
||||
if value {
|
||||
attributes.set(key, serde_json::Value::Bool(true), timestamp);
|
||||
attributes.set(key, 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, serde_json::Value::String(name.to_string()), timestamp);
|
||||
attributes.set(node::ui::DISPLAY_NAME, Value::Str(name.to_string()), timestamp);
|
||||
}
|
||||
|
||||
// One whole-vec attribute; per-slot LWW would be overkill for rename-on-output.
|
||||
@@ -451,9 +553,34 @@ fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(attributes: &mut crate::Attributes, metadata: &M, network_path: &[RuntimeNodeId], timestamp: TimeStamp) -> Result<(), ConversionError> {
|
||||
/// Node references here are remapped to stable storage IDs for the same reason `write_scope_injections`
|
||||
/// does it: a runtime ID is not stable across a round trip.
|
||||
fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
|
||||
attributes: &mut crate::Attributes,
|
||||
node_network: &NodeNetwork,
|
||||
network_path: &[RuntimeNodeId],
|
||||
parent_path: Option<&NodePath>,
|
||||
network_id: NetworkId,
|
||||
ids: NodeIds<'_, M>,
|
||||
timestamp: TimeStamp,
|
||||
) -> Result<(), ConversionError> {
|
||||
// The same source the IDs resolve through, so a network's attributes and the nodes they name agree.
|
||||
let Some(metadata) = ids.metadata else { return Ok(()) };
|
||||
if let Some(reference) = metadata.reference(network_path) {
|
||||
attributes.set(node::ui::REFERENCE, serde_json::Value::String(reference.to_string()), timestamp);
|
||||
attributes.set(node::ui::REFERENCE, Value::Str(reference.to_string()), timestamp);
|
||||
}
|
||||
|
||||
let to_storage_id = |runtime_id: RuntimeNodeId| ids.resolve(&child_path(parent_path, network_id, runtime_id), runtime_id);
|
||||
|
||||
// Only nodes the converted network still holds: the read side drops a stored ID it cannot find, so
|
||||
// persisting one for a node deleted or reparented elsewhere would leave stored state disagreeing with
|
||||
// what a peer converting the same input produces.
|
||||
let pinned_order: Vec<_> = metadata.pinned_order(network_path).into_iter().filter(|pinned| node_network.nodes.contains_key(pinned)).collect();
|
||||
if !pinned_order.is_empty() {
|
||||
let stored: Vec<NodeId> = pinned_order.into_iter().map(to_storage_id).collect();
|
||||
attributes
|
||||
.set_serialized(network::PINNED_ORDER, &stored, timestamp)
|
||||
.map_err(map_serialization_error(network::PINNED_ORDER))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -471,7 +598,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, serde_json::Value::String(value.to_string()), timestamp);
|
||||
attributes.set(key, Value::Str(value.to_string()), timestamp);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -486,14 +613,14 @@ fn write_ui_input_attributes<M: NodeMetadataSource + ?Sized>(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn convert_input(input: &GraphCraftNodeInput, parent_path: Option<&NodePath>, network_id: NetworkId, peer: PeerId) -> Result<NodeInput, ConversionError> {
|
||||
fn convert_input<M: NodeMetadataSource + ?Sized>(input: &GraphCraftNodeInput, parent_path: Option<&NodePath>, network_id: NetworkId, ids: NodeIds<'_, M>) -> Result<NodeInput, ConversionError> {
|
||||
Ok(match input {
|
||||
GraphCraftNodeInput::Node { node_id, output_index } => NodeInput::Node {
|
||||
id: child_path(parent_path, network_id, *node_id).to_global_id(peer),
|
||||
id: ids.resolve(&child_path(parent_path, network_id, *node_id), *node_id),
|
||||
index: (*output_index).try_into().map_err(|_| ConversionError::IndexOverflow(*output_index))?,
|
||||
},
|
||||
GraphCraftNodeInput::Value { tagged_value, exposed } => {
|
||||
let value = serde_json::to_value(&**tagged_value).map_err(|e| ConversionError::SerializationError(format!("{e:?}")))?;
|
||||
let value = to_value(&**tagged_value).map_err(|e| ConversionError::SerializationError(format!("{e:?}")))?;
|
||||
NodeInput::Value { value, exposed: *exposed }
|
||||
}
|
||||
GraphCraftNodeInput::Scope(s) => NodeInput::Scope(s.clone()),
|
||||
@@ -506,7 +633,9 @@ fn convert_input(input: &GraphCraftNodeInput, parent_path: Option<&NodePath>, ne
|
||||
})
|
||||
}
|
||||
|
||||
fn convert_input_attributes(input: &GraphCraftNodeInput) -> Result<crate::Attributes, ConversionError> {
|
||||
/// The non-ui attributes a slot carries, derived from the input itself: the declared type of an
|
||||
/// import, and a reflection node's metadata.
|
||||
pub fn convert_input_attributes(input: &GraphCraftNodeInput) -> Result<crate::Attributes, ConversionError> {
|
||||
let mut attributes = crate::Attributes::new();
|
||||
let timestamp = TimeStamp::ORIGIN;
|
||||
|
||||
@@ -533,6 +662,7 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
|
||||
child_metadata_path: &[RuntimeNodeId],
|
||||
registry: &mut Registry,
|
||||
ctx: &mut ConversionContext<'_, M>,
|
||||
recurse: bool,
|
||||
) -> Result<Implementation, ConversionError> {
|
||||
Ok(match implementation {
|
||||
DocumentNodeImplementation::ProtoNode(identifier) => {
|
||||
@@ -555,6 +685,7 @@ 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)
|
||||
@@ -564,10 +695,186 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
|
||||
// `to_runtime` -> `from_runtime` round trip reproduces the same `NetworkId` (and thus the
|
||||
// same node-path hashes underneath it).
|
||||
let nested_network_id = current_node_path.owned_network_id(ctx.peer);
|
||||
convert_network(nested_network, nested_network_id, Some(current_node_path), child_metadata_path, registry, ctx)?;
|
||||
if recurse {
|
||||
convert_network(nested_network, nested_network_id, Some(current_node_path), child_metadata_path, registry, ctx)?;
|
||||
}
|
||||
Implementation::Network(nested_network_id)
|
||||
}
|
||||
// TODO: Support Extract in the Registry format.
|
||||
DocumentNodeImplementation::Extract => return Err(ConversionError::UnsupportedImplementation),
|
||||
})
|
||||
}
|
||||
|
||||
/// Derives the storage IDs for entities addressed by runtime network paths, resolving each through
|
||||
/// the same [`NodeIds`] a whole-document conversion uses so scoped and whole-document conversions agree.
|
||||
pub struct PathResolver<'m> {
|
||||
metadata: Option<&'m dyn NodeMetadataSource>,
|
||||
peer: PeerId,
|
||||
}
|
||||
|
||||
impl<'m> PathResolver<'m> {
|
||||
/// Without a metadata source every node falls back to a hash of its location, which only matches a
|
||||
/// whole-document conversion while no node has a stored identity.
|
||||
pub fn new(metadata: Option<&'m dyn NodeMetadataSource>, peer: PeerId) -> Self {
|
||||
Self { metadata, peer }
|
||||
}
|
||||
|
||||
/// The storage `NetworkId` of the network at `local_path` (`ROOT_NETWORK` for the empty path).
|
||||
pub fn network_id(&self, local_path: &[RuntimeNodeId]) -> NetworkId {
|
||||
match self.owner_path(local_path) {
|
||||
None => ROOT_NETWORK,
|
||||
Some(owner) => owner.owned_network_id(self.peer),
|
||||
}
|
||||
}
|
||||
|
||||
/// The storage `NodeId` of the node with `local_id` inside the network at `local_path`.
|
||||
pub fn node_id(&self, local_path: &[RuntimeNodeId], local_id: RuntimeNodeId) -> NodeId {
|
||||
let owner = self.owner_path(local_path);
|
||||
self.ids(local_path).resolve(&child_path(owner.as_ref(), self.network_id(local_path), local_id), local_id)
|
||||
}
|
||||
|
||||
/// Converts one runtime input inside the network at `local_path` to its storage form, resolving
|
||||
/// node references to their storage IDs.
|
||||
pub fn convert_input_at(&self, input: &GraphCraftNodeInput, local_path: &[RuntimeNodeId]) -> Result<NodeInput, ConversionError> {
|
||||
let owner = self.owner_path(local_path);
|
||||
convert_input(input, owner.as_ref(), self.network_id(local_path), self.ids(local_path))
|
||||
}
|
||||
|
||||
/// The identity resolver for nodes addressed inside the network at `local_path`.
|
||||
fn ids<'a>(&self, local_path: &'a [RuntimeNodeId]) -> NodeIds<'a, dyn NodeMetadataSource + 'm>
|
||||
where
|
||||
'm: 'a,
|
||||
{
|
||||
NodeIds {
|
||||
metadata: self.metadata,
|
||||
metadata_path: local_path,
|
||||
peer: self.peer,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `NodePath` of the node owning the network at `local_path`, or `None` for the root network.
|
||||
fn owner_path(&self, local_path: &[RuntimeNodeId]) -> Option<NodePath> {
|
||||
let mut owner: Option<NodePath> = None;
|
||||
for &local_id in local_path {
|
||||
let network_id = match &owner {
|
||||
None => ROOT_NETWORK,
|
||||
Some(owner) => owner.owned_network_id(self.peer),
|
||||
};
|
||||
owner = Some(child_path(owner.as_ref(), network_id, local_id));
|
||||
}
|
||||
owner
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a chosen subset of runtime entities into a scratch [`Registry`] through the same
|
||||
/// encoders as a whole-document conversion, so staging can derive deltas for just those entities.
|
||||
pub struct ScopedConversion<'m> {
|
||||
ctx: ConversionContext<'m, dyn NodeMetadataSource + 'm>,
|
||||
resolver: PathResolver<'m>,
|
||||
}
|
||||
|
||||
impl<'m> ScopedConversion<'m> {
|
||||
pub fn new(metadata: &'m dyn NodeMetadataSource, peer: PeerId) -> Self {
|
||||
Self {
|
||||
ctx: ConversionContext {
|
||||
declaration_ids: HashMap::new(),
|
||||
declaration_bytes: HashMap::new(),
|
||||
declarations: HashMap::new(),
|
||||
network_ids: HashMap::new(),
|
||||
metadata,
|
||||
peer,
|
||||
},
|
||||
resolver: PathResolver::new(Some(metadata), peer),
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts the node with `local_id` in the network at `local_path` into `registry` under its
|
||||
/// stable IDs. `recurse` also converts the contents of any nested network the node implements;
|
||||
/// without it only the node itself is converted, with its nested network referenced by ID.
|
||||
pub fn convert_node_at(&mut self, registry: &mut Registry, local_path: &[RuntimeNodeId], local_id: RuntimeNodeId, doc_node: &DocumentNode, recurse: bool) -> Result<(), ConversionError> {
|
||||
let owner_path = self.resolver.owner_path(local_path);
|
||||
let location = NodeLocation {
|
||||
network_id: self.resolver.network_id(local_path),
|
||||
parent_path: owner_path.as_ref(),
|
||||
metadata_path: local_path,
|
||||
runtime_node_id: local_id,
|
||||
};
|
||||
|
||||
let mut node = convert_node(doc_node, location, registry, &mut self.ctx, recurse)?;
|
||||
node.attributes.set(node::ORIGINAL_NODE_ID, Value::Int(local_id.0.into()), TimeStamp::ORIGIN);
|
||||
registry.node_instances.insert(self.resolver.node_id(local_path, local_id), node);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Converts the entry of the network at `local_path` (its export slots and network-level
|
||||
/// attributes, not its nodes) into `registry`.
|
||||
pub fn convert_network_entry_at(&mut self, registry: &mut Registry, local_path: &[RuntimeNodeId], node_network: &NodeNetwork) -> Result<(), ConversionError> {
|
||||
let owner_path = self.resolver.owner_path(local_path);
|
||||
let network_id = self.resolver.network_id(local_path);
|
||||
|
||||
let exports = node_network
|
||||
.exports
|
||||
.iter()
|
||||
.map(|export| {
|
||||
Ok(ExportSlot {
|
||||
target: Some(convert_input(export, owner_path.as_ref(), network_id, self.ctx.ids(local_path))?),
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>, ConversionError>>()?;
|
||||
|
||||
let mut attributes = crate::Attributes::new();
|
||||
write_ui_network_attributes(&mut attributes, node_network, local_path, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
|
||||
write_scope_injections(&mut attributes, node_network, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
|
||||
|
||||
registry.networks.insert(
|
||||
network_id,
|
||||
Network {
|
||||
presence: TimeStamp::ORIGIN,
|
||||
exports,
|
||||
attributes,
|
||||
attributes_timestamp: TimeStamp::ORIGIN,
|
||||
},
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The extracted proto-node declarations: the bytes for the caller's byte store, and the same
|
||||
/// declarations decoded for its declaration cache.
|
||||
pub fn finish(self) -> (DeclarationBytes, crate::Declarations) {
|
||||
(self.ctx.declaration_bytes, self.ctx.declarations)
|
||||
}
|
||||
}
|
||||
|
||||
/// The `TaggedValue::Resource` IDs referenced by a stored node's value inputs.
|
||||
///
|
||||
/// Peeks at the externally-tagged serde shape (`{"Resource": <id>}`) rather than deserializing the
|
||||
/// whole `TaggedValue`, which can be arbitrarily large. `resource_ref_shape_matches_serde` asserts
|
||||
/// this stays in lockstep with the real serialization.
|
||||
pub fn node_value_resource_refs(node: &Node) -> impl Iterator<Item = ResourceId> + '_ {
|
||||
node.inputs.iter().filter_map(|slot| value_resource_ref(&slot.input))
|
||||
}
|
||||
|
||||
/// The `TaggedValue::Resource` ID referenced by a stored value input, if any.
|
||||
pub fn value_resource_ref(input: &NodeInput) -> Option<ResourceId> {
|
||||
match input {
|
||||
NodeInput::Value { value: Value::Object(fields), .. } => match fields.as_slice() {
|
||||
[(key, id)] if key == "Resource" => from_value(id).ok(),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod resource_ref_shape {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn resource_ref_shape_matches_serde() {
|
||||
let id = ResourceId::from_hash(&ResourceHash::from(b"shape test".as_slice()));
|
||||
let value = to_value(&TaggedValue::Resource(id)).expect("TaggedValue::Resource serializes");
|
||||
let parsed = value_resource_ref(&NodeInput::Value { value, exposed: false });
|
||||
assert_eq!(parsed, Some(id), "The shape peek in node_value_resource_refs must match TaggedValue's serde form");
|
||||
}
|
||||
}
|
||||
@@ -3,21 +3,26 @@
|
||||
//! [`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. 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.
|
||||
//! consumes. Appending a commit keeps the order; deltas arriving out of it are put back by
|
||||
//! a canonical sort.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use crate::{AttributesWrite, CrdtError, Delta, Rev, TimeStamp};
|
||||
use crate::{AttributesWrite, CrdtError, Delta, RegistryDelta, ResourceHash, Rev, TimeStamp, Value};
|
||||
|
||||
/// 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 {
|
||||
@@ -27,8 +32,9 @@ 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 index = deltas.iter().enumerate().map(|(position, delta)| (delta.id, position)).collect();
|
||||
Self { deltas, index }
|
||||
let mut history = Self::default();
|
||||
deltas.into_iter().for_each(|delta| history.push(delta));
|
||||
history
|
||||
}
|
||||
|
||||
pub fn get(&self, rev: Rev) -> Option<&Delta> {
|
||||
@@ -39,6 +45,11 @@ 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()
|
||||
}
|
||||
@@ -51,10 +62,22 @@ 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);
|
||||
}
|
||||
@@ -64,66 +87,24 @@ impl History {
|
||||
self.deltas.iter()
|
||||
}
|
||||
|
||||
/// 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);
|
||||
/// `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());
|
||||
}
|
||||
}
|
||||
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 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();
|
||||
let mut tips: Vec<Rev> = self.tips.iter().copied().collect();
|
||||
tips.sort_unstable();
|
||||
tips
|
||||
}
|
||||
@@ -142,7 +123,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: serde_json::Value, timestamp: TimeStamp) -> bool {
|
||||
pub fn annotate(&mut self, rev: Rev, key: &str, value: Value, timestamp: TimeStamp) -> bool {
|
||||
match self.index.get(&rev) {
|
||||
Some(&position) => {
|
||||
self.deltas[position].attributes.set(key, value, timestamp);
|
||||
|
||||
@@ -56,6 +56,8 @@ 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.
|
||||
@@ -119,9 +121,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();
|
||||
rmp_serde::to_vec(&("merge", parents)).expect("Merge identity fields must serialize")
|
||||
postcard::to_stdvec(&("merge", parents)).expect("Merge identity fields must serialize")
|
||||
}
|
||||
_ => rmp_serde::to_vec(&(parent, author, timestamp, delta_type)).expect("Delta identity fields must serialize"),
|
||||
_ => postcard::to_stdvec(&(parent, author, timestamp, delta_type)).expect("Delta identity fields must serialize"),
|
||||
};
|
||||
hasher.update(&bytes);
|
||||
let digest = hasher.finalize();
|
||||
|
||||
@@ -7,9 +7,11 @@ 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;
|
||||
@@ -24,12 +26,17 @@ 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::{RuntimeConversion, decode_declaration, encode_declaration};
|
||||
pub use from_runtime::{
|
||||
PathResolver, RuntimeConversion, ScopedConversion, convert_input_attributes, convert_resource_entry, decode_declaration, encode_declaration, encode_input_ui_attributes, encode_node_ui_attributes,
|
||||
node_value_resource_refs, value_resource_ref,
|
||||
};
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position};
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
@@ -37,6 +44,7 @@ pub use to_runtime::Declarations;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
mod bookkeeping;
|
||||
mod crdt;
|
||||
mod round_trip;
|
||||
}
|
||||
@@ -8,11 +8,17 @@ use std::collections::HashMap;
|
||||
|
||||
use core_types::uuid::NodeId as RuntimeNodeId;
|
||||
|
||||
/// One node's editor-side metadata, produced by `Registry::to_runtime_with_metadata`.
|
||||
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)]
|
||||
pub struct NodeMetadataEntry {
|
||||
pub network_path: Vec<RuntimeNodeId>,
|
||||
pub local_id: RuntimeNodeId,
|
||||
/// The node's storage identity. Restoring it pins the node to this identity, so a later conversion
|
||||
/// keeps it instead of re-deriving one from the node's location.
|
||||
pub storage_id: crate::NodeId,
|
||||
pub position: Option<Position>,
|
||||
pub is_layer: bool,
|
||||
pub display_name: Option<String>,
|
||||
@@ -24,19 +30,7 @@ pub struct NodeMetadataEntry {
|
||||
pub output_names: Vec<String>,
|
||||
}
|
||||
|
||||
impl NodeMetadataEntry {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.position.is_none()
|
||||
&& !self.is_layer
|
||||
&& self.display_name.is_none()
|
||||
&& !self.locked
|
||||
&& !self.pinned
|
||||
&& self.output_names.is_empty()
|
||||
&& self.input_metadata.iter().all(InputMetadataEntry::is_empty)
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-network metadata (navigation, previewing). Separate from `NodeMetadataEntry` since these are
|
||||
/// Per-network metadata. Separate from `NodeMetadataEntry` since these are
|
||||
/// properties of a network, not of any node.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct NetworkMetadataEntry {
|
||||
@@ -44,16 +38,12 @@ pub struct NetworkMetadataEntry {
|
||||
/// Empty = root network.
|
||||
pub network_path: Vec<RuntimeNodeId>,
|
||||
/// Stable storage id of this network. Lets the editor associate per-network, per-peer view state
|
||||
/// (node-graph nav + previewing, in `session.json`) with a network across reparenting.
|
||||
/// (the node-graph nav, in `session.json`) with a network across reparenting.
|
||||
pub network_id: crate::NetworkId,
|
||||
/// Matches the runtime's `NodeNetworkPersistentMetadata::reference` — definition lineage tag.
|
||||
/// Matches the runtime's `NodeNetworkPersistentMetadata::reference`: the definition lineage tag.
|
||||
pub reference: Option<String>,
|
||||
}
|
||||
|
||||
impl NetworkMetadataEntry {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.reference.is_none()
|
||||
}
|
||||
/// The display order of the network's pinned nodes.
|
||||
pub pinned_order: Vec<RuntimeNodeId>,
|
||||
}
|
||||
|
||||
/// Per-input editor metadata. Mirrors `InputPersistentMetadata` but wraps strings in `Option` so
|
||||
@@ -64,17 +54,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, serde_json::Value>,
|
||||
}
|
||||
|
||||
impl InputMetadataEntry {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.input_name.is_none() && self.input_description.is_none() && self.widget_override.is_none() && self.input_data.is_empty()
|
||||
}
|
||||
pub input_data: HashMap<String, Value>,
|
||||
}
|
||||
|
||||
/// Editor-side metadata source. Methods default to "no data" so implementors only override what
|
||||
/// they carry. Returns are JSON-shaped where the underlying types live editor-side (PTZ, etc.).
|
||||
/// they carry. Returns are type-erased as [`Value`] where the underlying types live editor-side (PTZ, etc.).
|
||||
pub trait NodeMetadataSource {
|
||||
fn position(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Option<Position> {
|
||||
None
|
||||
@@ -106,13 +90,25 @@ 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, serde_json::Value> {
|
||||
fn input_data(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId, _input_index: usize) -> HashMap<String, Value> {
|
||||
HashMap::new()
|
||||
}
|
||||
|
||||
/// The storage identity this node is pinned to, if it has one. A node the source does not name
|
||||
/// falls back to a hash of its location.
|
||||
fn storage_node_id(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Option<crate::NodeId> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The definition the network was instantiated from, if it still names one.
|
||||
fn reference(&self, _network_path: &[RuntimeNodeId]) -> Option<&str> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The display order of the network's pinned nodes.
|
||||
fn pinned_order(&self, _network_path: &[RuntimeNodeId]) -> Vec<RuntimeNodeId> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// No-op metadata source. Use when there's nothing to attach (synthetic networks, CLI tools).
|
||||
|
||||
@@ -1,12 +1,30 @@
|
||||
use crate::{Attributes, NetworkId, NodeId, ResourceId, TimeStamp, attributes_value_equal};
|
||||
use crate::{Attributes, NetworkId, NodeId, ResourceId, TimeStamp, Value, 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,
|
||||
}
|
||||
|
||||
@@ -43,14 +61,26 @@ 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 {
|
||||
implementation: Implementation::ProtoNode(ResourceId::new()),
|
||||
inputs: vec![],
|
||||
attributes: Attributes::new(),
|
||||
network: crate::ROOT_NETWORK,
|
||||
}
|
||||
Self::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::new()), 0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,6 +91,26 @@ 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)]
|
||||
@@ -70,7 +120,7 @@ pub enum NodeInput {
|
||||
index: u32,
|
||||
},
|
||||
Value {
|
||||
value: serde_json::Value,
|
||||
value: Value,
|
||||
exposed: bool,
|
||||
},
|
||||
Scope(Cow<'static, str>),
|
||||
@@ -92,10 +142,16 @@ 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 {
|
||||
@@ -120,7 +176,7 @@ impl Network {
|
||||
|
||||
/// One positional export slot. `target == None` marks an empty/removed slot. Timestamp drives LWW
|
||||
/// on concurrent `SetExport` ops.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ExportSlot {
|
||||
pub target: Option<NodeInput>,
|
||||
pub timestamp: TimeStamp,
|
||||
@@ -154,6 +210,19 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// `to_runtime` has to read back what `Node::new` writes into an unset slot, so its literal must stay
|
||||
/// in step with how `TaggedValue::None` serializes.
|
||||
#[test]
|
||||
fn unset_input_slot_deserializes_as_tagged_value_none() {
|
||||
let node = Node::new(crate::ROOT_NETWORK, Implementation::Network(crate::ROOT_NETWORK), 1);
|
||||
let NodeInput::Value { value, .. } = &node.inputs()[0].input else {
|
||||
panic!("a fresh slot holds a value input");
|
||||
};
|
||||
|
||||
let tagged: graph_craft::document::value::TaggedValue = 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]
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
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),
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,13 @@
|
||||
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
|
||||
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceEntry, 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>,
|
||||
@@ -9,13 +15,55 @@ pub struct Registry {
|
||||
/// Content-addressable resources (images, fonts, eventually proto-node declarations) referenced
|
||||
/// by `ResourceId`. See [`ResourceStore`].
|
||||
pub resources: ResourceStore,
|
||||
/// 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>,
|
||||
/// 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>,
|
||||
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
|
||||
@@ -85,10 +133,10 @@ impl Registry {
|
||||
}
|
||||
|
||||
pub(crate) fn attributes_value_equal(a: &Attributes, b: &Attributes) -> bool {
|
||||
if a.len() != b.len() {
|
||||
if crate::attributes::live(a).count() != crate::attributes::live(b).count() {
|
||||
return false;
|
||||
}
|
||||
a.iter().all(|(key, value)| b.get(key).is_some_and(|other| value.value == other.value))
|
||||
crate::attributes::live(a).all(|(key, value)| b.get(key).is_some_and(|other| !other.deleted && value.value == other.value))
|
||||
}
|
||||
|
||||
/// Value-level resource comparison: same resolved hashes and same source chains (keyed by
|
||||
@@ -100,8 +148,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.sources.len() == other.sources.len()
|
||||
&& entry.sources.iter().all(|(key, value)| other.source(key).is_some_and(|other_value| value.source == other_value.source))
|
||||
&& 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))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::{PeerId, TimeStamp};
|
||||
use crate::{PeerId, TimeStamp, Value, from_value, to_value};
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
@@ -11,13 +11,28 @@ pub struct SourceKey {
|
||||
pub peer: PeerId,
|
||||
}
|
||||
|
||||
/// One entry in a resource's source chain. The `source` body is type-erased (`serde_json::Value`)
|
||||
/// One entry in a resource's source chain. The `source` body is type-erased (`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: serde_json::Value,
|
||||
pub source: 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
|
||||
@@ -26,8 +41,13 @@ pub struct 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,
|
||||
}
|
||||
@@ -39,12 +59,22 @@ 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 { mut sources, hash, hash_timestamp } = Raw::deserialize(deserializer)?;
|
||||
let Raw {
|
||||
presence,
|
||||
mut sources,
|
||||
sources_timestamp,
|
||||
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.
|
||||
@@ -57,7 +87,13 @@ impl<'de> Deserialize<'de> for ResourceEntry {
|
||||
true
|
||||
});
|
||||
|
||||
Ok(Self { sources, hash, hash_timestamp })
|
||||
Ok(Self {
|
||||
presence,
|
||||
sources,
|
||||
sources_timestamp,
|
||||
hash,
|
||||
hash_timestamp,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,82 +102,107 @@ 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 = serde_json::to_value(graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
|
||||
let embedded = 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 })];
|
||||
let sources = vec![(
|
||||
SourceKey { priority, peer },
|
||||
SourceValue {
|
||||
source: embedded,
|
||||
timestamp,
|
||||
deleted: false,
|
||||
},
|
||||
)];
|
||||
|
||||
Self {
|
||||
presence: timestamp,
|
||||
sources,
|
||||
sources_timestamp: timestamp,
|
||||
hash: Some(hash),
|
||||
hash_timestamp: timestamp,
|
||||
}
|
||||
}
|
||||
|
||||
/// The source body and timestamp stored under `key`, if any.
|
||||
/// The live source stored under `key`, if any; a tombstone is absent.
|
||||
pub fn source(&self, key: &SourceKey) -> Option<&SourceValue> {
|
||||
self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)).ok().map(|index| &self.sources[index].1)
|
||||
self.find(key).ok().map(|index| &self.sources[index].1).filter(|value| !value.deleted)
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
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)),
|
||||
}
|
||||
/// 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))
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
|
||||
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)),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)) {
|
||||
Ok(index) if timestamp > self.sources[index].1.timestamp => {
|
||||
self.sources.remove(index);
|
||||
true
|
||||
/// 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)),
|
||||
_ => {}
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
self.sources_timestamp = self.sources_timestamp.max(other_floor);
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
/// Like [`set_source`](Self::set_source) but assigns unconditionally, for building an entry.
|
||||
pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) {
|
||||
self.put(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.
|
||||
pub fn remove_source(&mut self, key: &SourceKey, timestamp: TimeStamp) -> bool {
|
||||
if timestamp <= self.decided(key) {
|
||||
return 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.sources.iter().any(|(_, value)| {
|
||||
matches!(
|
||||
serde_json::from_value::<graphene_resource::DataSource>(value.source.clone()),
|
||||
Ok(graphene_resource::DataSource::Embedded)
|
||||
)
|
||||
})
|
||||
self.live_sources()
|
||||
.any(|(_, value)| matches!(from_value::<graphene_resource::DataSource>(&value.source), 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.sources.first().map(|(key, _)| key.priority.value()).unwrap_or(0.);
|
||||
let min_priority = self.live_sources().next().map(|(key, _)| key.priority.value()).unwrap_or(0.);
|
||||
SourceKey {
|
||||
priority: Priority::new(min_priority - 1.).expect("finite priority minus one is finite"),
|
||||
peer,
|
||||
@@ -225,15 +286,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. MessagePack (the storage format) can carry a
|
||||
/// than silently producing an unsound map key. Postcard (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 = rmp_serde::to_vec(&3.5_f64).unwrap();
|
||||
assert!(rmp_serde::from_slice::<Priority>(&finite).is_ok());
|
||||
let finite = postcard::to_stdvec(&3.5_f64).unwrap();
|
||||
assert!(postcard::from_bytes::<Priority>(&finite).is_ok());
|
||||
|
||||
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");
|
||||
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");
|
||||
}
|
||||
|
||||
/// `ResourceEntry`'s accessors rely on `sources` being sorted by `SourceKey`. Deserializing an
|
||||
@@ -248,20 +309,23 @@ mod tests {
|
||||
peer: PeerId(1),
|
||||
},
|
||||
SourceValue {
|
||||
source: serde_json::json!(priority),
|
||||
source: Value::Float(priority),
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
deleted: false,
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
// 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,
|
||||
});
|
||||
// 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,
|
||||
};
|
||||
|
||||
let entry: ResourceEntry = serde_json::from_value(unsorted).expect("deserialize");
|
||||
let entry: ResourceEntry = from_value(&to_value(&unsorted).expect("serialize")).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");
|
||||
}
|
||||
@@ -278,20 +342,23 @@ mod tests {
|
||||
(
|
||||
key,
|
||||
SourceValue {
|
||||
source: serde_json::json!(body),
|
||||
source: Value::Str(body.into()),
|
||||
timestamp: TimeStamp { counter, peer: PeerId(1) },
|
||||
deleted: false,
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
let with_duplicates = serde_json::json!({
|
||||
"sources": [entry(5, "newer"), entry(1, "older")],
|
||||
"hash": null,
|
||||
"hash_timestamp": TimeStamp::ORIGIN,
|
||||
});
|
||||
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 resource: ResourceEntry = serde_json::from_value(with_duplicates).expect("deserialize");
|
||||
let resource: ResourceEntry = from_value(&to_value(&with_duplicates).expect("serialize")).expect("deserialize");
|
||||
assert_eq!(resource.sources.len(), 1, "duplicate keys must collapse to one entry");
|
||||
assert_eq!(resource.sources[0].1.source, serde_json::json!("newer"), "the higher-timestamp value must win");
|
||||
assert_eq!(resource.sources[0].1.source, Value::Str("newer".into()), "the higher-timestamp value must win");
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,9 @@
|
||||
use crate::NodeMetadataSource;
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
use crate::from_runtime;
|
||||
use crate::{ApplyMode, Delta, Document, History, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId};
|
||||
use crate::{
|
||||
ApplyMode, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId, Value, to_value,
|
||||
};
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
@@ -27,22 +29,17 @@ impl Session {
|
||||
Self::with_peer(PeerId(core_types::uuid::generate_uuid()))
|
||||
}
|
||||
|
||||
/// Construct a session bound to a specific `PeerId`. Used by tests; production code wants
|
||||
/// `Session::new`.
|
||||
/// 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).
|
||||
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 {
|
||||
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,
|
||||
},
|
||||
document: Document::empty(peer, user),
|
||||
remote_tips: HashMap::new(),
|
||||
}
|
||||
}
|
||||
@@ -51,6 +48,22 @@ 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
|
||||
}
|
||||
@@ -64,8 +77,7 @@ 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
|
||||
/// 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).
|
||||
/// conversion, whose extracted declarations the caller persists and caches.
|
||||
///
|
||||
/// 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`
|
||||
@@ -76,11 +88,11 @@ impl Session {
|
||||
network: &graph_craft::document::NodeNetwork,
|
||||
metadata: &M,
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
) -> Result<(Vec<HotOp>, from_runtime::DeclarationBytes), CommitError> {
|
||||
) -> Result<(Vec<HotOp>, from_runtime::RuntimeConversion), 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.declaration_bytes))
|
||||
Ok((hot_ops, conversion))
|
||||
}
|
||||
|
||||
/// Resolve each runtime `network_path` to its stable [`NetworkId`] for this document's peer, so the
|
||||
@@ -105,7 +117,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 = serde_json::to_value(graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
|
||||
let embedded = to_value(&graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
|
||||
|
||||
let mut ops = Vec::new();
|
||||
for id in ids {
|
||||
@@ -129,31 +141,57 @@ impl Session {
|
||||
Ok(revs)
|
||||
}
|
||||
|
||||
/// Stages ops computed outside the session (an incremental runtime projection) as hot ops, the
|
||||
/// same way `stage_from_runtime` stages a diff's ops.
|
||||
pub fn stage_computed_ops(&mut self, ops: Vec<RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
self.stage_ops(ops)
|
||||
}
|
||||
|
||||
/// Apply each op as a hot op with a freshly-ticked timestamp, returning the staged frames in
|
||||
/// order. Each tick is strictly later than the last, so the final frame carries the latest
|
||||
/// timestamp, which is what the caller passes to `retire`.
|
||||
///
|
||||
/// The peer's first contribution is preceded by a `RegisterPeer` op, so the device's
|
||||
/// `PeerId → UserId` mapping is established (and, under causal delivery, observed by other peers)
|
||||
/// before any of its edits. A no-op batch doesn't register — registration rides a real edit.
|
||||
fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
/// 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.
|
||||
let mut pending: Vec<RegistryDelta> = ops.into_iter().collect();
|
||||
if pending.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
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 });
|
||||
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 });
|
||||
}
|
||||
|
||||
// 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,
|
||||
};
|
||||
self.document.apply_hot_op(hot_op.clone())?;
|
||||
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;
|
||||
staged.push(hot_op);
|
||||
}
|
||||
Ok(staged)
|
||||
@@ -161,19 +199,26 @@ 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*: 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
|
||||
/// 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
|
||||
/// 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 in ops {
|
||||
for (op, authored_at) in ops {
|
||||
// A new edit abandons any undone-forward branch: those revs stay in the DAG but are no
|
||||
// longer reachable via redo. (Mirrors the legacy editor clearing its redo history on
|
||||
// commit.) Done on the first real op so a no-op commit doesn't silently disable redo.
|
||||
@@ -181,10 +226,10 @@ impl Session {
|
||||
self.document.redo_stack.clear();
|
||||
}
|
||||
|
||||
let reverse = self.document.compute_reverse_delta(target, &op)?;
|
||||
let timestamp = self.document.clock.tick();
|
||||
let reverse = crate::prior::capture(self.document.registry_ref(target), &op);
|
||||
let timestamp = authored_at.unwrap_or_else(|| self.document.clock.tick());
|
||||
let parent = self.document.head;
|
||||
let author = self.document.peer;
|
||||
let author = timestamp.peer;
|
||||
|
||||
let delta = Delta::new(parent, author, timestamp, op, reverse);
|
||||
let rev = delta.id;
|
||||
@@ -208,7 +253,7 @@ impl Session {
|
||||
/// Wrap an already-materialized snapshot. Trusts `registry` to match `history`; advances the
|
||||
/// clock past every observed timestamp but does not re-apply ops. `history` is taken in on-disk
|
||||
/// (topological) order.
|
||||
pub fn load(peer: PeerId, registry: Registry, history: Vec<Delta>, head: Option<Rev>, redo_stack: Vec<Rev>, next_node_counter: u64) -> Self {
|
||||
pub fn load(peer: PeerId, user: UserId, 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);
|
||||
@@ -221,13 +266,11 @@ 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(),
|
||||
}
|
||||
@@ -235,8 +278,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, deltas: impl IntoIterator<Item = Delta>, next_node_counter: u64) -> Result<Self, CrdtError> {
|
||||
let mut session = Self::with_peer(peer);
|
||||
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);
|
||||
session.document.next_node_counter = next_node_counter;
|
||||
|
||||
for delta in deltas {
|
||||
@@ -251,9 +294,21 @@ impl Session {
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
/// Apply a hot op without going through the broadcast stream.
|
||||
/// Apply a hot op from another peer. Idempotent, and a no-op for one history already covers: a late
|
||||
/// delivery must not put a retired op back in the hot log.
|
||||
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
|
||||
self.document.apply_hot_op(hot_op)
|
||||
self.document.replay_hot_op(hot_op)
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
|
||||
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
|
||||
@@ -262,57 +317,52 @@ impl Session {
|
||||
self.document.replay_hot_op(hot_op)
|
||||
}
|
||||
|
||||
/// 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);
|
||||
/// 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)?;
|
||||
}
|
||||
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))
|
||||
Ok(scratch.working_registry)
|
||||
}
|
||||
|
||||
/// 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`.
|
||||
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.
|
||||
///
|
||||
/// 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 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;
|
||||
/// 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));
|
||||
|
||||
self.commit_ops(drained.into_iter().map(|hot_op| hot_op.op), true)
|
||||
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.
|
||||
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)
|
||||
}
|
||||
/// 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) {
|
||||
@@ -323,38 +373,36 @@ 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: serde_json::Value) -> bool {
|
||||
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: Value) -> bool {
|
||||
let timestamp = self.document.clock.tick();
|
||||
self.document.history.annotate(rev, key, value, timestamp)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// 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.
|
||||
pub fn can_undo(&self) -> bool {
|
||||
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()
|
||||
self.document.head.is_some_and(|head| self.interaction_start_parent(head, true).is_some())
|
||||
}
|
||||
|
||||
/// 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;
|
||||
/// 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;
|
||||
loop {
|
||||
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);
|
||||
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);
|
||||
}
|
||||
current = parent;
|
||||
}
|
||||
@@ -364,37 +412,22 @@ impl Session {
|
||||
!self.document.redo_stack.is_empty()
|
||||
}
|
||||
|
||||
/// Silent-zone undo of one *interaction*: revert deltas walking `head` back along first-parents until
|
||||
/// it reaches the previous interaction boundary (a delta marked `interaction_end`) or the empty root. One
|
||||
/// interaction spans several deltas (one `commit_from_runtime` batch), so undo reverts the whole run,
|
||||
/// not a single delta — matching the legacy per-interaction undo granularity. The undone interaction's
|
||||
/// `head` rev is pushed onto the redo stack. Reflog semantics: the DAG is never rewritten.
|
||||
/// Silent-zone undo of one interaction: 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.
|
||||
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)?;
|
||||
|
||||
// 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)?;
|
||||
while let Some(rev) = self.document.head.filter(|&rev| rev != base) {
|
||||
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
|
||||
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(_) => {}
|
||||
}
|
||||
self.document.revert_delta(&delta);
|
||||
self.document.head = delta.parent;
|
||||
}
|
||||
|
||||
// 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();
|
||||
// With ops hot, working is the rewound snapshot plus them.
|
||||
if !self.document.hot_log.is_empty() {
|
||||
self.document.rebuild_working();
|
||||
}
|
||||
self.document.redo_stack.push(checkpoint);
|
||||
Ok(checkpoint)
|
||||
}
|
||||
@@ -414,23 +447,28 @@ impl Session {
|
||||
forward.push(delta);
|
||||
}
|
||||
|
||||
// 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`.
|
||||
// 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();
|
||||
for delta in forward.into_iter().rev() {
|
||||
self.document.force_apply_op(delta.kind.clone(), delta.timestamp)?;
|
||||
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.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, registry: Registry) -> Result<Self, CrdtError> {
|
||||
pub fn bootstrap_from_registry(peer: PeerId, user: UserId, registry: Registry) -> Result<Self, CrdtError> {
|
||||
let ops = crate::delta::compute_deltas(&Registry::default(), ®istry);
|
||||
let mut session = Self::with_peer(peer);
|
||||
let mut session = Self::with_identity(peer, user);
|
||||
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();
|
||||
@@ -461,16 +499,42 @@ 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 { entry, .. } => hashes.extend(entry.hash),
|
||||
RegistryDelta::RemoveResource { snapshot, .. } => hashes.extend(snapshot.hash),
|
||||
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);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
hashes
|
||||
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()
|
||||
}
|
||||
|
||||
pub fn hot_log(&self) -> &[HotOp] {
|
||||
@@ -501,7 +565,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 resurrection failure (e.g. `NotFoundInHistory`).
|
||||
/// test can observe a 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(|_| ())
|
||||
@@ -514,6 +578,29 @@ 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`.
|
||||
@@ -539,10 +626,122 @@ 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")]
|
||||
@@ -553,10 +752,6 @@ 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")]
|
||||
@@ -565,9 +760,6 @@ 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 },
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
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
@@ -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};
|
||||
use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry, from_value};
|
||||
|
||||
/// Helper function to verify a NodeNetwork can be compiled successfully.
|
||||
/// Note: This only works for complete networks with all inputs resolved.
|
||||
@@ -20,12 +20,10 @@ 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 bytes in hand and rebuild a
|
||||
/// `Declarations` map for the back-conversion.
|
||||
/// these tests have no byte store, so they keep the extracted `Declarations` in hand 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");
|
||||
let declarations = conversion.declarations().expect("rebuild declarations");
|
||||
(conversion.registry, declarations)
|
||||
(conversion.registry, conversion.declarations)
|
||||
}
|
||||
|
||||
/// A one-node network whose single node references `id` via a `TaggedValue::Resource` input, so
|
||||
@@ -477,7 +475,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().expect("rebuild declarations");
|
||||
let declarations = conversion.declarations;
|
||||
let registry = conversion.registry;
|
||||
|
||||
let (converted, entries) = registry.to_runtime_with_metadata(&declarations).expect("Failed to convert Registry back with metadata");
|
||||
@@ -532,7 +530,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)| serde_json::from_value(v.source.clone()).expect("source body decodes")).collect();
|
||||
let decoded: Vec<DataSource> = entry.sources.iter().map(|(_, v)| from_value(&v.source).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.
|
||||
@@ -611,10 +609,9 @@ fn unreferenced_runtime_resource_is_not_snapshotted() {
|
||||
assert!(!registry.resources.contains_key(&orphan), "the unreferenced (orphan) resource must not be snapshotted");
|
||||
}
|
||||
|
||||
/// A node-input `TaggedValue::F64` must survive the storage round-trip bit-exact. Inputs are stored as a
|
||||
/// 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.
|
||||
/// 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.
|
||||
#[test]
|
||||
fn node_input_f64_round_trips_bit_exact() {
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
@@ -625,7 +622,7 @@ fn node_input_f64_round_trips_bit_exact() {
|
||||
nodes: [(
|
||||
NodeId(0),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::value(TaggedValue::F64(precise), false)],
|
||||
inputs: vec![NodeInput::value(TaggedValue::Number(precise), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -642,8 +639,8 @@ fn node_input_f64_round_trips_bit_exact() {
|
||||
let NodeInput::Value { tagged_value, .. } = input else {
|
||||
panic!("expected a value input, got {input:?}")
|
||||
};
|
||||
let TaggedValue::F64(actual) = &**tagged_value else {
|
||||
panic!("expected F64, got {:?}", tagged_value)
|
||||
let TaggedValue::Number(actual) = &**tagged_value else {
|
||||
panic!("expected Number, got {:?}", tagged_value)
|
||||
};
|
||||
|
||||
assert_eq!(actual.to_bits(), precise.to_bits(), "f64 node input drifted: {actual} != {precise}");
|
||||
@@ -661,7 +658,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, serde_json::json!(7), TimeStamp::ORIGIN);
|
||||
node.attributes.set(crate::attr::node::ORIGINAL_NODE_ID, crate::Value::Int(7), TimeStamp::ORIGIN);
|
||||
}
|
||||
|
||||
let error = registry.to_runtime_with_metadata(&declarations).expect_err("duplicate runtime ID must error");
|
||||
@@ -760,18 +757,28 @@ 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,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -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};
|
||||
use crate::{AttributesRead, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId, Value, from_value};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ConversionError {
|
||||
@@ -38,7 +38,8 @@ pub enum ConversionError {
|
||||
pub type Declarations = std::collections::HashMap<ResourceId, ProtoNode>;
|
||||
|
||||
impl Registry {
|
||||
/// Returns the network plus per-node metadata entries (one per node carrying any `ui::*` attribute).
|
||||
/// Returns the network plus one metadata entry per node, since every node carries an identity to
|
||||
/// restore even when it has no `ui::*` attribute.
|
||||
pub fn to_runtime_with_metadata(&self, declarations: &Declarations) -> Result<(NodeNetwork, Vec<NodeMetadataEntry>), ConversionError> {
|
||||
let (network, node_entries, _) = self.to_runtime_with_full_metadata(declarations)?;
|
||||
Ok((network, node_entries))
|
||||
@@ -50,19 +51,7 @@ impl Registry {
|
||||
let mut node_metadata = Some(Vec::new());
|
||||
let mut network_metadata = Some(Vec::new());
|
||||
|
||||
// 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,
|
||||
};
|
||||
let context = ConversionContext::new(self, declarations);
|
||||
|
||||
// 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`.
|
||||
@@ -74,15 +63,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 `serde_json::Value` form back to
|
||||
/// sorted by key) with bodies decoded from their type-erased `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.sources {
|
||||
let decoded: graphene_resource::DataSource = serde_json::from_value(source.source.clone()).map_err(|error| ConversionError::DeserializationError(error.to_string()))?;
|
||||
for (_, source) in entry.live_sources() {
|
||||
let decoded: graphene_resource::DataSource = from_value(&source.source).map_err(|error| ConversionError::DeserializationError(error.to_string()))?;
|
||||
registry.push_source_back(id, decoded);
|
||||
}
|
||||
if let Some(hash) = entry.hash {
|
||||
@@ -103,6 +92,26 @@ 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 ®istry.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
|
||||
@@ -165,21 +174,19 @@ fn convert_network(
|
||||
node_collector: &mut Option<Vec<NodeMetadataEntry>>,
|
||||
network_collector: &mut Option<Vec<NetworkMetadataEntry>>,
|
||||
) -> Result<NodeNetwork, ConversionError> {
|
||||
let network = context.registry.networks.get(&network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
|
||||
let network = context.registry.network_or_removed(network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
|
||||
|
||||
if let Some(collector) = network_collector.as_mut() {
|
||||
collector.push(extract_network_metadata(&network.attributes, metadata_path, network_id));
|
||||
collector.push(extract_network_metadata(context.registry, &network.attributes, metadata_path, network_id));
|
||||
}
|
||||
|
||||
let mut nodes: FxHashMap<RuntimeNodeId, DocumentNode> = FxHashMap::default();
|
||||
for &(global_id, node) in context.nodes_by_network.get(&network_id).map(Vec::as_slice).unwrap_or_default() {
|
||||
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);
|
||||
let runtime_id = runtime_node_id(global_id, node);
|
||||
let local_id = runtime_id.0;
|
||||
|
||||
if let Some(collector) = node_collector.as_mut()
|
||||
&& let Some(entry) = extract_ui_metadata(node, metadata_path, runtime_id)
|
||||
{
|
||||
collector.push(entry);
|
||||
if let Some(collector) = node_collector.as_mut() {
|
||||
collector.push(extract_ui_metadata(node, global_id, metadata_path, runtime_id));
|
||||
}
|
||||
|
||||
let doc_node = convert_node(context, node, metadata_path, runtime_id, node_collector, network_collector)?;
|
||||
@@ -233,16 +240,15 @@ fn read_scope_injections(registry: &Registry, network_id: NetworkId, attributes:
|
||||
});
|
||||
};
|
||||
|
||||
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)))
|
||||
Ok((key, (runtime_node_id(storage_id, referenced), ty)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Returns `None` when the node has no `ui::*` attributes at all so callers don't end up with
|
||||
/// empty entries for unconverted-from-runtime nodes. `input_metadata` is always sized to match
|
||||
/// `node.inputs.len()` for a strict slot-by-slot rebuild; empty slots use `InputMetadataEntry::default()`.
|
||||
fn extract_ui_metadata(node: &crate::Node, network_path: &[RuntimeNodeId], local_id: RuntimeNodeId) -> Option<NodeMetadataEntry> {
|
||||
/// Emitted for every node, since `storage_id` is worth restoring even where no `ui::*` attribute is.
|
||||
/// `input_metadata` is always sized to match `node.inputs.len()` for a strict slot-by-slot rebuild;
|
||||
/// empty slots use `InputMetadataEntry::default()`.
|
||||
fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[RuntimeNodeId], local_id: RuntimeNodeId) -> NodeMetadataEntry {
|
||||
let position: Option<Position> = node.attributes.get_typed(node::ui::POSITION);
|
||||
let is_layer = node.attributes.get_or(node::ui::IS_LAYER, false);
|
||||
let display_name: Option<String> = node.attributes.get_typed(node::ui::DISPLAY_NAME);
|
||||
@@ -252,9 +258,10 @@ fn extract_ui_metadata(node: &crate::Node, network_path: &[RuntimeNodeId], local
|
||||
|
||||
let input_metadata: Vec<InputMetadataEntry> = node.inputs.iter().map(|slot| &slot.attributes).map(extract_input_metadata).collect();
|
||||
|
||||
let entry = NodeMetadataEntry {
|
||||
NodeMetadataEntry {
|
||||
network_path: network_path.to_vec(),
|
||||
local_id,
|
||||
storage_id,
|
||||
position,
|
||||
is_layer,
|
||||
display_name,
|
||||
@@ -262,22 +269,36 @@ fn extract_ui_metadata(node: &crate::Node, network_path: &[RuntimeNodeId], local
|
||||
pinned,
|
||||
input_metadata,
|
||||
output_names,
|
||||
};
|
||||
(!entry.is_empty()).then_some(entry)
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_network_metadata(attributes: &crate::Attributes, network_path: &[RuntimeNodeId], network_id: NetworkId) -> NetworkMetadataEntry {
|
||||
/// Node references stored here are storage IDs, resolved back to runtime-local IDs the way
|
||||
/// `read_scope_injections` does. A reference to a node that is no longer in this network is dropped
|
||||
/// rather than failing the conversion: a pinned node can have been deleted.
|
||||
fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes, network_path: &[RuntimeNodeId], network_id: NetworkId) -> NetworkMetadataEntry {
|
||||
let to_runtime_id = |storage_id: NodeId| {
|
||||
let node = registry.node_instances.get(&storage_id).filter(|node| node.network == network_id)?;
|
||||
Some(runtime_node_id(storage_id, node))
|
||||
};
|
||||
|
||||
let pinned_order = attributes
|
||||
.get_typed::<Vec<NodeId>>(network::PINNED_ORDER)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter_map(to_runtime_id)
|
||||
.collect();
|
||||
|
||||
NetworkMetadataEntry {
|
||||
network_path: network_path.to_vec(),
|
||||
network_id,
|
||||
reference: attributes.get_typed(node::ui::REFERENCE),
|
||||
pinned_order,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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, serde_json::Value> = attributes
|
||||
.iter()
|
||||
let input_data: HashMap<String, Value> = crate::attributes::live(attributes)
|
||||
.filter_map(|(key, value)| key.strip_prefix(node::input::ui::DATA_PREFIX).map(|sub_key| (sub_key.to_owned(), value.value.clone())))
|
||||
.collect();
|
||||
|
||||
@@ -319,7 +340,9 @@ 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 } => {
|
||||
let referenced = registry.node_instances.get(node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
|
||||
// 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))?;
|
||||
|
||||
// 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.
|
||||
@@ -330,14 +353,13 @@ 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: RuntimeNodeId(local_id),
|
||||
node_id: runtime_node_id(*node_id, referenced),
|
||||
output_index: *output_index as usize,
|
||||
}
|
||||
}
|
||||
NodeInput::Value { value, exposed } => {
|
||||
let tagged_value: TaggedValue = serde_json::from_value(value.clone()).map_err(|e| ConversionError::DeserializationError(format!("TaggedValue: {e:?}")))?;
|
||||
let tagged_value: TaggedValue = from_value(value).map_err(|e| ConversionError::DeserializationError(format!("TaggedValue: {e:?}")))?;
|
||||
GraphCraftNodeInput::Value {
|
||||
tagged_value: MemoHash::new(tagged_value),
|
||||
exposed: *exposed,
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
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]);
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,15 @@ 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"]
|
||||
|
||||
@@ -14,14 +14,14 @@ impl Editor {
|
||||
environment: Environment,
|
||||
uuid_random_seed: u64,
|
||||
resource_storage: Arc<dyn ResourceStorage>,
|
||||
working_copy_root: Option<std::path::PathBuf>,
|
||||
document_store: Arc<dyn document_container::store::DocumentStore>,
|
||||
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, working_copy_root);
|
||||
let mut dispatcher = Dispatcher::new(resource_storage, document_store);
|
||||
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);
|
||||
|
||||
@@ -193,5 +193,9 @@ 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;
|
||||
+10
-11
@@ -89,16 +89,19 @@ 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>, working_copy_root: Option<std::path::PathBuf>) -> Self {
|
||||
pub fn new(resource_storage: Arc<dyn ResourceStorage>, document_store: Arc<dyn document_container::store::DocumentStore>) -> Self {
|
||||
let mut s = Self::default();
|
||||
s.message_handlers.resource_storage_message_handler = ResourceStorageMessageHandler::new(resource_storage);
|
||||
s.message_handlers.portfolio_message_handler.set_working_copy_root(working_copy_root);
|
||||
s.message_handlers.portfolio_message_handler.set_document_store(document_store);
|
||||
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()), None);
|
||||
let mut s = Self::new(
|
||||
Arc::new(graph_craft::application_io::resource::HashMapResourceStorage::new()),
|
||||
Arc::new(document_container::store::MemoryStore::default()),
|
||||
);
|
||||
s.message_handlers.portfolio_message_handler = PortfolioMessageHandler::with_executor(executor);
|
||||
s
|
||||
}
|
||||
@@ -496,15 +499,11 @@ mod test {
|
||||
if let FrontendMessage::UpdateLayout {
|
||||
layout_target: LayoutTarget::DialogColumn1,
|
||||
diff,
|
||||
} = response
|
||||
} = response && let DiffUpdate::Layout(sub_layout) = &diff[0].new_value
|
||||
&& let LayoutGroup::Row(WidgetRow { widgets }) = &sub_layout.0[0]
|
||||
&& let Widget::TextLabel(TextLabel { value, .. }) = &*widgets[0].widget
|
||||
{
|
||||
if let DiffUpdate::Layout(sub_layout) = &diff[0].new_value {
|
||||
if let LayoutGroup::Row(WidgetRow { widgets }) = &sub_layout.0[0] {
|
||||
if let Widget::TextLabel(TextLabel { value, .. }) = &*widgets[0].widget {
|
||||
print_problem_to_terminal_on_failure(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
print_problem_to_terminal_on_failure(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,3 +19,5 @@ 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;
|
||||
@@ -95,7 +95,7 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
||||
.network_interface
|
||||
.node_metadata(&layer.to_node(), &[])
|
||||
.map(|node| node.persistent_metadata.display_name.clone())
|
||||
.and_then(|name| if name.is_empty() { None } else { Some(name) })
|
||||
.filter(|name| !name.is_empty())
|
||||
.unwrap_or_else(|| "Artboard".to_string());
|
||||
(layer, name)
|
||||
})
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
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>,
|
||||
@@ -30,7 +34,26 @@ impl DialogLayoutHolder for CloseAllDocumentsDialog {
|
||||
|
||||
impl LayoutHolder for CloseAllDocumentsDialog {
|
||||
fn layout(&self) -> Layout {
|
||||
let unsaved_list = "• ".to_string() + &self.unsaved_document_names.join("\n• ");
|
||||
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}");
|
||||
}
|
||||
|
||||
Layout(vec![
|
||||
LayoutGroup::row(vec![TextLabel::new("Save documents before closing them?").bold(true).multiline(true).widget_instance()]),
|
||||
|
||||
@@ -118,22 +118,9 @@ 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,7 +1,5 @@
|
||||
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::*;
|
||||
@@ -12,9 +10,6 @@ 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,
|
||||
}
|
||||
|
||||
@@ -465,7 +465,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
];
|
||||
let (mut key_up, mut key_down, mut key_up_no_repeat, mut key_down_no_repeat, mut double_click, mut wheel_scroll, mut pointer_move, mut pointer_shake) = mappings;
|
||||
|
||||
let sort = |list: &mut KeyMappingEntries| list.0.sort_by(|a, b| b.modifiers.count_ones().cmp(&a.modifiers.count_ones()));
|
||||
let sort = |list: &mut KeyMappingEntries| list.0.sort_by_key(|entry| std::cmp::Reverse(entry.modifiers.count_ones()));
|
||||
// Sort the sublists of `key_up`, `key_down`, `key_up_no_repeat`, and `key_down_no_repeat`
|
||||
for list in [&mut key_up, &mut key_down, &mut key_up_no_repeat, &mut key_down_no_repeat] {
|
||||
for sublist in list {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod layout_widget;
|
||||
pub mod tooltip_markdown;
|
||||
pub mod widgets;
|
||||
|
||||
pub mod widget_prelude {
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
//! 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>&</b>"), "<b>&</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,10 +215,6 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
|
||||
List<Gradient>,
|
||||
List<String>,
|
||||
List<f64>,
|
||||
List<f32>,
|
||||
List<u32>,
|
||||
List<u64>,
|
||||
List<i32>,
|
||||
List<i64>,
|
||||
List<bool>,
|
||||
List<DVec2>,
|
||||
@@ -275,10 +271,6 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
|
||||
Item<Gradient>,
|
||||
Item<String>,
|
||||
Item<f64>,
|
||||
Item<f32>,
|
||||
Item<u32>,
|
||||
Item<u64>,
|
||||
Item<i32>,
|
||||
Item<i64>,
|
||||
Item<bool>,
|
||||
Item<DVec2>,
|
||||
@@ -577,7 +569,7 @@ impl TableItemLayout for Coverage {
|
||||
|
||||
impl TableItemLayout for TransferCurve {
|
||||
fn type_name() -> &'static str {
|
||||
"Transfer Curve"
|
||||
"TransferCurve"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
let points = self.points().len();
|
||||
@@ -842,37 +834,12 @@ impl TableItemLayout for Gradient {
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_table_item_layout_for_number {
|
||||
($($ty:ty => $type_name:literal),* $(,)?) => {
|
||||
$(
|
||||
impl TableItemLayout for $ty {
|
||||
fn type_name() -> &'static str {
|
||||
$type_name
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{self}")
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
|
||||
}
|
||||
}
|
||||
)*
|
||||
}
|
||||
}
|
||||
impl_table_item_layout_for_number!(
|
||||
u32 => "Number (u32)",
|
||||
i32 => "Number (i32)",
|
||||
u64 => "Number (u64)",
|
||||
i64 => "Number (i64)",
|
||||
);
|
||||
|
||||
impl TableItemLayout for f32 {
|
||||
impl TableItemLayout for i64 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (f32)"
|
||||
"Integer"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
// Only infinity widens to f64 without gaining digits, so finite values keep the f32 spelling
|
||||
if self.is_infinite() { format_f64(*self as f64) } else { format!("{self}") }
|
||||
format!("{self}")
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
|
||||
@@ -968,26 +935,6 @@ fn string_preview(value: &str) -> String {
|
||||
first_line.chars().take(MAX_CHARACTERS - 1).chain(['…']).collect()
|
||||
}
|
||||
|
||||
impl TableItemLayout for Option<f64> {
|
||||
fn type_name() -> &'static str {
|
||||
"Option<f64>"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
"Option<f64>".to_string()
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
let text = match self {
|
||||
Some(value) => format!("Some({})", format_f64(round_away_float_noise(*value))),
|
||||
None => "None".to_string(),
|
||||
};
|
||||
|
||||
vec![TextLabel::new(text).selectable(true).narrow(true).widget_instance()]
|
||||
}
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(self.value_widgets(PathStep::Element(0), _data))]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for DVec2 {
|
||||
fn type_name() -> &'static str {
|
||||
"Vec2"
|
||||
@@ -1272,13 +1219,8 @@ macro_rules! known_item_types {
|
||||
DVec2,
|
||||
Affine2,
|
||||
Vec2,
|
||||
Option<f64>,
|
||||
f64,
|
||||
f32,
|
||||
u8,
|
||||
u32,
|
||||
u64,
|
||||
i32,
|
||||
i64,
|
||||
bool,
|
||||
String,
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
|
||||
use document_graph_storage::Registry;
|
||||
use document_graph_storage::{Declarations, Registry, Value};
|
||||
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry, ResourceStorage};
|
||||
|
||||
use super::utility_types::network_interface::NodeNetworkInterface;
|
||||
use super::utility_types::network_interface::storage_metadata::{StorageMetadataView, collect_network_view_settings};
|
||||
use super::utility_types::network_interface::editor_delta::{EditorDelta, construct_batch};
|
||||
use super::utility_types::network_interface::storage_metadata::{StorageMetadataView, build_interface_from_storage, collect_network_view_settings};
|
||||
|
||||
/// Per-document undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor that is
|
||||
/// becoming the authoritative history. Owns the dual-stack bookkeeping push/pop/clear and the cursor's stage/retire/move/verify
|
||||
@@ -24,6 +25,25 @@ 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 {
|
||||
@@ -79,9 +99,23 @@ impl DocumentHistory {
|
||||
self.storage.as_mut()
|
||||
}
|
||||
|
||||
/// 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;
|
||||
/// 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();
|
||||
}
|
||||
|
||||
/// Retire the pending staged hot ops into durable Gdd history as one undo unit. Called at each undo-step
|
||||
@@ -94,36 +128,83 @@ impl DocumentHistory {
|
||||
}
|
||||
}
|
||||
|
||||
/// Stage the runtime snapshot into the `Gdd` working copy at each `CommitTransaction`. No-op while
|
||||
/// unmounted. Proto-node declaration bytes go into `byte_store` (the app-global resource cache). The
|
||||
/// staged hot ops are retired by [`retire_storage_interaction`](Self::retire_storage_interaction) at
|
||||
/// undo-step boundaries. `validate` (the `validate_storage_round_trip` preference) gates the per-commit
|
||||
/// round-trip check, off by default for its perf cost.
|
||||
pub fn stage_snapshot(
|
||||
&mut self,
|
||||
interface: &NodeNetworkInterface,
|
||||
registry: &ResourceRegistry,
|
||||
view_settings: BTreeMap<String, serde_json::Value>,
|
||||
legacy_document: &str,
|
||||
byte_store: &dyn ResourceStorage,
|
||||
) {
|
||||
/// 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;
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
|
||||
let network = interface.document_network();
|
||||
let staged = match needs_whole_document_stage {
|
||||
true => Self::stage_whole_document(storage, interface, registry, byte_store),
|
||||
// An autosave with nothing edited since the last commit still persists the view state below.
|
||||
false if deltas.is_empty() => Ok(Declarations::new()),
|
||||
// The batch is drained by the time it reaches here, so a failed staging would leave the working copy
|
||||
// permanently behind. Converting the whole document restages the same edit from whatever the working
|
||||
// copy holds, including a batch that failed partway through.
|
||||
false => Self::stage_recorded(storage, deltas, interface, registry, byte_store).or_else(|error| {
|
||||
log::error!("Staging recorded deltas failed, falling back to a whole document snapshot: {error}");
|
||||
Self::stage_whole_document(storage, interface, registry, byte_store)
|
||||
}),
|
||||
};
|
||||
match staged {
|
||||
Ok(declarations) => {
|
||||
self.declarations.extend(declarations);
|
||||
self.needs_whole_document_stage = false;
|
||||
}
|
||||
Err(error) => {
|
||||
log::error!("Storage snapshot staging failed: {error}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
self.persist_view_state(interface, view_settings);
|
||||
}
|
||||
|
||||
/// Converts the whole document and stages the difference from what the working copy holds.
|
||||
///
|
||||
/// Stages without retiring: a tool drag fires several `CommitTransaction`s but is one legacy undo
|
||||
/// step, so the ops accumulate in the hot log and coalesce at the next undo-step boundary.
|
||||
fn stage_whole_document(storage: &mut document_format::GddV1, interface: &NodeNetworkInterface, registry: &ResourceRegistry, byte_store: &dyn ResourceStorage) -> Result<Declarations, String> {
|
||||
let metadata_view = StorageMetadataView::new(interface);
|
||||
storage
|
||||
.stage_runtime_snapshot(interface.document_network(), &metadata_view, registry, byte_store)
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
/// Stages what the store recorded since the last drain.
|
||||
///
|
||||
/// This and the whole-document conversion produce the same registry for the same edit, which
|
||||
/// `verify_round_trip` checks when the `validate_storage_round_trip` preference is on. They differ in
|
||||
/// what they cost and in what they can miss: a conversion sees every change however it was made,
|
||||
/// while this sees only what went through the store, so a write that bypasses it is not persisted.
|
||||
fn stage_recorded(
|
||||
storage: &mut document_format::GddV1,
|
||||
deltas: &[EditorDelta],
|
||||
interface: &NodeNetworkInterface,
|
||||
registry: &ResourceRegistry,
|
||||
byte_store: &dyn ResourceStorage,
|
||||
) -> Result<Declarations, String> {
|
||||
let peer = storage.session().peer();
|
||||
let metadata_view = StorageMetadataView::new(interface);
|
||||
let constructed = construct_batch(deltas, storage.registry(), registry, &metadata_view, peer).map_err(|error| error.to_string())?;
|
||||
|
||||
storage
|
||||
.stage_constructed_ops(constructed.ops, &constructed.declarations.bytes, byte_store)
|
||||
.map_err(|error| error.to_string())?;
|
||||
Ok(constructed.declarations.decoded)
|
||||
}
|
||||
|
||||
/// The parts of a commit that are not the graph: the per-peer and per-network view settings.
|
||||
fn persist_view_state(&mut self, interface: &NodeNetworkInterface, view_settings: BTreeMap<String, Value>) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
|
||||
let network_view_settings = storage
|
||||
.network_ids(network, &metadata_view)
|
||||
.network_ids(interface.document_network(), &StorageMetadataView::new(interface))
|
||||
.ok()
|
||||
.map(|network_ids| collect_network_view_settings(interface, &network_ids));
|
||||
|
||||
// Stage without retiring: a tool drag fires several `CommitTransaction`s but is one legacy undo
|
||||
// step, so the deltas accumulate as hot ops and coalesce at the next undo-step boundary.
|
||||
if let Err(error) = storage.stage_runtime_snapshot(network, &metadata_view, registry, byte_store) {
|
||||
log::error!("Storage snapshot staging failed: {error}");
|
||||
return;
|
||||
}
|
||||
|
||||
if let Err(error) = storage.set_view_settings(view_settings) {
|
||||
log::error!("Persisting view settings failed: {error}");
|
||||
}
|
||||
@@ -133,40 +214,51 @@ impl DocumentHistory {
|
||||
{
|
||||
log::error!("Persisting per-network view settings failed: {error}");
|
||||
}
|
||||
|
||||
// Dual-write soak: embed the legacy `.graphite` bytes so the new format
|
||||
// can be validated against (and recovered from) the old one on open.
|
||||
if let Err(error) = storage.store_legacy_document(legacy_document.as_bytes()) {
|
||||
log::error!("Embedding legacy document into working copy failed: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the `Gdd` undo/redo cursor along the retired interaction chain, flushing any open interaction
|
||||
/// 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> {
|
||||
/// first, and rebuild the interface from the rewound registry using the declaration cache.
|
||||
pub fn move_cursor(&mut self, undo: bool) -> Result<NodeNetworkInterface, CursorMoveError> {
|
||||
self.retire_storage_interaction();
|
||||
|
||||
let storage = self.storage.as_mut()?;
|
||||
let storage = self.storage.as_mut().ok_or(CursorMoveError::NotMoved)?;
|
||||
|
||||
let moved = if undo {
|
||||
if !storage.can_undo() {
|
||||
return None;
|
||||
return Err(CursorMoveError::NotMoved);
|
||||
}
|
||||
storage.undo().map(|_| ())
|
||||
} else {
|
||||
if !storage.can_redo() {
|
||||
return None;
|
||||
return Err(CursorMoveError::NotMoved);
|
||||
}
|
||||
storage.redo().map(|_| ())
|
||||
};
|
||||
if let Err(error) = moved {
|
||||
log::error!("Storage undo/redo cursor move failed: {error}");
|
||||
return None;
|
||||
return Err(CursorMoveError::NotMoved);
|
||||
}
|
||||
|
||||
Some(storage.clone())
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
||||
// Soak round-trip verification (runtime-gated by `validate_storage_round_trip`)
|
||||
@@ -193,13 +285,7 @@ impl DocumentHistory {
|
||||
}
|
||||
};
|
||||
let target = &conversion.registry;
|
||||
let declarations = match conversion.declarations() {
|
||||
Ok(declarations) => declarations,
|
||||
Err(error) => {
|
||||
log::error!("storage round-trip: declaration rebuild failed: {error}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let declarations = &conversion.declarations;
|
||||
|
||||
let stored = storage.registry();
|
||||
if !stored.value_equal(target) {
|
||||
@@ -213,7 +299,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,6 +32,8 @@ 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;
|
||||
@@ -148,6 +150,10 @@ 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>,
|
||||
@@ -199,6 +205,7 @@ 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,
|
||||
@@ -406,8 +413,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, resource_storage, responses),
|
||||
DocumentMessage::DocumentHistoryForward => self.redo_with_history(document_id, viewport, resource_storage, responses),
|
||||
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::DocumentStructureChanged => {
|
||||
if layers_panel_open {
|
||||
self.network_interface.load_structure();
|
||||
@@ -563,6 +570,7 @@ 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() {
|
||||
@@ -1808,7 +1816,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, name: String, path: Option<std::path::PathBuf>) -> Self {
|
||||
pub fn from_storage(interface: NodeNetworkInterface, storage: document_format::GddV1, declarations: Declarations, name: String, path: Option<std::path::PathBuf>) -> Self {
|
||||
let mut document = Self {
|
||||
network_interface: interface,
|
||||
name,
|
||||
@@ -1821,7 +1829,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(Some(storage));
|
||||
document.history.set_storage(storage, declarations);
|
||||
|
||||
document
|
||||
}
|
||||
@@ -1833,6 +1841,12 @@ impl DocumentMessageHandler {
|
||||
self.network_interface.validate_output_names(node_id, node, &path);
|
||||
}
|
||||
|
||||
// Restoring the parallel-array invariant is how the document arrives, not an edit to it, so what the
|
||||
// fix-ups recorded must not ride along in the first real commit. They still have to reach storage,
|
||||
// so the next commit converts the whole document rather than staging the batch that follows them.
|
||||
self.network_interface.discard_deltas();
|
||||
self.history.require_whole_document_stage();
|
||||
|
||||
self.network_interface.load_structure();
|
||||
}
|
||||
|
||||
@@ -2016,9 +2030,14 @@ impl DocumentMessageHandler {
|
||||
self.history.storage_mut()
|
||||
}
|
||||
|
||||
/// 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);
|
||||
/// 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();
|
||||
}
|
||||
|
||||
/// Retire the pending staged hot ops into durable Gdd history as one undo unit.
|
||||
@@ -2026,15 +2045,36 @@ impl DocumentMessageHandler {
|
||||
self.history.retire_storage_interaction();
|
||||
}
|
||||
|
||||
/// Stages the runtime network into the `Gdd` working copy.
|
||||
pub fn commit_storage_snapshot(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage, validate: bool) {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::DocumentSettings;
|
||||
/// Marks the working copy as needing a whole-document stage on its next commit, for a change to the
|
||||
/// runtime that went unrecorded.
|
||||
pub(crate) fn require_whole_document_stage(&mut self) {
|
||||
self.history.require_whole_document_stage();
|
||||
}
|
||||
|
||||
/// Stages what the store recorded since the last commit into the `Gdd` working copy.
|
||||
///
|
||||
/// The batch boundary: everything the interface recorded since the last one is this commit's batch.
|
||||
/// Draining happens whether or not a working copy is mounted, so the buffer cannot grow across a
|
||||
/// session that never mounts one.
|
||||
pub fn commit_storage_snapshot(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage, validate: bool) {
|
||||
let deltas = self.network_interface.take_deltas();
|
||||
if self.history.storage().is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
let view_settings = DocumentSettings {
|
||||
let view_settings = self.storage_view_settings();
|
||||
self.history.stage_snapshot(&deltas, &self.network_interface, &self.resources.registry, view_settings, 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> {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::DocumentSettings;
|
||||
|
||||
DocumentSettings {
|
||||
document_ptz: &self.document_ptz,
|
||||
render_mode: &self.render_mode,
|
||||
overlays_visibility: &self.overlays_visibility_settings,
|
||||
@@ -2042,24 +2082,15 @@ impl DocumentMessageHandler {
|
||||
snapping_state: &self.snapping_state,
|
||||
collapsed: &self.collapsed,
|
||||
}
|
||||
.to_view_map();
|
||||
|
||||
let legacy_document = self.serialize_document();
|
||||
|
||||
self.history
|
||||
.stage_snapshot(&self.network_interface, &self.resources.registry, view_settings, legacy_document.as_str(), byte_store);
|
||||
|
||||
if validate {
|
||||
self.history.verify_round_trip(&self.network_interface, &self.resources.registry);
|
||||
}
|
||||
.to_view_map()
|
||||
}
|
||||
|
||||
/// Restore `view_settings` map into the document.
|
||||
pub fn apply_stored_document_settings(&mut self, view_settings: &std::collections::BTreeMap<String, serde_json::Value>) {
|
||||
pub fn apply_stored_document_settings(&mut self, view_settings: &std::collections::BTreeMap<String, document_graph_storage::Value>) {
|
||||
use document_graph_storage::attr::session::doc;
|
||||
|
||||
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())
|
||||
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())
|
||||
}
|
||||
|
||||
if let Some(value) = decode(view_settings, doc::PTZ) {
|
||||
@@ -2082,24 +2113,27 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Swap in the interface rebuilt from the `Gdd` cursor. Always overwrites the interface.
|
||||
pub(crate) fn apply_gdd_cursor_rebuild(&mut self, mut rebuilt: NodeNetworkInterface, had_oracle: bool, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
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();
|
||||
@@ -2410,7 +2444,7 @@ impl DocumentMessageHandler {
|
||||
paths
|
||||
}
|
||||
|
||||
pub fn undo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, resource_storage: &ResourceStorageMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
pub fn undo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
let legacy_applied = if let Some(previous_network) = self.undo(viewport, responses) {
|
||||
self.history.push_redo(previous_network);
|
||||
true
|
||||
@@ -2418,7 +2452,7 @@ impl DocumentMessageHandler {
|
||||
false
|
||||
};
|
||||
|
||||
self.drive_storage_undo_redo(document_id, resource_storage, legacy_applied, true, responses);
|
||||
self.drive_storage_undo_redo(document_id, legacy_applied, true, validate, responses);
|
||||
}
|
||||
|
||||
/// Installs a history snapshot as the active network interface, carrying over the current view state and structure load, and returns the replaced interface.
|
||||
@@ -2452,7 +2486,7 @@ impl DocumentMessageHandler {
|
||||
|
||||
Some(previous_network)
|
||||
}
|
||||
pub fn redo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, resource_storage: &ResourceStorageMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
pub fn redo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
let legacy_applied = if let Some(previous_network) = self.redo(viewport, responses) {
|
||||
self.history.push_undo(previous_network);
|
||||
true
|
||||
@@ -2460,7 +2494,7 @@ impl DocumentMessageHandler {
|
||||
false
|
||||
};
|
||||
|
||||
self.drive_storage_undo_redo(document_id, resource_storage, legacy_applied, false, responses);
|
||||
self.drive_storage_undo_redo(document_id, legacy_applied, false, validate, responses);
|
||||
}
|
||||
|
||||
pub fn redo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
|
||||
@@ -2795,9 +2829,9 @@ impl DocumentMessageHandler {
|
||||
self.network_interface.move_node_to_chain_start(&solidify_id, layer, &[], false);
|
||||
|
||||
if has_fill && has_stroke {
|
||||
let (existing_index, new_index) = (0_f64, 1_f64);
|
||||
let (existing_index, new_index) = (0_i64, 1_i64);
|
||||
|
||||
let existing_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(existing_index), false))]);
|
||||
let existing_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Integer(existing_index), false))]);
|
||||
let existing_index_id = NodeId::new();
|
||||
self.network_interface.insert_node(existing_index_id, existing_index_template, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&existing_index_id, layer, &[], false);
|
||||
@@ -2819,7 +2853,7 @@ impl DocumentMessageHandler {
|
||||
self.network_interface.set_display_name(&new_layer_id, original_name, &[]);
|
||||
}
|
||||
|
||||
let new_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(new_index), false))]);
|
||||
let new_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Integer(new_index), false))]);
|
||||
let new_index_id = NodeId::new();
|
||||
self.network_interface.insert_node(new_index_id, new_index_template, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&new_index_id, new_layer, &[], false);
|
||||
@@ -4106,10 +4140,11 @@ mod document_message_handler_tests {
|
||||
async fn get_layer_by_bounds(editor: &mut EditorTestUtils, min_x: f64, min_y: f64) -> Option<LayerNodeIdentifier> {
|
||||
let document = editor.active_document();
|
||||
for layer in document.metadata().all_layers() {
|
||||
if let Some(bbox) = document.metadata().bounding_box_viewport(layer) {
|
||||
if (bbox[0].x - min_x).abs() < 1. && (bbox[0].y - min_y).abs() < 1. {
|
||||
return Some(layer);
|
||||
}
|
||||
if let Some(bbox) = document.metadata().bounding_box_viewport(layer)
|
||||
&& (bbox[0].x - min_x).abs() < 1.
|
||||
&& (bbox[0].y - min_y).abs() < 1.
|
||||
{
|
||||
return Some(layer);
|
||||
}
|
||||
}
|
||||
None
|
||||
@@ -4166,7 +4201,6 @@ mod document_message_handler_tests {
|
||||
// The operation completed without crashing
|
||||
// Verifying application still functions by performing another operation
|
||||
editor.handle_message(DocumentMessage::CreateEmptyFolder).await;
|
||||
assert!(true, "Application didn't crash after folder move operation");
|
||||
}
|
||||
|
||||
// Merging nodes whose output isn't wired downstream produces an encapsulating subnetwork with no exports.
|
||||
|
||||
+4
-4
@@ -287,7 +287,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
// Insert the main chain node (Blend or Morph) depending on whether a blend count is provided, referencing
|
||||
// its control path input by the Blend template's named position or the Morph proto node's parameter symbol
|
||||
let (path_input_connector, layer_alias, path_alias) = if let Some(count) = blend_count {
|
||||
let blend_node_id = modify_inputs.insert_blend_data(layer, count as f64);
|
||||
let blend_node_id = modify_inputs.insert_blend_data(layer, count as i64);
|
||||
(InputConnector::node_at_index(blend_node_id, BLEND_PATH_INPUT_INDEX), "Blend", "Blend Path")
|
||||
} else {
|
||||
let morph_node_id = modify_inputs.insert_morph_data(layer);
|
||||
@@ -881,9 +881,9 @@ fn insert_brush_strokes_chain(network_interface: &mut NodeNetworkInterface, laye
|
||||
let strokes_node = strokes_node_type.node_template_input_override([
|
||||
Some(NodeInput::value(TaggedValue::Strokes(Vec::new()), false)),
|
||||
Some(NodeInput::value(TaggedValue::Color(color), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(diameter), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(hardness), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(flow), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(diameter), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(hardness), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(flow), false)),
|
||||
]);
|
||||
network_interface.insert_node(strokes_node_id, strokes_node, &[]);
|
||||
network_interface.set_input(&InputConnector::node_at_index(layer.to_node(), 1), NodeInput::node(strokes_node_id, 0), &[]);
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn update_transform(network_interface: &mut NodeNetworkInterface, node_id: &
|
||||
);
|
||||
network_interface.set_input(
|
||||
&InputConnector::node(*node_id, graphene_std::transform_nodes::transform::RotationInput),
|
||||
NodeInput::value(TaggedValue::F64(rotation), false),
|
||||
NodeInput::value(TaggedValue::Number(rotation), false),
|
||||
&[],
|
||||
);
|
||||
network_interface.set_input(
|
||||
@@ -70,7 +70,7 @@ pub fn get_current_transform(inputs: &[NodeInput]) -> DAffine2 {
|
||||
} else {
|
||||
DVec2::ZERO
|
||||
};
|
||||
let rotation = if let Some(&TaggedValue::F64(rotation)) = inputs[2].as_value() { rotation } else { 0. };
|
||||
let rotation = if let Some(&TaggedValue::Number(rotation)) = inputs[2].as_value() { rotation } else { 0. };
|
||||
let scale = if let Some(&TaggedValue::DVec2(scale)) = inputs[3].as_value() { scale } else { DVec2::ONE };
|
||||
let skew = if let Some(&TaggedValue::DVec2(skew)) = inputs[4].as_value() { skew } else { DVec2::ZERO };
|
||||
|
||||
|
||||
@@ -94,10 +94,10 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.network_interface.move_node_to_chain_start(&boolean_id, layer, &[], self.import);
|
||||
}
|
||||
|
||||
pub fn insert_blend_data(&mut self, layer: LayerNodeIdentifier, count: f64) -> NodeId {
|
||||
pub fn insert_blend_data(&mut self, layer: LayerNodeIdentifier, count: i64) -> NodeId {
|
||||
let blend = resolve_network_node_type("Blend")
|
||||
.expect("Blend node does not exist")
|
||||
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::F64(count), false))]);
|
||||
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::Integer(count), false))]);
|
||||
|
||||
let blend_id = NodeId::new();
|
||||
self.network_interface.insert_node(blend_id, blend, &[]);
|
||||
@@ -109,7 +109,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
pub fn insert_morph_data(&mut self, layer: LayerNodeIdentifier) -> NodeId {
|
||||
let morph = resolve_proto_node_type(graphene_std::vector::morph::IDENTIFIER)
|
||||
.expect("Morph node does not exist")
|
||||
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::F64(0.5), false))]);
|
||||
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::Number(0.5), false))]);
|
||||
|
||||
let morph_id = NodeId::new();
|
||||
self.network_interface.insert_node(morph_id, morph, &[]);
|
||||
@@ -131,7 +131,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
// Add Auto-Tangents node (between Origins to Polyline and Path), with spread=1 and preserve_existing=false
|
||||
let auto_tangents = resolve_proto_node_type(graphene_std::vector::auto_tangents::IDENTIFIER)
|
||||
.expect("Auto-Tangents node does not exist")
|
||||
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(1.), false)), Some(NodeInput::value(TaggedValue::Bool(false), false))]);
|
||||
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Number(1.), false)), Some(NodeInput::value(TaggedValue::Bool(false), false))]);
|
||||
let auto_tangents_id = NodeId::new();
|
||||
self.network_interface.insert_node(auto_tangents_id, auto_tangents, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&auto_tangents_id, layer, &[], self.import);
|
||||
@@ -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_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);
|
||||
}
|
||||
|
||||
if include_stroke {
|
||||
@@ -175,13 +175,14 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.network_interface.move_node_to_chain_start(&stroke_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")
|
||||
// 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")
|
||||
.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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,14 +194,14 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
Some(NodeInput::value(TaggedValue::None, false)),
|
||||
Some(NodeInput::value(TaggedValue::String(text), false)),
|
||||
Some(NodeInput::value(TaggedValue::Resource(font_resource_id), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.font_size), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.line_height_ratio), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.letter_spacing), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.letter_tilt), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.font_size), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.line_height_ratio), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.letter_spacing), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.letter_tilt), false)),
|
||||
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_width.is_some()), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.max_width.unwrap_or(100.)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.max_width.unwrap_or(100.)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_height.is_some()), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.max_height.unwrap_or(100.)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.max_height.unwrap_or(100.)), false)),
|
||||
Some(NodeInput::value(TaggedValue::TextAlign(typesetting.align), false)),
|
||||
]);
|
||||
let text_to_vector = resolve_proto_node_type(graphene_std::text::text_to_vector::IDENTIFIER)
|
||||
@@ -526,7 +527,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
);
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::OpacityInput),
|
||||
NodeInput::value(TaggedValue::F64(opacity * 100.), false),
|
||||
NodeInput::value(TaggedValue::Number(opacity * 100.), false),
|
||||
false,
|
||||
);
|
||||
}
|
||||
@@ -555,7 +556,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
);
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::FillInput),
|
||||
NodeInput::value(TaggedValue::F64(fill * 100.), false),
|
||||
NodeInput::value(TaggedValue::Number(fill * 100.), false),
|
||||
false,
|
||||
);
|
||||
}
|
||||
@@ -666,7 +667,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_positions::PositionsInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(positions), false), false);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Numbers(positions), false), false);
|
||||
}
|
||||
|
||||
/// The 'Gradient Midpoints' counterpart of [`Self::gradient_positions_set`], likewise update-only.
|
||||
@@ -690,7 +691,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_midpoints::MidpointsInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(midpoints), false), false);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Numbers(midpoints), false), false);
|
||||
}
|
||||
|
||||
/// Update the transform to map the unit gradient ((0,0), (1, 0)) to the geometry's local space.
|
||||
@@ -865,7 +866,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(color.map_or_else(TaggedValue::no_paint, TaggedValue::Color), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::WeightInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.weight), false), true);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.weight), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::AlignInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeAlign(stroke.align), false), false);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::CapInput);
|
||||
@@ -873,11 +874,11 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::JoinInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeJoin(stroke.join), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::MiterLimitInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.join_miter_limit), false), false);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.join_miter_limit), false), false);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashPatternInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::DashPattern(stroke.dash_lengths), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.dash_offset), false), true);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.dash_offset), false), true);
|
||||
}
|
||||
|
||||
/// Update the transform value of the upstream Transform node based a change to its existing value and the given parent transform.
|
||||
|
||||
@@ -3,7 +3,7 @@ mod document_history;
|
||||
mod document_message;
|
||||
mod document_message_handler;
|
||||
#[cfg(test)]
|
||||
mod storage_tests;
|
||||
pub(crate) 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::DocumentHistory;
|
||||
pub(crate) use document_history::{CursorMoveError, 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.angle_to(end_offset);
|
||||
let angle = start_offset.try_angle_to(end_offset).unwrap_or(0.);
|
||||
|
||||
tilt_raw_not_snapped + angle
|
||||
};
|
||||
|
||||
@@ -40,17 +40,30 @@ pub struct NodePropertiesContext<'a> {
|
||||
impl NodePropertiesContext<'_> {
|
||||
pub fn call_widget_override(&mut self, node_id: &NodeId, index: usize) -> Option<Vec<LayoutGroup>> {
|
||||
let input_properties_row = self.network_interface.persistent_input_metadata(node_id, index, self.selection_network_path)?;
|
||||
if let Some(widget_override) = &input_properties_row.widget_override {
|
||||
let Some(widget_override_lambda) = INPUT_OVERRIDES.get(widget_override) else {
|
||||
log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override");
|
||||
|
||||
// The stored override wins, falling back to the definition's own so documents saved before it gained one still
|
||||
// pick it up. Only `Custom` is recovered, since the other kinds also need input data stored at insertion time.
|
||||
let widget_override = input_properties_row.widget_override.clone().or_else(|| {
|
||||
let implementation = self.network_interface.implementation(node_id, self.selection_network_path)?;
|
||||
let DocumentNodeImplementation::ProtoNode(proto_node_identifier) = implementation else {
|
||||
return None;
|
||||
};
|
||||
widget_override_lambda(*node_id, index, self)
|
||||
.map_err(|error| log::error!("Error in widget override lambda: {error}"))
|
||||
.ok()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
|
||||
let metadata = registry::NODE_METADATA.lock().unwrap();
|
||||
let field = metadata.get(proto_node_identifier)?.fields.get(index)?;
|
||||
match field.widget_override {
|
||||
registry::RegistryWidgetOverride::Custom(name) => Some(name.to_string()),
|
||||
_ => None,
|
||||
}
|
||||
})?;
|
||||
|
||||
let Some(widget_override_lambda) = INPUT_OVERRIDES.get(&widget_override) else {
|
||||
log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override");
|
||||
return None;
|
||||
};
|
||||
widget_override_lambda(*node_id, index, self)
|
||||
.map_err(|error| log::error!("Error in widget override lambda: {error}"))
|
||||
.ok()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -348,14 +361,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
// 2: Max (clamp subpath count to at least 1 for empty path case)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::F64(1.), false)],
|
||||
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
// 3: Floor (integer count per subpath)
|
||||
// 3: As Number (the integer count enters the network's decimal math)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(item!(f64), 1)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(item!(i64), 1)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 13)),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -369,14 +382,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
// 5: Subtract (count - 1, open subpath denominator)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::subtract::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::F64(1.), false)],
|
||||
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 14)),
|
||||
..Default::default()
|
||||
},
|
||||
// 6: Read Index (current repetition index)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(context::read_index::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::U32(0), false)],
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -425,7 +438,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
// 13: Multiply (fraction × 0.9999999999 to avoid overflowing to the next subpath)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::F64(0.9999999999), false)],
|
||||
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::Number(0.9999999999), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -459,14 +472,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
// 17: Max (clamp count to at least 1)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::F64(1.), false)],
|
||||
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 13)),
|
||||
..Default::default()
|
||||
},
|
||||
// 18: Max (clamp open-path denominator to at least 1 to avoid division by zero when count = 1)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::F64(1.), false)],
|
||||
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 14)),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -479,7 +492,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(list!(Vector), true),
|
||||
NodeInput::value(TaggedValue::F64(10.), false),
|
||||
NodeInput::value(TaggedValue::Integer(10), false),
|
||||
NodeInput::value(TaggedValue::Bool(Default::default()), false),
|
||||
NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false),
|
||||
NodeInput::type_default(item!(Vector), false),
|
||||
@@ -801,7 +814,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
inputs: vec![
|
||||
NodeInput::import(item!(String), 0),
|
||||
NodeInput::import(item!(String), 1),
|
||||
NodeInput::import(item!(f64), 2),
|
||||
NodeInput::import(item!(i64), 2),
|
||||
NodeInput::import(item!(bool), 3),
|
||||
NodeInput::import(item!(bool), 4),
|
||||
],
|
||||
@@ -811,14 +824,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
},
|
||||
// Node 1: item_at_index at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them)
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::item_at_index::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// Node 2: remove_at_index at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::remove_at_index::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 2)),
|
||||
..Default::default()
|
||||
@@ -833,7 +846,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
inputs: vec![
|
||||
NodeInput::value(TaggedValue::String(String::new()), true),
|
||||
NodeInput::value(TaggedValue::String(String::new()), false),
|
||||
NodeInput::value(TaggedValue::F64(0.), false),
|
||||
NodeInput::value(TaggedValue::Integer(0), false),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
],
|
||||
@@ -927,7 +940,6 @@ fn static_node_properties() -> NodeProperties {
|
||||
map.insert("offset_path_properties".to_string(), Box::new(node_properties::offset_path_properties));
|
||||
map.insert("selective_color_properties".to_string(), Box::new(node_properties::selective_color_properties));
|
||||
map.insert("exposure_properties".to_string(), Box::new(node_properties::exposure_properties));
|
||||
map.insert("math_properties".to_string(), Box::new(node_properties::math_properties));
|
||||
map.insert("format_number_properties".to_string(), Box::new(node_properties::format_number_properties));
|
||||
map.insert("string_capitalization_properties".to_string(), Box::new(node_properties::string_capitalization_properties));
|
||||
map.insert("rectangle_properties".to_string(), Box::new(node_properties::rectangle_properties));
|
||||
@@ -1098,6 +1110,11 @@ fn static_input_properties() -> InputProperties {
|
||||
))])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
// A type-witness input, whose stored value's type selects the node's row: the dropdown lists the types the rows accept there
|
||||
"type_choice".to_string(),
|
||||
Box::new(|node_id, index, context| Ok(vec![node_properties::type_choice_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context))])),
|
||||
);
|
||||
map.insert(
|
||||
"vec2".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
@@ -1351,7 +1368,7 @@ fn static_input_properties() -> InputProperties {
|
||||
let Some(input) = document_node.inputs.get(index) else {
|
||||
return Err("Input not found in transform rotation input override".to_string());
|
||||
};
|
||||
if let Some(&TaggedValue::F64(val)) = input.as_non_exposed_value() {
|
||||
if let Some(&TaggedValue::Number(val)) = input.as_non_exposed_value() {
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(val))
|
||||
@@ -1360,7 +1377,7 @@ fn static_input_properties() -> InputProperties {
|
||||
.range_min(Some(-180.))
|
||||
.range_max(Some(180.))
|
||||
.on_update(node_properties::update_value_at_index(
|
||||
|number_input: &NumberInput| TaggedValue::F64(number_input.value.unwrap()),
|
||||
|number_input: &NumberInput| TaggedValue::Number(number_input.value.unwrap()),
|
||||
node_id,
|
||||
index,
|
||||
))
|
||||
@@ -1448,6 +1465,22 @@ 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| {
|
||||
|
||||
@@ -57,6 +57,8 @@ 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,
|
||||
@@ -410,19 +412,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
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(©_ids, selection_network_path).collect::<Vec<_>>();
|
||||
|
||||
let new_ids = nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect::<HashMap<_, _>>();
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::AddNodes { nodes, new_ids: new_ids.clone() });
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet {
|
||||
nodes: new_ids.values().cloned().collect(),
|
||||
});
|
||||
Self::duplicate_selected_nodes(network_interface, selection_network_path, responses);
|
||||
}
|
||||
NodeGraphMessage::EnterNestedNetwork => {
|
||||
// Do not enter the nested network if the node was dragged
|
||||
@@ -799,6 +790,7 @@ 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(),
|
||||
@@ -1044,6 +1036,7 @@ 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);
|
||||
}
|
||||
|
||||
@@ -1171,13 +1164,17 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
if self.begin_dragging {
|
||||
self.begin_dragging = false;
|
||||
if ipp.keyboard.get(Key::Alt as usize) {
|
||||
responses.add(NodeGraphMessage::DuplicateSelectedNodes);
|
||||
// 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);
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1483,6 +1480,7 @@ 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;
|
||||
@@ -1529,15 +1527,17 @@ 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);
|
||||
|
||||
// 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;
|
||||
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;
|
||||
|
||||
// Undo to the state of the graph before shaking
|
||||
responses.add(DocumentMessage::AbortTransaction);
|
||||
// Undo to the state of the graph before shaking (skip for Alt-drag to avoid removing the duplicates)
|
||||
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,7 +1622,9 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
}
|
||||
}
|
||||
}
|
||||
responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { graph_delta, rubber_band: false });
|
||||
if !self.duplicated_in_drag {
|
||||
responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { graph_delta, rubber_band: false });
|
||||
}
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
@@ -2260,6 +2262,20 @@ 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(©_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 {
|
||||
@@ -2704,7 +2720,7 @@ impl NodeGraphMessageHandler {
|
||||
added_wires
|
||||
}
|
||||
|
||||
fn collect_nodes(&self, network_interface: &mut NodeNetworkInterface, breadcrumb_network_path: &[NodeId]) -> Vec<FrontendNode> {
|
||||
pub(crate) fn collect_nodes(&self, network_interface: &mut NodeNetworkInterface, breadcrumb_network_path: &[NodeId]) -> Vec<FrontendNode> {
|
||||
let Some(network) = network_interface.nested_network(breadcrumb_network_path) else {
|
||||
log::error!("Could not get nested network when collecting nodes");
|
||||
return Vec::new();
|
||||
@@ -2739,15 +2755,14 @@ impl NodeGraphMessageHandler {
|
||||
(false, false)
|
||||
};
|
||||
|
||||
let is_export = network_interface
|
||||
.input_from_connector(&InputConnector::Export(0), breadcrumb_network_path)
|
||||
.is_some_and(|export| export.as_node().is_some_and(|export_node_id| node_id == export_node_id));
|
||||
let is_root_node = network_interface.root_node(breadcrumb_network_path).is_some_and(|root_node| root_node.node_id == node_id);
|
||||
|
||||
let Some(position) = network_interface.position(&node_id, breadcrumb_network_path) else {
|
||||
log::error!("Could not get position for node: {node_id}");
|
||||
continue;
|
||||
};
|
||||
let is_export = network_interface
|
||||
.input_from_connector(&InputConnector::Export(0), breadcrumb_network_path)
|
||||
.is_some_and(|export| export.as_node().is_some_and(|export_node_id| node_id == export_node_id));
|
||||
let is_root_node = network_interface.root_node(breadcrumb_network_path).is_some_and(|root_node| root_node.node_id == node_id);
|
||||
let previewed = is_export && !is_root_node;
|
||||
|
||||
let locked = network_interface.is_locked(&node_id, breadcrumb_network_path);
|
||||
@@ -2930,6 +2945,7 @@ 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,
|
||||
@@ -2961,6 +2977,7 @@ 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,6 +2,7 @@
|
||||
|
||||
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;
|
||||
@@ -24,7 +25,7 @@ use graphene_std::raster::{
|
||||
AdjustmentChannel, BlendMode, CellularDistanceFunction, CellularReturnType, Color, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RedGreenBlueAlpha,
|
||||
RelativeAbsolute, SelectiveColorChoice, TonalRange,
|
||||
};
|
||||
use graphene_std::raster_types::Image;
|
||||
use graphene_std::raster_types::{CPU, GPU, Image, Raster};
|
||||
use graphene_std::text::{Font, TextAlign};
|
||||
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
||||
use graphene_std::transfer_curve::TransferCurve;
|
||||
@@ -38,7 +39,9 @@ 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> {
|
||||
@@ -170,14 +173,19 @@ pub fn start_widgets(parameter_widgets_info: &ParameterWidgetsInfo) -> Vec<Widge
|
||||
widgets
|
||||
}
|
||||
|
||||
/// The numeric bounds and widget mode of a number parameter, sourced from the node's field metadata.
|
||||
/// The presentation of a parameter's widget, sourced from the node's field metadata: numeric bounds, widget modes, and unit of measure.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub(crate) struct NumberOptions {
|
||||
pub(crate) struct ParameterOptions {
|
||||
pub soft_min: Option<f64>,
|
||||
pub soft_max: Option<f64>,
|
||||
pub hard_min: Option<f64>,
|
||||
pub hard_max: Option<f64>,
|
||||
pub slider: bool,
|
||||
pub multiline: bool,
|
||||
pub progression: bool,
|
||||
pub unit: Option<&'static str>,
|
||||
pub display_decimal_places: Option<u32>,
|
||||
pub step: Option<f64>,
|
||||
}
|
||||
|
||||
/// The values a range slider's two ends map to linearly and the one its double-click restores, if known.
|
||||
@@ -206,29 +214,25 @@ fn definition_default_number(parameter_widgets_info: &ParameterWidgetsInfo) -> O
|
||||
let input = resolve_document_node_type(&identifier)?.node_template.inputs.get(parameter_widgets_info.index)?;
|
||||
|
||||
match input.as_value()? {
|
||||
TaggedValue::F64(value) => Some(*value),
|
||||
TaggedValue::F32(value) => Some(*value as f64),
|
||||
TaggedValue::Number(value) => Some(*value),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn property_from_type(
|
||||
node_id: NodeId,
|
||||
index: usize,
|
||||
ty: &Type,
|
||||
number_options: NumberOptions,
|
||||
unit: Option<&str>,
|
||||
display_decimal_places: Option<u32>,
|
||||
step: Option<f64>,
|
||||
context: &mut NodePropertiesContext,
|
||||
) -> Result<Vec<LayoutGroup>, Vec<LayoutGroup>> {
|
||||
let NumberOptions {
|
||||
pub(crate) fn property_from_type(node_id: NodeId, index: usize, ty: &Type, options: ParameterOptions, context: &mut NodePropertiesContext) -> Result<Vec<LayoutGroup>, Vec<LayoutGroup>> {
|
||||
let ParameterOptions {
|
||||
soft_min,
|
||||
soft_max,
|
||||
hard_min,
|
||||
hard_max,
|
||||
slider,
|
||||
} = number_options;
|
||||
multiline,
|
||||
progression,
|
||||
unit,
|
||||
display_decimal_places,
|
||||
step,
|
||||
} = options;
|
||||
|
||||
let mut number_input = NumberInput::default();
|
||||
if slider {
|
||||
number_input = number_input.mode_range();
|
||||
@@ -243,10 +247,8 @@ pub(crate) fn property_from_type(
|
||||
number_input = number_input.step(step);
|
||||
}
|
||||
|
||||
// Applies the parameter's typing clamp and slider extent to the widget, given the type's own default bounds.
|
||||
// Per end: the clamp is the hard bound (or unbounded if only a soft bound is given, since soft is a suggested
|
||||
// extent rather than a limit), and the slider extent is the soft bound, each falling back to the hard bound
|
||||
// and then to the type default when unspecified. An end with any explicit bound ignores the type default.
|
||||
// The hard bound sets the typing clamp, and the soft bound (or the hard one) the slider extent, each falling
|
||||
// back to the passed-in default. A soft bound alone leaves that end unclamped, since soft is only a suggestion.
|
||||
let bounded = |number_input: NumberInput, type_min: f64, type_max: f64| {
|
||||
let clamp_min = hard_min.unwrap_or(if soft_min.is_some() { f64::NEG_INFINITY } else { type_min });
|
||||
let clamp_max = hard_max.unwrap_or(if soft_max.is_some() { f64::INFINITY } else { type_max });
|
||||
@@ -260,12 +262,11 @@ pub(crate) fn property_from_type(
|
||||
.range_max(Some(extent_max).filter(|bound| bound.is_finite()))
|
||||
};
|
||||
|
||||
// A range-mode number clamped at both ends by its own hard bounds, or by a type whose extent is a true limit, becomes a range
|
||||
// slider beside its number input, unless a soft bound lets typing pass the slider. An Angle's type default is no such limit.
|
||||
// A range-mode number hard-clamped at both ends becomes a range slider beside its number input, unless a soft bound lets typing pass it
|
||||
let no_soft_bounds = soft_min.is_none() && soft_max.is_none();
|
||||
let hard_both_ends = hard_min.is_some() && hard_max.is_some();
|
||||
let number_or_slider = |default_info: ParameterWidgetsInfo, number_input: NumberInput, type_limits: bool| -> LayoutGroup {
|
||||
let fixed_extent = number_input.mode == NumberInputMode::Range && no_soft_bounds && (hard_both_ends || type_limits);
|
||||
let number_or_slider = |default_info: ParameterWidgetsInfo, number_input: NumberInput| -> LayoutGroup {
|
||||
let fixed_extent = number_input.mode == NumberInputMode::Range && no_soft_bounds && hard_both_ends;
|
||||
match (number_input.min, number_input.max) {
|
||||
(Some(min), Some(max)) if fixed_extent && min.is_finite() && max.is_finite() && min < max => {
|
||||
let default = definition_default_number(&default_info);
|
||||
@@ -298,112 +299,98 @@ pub(crate) fn property_from_type(
|
||||
let mut extra_widgets = vec![];
|
||||
let widgets = match ty {
|
||||
Type::Concrete(concrete_type) => {
|
||||
match concrete_type.alias.as_ref().map(|x| x.as_ref()) {
|
||||
// Aliased types (ambiguous values)
|
||||
Some("Percentage") | Some("PercentageF32") => number_or_slider(default_info, bounded(number_input.percentage(), 0., 100.), true),
|
||||
Some("SignedPercentage") | Some("SignedPercentageF32") => number_or_slider(default_info, bounded(number_input.percentage(), -100., 100.), true),
|
||||
Some("Angle") | Some("AngleF32") => number_or_slider(default_info, bounded(number_input.mode_range(), -180., 180.).unit(unit.unwrap_or("°")), false),
|
||||
Some("Multiplier") => number_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY).unit(unit.unwrap_or("x"))).into(),
|
||||
Some("PixelLength") => number_widget(default_info, bounded(number_input, 0., f64::INFINITY).unit(unit.unwrap_or(" px"))).into(),
|
||||
Some("Length") => number_widget(default_info, bounded(number_input, 0., f64::INFINITY)).into(),
|
||||
Some("Fraction") => number_or_slider(default_info, bounded(number_input.mode_range(), 0., 1.), true),
|
||||
Some("Progression") => progression_widget(default_info, bounded(number_input, 0., f64::INFINITY)).into(),
|
||||
Some("SignedInteger") => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
|
||||
Some("SeedValue") => number_widget(default_info, bounded(number_input.int(), 0., f64::INFINITY)).into(),
|
||||
Some("PixelSize") => vec2_widget(default_info, "X", "Y", unit.unwrap_or(" px"), None, false),
|
||||
Some("TextArea") => text_area_widget(default_info).into(),
|
||||
use std::any::TypeId;
|
||||
|
||||
// For all other types, use TypeId-based matching
|
||||
_ => {
|
||||
use std::any::TypeId;
|
||||
// The compiler peels a rank-0 `Item` cell to its element before this arm runs, so widgets dispatch on the bare element `T`
|
||||
fn id_is<T: 'static>(id: TypeId) -> bool {
|
||||
id == TypeId::of::<T>()
|
||||
}
|
||||
|
||||
// The compiler peels a rank-0 `Item` cell to its element before this arm runs, so widgets dispatch on the bare element `T`
|
||||
fn id_is<T: 'static>(id: TypeId) -> bool {
|
||||
id == TypeId::of::<T>()
|
||||
}
|
||||
|
||||
match concrete_type.id {
|
||||
// ===============
|
||||
// PRIMITIVE TYPES
|
||||
// ===============
|
||||
Some(x) if id_is::<f64>(x) || id_is::<f32>(x) => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY), false),
|
||||
Some(x) if id_is::<u32>(x) => number_widget(default_info, bounded(number_input.int(), 0., f64::from(u32::MAX))).into(),
|
||||
Some(x) if id_is::<u64>(x) => number_widget(default_info, bounded(number_input.int(), 0., f64::INFINITY)).into(),
|
||||
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
|
||||
Some(x) if id_is::<String>(x) => text_widget(default_info).into(),
|
||||
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", "", None, false),
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
// ============
|
||||
// STRUCT TYPES
|
||||
// ============
|
||||
Some(x) if id_is::<Font>(x) => font_widget(default_info),
|
||||
Some(x) if id_is::<TransferCurve>(x) => transfer_curve_widget(default_info),
|
||||
Some(x) if id_is::<Footprint>(x) => footprint_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Box<VectorModification>>(x) => vector_modification_widget(default_info).into(),
|
||||
Some(x) if id_is::<Image<Color>>(x) => image_data_widget(default_info).into(),
|
||||
Some(x) if id_is::<Resource>(x) => resource_widget(default_info, Vec::new()).into(),
|
||||
// ===============================
|
||||
// MANUALLY IMPLEMENTED ENUM TYPES
|
||||
// ===============================
|
||||
Some(x) if id_is::<ReferencePoint>(x) => reference_point_widget(default_info, false).into(),
|
||||
Some(x) if id_is::<BlendMode>(x) => blend_mode_widget(default_info),
|
||||
// =========================
|
||||
// AUTO-GENERATED ENUM TYPES
|
||||
// =========================
|
||||
Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<GradientInterpolation>(x) => enum_choice::<GradientInterpolation>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RealTimeMode>(x) => enum_choice::<RealTimeMode>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RedGreenBlue>(x) => enum_choice::<RedGreenBlue>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RedGreenBlueAlpha>(x) => enum_choice::<RedGreenBlueAlpha>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<XY>(x) => enum_choice::<XY>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StringCapitalization>(x) => enum_choice::<StringCapitalization>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<TextDenomination>(x) => enum_choice::<TextDenomination>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<NoiseType>(x) => enum_choice::<NoiseType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<FractalType>(x) => enum_choice::<FractalType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<CellularDistanceFunction>(x) => enum_choice::<CellularDistanceFunction>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<CellularReturnType>(x) => enum_choice::<CellularReturnType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<DomainWarpType>(x) => enum_choice::<DomainWarpType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<RelativeAbsolute>(x) => enum_choice::<RelativeAbsolute>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<TonalRange>(x) => enum_choice::<TonalRange>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<AdjustmentChannel>(x) => enum_choice::<AdjustmentChannel>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<HueSaturationRange>(x) => enum_choice::<HueSaturationRange>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<GridType>(x) => enum_choice::<GridType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StrokeCap>(x) => enum_choice::<StrokeCap>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StrokeJoin>(x) => enum_choice::<StrokeJoin>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StrokeAlign>(x) => enum_choice::<StrokeAlign>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<ArcType>(x) => enum_choice::<ArcType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RowsOrColumns>(x) => enum_choice::<RowsOrColumns>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<TextAlign>(x) => enum_choice::<TextAlign>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<MergeByDistanceAlgorithm>(x) => enum_choice::<MergeByDistanceAlgorithm>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<ExtrudeJoiningAlgorithm>(x) => enum_choice::<ExtrudeJoiningAlgorithm>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<PointSpacingType>(x) => enum_choice::<PointSpacingType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<BooleanOperation>(x) => enum_choice::<BooleanOperation>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).property_row(),
|
||||
// =====
|
||||
// OTHER
|
||||
// =====
|
||||
_ => return Err(unsupported_widgets(default_info, concrete_type.to_string())),
|
||||
}
|
||||
}
|
||||
match concrete_type.id {
|
||||
// ===============
|
||||
// PRIMITIVE TYPES
|
||||
// ===============
|
||||
Some(x) if id_is::<f64>(x) => match progression {
|
||||
true => progression_widget(default_info, bounded(number_input, 0., f64::INFINITY)).into(),
|
||||
false => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)),
|
||||
},
|
||||
Some(x) if id_is::<i64>(x) => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
|
||||
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
|
||||
Some(x) if id_is::<String>(x) => match multiline {
|
||||
true => text_area_widget(default_info).into(),
|
||||
false => text_widget(default_info).into(),
|
||||
},
|
||||
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false),
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
// ============
|
||||
// STRUCT TYPES
|
||||
// ============
|
||||
Some(x) if id_is::<Font>(x) => font_widget(default_info),
|
||||
Some(x) if id_is::<TransferCurve>(x) => transfer_curve_widget(default_info),
|
||||
Some(x) if id_is::<Footprint>(x) => footprint_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Box<VectorModification>>(x) => vector_modification_widget(default_info).into(),
|
||||
Some(x) if id_is::<Image<Color>>(x) => image_data_widget(default_info).into(),
|
||||
Some(x) if id_is::<Resource>(x) => resource_widget(default_info, Vec::new()).into(),
|
||||
// ===============================
|
||||
// MANUALLY IMPLEMENTED ENUM TYPES
|
||||
// ===============================
|
||||
Some(x) if id_is::<ReferencePoint>(x) => reference_point_widget(default_info, false).into(),
|
||||
Some(x) if id_is::<BlendMode>(x) => blend_mode_widget(default_info),
|
||||
// =========================
|
||||
// AUTO-GENERATED ENUM TYPES
|
||||
// =========================
|
||||
Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<GradientInterpolation>(x) => enum_choice::<GradientInterpolation>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RealTimeMode>(x) => enum_choice::<RealTimeMode>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RedGreenBlue>(x) => enum_choice::<RedGreenBlue>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RedGreenBlueAlpha>(x) => enum_choice::<RedGreenBlueAlpha>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<XY>(x) => enum_choice::<XY>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StringCapitalization>(x) => enum_choice::<StringCapitalization>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<TextDenomination>(x) => enum_choice::<TextDenomination>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<NoiseType>(x) => enum_choice::<NoiseType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<FractalType>(x) => enum_choice::<FractalType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<CellularDistanceFunction>(x) => enum_choice::<CellularDistanceFunction>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<CellularReturnType>(x) => enum_choice::<CellularReturnType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<DomainWarpType>(x) => enum_choice::<DomainWarpType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<RelativeAbsolute>(x) => enum_choice::<RelativeAbsolute>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<TonalRange>(x) => enum_choice::<TonalRange>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<AdjustmentChannel>(x) => enum_choice::<AdjustmentChannel>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<HueSaturationRange>(x) => enum_choice::<HueSaturationRange>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<GridType>(x) => enum_choice::<GridType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StrokeCap>(x) => enum_choice::<StrokeCap>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StrokeJoin>(x) => enum_choice::<StrokeJoin>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StrokeAlign>(x) => enum_choice::<StrokeAlign>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<ArcType>(x) => enum_choice::<ArcType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RowsOrColumns>(x) => enum_choice::<RowsOrColumns>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<TextAlign>(x) => enum_choice::<TextAlign>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<MergeByDistanceAlgorithm>(x) => enum_choice::<MergeByDistanceAlgorithm>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<ExtrudeJoiningAlgorithm>(x) => enum_choice::<ExtrudeJoiningAlgorithm>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<PointSpacingType>(x) => enum_choice::<PointSpacingType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<BooleanOperation>(x) => enum_choice::<BooleanOperation>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).property_row(),
|
||||
// =====
|
||||
// OTHER
|
||||
// =====
|
||||
_ => return Err(unsupported_widgets(default_info, concrete_type.to_string())),
|
||||
}
|
||||
}
|
||||
Type::Item(element) => return property_from_type(node_id, index, element, number_options, unit, display_decimal_places, step, context),
|
||||
Type::Item(element) => return property_from_type(node_id, index, element, options, context),
|
||||
Type::List(element) => match element.as_ref() {
|
||||
Type::Concrete(element_type) if element_type.name == std::any::type_name::<f64>() => array_of_number_widget(default_info, TextInput::default()).into(),
|
||||
_ => return Err(unsupported_widgets(default_info, ty.to_string())),
|
||||
},
|
||||
Type::Generic(_) => vec![TextLabel::new("Generic Type (Not Supported)").widget_instance()].into(),
|
||||
Type::Fn(_, out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
|
||||
Type::Future(out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
|
||||
Type::Fn(_, out) => return property_from_type(node_id, index, out, options, context),
|
||||
Type::Future(out) => return property_from_type(node_id, index, out, options, context),
|
||||
};
|
||||
|
||||
extra_widgets.push(widgets);
|
||||
@@ -430,6 +417,60 @@ 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(¶meter_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(¶meter_widgets_info);
|
||||
|
||||
@@ -807,7 +848,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.widget_instance(),
|
||||
]);
|
||||
}
|
||||
Some(&TaggedValue::F64(value)) => {
|
||||
Some(&TaggedValue::Number(value)) => {
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(value))
|
||||
@@ -846,14 +887,14 @@ pub fn array_of_number_widget(parameter_widgets_info: ParameterWidgetsInfo, text
|
||||
.filter(|x| !x.is_empty())
|
||||
.map(graphene_std::core_types::misc::parse_f64)
|
||||
.collect::<Option<Vec<_>>>()
|
||||
.map(TaggedValue::F64Array)
|
||||
.map(TaggedValue::Numbers)
|
||||
};
|
||||
|
||||
let Some(input) = parameter_widgets_info.input() else {
|
||||
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||
return vec![];
|
||||
};
|
||||
if let Some(TaggedValue::F64Array(values)) = &input.as_non_exposed_value() {
|
||||
if let Some(TaggedValue::Numbers(values)) = &input.as_non_exposed_value() {
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
text_input
|
||||
@@ -1008,7 +1049,7 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
|
||||
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||
return vec![];
|
||||
};
|
||||
if let Some(&TaggedValue::F64(x)) = input.as_non_exposed_value() {
|
||||
if let Some(&TaggedValue::Number(x)) = input.as_non_exposed_value() {
|
||||
let whole_part = x.trunc();
|
||||
let fractional_part = x.fract();
|
||||
|
||||
@@ -1021,7 +1062,7 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
|
||||
.min(0.)
|
||||
.max(0.99999)
|
||||
.value(Some(fractional_part))
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::F64(whole_part + input.value.unwrap())))
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::Number(whole_part + input.value.unwrap())))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
@@ -1033,7 +1074,7 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
|
||||
.min(0.)
|
||||
.is_integer(true)
|
||||
.value(Some(whole_part))
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::F64(input.value.unwrap() + fractional_part)))
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::Number(input.value.unwrap() + fractional_part)))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
])
|
||||
@@ -1120,35 +1161,19 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
|
||||
return vec![];
|
||||
};
|
||||
match input.as_non_exposed_value() {
|
||||
Some(&TaggedValue::F64(x)) => widgets.extend_from_slice(&[
|
||||
Some(&TaggedValue::Number(x)) => widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
number_props
|
||||
.value(Some(x))
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::F64(x.value.unwrap())))
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::Number(x.value.unwrap())))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]),
|
||||
Some(&TaggedValue::F32(x)) => widgets.extend_from_slice(&[
|
||||
Some(&TaggedValue::Integer(x)) => widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
number_props
|
||||
.value(Some(x as f64))
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::F32(x.value.unwrap() as f32)))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]),
|
||||
Some(&TaggedValue::U32(x)) => widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
number_props
|
||||
.value(Some(x as f64))
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::U32((x.value.unwrap()) as u32)))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]),
|
||||
Some(&TaggedValue::U64(x)) => widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
number_props
|
||||
.value(Some(x as f64))
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::U64((x.value.unwrap()) as u64)))
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::Integer(x.value.unwrap().round() as i64)))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]),
|
||||
@@ -1157,7 +1182,7 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
|
||||
number_props
|
||||
// We use an arbitrary `y` instead of an arbitrary `x` here because the "Grid" node's "Spacing" value's height should be used from rectangular mode when transferred to "Y Spacing" in isometric mode
|
||||
.value(Some(dvec2.y))
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::F64(x.value.unwrap())))
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::Number(x.value.unwrap())))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]),
|
||||
@@ -1201,6 +1226,96 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
|
||||
LayoutGroup::row(widgets).with_tooltip_description("Formula used for blending.")
|
||||
}
|
||||
|
||||
/// A dropdown choosing among the types this input takes across the node's registered rows. The input is a type witness:
|
||||
/// its stored value's type, not the value itself, selects the row, which is how a node offers a choice of output type.
|
||||
pub fn type_choice_widget(parameter_widgets_info: ParameterWidgetsInfo) -> LayoutGroup {
|
||||
let mut widgets = start_widgets(¶meter_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(¶meter_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(¤t.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(¶meter_widgets_info);
|
||||
|
||||
@@ -1719,7 +1834,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodePropertiesCont
|
||||
let exposed = input.is_some_and(|input| input.is_exposed());
|
||||
let value = input
|
||||
.and_then(|input| input.as_value())
|
||||
.and_then(|tagged| if let TaggedValue::F32(value) = tagged { Some(*value as f64) } else { None })
|
||||
.and_then(|tagged| if let TaggedValue::Number(value) = tagged { Some(*value) } else { None })
|
||||
.unwrap_or(0.);
|
||||
(exposed, value)
|
||||
})
|
||||
@@ -1842,7 +1957,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodePropertiesCont
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index,
|
||||
value: TaggedValue::F32(scale.value(scale_position) as f32).into(),
|
||||
value: TaggedValue::Number(scale.value(scale_position)).into(),
|
||||
}
|
||||
.into()
|
||||
}
|
||||
@@ -1878,11 +1993,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodePropertiesCont
|
||||
.value(Some(current))
|
||||
.min_width(60)
|
||||
.max_width(60)
|
||||
.on_update(update_value_at_index(
|
||||
move |widget: &NumberInput| TaggedValue::F32(widget.value.unwrap_or(0.) as f32),
|
||||
node_id,
|
||||
input_index,
|
||||
))
|
||||
.on_update(update_value_at_index(move |widget: &NumberInput| TaggedValue::Number(widget.value.unwrap_or(0.)), node_id, input_index))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
);
|
||||
@@ -1906,8 +2017,8 @@ pub(crate) fn hue_saturation_properties(node_id: NodeId, context: &mut NodePrope
|
||||
Some(TaggedValue::HueSaturationRange(range)) => *range,
|
||||
_ => HueSaturationRange::Master,
|
||||
};
|
||||
let f32_value = |parameter: &ParameterRef| match document_node.inputs.get(parameter.input_index).and_then(|input| input.as_value()) {
|
||||
Some(TaggedValue::F32(value)) => *value,
|
||||
let slider_value = |parameter: &ParameterRef| match document_node.inputs.get(parameter.input_index).and_then(|input| input.as_value()) {
|
||||
Some(TaggedValue::Number(value)) => *value as f32,
|
||||
_ => 0.,
|
||||
};
|
||||
|
||||
@@ -1975,9 +2086,9 @@ pub(crate) fn hue_saturation_properties(node_id: NodeId, context: &mut NodePrope
|
||||
Gradient::from((0..=stops).map(stop).collect::<Vec<_>>())
|
||||
};
|
||||
let saturation_track = if colorize_value {
|
||||
toward_hue(f32_value(&hue) / 360.)
|
||||
toward_hue(slider_value(&hue) / 360.)
|
||||
} else if let Some([_, range_start, range_end, _]) = &range_values {
|
||||
let (start, end) = (f32_value(range_start), f32_value(range_end));
|
||||
let (start, end) = (slider_value(range_start), slider_value(range_end));
|
||||
let center = start + (end - start).rem_euclid(360.) / 2.;
|
||||
toward_hue(center / 360.)
|
||||
} else {
|
||||
@@ -2121,8 +2232,7 @@ fn slider_row(
|
||||
};
|
||||
// An exposed input shows only its label and source
|
||||
let (current, tagged_value): (f64, fn(f64) -> TaggedValue) = match input.as_non_exposed_value() {
|
||||
Some(&TaggedValue::F64(value)) => (value, TaggedValue::F64),
|
||||
Some(&TaggedValue::F32(value)) => (value as f64, |value| TaggedValue::F32(value as f32)),
|
||||
Some(&TaggedValue::Number(value)) => (value, TaggedValue::Number),
|
||||
_ => return widgets,
|
||||
};
|
||||
let ParameterWidgetsInfo { node_id, index, .. } = parameter_widgets_info;
|
||||
@@ -2184,7 +2294,7 @@ fn gradient_slider_row(
|
||||
.ok()
|
||||
.and_then(|document_node| document_node.inputs.get(input_index))
|
||||
.and_then(|input| input.as_non_exposed_value())
|
||||
.and_then(|tagged| if let TaggedValue::F32(value) = tagged { Some(*value as f64) } else { None });
|
||||
.and_then(|tagged| if let TaggedValue::Number(value) = tagged { Some(*value) } else { None });
|
||||
|
||||
// Only add the slider and number widgets when the input is not exposed
|
||||
if let Some(current) = current {
|
||||
@@ -2193,7 +2303,7 @@ fn gradient_slider_row(
|
||||
max: value_max,
|
||||
default: Some(default_value),
|
||||
};
|
||||
let value_at = move |position| TaggedValue::F32(slider.value(position) as f32);
|
||||
let value_at = move |position| TaggedValue::Number(slider.value(position));
|
||||
|
||||
row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
row.push(
|
||||
@@ -2216,11 +2326,7 @@ fn gradient_slider_row(
|
||||
.min_width(60)
|
||||
.max_width(60)
|
||||
.display_decimal_places(0)
|
||||
.on_update(update_value_at_index(
|
||||
move |widget: &NumberInput| TaggedValue::F32(widget.value.unwrap_or(0.) as f32),
|
||||
node_id,
|
||||
input_index,
|
||||
))
|
||||
.on_update(update_value_at_index(move |widget: &NumberInput| TaggedValue::Number(widget.value.unwrap_or(0.)), node_id, input_index))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
);
|
||||
@@ -2642,7 +2748,7 @@ pub(crate) fn format_number_properties(node_id: NodeId, context: &mut NodeProper
|
||||
let (no_decimals, decimal_sep_value, use_thousands, thousands_sep_value) = match get_document_node(node_id, context) {
|
||||
Ok(document_node) => {
|
||||
let decimal_places = match document_node.input(DecimalPlacesInput).and_then(|input| input.as_value()) {
|
||||
Some(&TaggedValue::U32(x)) => x,
|
||||
Some(&TaggedValue::Integer(x)) => x,
|
||||
_ => 2,
|
||||
};
|
||||
let decimal_sep = match document_node.input(DecimalSeparatorInput).and_then(|input| input.as_non_exposed_value()) {
|
||||
@@ -2966,10 +3072,7 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let mut number_options = NumberOptions::default();
|
||||
let mut display_decimal_places = None;
|
||||
let mut step = None;
|
||||
let mut unit_suffix = None;
|
||||
let mut options = ParameterOptions::default();
|
||||
let input_type = match implementation {
|
||||
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => 'early_return: {
|
||||
// Clone to end the `network_interface` borrow held via `implementation`, freeing the mutable borrow `input_type` needs below
|
||||
@@ -2982,16 +3085,18 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
|
||||
.get(&proto_node_identifier)
|
||||
.and_then(|metadata| metadata.fields.get(input_index))
|
||||
{
|
||||
number_options = NumberOptions {
|
||||
options = ParameterOptions {
|
||||
soft_min: field.number_soft_min,
|
||||
soft_max: field.number_soft_max,
|
||||
hard_min: field.number_hard_min,
|
||||
hard_max: field.number_hard_max,
|
||||
slider: field.number_mode_range,
|
||||
multiline: field.multiline,
|
||||
progression: field.progression,
|
||||
unit: field.unit,
|
||||
display_decimal_places: field.number_display_decimal_places,
|
||||
step: field.number_step,
|
||||
};
|
||||
display_decimal_places = field.number_display_decimal_places;
|
||||
unit_suffix = field.unit;
|
||||
step = field.number_step;
|
||||
default_type = field.default_type.clone();
|
||||
}
|
||||
|
||||
@@ -3019,7 +3124,7 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
|
||||
.unwrap_or(concrete!(())),
|
||||
};
|
||||
|
||||
property_from_type(node_id, input_index, &input_type, number_options, unit_suffix, display_decimal_places, step, context).unwrap_or_else(|value| value)
|
||||
property_from_type(node_id, input_index, &input_type, options, context).unwrap_or_else(|value| value)
|
||||
});
|
||||
|
||||
layout.extend(row);
|
||||
@@ -3404,63 +3509,6 @@ pub fn offset_path_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
vec![LayoutGroup::row(distance), join, LayoutGroup::row(miter_limit)]
|
||||
}
|
||||
|
||||
pub fn math_properties(node_id: NodeId, context: &mut NodePropertiesContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::math_nodes::math::*;
|
||||
|
||||
let expression = (|| {
|
||||
let mut widgets = start_widgets(&ParameterWidgetsInfo::new(node_id, ExpressionInput, true, context));
|
||||
|
||||
let document_node = match get_document_node(node_id, context) {
|
||||
Ok(document_node) => document_node,
|
||||
Err(err) => {
|
||||
log::error!("Could not get document node in offset_path_properties: {err}");
|
||||
return Vec::new();
|
||||
}
|
||||
};
|
||||
let Some(input) = document_node.input(ExpressionInput) else {
|
||||
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||
return vec![];
|
||||
};
|
||||
if let Some(TaggedValue::String(x)) = &input.as_non_exposed_value() {
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextInput::new(x.clone())
|
||||
.centered(true)
|
||||
.on_update(update_value(
|
||||
|x: &TextInput| {
|
||||
TaggedValue::String({
|
||||
let mut expression = x.value.trim().to_string();
|
||||
|
||||
if ["+", "-", "*", "/", "^"].iter().any(|&infix| infix == expression) {
|
||||
expression = format!("A {expression} B");
|
||||
} else if expression == "^" {
|
||||
expression = String::from("A^B");
|
||||
} else if expression == "%" || expression == "mod" {
|
||||
expression = String::from("mod(a, b)");
|
||||
}
|
||||
|
||||
expression
|
||||
})
|
||||
},
|
||||
node_id,
|
||||
ExpressionInput,
|
||||
))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
])
|
||||
}
|
||||
widgets
|
||||
})();
|
||||
let operand_b = number_widget(ParameterWidgetsInfo::new(node_id, OperandBInput, true, context), NumberInput::default());
|
||||
let operand_a_hint = vec![TextLabel::new("(Operand A is the primary input)").widget_instance()];
|
||||
|
||||
vec![
|
||||
LayoutGroup::row(expression).with_tooltip_description(r#"A math expression that may incorporate "A" and/or "B", such as "sqrt(A + B) - B^2"."#),
|
||||
LayoutGroup::row(operand_b).with_tooltip_description(r#"The value of "B" when calculating the expression."#),
|
||||
LayoutGroup::row(operand_a_hint).with_tooltip_description(r#""A" is fed by the value from the previous node in the primary data flow, or it is 0 if disconnected."#),
|
||||
]
|
||||
}
|
||||
|
||||
pub struct ParameterWidgetsInfo<'a> {
|
||||
document_id: DocumentId,
|
||||
network_interface: &'a NodeNetworkInterface,
|
||||
@@ -3699,3 +3747,53 @@ 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" | "f32" | "u32" | "u64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
|
||||
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
|
||||
raster if raster.starts_with("Raster") => Self::Raster,
|
||||
_ => Self::General,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
//! 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());
|
||||
}
|
||||
@@ -4,9 +4,9 @@
|
||||
//! metadata survives the conversion. The end-to-end save/reopen pipeline is covered separately in
|
||||
//! [`round_trip_tests`](super::round_trip_tests).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
|
||||
use document_graph_storage::{NodeMetadataSource, PeerId, Registry};
|
||||
use document_graph_storage::{NodeMetadataSource, PeerId, Registry, to_value};
|
||||
|
||||
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().expect("rebuild declarations");
|
||||
let declarations = conversion.declarations;
|
||||
let registry = conversion.registry;
|
||||
|
||||
let (_converted_network, entries) = registry.to_runtime_with_metadata(&declarations).expect("to_runtime_with_metadata failed");
|
||||
@@ -57,22 +57,6 @@ fn editor_metadata_round_trip_against_demo() {
|
||||
|| !source.input_data(&network_path, local_id, i).is_empty()
|
||||
});
|
||||
|
||||
let any_metadata = expected_position.is_some()
|
||||
|| expected_is_layer
|
||||
|| expected_display.as_deref().is_some_and(|s| !s.is_empty())
|
||||
|| expected_locked
|
||||
|| expected_pinned
|
||||
|| any_input_metadata_present
|
||||
|| !expected_output_names.is_empty();
|
||||
|
||||
if !any_metadata {
|
||||
assert!(
|
||||
!entries_by_address.contains_key(&(network_path.clone(), local_id)),
|
||||
"node {local_id:?} in network {network_path:?} has no editor metadata but produced an entry"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
let entry = entries_by_address
|
||||
.get(&(network_path.clone(), local_id))
|
||||
.unwrap_or_else(|| panic!("missing entry for node {local_id:?} in network {network_path:?}"));
|
||||
@@ -153,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().expect("rebuild declarations");
|
||||
let declarations = conversion.declarations;
|
||||
let registry = conversion.registry;
|
||||
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime_with_full_metadata failed");
|
||||
|
||||
@@ -262,6 +246,76 @@ fn editor_interface_rebuild_round_trip() {
|
||||
assert!(checked_any_reference, "demo artwork produced no reference metadata: fixture is wrong or extraction is broken");
|
||||
}
|
||||
|
||||
/// The rebuild pins every node to the identity storage named it, rather than leaving it to be
|
||||
/// re-derived. Re-converting under a different peer is the sharp test: a location hash mixes the peer
|
||||
/// in, so it would produce an entirely different set of IDs.
|
||||
#[test]
|
||||
fn rebuilt_interface_keeps_storage_identities() {
|
||||
let document = load_demo("changing-seasons.graphite");
|
||||
let view = StorageMetadataView::new(&document.network_interface);
|
||||
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let conversion = Registry::convert_from_runtime(&network, &view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
|
||||
let declarations = conversion.declarations;
|
||||
let registry = conversion.registry;
|
||||
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime_with_full_metadata failed");
|
||||
|
||||
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage failed");
|
||||
|
||||
let reconverted_network = rebuilt.document_network().clone();
|
||||
let reconverted = Registry::convert_from_runtime(&reconverted_network, &StorageMetadataView::new(&rebuilt), &Default::default(), PeerId(9)).expect("re-convert from_runtime failed");
|
||||
|
||||
let stored_ids: BTreeSet<_> = registry.node_instances.keys().copied().collect();
|
||||
let reconverted_ids: BTreeSet<_> = reconverted.registry.node_instances.keys().copied().collect();
|
||||
|
||||
assert!(!stored_ids.is_empty(), "demo artwork produced no nodes: fixture is wrong");
|
||||
assert_eq!(reconverted_ids, stored_ids, "re-converting the rebuilt interface under a different peer changed the node identities");
|
||||
}
|
||||
|
||||
/// Migrating an opened document must leave the recorded-delta buffer empty.
|
||||
#[test]
|
||||
fn migrating_a_document_records_no_changes() {
|
||||
let mut document = load_demo("painted-dreams.graphite");
|
||||
document.network_interface.discard_deltas();
|
||||
|
||||
crate::messages::portfolio::document_migration::document_migration_upgrades(&mut document, false);
|
||||
|
||||
let recorded = document.network_interface.take_deltas();
|
||||
assert!(recorded.is_empty(), "migration left {} recorded changes behind", recorded.len());
|
||||
}
|
||||
|
||||
/// The pinned display order is document state, so it survives a registry round trip. It names nodes and
|
||||
/// the stored form uses storage IDs, so this also checks the references resolve back to the right
|
||||
/// runtime nodes.
|
||||
#[test]
|
||||
fn pinned_order_round_trips_through_the_registry() {
|
||||
let mut document = load_demo("changing-seasons.graphite");
|
||||
|
||||
let pinned: Vec<_> = document.network_interface.document_network().nodes.keys().copied().take(3).collect();
|
||||
assert_eq!(pinned.len(), 3, "demo artwork should have at least three nodes: fixture is wrong");
|
||||
|
||||
{
|
||||
let interface = &mut document.network_interface;
|
||||
let Some(mut network) = interface.network_mut(&[]) else {
|
||||
panic!("the document network should resolve")
|
||||
};
|
||||
network.set_pinned_order(pinned.clone());
|
||||
}
|
||||
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let view = StorageMetadataView::new(&document.network_interface);
|
||||
let conversion = Registry::convert_from_runtime(&network, &view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
|
||||
let declarations = conversion.declarations;
|
||||
let (rebuilt_network, node_entries, network_entries) = conversion.registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime failed");
|
||||
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage failed");
|
||||
|
||||
let rebuilt_metadata = rebuilt.network_metadata(&[]).expect("the rebuilt document network should resolve");
|
||||
assert_eq!(
|
||||
rebuilt_metadata.persistent_metadata.pinned_node_order, pinned,
|
||||
"the pinned display order did not survive the registry round trip"
|
||||
);
|
||||
}
|
||||
|
||||
/// Per-peer view settings (`ui::doc::*`) survive the `session.json` round-trip: serialize them into
|
||||
/// the view map, then apply it onto a fresh handler and confirm each field matches.
|
||||
#[test]
|
||||
@@ -288,26 +342,14 @@ fn document_settings_round_trip() {
|
||||
let mut restored = DocumentMessageHandler::default();
|
||||
restored.apply_stored_document_settings(&view_settings);
|
||||
|
||||
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.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.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(),
|
||||
to_value(&restored.overlays_visibility_settings).unwrap(),
|
||||
to_value(&document.overlays_visibility_settings).unwrap(),
|
||||
"overlays"
|
||||
);
|
||||
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");
|
||||
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");
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
//!
|
||||
//! Shared fixtures live in [`test_support`].
|
||||
|
||||
mod lifecycle_tests;
|
||||
mod metadata_tests;
|
||||
mod round_trip_tests;
|
||||
mod test_support;
|
||||
pub(crate) 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,
|
||||
//! MessagePack codecs, hot-op retirement, file layout, replay-on-open) that the debug-only
|
||||
//! postcard 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};
|
||||
use document_graph_storage::{NodeMetadataSource, PeerId, to_value};
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
|
||||
use super::test_support::{RoundTrip, node_paths, round_trip_through_gdd};
|
||||
@@ -158,9 +158,7 @@ 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())
|
||||
.await
|
||||
.expect("create_in");
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).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)
|
||||
@@ -176,7 +174,7 @@ async fn edit_after_open_commits_cleanly() {
|
||||
{
|
||||
let document = editor.active_document_mut();
|
||||
document.network_interface = rebuilt;
|
||||
document.set_storage(Some(reopened));
|
||||
document.set_storage(reopened, declarations);
|
||||
document.finalize_storage_load();
|
||||
}
|
||||
|
||||
@@ -210,9 +208,7 @@ 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())
|
||||
.await
|
||||
.expect("create_in");
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).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) {
|
||||
@@ -263,9 +259,7 @@ 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())
|
||||
.await
|
||||
.expect("create_in");
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
|
||||
async fn commit_interaction(gdd: &mut GddV1, document: &DocumentMessageHandler, byte_store: &HashMapResourceStorage) {
|
||||
let network = document.network_interface.document_network().clone();
|
||||
@@ -334,7 +328,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).await;
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
// 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();
|
||||
@@ -373,9 +367,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(&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");
|
||||
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");
|
||||
}
|
||||
|
||||
/// The exported `.gdd` archive must carry `session.json` so view settings (notably the document PTZ)
|
||||
@@ -387,15 +381,13 @@ 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())
|
||||
.await
|
||||
.expect("create_in");
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).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(), serde_json::to_value(ptz).unwrap())]);
|
||||
let view_settings = std::collections::BTreeMap::from([(doc::PTZ.to_string(), 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.
|
||||
@@ -410,7 +402,7 @@ async fn gdd_archive_round_trips_view_settings() {
|
||||
|
||||
assert_eq!(
|
||||
reopened.view_settings().get(doc::PTZ),
|
||||
Some(&serde_json::to_value(ptz).unwrap()),
|
||||
Some(&to_value(&ptz).unwrap()),
|
||||
"the document PTZ must survive a .gdd archive export/open (session.json travels in the archive)"
|
||||
);
|
||||
}
|
||||
@@ -437,9 +429,7 @@ 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())
|
||||
.await
|
||||
.expect("create_in");
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
let document = editor.active_document();
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let view = StorageMetadataView::new(&document.network_interface);
|
||||
@@ -472,14 +462,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 mount-time snapshot (as `DocumentStorageMounted` does), then draw a rect
|
||||
/// new-document base as the attach-time snapshot (as `StorageAttached` 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).await;
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
// Mount-time snapshot: capture the new-document graph as the base interaction.
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
|
||||
@@ -569,7 +559,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).await;
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
|
||||
editor.handle_message(paste_named_image()).await;
|
||||
@@ -601,7 +591,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).await;
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
let base = editor.active_document().network_interface.document_network().clone();
|
||||
|
||||
@@ -674,11 +664,9 @@ fn assert_cursor_matches_runtime(document: &DocumentMessageHandler, at: &str) {
|
||||
|
||||
/// Mount a fresh in-memory `Gdd` onto the active document so `commit_storage_snapshot` (the real
|
||||
/// autosave path) runs against it. Returns the byte store the document's resources resolve through.
|
||||
async fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> 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));
|
||||
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());
|
||||
HashMapResourceStorage::new()
|
||||
}
|
||||
|
||||
@@ -701,7 +689,7 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
|
||||
})
|
||||
.await;
|
||||
|
||||
let byte_store = mount_in_memory_storage(&mut editor).await;
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
|
||||
// First autosave: captures the loaded document. `verify_storage_round_trip` panics on drift.
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
@@ -769,7 +757,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::OpenDocumentFile {
|
||||
.handle_message(PortfolioMessage::OpenLegacyDocumentFile {
|
||||
document_name: None,
|
||||
document_path: None,
|
||||
document_serialized_content: serialized,
|
||||
@@ -792,7 +780,7 @@ async fn legacy_four_input_fill_migrates_to_the_split_transform_shape() {
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor
|
||||
.handle_message(PortfolioMessage::OpenDocumentFile {
|
||||
.handle_message(PortfolioMessage::OpenLegacyDocumentFile {
|
||||
document_name: None,
|
||||
document_path: None,
|
||||
document_serialized_content: LEGACY_DOCUMENT.to_string(),
|
||||
@@ -850,7 +838,7 @@ async fn eight_input_fill_migrates_the_spread_input_into_the_ramp() {
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor
|
||||
.handle_message(PortfolioMessage::OpenDocumentFile {
|
||||
.handle_message(PortfolioMessage::OpenLegacyDocumentFile {
|
||||
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, serde_json::Value>,
|
||||
pub view_settings: std::collections::BTreeMap<String, document_graph_storage::Value>,
|
||||
}
|
||||
|
||||
/// Push `document`'s current runtime state through a fresh in-memory `Gdd` and reopen it. The commit goes
|
||||
@@ -56,9 +56,7 @@ 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())
|
||||
.await
|
||||
.expect("create_in");
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let view = StorageMetadataView::new(&document.network_interface);
|
||||
|
||||
@@ -1,14 +1,22 @@
|
||||
mod apply;
|
||||
mod caches;
|
||||
#[cfg(test)]
|
||||
mod characterization_tests;
|
||||
mod deserialization;
|
||||
pub mod editor_delta;
|
||||
#[cfg(test)]
|
||||
mod editor_delta_tests;
|
||||
mod frontend;
|
||||
mod geometry;
|
||||
mod hit_tests;
|
||||
mod invalidation;
|
||||
mod layout;
|
||||
mod memo_network;
|
||||
mod mutations;
|
||||
mod queries;
|
||||
mod resolved_types;
|
||||
pub mod storage_metadata;
|
||||
mod store;
|
||||
mod structure;
|
||||
mod template;
|
||||
mod types;
|
||||
@@ -16,6 +24,9 @@ mod types;
|
||||
mod validation;
|
||||
mod view;
|
||||
|
||||
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
|
||||
use store::Guarded;
|
||||
pub use store::NodeLocator;
|
||||
pub use template::*;
|
||||
pub use types::*;
|
||||
pub use view::{NetworkError, NetworkView};
|
||||
@@ -59,9 +70,9 @@ use std::sync::Arc;
|
||||
pub struct NodeNetworkInterface {
|
||||
/// The node graph that generates this document's artwork. It recursively stores its sub-graphs, so this root graph is the whole snapshot of the document content.
|
||||
/// A public mutable reference should never be created. It should only be mutated through custom setters which perform the necessary side effects to keep network_metadata in sync
|
||||
network: MemoNetwork,
|
||||
network: Guarded<MemoNetwork>,
|
||||
/// Stores all editor information for a NodeNetwork. Should automatically kept in sync by the setter methods when changes to the document network are made.
|
||||
network_metadata: NodeNetworkMetadata,
|
||||
network_metadata: Guarded<NodeNetworkMetadata>,
|
||||
// TODO: Wrap in a TransientCache
|
||||
/// Stores the document network's structural topology. Should automatically kept in sync by the setter methods when changes to the document network are made.
|
||||
#[serde(skip)]
|
||||
@@ -71,6 +82,14 @@ pub struct NodeNetworkInterface {
|
||||
pub resolved_types: ResolvedDocumentNodeTypes,
|
||||
#[serde(skip)]
|
||||
transaction_status: TransactionStatus,
|
||||
/// What the writes since the last drain changed, in write order, appended by `store.rs` alone.
|
||||
///
|
||||
/// Emitting here rather than in the mutators makes it impossible to write without saying what was
|
||||
/// written, the same way writing through the store makes it impossible to update one tree without
|
||||
/// the other. Transient: a snapshot clone starts empty, since the snapshot is a state rather than
|
||||
/// a set of changes.
|
||||
#[serde(skip)]
|
||||
deltas: Vec<EditorDelta>,
|
||||
}
|
||||
|
||||
impl Clone for NodeNetworkInterface {
|
||||
@@ -81,6 +100,7 @@ impl Clone for NodeNetworkInterface {
|
||||
document_metadata: Default::default(),
|
||||
resolved_types: Default::default(),
|
||||
transaction_status: TransactionStatus::Finished,
|
||||
deltas: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -92,9 +112,14 @@ impl PartialEq for NodeNetworkInterface {
|
||||
}
|
||||
|
||||
impl NodeNetworkInterface {
|
||||
/// Normalizes the stored types of every node at every nesting level, for an older document whose stored types predate the current form.
|
||||
pub fn normalize_stored_types(&mut self) {
|
||||
self.migrate_graph(NodeNetwork::normalize_stored_types);
|
||||
}
|
||||
|
||||
/// Add DocumentNodePath input to the PathModifyNode protonode
|
||||
pub fn migrate_path_modify_node(&mut self) {
|
||||
fix_network(self.document_network_mut());
|
||||
self.migrate_graph(fix_network);
|
||||
fn fix_network(network: &mut NodeNetwork) {
|
||||
for node in network.nodes.values_mut() {
|
||||
if let Some(network) = node.implementation.get_network_mut() {
|
||||
@@ -136,11 +161,11 @@ mod network_interface_tests {
|
||||
content: ClipboardContentRaw::Text(clipboard),
|
||||
})
|
||||
.await;
|
||||
let nodes = &mut editor.active_document_mut().network_interface.network_mut(&[]).unwrap().nodes;
|
||||
let orignal = nodes.remove(&rectangle).expect("original node should exist");
|
||||
let nodes = &editor.active_document().network_interface.document_network().nodes;
|
||||
let original = nodes.get(&rectangle).expect("original node should exist");
|
||||
assert!(
|
||||
nodes.values().any(|other| *other == orignal),
|
||||
"duplicated node should exist\nother nodes: {nodes:#?}\norignal {orignal:#?}"
|
||||
nodes.iter().any(|(node_id, other)| *node_id != rectangle && other == original),
|
||||
"duplicated node should exist\nother nodes: {nodes:#?}\noriginal {original:#?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
use super::*;
|
||||
use graph_craft::runtime_delta::RuntimeDelta;
|
||||
|
||||
impl NodeNetworkInterface {
|
||||
/// Mirrors a delta into the interface without recording it.
|
||||
///
|
||||
/// A delta reaching here came from somewhere else, so recording it would offer a change this peer
|
||||
/// never made back to whoever sent it. Writing through the store and then dropping what the store
|
||||
/// recorded keeps the two parallel trees written by one place, which is the property the store
|
||||
/// exists for, without the echo.
|
||||
#[cfg_attr(not(test), expect(dead_code, reason = "no caller until deltas from another peer are replayed; the replay tests exercise it"))]
|
||||
pub(crate) fn apply(&mut self, delta: &EditorDelta) {
|
||||
let recorded = self.deltas.len();
|
||||
self.mirror(delta);
|
||||
self.deltas.truncate(recorded);
|
||||
}
|
||||
|
||||
fn mirror(&mut self, delta: &EditorDelta) {
|
||||
match delta {
|
||||
// The metadata arrives separately, so a node lands with default metadata that the paired
|
||||
// snapshot then fills in
|
||||
EditorDelta::Graph(RuntimeDelta::AddNode { network_path, node_id, node }) | EditorDelta::Graph(RuntimeDelta::ReplaceNode { network_path, node_id, node }) => {
|
||||
let template = NodeTemplate::from_parts((**node).clone(), DocumentNodePersistentMetadata::default());
|
||||
self.insert_node_entry(NodeLocator::new(*node_id, network_path), template);
|
||||
}
|
||||
|
||||
EditorDelta::Graph(RuntimeDelta::RemoveNode { network_path, node_id }) => {
|
||||
self.remove_node_entry(NodeLocator::new(*node_id, network_path));
|
||||
}
|
||||
|
||||
EditorDelta::Graph(RuntimeDelta::SetInput {
|
||||
network_path,
|
||||
node_id,
|
||||
input_index,
|
||||
input,
|
||||
}) => {
|
||||
self.set_input_slot(&InputConnector::node_at_index(*node_id, *input_index), network_path, input.clone());
|
||||
}
|
||||
|
||||
EditorDelta::Graph(RuntimeDelta::SetInputs { network_path, node_id, inputs }) => {
|
||||
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { return };
|
||||
|
||||
// The slots are what changed; their metadata follows in the paired delta. Resizing keeps the
|
||||
// two arrays the same length in the meantime, which the rest of the interface assumes.
|
||||
let mut input_metadata = node.input_metadata().to_vec();
|
||||
input_metadata.resize(inputs.len(), InputMetadata::default());
|
||||
node.replace_inputs(inputs.clone(), input_metadata);
|
||||
}
|
||||
|
||||
EditorDelta::Graph(RuntimeDelta::SetExport { network_path, export_index, input }) => match input {
|
||||
None => {
|
||||
self.remove_export_slot(network_path, *export_index);
|
||||
}
|
||||
// A peer can name a slot past the end of this network's exports, which is an insert here
|
||||
// rather than a write to a slot that does not exist yet.
|
||||
Some(input) if *export_index >= self.number_of_exports(network_path) => {
|
||||
self.insert_export_slot(network_path, *export_index, input.clone(), String::new());
|
||||
}
|
||||
Some(input) => {
|
||||
self.set_input_slot(&InputConnector::Export(*export_index), network_path, input.clone());
|
||||
}
|
||||
},
|
||||
|
||||
EditorDelta::Graph(RuntimeDelta::SetVisibility { network_path, node_id, visible }) => {
|
||||
if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) {
|
||||
node.set_visible(*visible);
|
||||
}
|
||||
}
|
||||
|
||||
EditorDelta::Graph(RuntimeDelta::SetCallArgument { network_path, node_id, call_argument }) => {
|
||||
if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) {
|
||||
node.set_call_argument(call_argument.clone());
|
||||
}
|
||||
}
|
||||
|
||||
EditorDelta::Graph(RuntimeDelta::SetContextFeatures {
|
||||
network_path,
|
||||
node_id,
|
||||
context_features,
|
||||
}) => {
|
||||
if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) {
|
||||
node.set_context_features(*context_features);
|
||||
}
|
||||
}
|
||||
|
||||
EditorDelta::NodeMetadataSnapshot { network_path, node_id, metadata } => {
|
||||
if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) {
|
||||
node.replace_metadata((**metadata).clone());
|
||||
}
|
||||
}
|
||||
|
||||
EditorDelta::NodeInputMetadata {
|
||||
network_path,
|
||||
node_id,
|
||||
input_metadata,
|
||||
} => {
|
||||
if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) {
|
||||
node.set_input_metadata(input_metadata.clone());
|
||||
}
|
||||
}
|
||||
|
||||
EditorDelta::NodeMetadata { network_path, node_id, change } => {
|
||||
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { return };
|
||||
match change {
|
||||
NodeMetadataChange::NodeType(node_type) => node.set_node_type(node_type.clone()),
|
||||
NodeMetadataChange::DisplayName(display_name) => node.set_display_name(display_name.clone()),
|
||||
NodeMetadataChange::Locked(locked) => node.set_locked(*locked),
|
||||
NodeMetadataChange::Pinned(pinned) => node.set_pinned(*pinned),
|
||||
NodeMetadataChange::OutputNames(output_names) => node.set_output_names(output_names.clone()),
|
||||
NodeMetadataChange::InputName { index, name } => node.set_input_name(*index, name.clone()),
|
||||
NodeMetadataChange::WidgetOverride { index, widget_override } => node.set_widget_override(*index, widget_override.clone()),
|
||||
};
|
||||
}
|
||||
|
||||
EditorDelta::NetworkMetadata { network_path, change } => {
|
||||
let Some(mut network) = self.network_mut(network_path) else { return };
|
||||
match change {
|
||||
NetworkMetadataChange::Reference(reference) => network.set_reference(reference.clone()),
|
||||
NetworkMetadataChange::PinnedOrder(order) => network.set_pinned_order(order.clone()),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+214
-532
File diff suppressed because it is too large.
Load diff
+228
-1
@@ -1,4 +1,4 @@
|
||||
use super::{InputConnector, OutputConnector, Previewing, RootNode, TransactionStatus};
|
||||
use super::{InputConnector, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, 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;
|
||||
@@ -126,6 +126,52 @@ async fn cyclic_connection_is_rejected_without_side_effects() {
|
||||
assert_invariants(&editor, "after rejecting a cyclic connection");
|
||||
}
|
||||
|
||||
/// The check answers for the network with the proposed input substituted, so it has to see a loop that
|
||||
/// closes through intermediate nodes rather than only one that connects two neighbors.
|
||||
#[tokio::test]
|
||||
async fn a_cycle_closing_through_a_chain_is_rejected() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let a = editor.create_node_by_name(rectangle_definition()).await;
|
||||
let b = editor.create_node_by_name(rectangle_definition()).await;
|
||||
let c = editor.create_node_by_name(rectangle_definition()).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.set_input(&InputConnector::node_at_index(a, 1), NodeInput::node(b, 0), &[]);
|
||||
network_interface.set_input(&InputConnector::node_at_index(b, 1), NodeInput::node(c, 0), &[]);
|
||||
|
||||
// `a` already reaches `c` through `b`, so feeding `a` back into `c` closes a three-node loop
|
||||
let input_before = network_interface.input_from_connector(&InputConnector::node_at_index(c, 1), &[]).cloned();
|
||||
network_interface.set_input(&InputConnector::node_at_index(c, 1), NodeInput::node(a, 0), &[]);
|
||||
|
||||
let input_after = network_interface.input_from_connector(&InputConnector::node_at_index(c, 1), &[]).cloned();
|
||||
assert_eq!(input_before, input_after, "A cycle closing through an intermediate node should be rejected");
|
||||
|
||||
assert_invariants(&editor, "after rejecting a chained cyclic connection");
|
||||
}
|
||||
|
||||
/// An export is not something a node takes as input, so connecting one cannot close a loop and must
|
||||
/// not be refused.
|
||||
#[tokio::test]
|
||||
async fn connecting_an_export_is_never_cyclic() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let node = editor.create_node_by_name(rectangle_definition()).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.set_input(&InputConnector::Export(0), NodeInput::node(node, 0), &[]);
|
||||
|
||||
assert_eq!(
|
||||
network_interface.input_from_connector(&InputConnector::Export(0), &[]).cloned(),
|
||||
Some(NodeInput::node(node, 0)),
|
||||
"Connecting a node to the export should be accepted"
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after connecting the export");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn toggling_preview_on_a_disconnected_export() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
@@ -401,3 +447,184 @@ async fn toggle_preview_transitions_with_a_connected_export() {
|
||||
|
||||
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"));
|
||||
}
|
||||
|
||||
fn value_input() -> NodeInput {
|
||||
NodeInput::value(TaggedValue::None, false)
|
||||
}
|
||||
|
||||
/// 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()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
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"
|
||||
);
|
||||
}
|
||||
|
||||
// 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);
|
||||
|
||||
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, &[]);
|
||||
};
|
||||
|
||||
// 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");
|
||||
|
||||
// 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.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");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserting_and_deleting_nodes_keeps_the_loaded_wire_cache_exact() {
|
||||
let (mut network_interface, _, node, _) = wired_interface();
|
||||
|
||||
network_interface.insert_node(NodeId(4), NodeTemplate::default(), &[]);
|
||||
assert_interface_invariants(&network_interface, "after inserting a node while the cache is loaded");
|
||||
|
||||
network_interface.delete_nodes(vec![node], false, &[]);
|
||||
assert_interface_invariants(&network_interface, "after deleting a wired node");
|
||||
}
|
||||
|
||||
#[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());
|
||||
|
||||
// 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()));
|
||||
}
|
||||
+2
@@ -141,6 +141,8 @@ impl From<DocumentNodePersistentMetadataStringReference> for DocumentNodePersist
|
||||
metadata.persistent_metadata.reference = old.reference;
|
||||
}
|
||||
DocumentNodePersistentMetadata {
|
||||
// Predates stored identities, so this node falls back to a hash of its location
|
||||
storage_id: None,
|
||||
display_name: old.display_name,
|
||||
input_metadata: old.input_metadata,
|
||||
output_names: old.output_names,
|
||||
|
||||
Loaded 100 of 290 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user