Compare commits

...
Author SHA1 Message Date
Dennis Kobert 366283d4cb Add the History panel 2026-11-02 18:03:34 +00:00
Dennis Kobert dcb856ec92 Add graphene-cli host, join and watch 2026-11-02 18:03:34 +00:00
Dennis Kobert 4a36446f69 Show other peers' pointers 2026-11-02 18:01:25 +00:00
Dennis Kobert 837bf98dec Add live sessions and the Session panel 2026-11-02 18:01:25 +00:00
Dennis Kobert eaddede0a7 Reconcile the interface with storage, undo hot steps 2026-11-02 18:01:25 +00:00
Dennis Kobert 8d8393100d Mint a fresh peer when the user changes 2026-11-02 18:01:25 +00:00
Dennis Kobert 1199d312e4 Compile the definitions table directly instead of inlining it before preprocessing (#4903)
* Compile the definitions table directly instead of inlining it before preprocessing

* Resolve scope inputs against each instance's enclosing scopes, specializing entries whose contexts differ in type
2026-11-02 18:59:22 +01:00
Timon b2cffdfd26 Fix saving leaving the document marked as unsaved on web (#4909) 2026-11-02 17:55:03 +00:00
Timon 6479e0aeba Simplify node graph runtime scheduling (#4907)
* Revert "Limit number of instant graph reevaluations (#4758)"

* Read requests and apply graph updates once per frame
2026-11-02 17:37:00 +00:00
Keavon Chambers bfd85cab6f Replace 'Copy to Points' and 'Assign Colors' with a family of 'Vary' nodes (#4906)
* Replace 'Copy to Points' and 'Assign Colors' with a family of 'Vary' nodes

* Resolve the type of Copy to Points content wired from a secondary output
2026-11-02 14:45:28 +00:00
Dennis Kobert 67e5b899d4 Let migrations choose a target per anchor, ask the compiler, and run on whole states 2026-11-02 14:17:49 +00:00
Dennis Kobert 488c992250 Run headless editor tests on a vulkan software GPU (#4880)
* Run headless editor tests on a software GPU

* Update comment
2026-11-02 10:49:00 +00:00
Keavon Chambers 640aded2b2 Add mipmaps to images so they average their pixels when zoomed out (#4908) 2026-11-02 09:55:45 +00:00
169 changed files with 9649 additions and 1354 deletions

No files matched your search

+2 -2
View File
@@ -1,2 +1,2 @@
https://github.com/Keavon/graphite-branded-assets/archive/2b13ba7ab77cc98cde645583e42e61ce4293def2.tar.gz
77abd4423cda8cba9f097a64d5337f48ad23f31bd537bb553aa654a128b2a51d
https://github.com/Keavon/graphite-branded-assets/archive/4e42efe8dbf2ae2d82e12123aa9c103d5740a465.tar.gz
6b7883a26952c77aad56758a11207761c2fcd1b61bf6dd5996c3cf9d4eb1cb5e
+4
View File
@@ -163,6 +163,10 @@ jobs:
with:
version: ${{ env.SCCACHE_VERSION }}
# GitHub's runners have no GPU, so the editor's tests render on Mesa's software Vulkan driver
- name: 🎮 Install a software Vulkan driver
run: sudo apt-get update && sudo apt-get install --yes mesa-vulkan-drivers
- name: 🦀 Fetch Rust dependencies
run: cargo fetch --locked
+6 -1
View File
@@ -47,12 +47,17 @@ let
# Plotting tools
pkgs.graphviz
];
libs = [
pkgs.vulkan-loader
];
env = {
VK_ADD_DRIVER_FILES = "${pkgs.mesa}/share/vulkan/icd.d/lvp_icd.${pkgs.stdenv.hostPlatform.uname.processor}.json";
};
}
(lib.optionalAttrs desktop (
{
libs = [
pkgs.wayland
pkgs.vulkan-loader
pkgs.libGL
pkgs.libxkbcommon
self.packages.${system}.graphite-cef
Generated
+38 -3
View File
@@ -1300,6 +1300,7 @@ dependencies = [
"tinyvec",
"tsify",
"wasm-bindgen",
"web-time",
]
[[package]]
@@ -1776,6 +1777,19 @@ dependencies = [
"thiserror 2.0.18",
]
[[package]]
name = "document-live"
version = "0.0.0"
dependencies = [
"document-container",
"document-format",
"document-graph-storage",
"graph-craft",
"log",
"peer-transport",
"thiserror 2.0.18",
]
[[package]]
name = "downcast-rs"
version = "1.2.1"
@@ -2702,12 +2716,16 @@ dependencies = [
"clap",
"document-container",
"document-format",
"document-graph-storage",
"document-live",
"fern",
"getrandom 0.3.3",
"graph-craft",
"graphene-std",
"image",
"interpreted-executor",
"log",
"migration-compiled",
"migration-formats",
"migration-nodes",
"preprocessor",
@@ -2715,6 +2733,7 @@ dependencies = [
"tokio",
"wgpu",
"wgpu-executor",
"winit",
]
[[package]]
@@ -2989,11 +3008,13 @@ dependencies = [
"kurbo",
"log",
"math-parser",
"migration-compiled",
"migration-formats",
"migration-nodes",
"node-macro",
"num_enum",
"once_cell",
"peer-transport",
"preprocessor",
"reqwest",
"serde",
@@ -4367,6 +4388,19 @@ dependencies = [
"autocfg",
]
[[package]]
name = "migration-compiled"
version = "0.0.0"
dependencies = [
"document-graph-storage",
"graph-craft",
"graphene-std",
"migration-core",
"migration-runner",
"preprocessor",
"serde",
]
[[package]]
name = "migration-core"
version = "0.0.0"
@@ -4410,6 +4444,7 @@ dependencies = [
name = "migration-nodes"
version = "0.0.0"
dependencies = [
"document-graph-storage",
"migration-core",
"migration-runner",
"serde",
@@ -8024,7 +8059,7 @@ dependencies = [
[[package]]
name = "vello_common"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=f20a8dde35de04c44d05e88b33864f27ad7d6f70#f20a8dde35de04c44d05e88b33864f27ad7d6f70"
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
dependencies = [
"bytemuck",
"fearless_simd",
@@ -8039,7 +8074,7 @@ dependencies = [
[[package]]
name = "vello_gpu"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=f20a8dde35de04c44d05e88b33864f27ad7d6f70#f20a8dde35de04c44d05e88b33864f27ad7d6f70"
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
dependencies = [
"bytemuck",
"hashbrown 0.17.1",
@@ -8053,7 +8088,7 @@ dependencies = [
[[package]]
name = "vello_gpu_shaders"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=f20a8dde35de04c44d05e88b33864f27ad7d6f70#f20a8dde35de04c44d05e88b33864f27ad7d6f70"
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
dependencies = [
"naga",
"wesl",
+8 -3
View File
@@ -17,7 +17,9 @@ members = [
"document/migrations/formats",
"document/migrations/snapshot",
"document/migrations/nodes",
"document/migrations/compiled",
"document/peer-transport",
"document/live",
"editor",
"frontend/wrapper",
"libraries/dyn-any",
@@ -113,8 +115,10 @@ migration-core = { path = "document/migrations/core", default-features = false }
migration-macros = { path = "document/migrations/macros" }
migration-runner = { path = "document/migrations/runner" }
migration-formats = { path = "document/migrations/formats" }
migration-compiled = { path = "document/migrations/compiled" }
migration-nodes = { path = "document/migrations/nodes" }
peer-transport = { path = "document/peer-transport" }
document-live = { path = "document/live" }
raster-nodes = { path = "node-graph/nodes/raster" }
graphene-std = { path = "node-graph/nodes/gstd" }
interpreted-executor = { path = "node-graph/interpreted-executor" }
@@ -139,6 +143,7 @@ serde_bytes = "0.11"
serde-wasm-bindgen = "0.6"
reqwest = { version = "0.13", features = ["blocking", "json"] }
futures = "0.3"
web-time = "1.1"
env_logger = "0.11"
log = "0.4"
bitflags = { version = "2.4", features = ["serde"] }
@@ -303,6 +308,6 @@ debug = true
[patch.crates-io]
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
# TODO: Remove these once the fork's fixes are upstreamed and released
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "f20a8dde35de04c44d05e88b33864f27ad7d6f70" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "f20a8dde35de04c44d05e88b33864f27ad7d6f70" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "f20a8dde35de04c44d05e88b33864f27ad7d6f70" }
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[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":4,"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}],[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}],[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}],[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}],[4,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[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}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"Number":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}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false}],[1789832635968548900,{"inputs":[{"Node":{"node_id":1924303400883620400,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.9822506,"green":0.20507872,"blue":0.012983031,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.25,"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}},{Line 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}],[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":{"Definition":3927671882444294739},"visible":true,"skip_deduplication":false}],[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}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"Number":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}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false}],[1789832635968548900,{"inputs":[{"Node":{"node_id":1924303400883620400,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.9822506,"green":0.20507872,"blue":0.012983031,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.25,"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":[9.4105020317595,0.0,0.0,9.4105020317595,-5.928761491996683,27.64206180233515]},"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}],[1924303400883620400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[12399235852192450000,16255990754021933000,15620668684239604000,5432878891027338000],"remove":[5992115648840007000],"delta":[[5432878891027338000,[-0.8525377229081244,-6.779663923182397]],[12399235852192450000,[3.4492455418381667,-6.252914951989055]],[15620668684239604000,[-7.105427357601002e-15,61.89300411522633]],[16255990754021933000,[3.423868312757215,60.83950617283953]]]},"segments":{"add":[1366074222973177300,9911415907547690000,3820594103877681000,5933636287523951000],"remove":[16939395239973712000],"start_point":[[1366074222973177300,12399235852192450000],[3820594103877681000,15620668684239604000],[5933636287523951000,5432878891027338000],[9911415907547690000,16255990754021933000]],"end_point":[[1366074222973177300,16255990754021933000],[3820594103877681000,5432878891027338000],[5933636287523951000,12399235852192450000],[9911415907547690000,15620668684239604000]],"handle_primary":[[1366074222973177300,[-12.729766803840905,34.6776406035666]],[3820594103877681000,[-1.2746024488136916,-0.5300005080526233]],[5933636287523951000,[0.0,0.0Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Definition":2345381328536166816},"visible":true,"skip_deduplication":false}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":[[1,[0.0,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]]]},"add_g1_continuous":[],"remove_g1_continuous":[],"path_breaks":[1]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Definition":17990361595748109803},"visible":true,"skip_deduplication":false}],[665049002420596400,{"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,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"remove":[],"delta":[[1,[-103.55555555555554,126.66666666666664]],[2,[-67.55555555555554,158.22222222222217]],[3,[45.77777777777777,145.33333333333331]],[4,[18.66666666666663,157.77777777777771]],[5,[66.22222222222223,152.88888888888886]],[6,[123.99999999999994,148.4444444444444]],[7,[229.33333333333331,152.4444444444444]],[8,[252.4444444444444,124.88888888888886]],[9,[156.4444444444444,97.33333333333331]],[10,[216.4444444444444,72.4444444444444]],[11,[136.88888888888886,39.111111111111086]],[12,[199.5555555555555,10.666666666666629]],[13,[153.77777777777777,-1.3333333333333712]],[14,[183.11111111111103,-19.111111111111143]],[15,[111.11111111111114,-60.888888888888914]],[16,[159.5555555555555,-75.55555555555557]],[17,[123.99999999999994,-84.00000000000003]],[18,[145.77777777777777,-97.7777777777778]],[19,[90.66666666666664,-129.33333333333334]],[20,[128.4444444444444,-142.22222222222223]],[21,[76.0,-202.22222222222223]],[22,[71.11111111111109,-201.7777777777778]],[23,[19.555555555555543,-139.55555555555557]],[24,[57.77777777777777,-129.33333333333334]],[25,[0.8888888888888573,-94.66666666666669]],[26,[22.66666666666663,-81.33333333333337]],[27,[-11.111111111111144,-72.00000000000003]],[28,[39.111111111111086,-58.22222222222226]],[29,[-32.888888888888914,-14.666666666666686]],[30,[-9.333333333333371,0.0]],[31,[-53.33333333333337,13.777777777777771]],[32,[9.333333333333314,38.66666666666663]],[33,[-78.22222222222223,75.55555555555554]],[34,[-5.333333333333371,99.11111111111109]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"remove":[],"sLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]]},"add_g1_continuous":[],"remove_g1_continuous":[],"path_breaks":[1]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Definition":11972573546269881380},"visible":true,"skip_deduplication":false}],[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}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Definition":16663118882744990321},"visible":true,"skip_deduplication":false}],[421715625023770179,{"inputs":[{"Node":{"node_id":3670529450440935325,"output_index":0}},{"Node":{"node_id":18214377096178867498,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Definition":376741554282583191},"visible":true,"skip_deduplication":false}],[431994205232245356,{"inputs":[{"Node":{"node_id":12387541320114693418,"output_index":0}},{"Node":{"node_id":14894569344576297448,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Definition":4973965320410448070},"visible":true,"skip_deduplication":false}],[454416440369338250,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2],"remove":[],"delta":[[1,[696.0,593.3333333333333]],[2,[733.7777777777778,518.6666666666666]]]},"segments":{"add":[1],"remove":[],"start_point":[[1,1]],"end_point":[[1,2]],"handle_primary":[[1,[0.0,0.0]]],"handle_end":[[1,[-18.666666666666515,26.66666666666663]]]},"add_g1_continuous":[],"remove_g1_continuous":[],"path_breaks":[1]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Definition":2691771812247834901},"visible":true,"skip_deduplication":false}],[501401493219507773,{"inputs":[{"Node":{"node_id":9425359632144678256,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.5271152,"green":0.02121901,"blue":0.015996292,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.5271152,"green":0.02121901,"blue":0.015996292,"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":[15.687661979265044,0.0,0.0,15.687661979265044,606.9205403814434,96.19238853662318]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedConLine truncated
+35 -26
View File
@@ -4,8 +4,7 @@ use std::fs;
use std::io::Read;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, SyncSender};
use std::sync::mpsc::{Receiver, Sender};
use std::thread;
use std::time::{Duration, Instant};
use winit::application::ApplicationHandler;
@@ -43,14 +42,14 @@ pub(crate) struct App {
app_event_receiver: Receiver<AppEvent>,
app_event_scheduler: AppEventScheduler,
desktop_wrapper: DesktopWrapper,
runtime_command_sender: Sender<RuntimeCommand>,
ui: UiInstance,
ui_frame_received: bool,
start_render_sender: SyncSender<()>,
ui_initialized: Option<Instant>,
web_communication_startup_buffer: Vec<Vec<u8>>,
ui_frame_received: bool,
ui_startup_buffer: Vec<Vec<u8>>,
preferences: preferences::DesktopPreferences,
launch_documents: Option<Vec<PathBuf>>,
exiting: Arc<AtomicBool>,
exiting: bool,
exit_reason: ExitReason,
}
@@ -74,9 +73,7 @@ impl App {
})
.expect("Error setting Ctrl-C handler");
let exiting = Arc::new(AtomicBool::new(false));
let (start_render_sender, start_render_receiver) = std::sync::mpsc::sync_channel(1);
let (runtime_command_sender, start_render_receiver) = std::sync::mpsc::channel();
let async_runtime = tokio::runtime::Builder::new_multi_thread()
.thread_name("graphite-async")
@@ -90,9 +87,9 @@ impl App {
let editor_wake = move || {
wake_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Wake));
};
let runtime_wake_sender = start_render_sender.clone();
let runtime_wake_sender = runtime_command_sender.clone();
let runtime_wake = move || {
let _ = runtime_wake_sender.try_send(());
let _ = runtime_wake_sender.send(RuntimeCommand::Run);
};
let wgpu_executor = WgpuExecutor::with_context(wgpu_context).expect("Failed to create WgpuExecutor");
let (desktop_wrapper, mut node_runtime) = DesktopWrapper::new(
@@ -106,17 +103,23 @@ impl App {
);
let rendering_app_event_scheduler = app_event_scheduler.clone();
let exiting_clone = exiting.clone();
std::thread::spawn(move || {
let mut update = false;
loop {
if update {
node_runtime.update();
}
let texture = async_runtime.block_on(node_runtime.run());
rendering_app_event_scheduler.schedule(AppEvent::ViewportTexture(texture));
let timeout = node_runtime.until_next_frame().unwrap_or(Duration::from_millis(10));
if start_render_receiver.recv_timeout(timeout).is_err() {
node_runtime.begin_frame();
}
if exiting_clone.load(Ordering::Relaxed) {
break;
let first = start_render_receiver.recv_timeout(Duration::from_millis(100)).unwrap_or(RuntimeCommand::Update);
update = false;
for reason in std::iter::once(first).chain(start_render_receiver.try_iter()) {
match reason {
RuntimeCommand::Update => update = true,
RuntimeCommand::Run => {}
RuntimeCommand::Exit => return,
}
}
}
});
@@ -138,12 +141,12 @@ impl App {
desktop_wrapper,
ui,
ui_frame_received: false,
start_render_sender,
runtime_command_sender,
ui_initialized: None,
web_communication_startup_buffer: Vec::new(),
ui_startup_buffer: Vec::new(),
preferences,
launch_documents: Some(launch_documents),
exiting,
exiting: false,
exit_reason: ExitReason::Shutdown,
}
}
@@ -154,10 +157,10 @@ impl App {
}
fn exit(&mut self, reason: Option<ExitReason>) {
if self.exiting.swap(true, Ordering::Relaxed) {
if std::mem::replace(&mut self.exiting, true) {
return;
}
let _ = self.start_render_sender.send(());
let _ = self.runtime_command_sender.send(RuntimeCommand::Exit);
if let Some(reason) = reason {
self.exit_reason = reason;
}
@@ -464,7 +467,7 @@ impl App {
if self.ui_initialized.is_some() {
self.ui.send(UiCommand::Message(message));
} else {
self.web_communication_startup_buffer.push(message);
self.ui_startup_buffer.push(message);
}
}
@@ -473,7 +476,7 @@ impl App {
AppEvent::WebCommunicationInitialized => {
self.ui_initialized = Some(Instant::now());
self.ui_frame_received = false;
for message in self.web_communication_startup_buffer.drain(..) {
for message in self.ui_startup_buffer.drain(..) {
self.ui.send(UiCommand::Message(message));
}
}
@@ -649,7 +652,7 @@ impl ApplicationHandler for App {
}
Err(other) => tracing::error!("Render error: {:?}", other),
}
let _ = self.start_render_sender.try_send(());
let _ = self.runtime_command_sender.send(RuntimeCommand::Update);
}
if !self.ui_frame_received
@@ -759,6 +762,12 @@ impl ApplicationHandler for App {
}
}
enum RuntimeCommand {
Update,
Run,
Exit,
}
pub(crate) enum ExitReason {
Shutdown,
Restart,
@@ -99,6 +99,12 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
FrontendMessage::TriggerClipboardWrite { content } => {
dispatcher.respond(DesktopFrontendMessage::ClipboardWrite { content });
}
// No web origin here, so use the hosted editor
FrontendMessage::TriggerSessionLinkCopy { token } => {
dispatcher.respond(DesktopFrontendMessage::ClipboardWrite {
content: format!("https://editor.graphite.rs/?session={token}"),
});
}
FrontendMessage::WindowPointerLock => {
dispatcher.respond(DesktopFrontendMessage::PointerLock);
}
+1 -2
View File
@@ -8,7 +8,6 @@ use graphite_editor::node_graph_executor::NodeRuntime;
use message_dispatcher::DesktopWrapperMessageDispatcher;
use messages::{DesktopFrontendMessage, DesktopWrapperMessage};
use std::sync::Arc;
use std::time::Instant;
pub use graph_craft::application_io::resource::MmapResourceStorage;
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
@@ -64,7 +63,7 @@ impl DesktopWrapper {
.with_resource_storage(resource_storage)
.with_document_store(document_store),
)
.with_runtime(RuntimeBuilder::new(Arc::new(Instant::now())).with_wake(runtime_wake).with_application_io(application_io))
.with_runtime(RuntimeBuilder::new().with_wake(runtime_wake).with_application_io(application_io))
.with_spawner(spawner)
.with_random_seed(random_seed)
.build();
+4
View File
@@ -58,4 +58,8 @@ pub enum Error {
#[cfg(feature = "network")]
#[error("network error: {0}")]
Network(#[from] peer_transport::PacketError),
/// The room knows this device by its peer, so the user can't change.
#[cfg(feature = "network")]
#[error("the user cannot change while the document is connected")]
UserChangeWhileConnected,
}
+64 -6
View File
@@ -94,6 +94,7 @@ pub struct Gdd<L: Layout = GddV1Layout> {
pub(crate) manifest: Manifest,
/// See [`HistoryMetadata`].
pub(crate) metadata: HistoryMetadata,
pub(crate) wall_clock_ms: Option<f64>,
/// Per-peer view settings (PTZ, rulers, etc.), persisted in `session.json` not the registry, so
/// they stay out of the CRDT/history. Opaque to the storage layer; the editor owns the keys/values.
pub(crate) view_settings: std::collections::BTreeMap<String, document_graph_storage::Value>,
@@ -110,6 +111,9 @@ pub struct Gdd<L: Layout = GddV1Layout> {
/// What peers changed since [`take_remote_changes`](Self::take_remote_changes) last took it.
#[cfg(feature = "network")]
pub(crate) remote_changes: network::RemoteChanges,
pub(crate) interactions_seen: std::collections::HashMap<document_graph_storage::HotOpId, f64>,
pub(crate) own_last_staged_ms: Option<f64>,
pub(crate) own_staged_since_tick: bool,
/// Whether the document belongs in its room, persisted so a reopen reconnects.
pub(crate) shared: bool,
}
@@ -123,14 +127,29 @@ pub(crate) struct PendingPersist {
pub(crate) snapshot: bool,
}
/// What [`Gdd::open_in_with`] passes on to node migrations.
#[derive(Default)]
struct MigrationInputs<'a> {
#[cfg(feature = "migrations")]
byte_store: Option<&'a dyn graphene_resource::LoadResource>,
#[cfg(feature = "migrations")]
host: Option<&'a dyn migration_core::MigrationHost>,
#[cfg(not(feature = "migrations"))]
_lifetime: std::marker::PhantomData<&'a ()>,
}
impl<L: Layout + Clone> Clone for Gdd<L> {
fn clone(&self) -> Self {
Self {
view_settings: self.view_settings.clone(),
network_view_settings: self.network_view_settings.clone(),
wall_clock_ms: self.wall_clock_ms,
byte_store: self.byte_store.clone(),
migrated: self.migrated,
shared: self.shared,
interactions_seen: self.interactions_seen.clone(),
own_last_staged_ms: self.own_last_staged_ms,
own_staged_since_tick: self.own_staged_since_tick,
..Self::assemble(self.session.clone(), self.working.clone(), self.layout.clone(), self.manifest.clone(), self.metadata.clone())
}
}
@@ -145,6 +164,7 @@ impl<L: Layout> Gdd<L> {
layout,
manifest,
metadata,
wall_clock_ms: None,
view_settings: Default::default(),
network_view_settings: Default::default(),
byte_store: None,
@@ -155,6 +175,9 @@ impl<L: Layout> Gdd<L> {
pending_persist: PendingPersist::default(),
#[cfg(feature = "network")]
remote_changes: network::RemoteChanges::default(),
interactions_seen: Default::default(),
own_last_staged_ms: None,
own_staged_since_tick: false,
shared: false,
}
}
@@ -175,10 +198,10 @@ impl<L: Layout + Default> Gdd<L> {
/// Create a fresh, empty working copy at `path` bound to `peer`. Writes a default manifest
/// and session state; the caller fills in editor metadata via [`Gdd::update_manifest`].
pub fn create(path: &Path, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
pub fn create(path: &Path, peer: PeerId, user: UserId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
let working = AnyContainer::Folder(FolderBackend::create(path)?);
let layout = L::default();
Self::create_in(working, layout, peer, document_uuid, editor_version, stdlib_version)
Self::create_in(working, layout, peer, user, document_uuid, editor_version, stdlib_version)
}
}
@@ -195,12 +218,43 @@ impl<L: Layout> Gdd<L> {
Self::open_in(working, layout).await
}
/// [`open_from_archive`](Self::open_from_archive), offering migrations what [`open_in_with`](Self::open_in_with) describes.
#[cfg(all(feature = "migrations", any(feature = "zip", feature = "xz")))]
pub async fn open_from_archive_with(
bytes: &[u8],
mut working: AnyContainer,
layout: L,
byte_store: Option<&dyn graphene_resource::LoadResource>,
host: Option<&dyn migration_core::MigrationHost>,
) -> Result<Self, Error> {
document_container::archive::open_auto(bytes, &mut working)?;
Self::open_in_with(working, layout, byte_store, host).await
}
/// Backend-agnostic open. Splits out so tests can supply a [`document_container::backends::memory::MemoryBackend`].
///
/// # Errors
/// [`Error::MissingManifest`] if the container holds no manifest, [`Error::WrongFormat`] / [`Error::UnsupportedVersion`]
/// if it fails validation, plus the usual [`Error::Read`] / [`Error::Codec`] / [`Error::Crdt`] if a payload is malformed.
/// Reads the manifest without opening the copy, which may be another writer's.
pub async fn read_manifest(working: &AnyContainer, layout: &L) -> Result<Manifest, Error> {
Ok(io::read_single(working, layout.manifest_basename(), MANIFEST_CODEC).await?)
}
pub async fn open_in(working: AnyContainer, layout: L) -> Result<Self, Error> {
Self::open_stored(working, layout, MigrationInputs::default()).await
}
/// [`open_in`](Self::open_in), offering migrations what only the caller has. `host` gives them the compiler, and without one, those asking for it
/// settle on their fallback for good. `byte_store` holds declarations the container doesn't, such as the editor's global cache.
#[cfg(feature = "migrations")]
pub async fn open_in_with(working: AnyContainer, layout: L, byte_store: Option<&dyn graphene_resource::LoadResource>, host: Option<&dyn migration_core::MigrationHost>) -> Result<Self, Error> {
Self::open_stored(working, layout, MigrationInputs { byte_store, host }).await
}
#[cfg_attr(not(feature = "migrations"), expect(unused_variables, reason = "only node migrations use what the caller offers"))]
async fn open_stored(working: AnyContainer, layout: L, inputs: MigrationInputs<'_>) -> Result<Self, Error> {
persist::finish_staged_rewrite(&working, &layout).await?;
let manifest: Manifest = match io::read_single(&working, layout.manifest_basename(), MANIFEST_CODEC).await {
@@ -291,7 +345,7 @@ impl<L: Layout> Gdd<L> {
#[cfg(feature = "migrations")]
{
let migrated_nodes = gdd.migrate_nodes().await?;
let migrated_nodes = gdd.migrate_nodes(inputs.byte_store, inputs.host).await?;
gdd.migrated = format_outcome.is_some() || migrated_nodes;
if gdd.migrated {
gdd.manifest.format_version = gdd.manifest.format_version.max(manifest::SUPPORTED_FORMAT_VERSION);
@@ -307,18 +361,18 @@ impl<L: Layout> Gdd<L> {
/// Backend-agnostic create. Records the working-copy default codecs (see `DEFAULT_*_CODEC`) in
/// the manifest and writes each payload with its recorded codec.
pub fn create_in(working: AnyContainer, layout: L, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
pub fn create_in(working: AnyContainer, layout: L, peer: PeerId, user: UserId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
let manifest = Manifest::new(document_uuid, editor_version, stdlib_version);
let codecs = manifest.codecs;
io::write_single(&working, layout.manifest_basename(), MANIFEST_CODEC, &manifest)?;
let session_state = SessionState {
peer_id: peer,
user_id: UserId(peer.0),
user_id: user,
..Default::default()
};
io::write_single(&working, layout.session_basename(), codecs.session, &Sorted(&session_state))?;
let session = Session::with_peer(peer);
let session = Session::with_identity(peer, user);
io::write_single(&working, layout.registry_basename(), codecs.registry, &Sorted(session.registry()))?;
Ok(Self::assemble(session, working, layout, manifest, HistoryMetadata::default()))
@@ -413,6 +467,10 @@ impl<L: Layout> Gdd<L> {
self.session.all_referenced_resource_hashes()
}
pub fn resource_gc_roots(&self) -> std::collections::HashSet<ResourceHash> {
self.session.resource_gc_roots()
}
/// Drop the session and return the working-copy container + layout.
pub fn into_storage(self) -> (AnyContainer, L) {
(self.working, self.layout)
+76 -14
View File
@@ -4,8 +4,9 @@
use std::collections::{BTreeSet, HashMap};
use document_container::AsyncContainer;
use document_graph_storage::{Delta, EncodedDeclaration, HistoryMetadata, PeerId, Registry, ResourceEntry, ResourceId, Rev, Session, Subject, TimeStamp};
use migration_core::{Declaration, DeclarationResolver, NodeMigration, Payload, PayloadCodec};
use document_graph_storage::{Declarations, Delta, EncodedDeclaration, HistoryMetadata, PeerId, Registry, ResourceEntry, ResourceId, Rev, Session, Subject, TimeStamp};
use graphene_resource::LoadResource;
use migration_core::{Declaration, DeclarationResolver, MigrationHost, NodeMigration, Payload, PayloadCodec};
use migration_runner::{DocumentPayloads, HistoryOutcome, RunnerError, holds, migrate_history, migrate_registry, references, registry_at, run_format_migrations};
use crate::error::Error;
@@ -61,32 +62,37 @@ fn payload_codec(codec: Codec) -> PayloadCodec {
}
impl<L: Layout> Gdd<L> {
/// Rewrite history through every registered node migration whose source declaration it references. Returns whether any ran.
pub(crate) async fn migrate_nodes(&mut self) -> Result<bool, Error> {
/// Rewrite history through every registered node migration whose source declaration it references, in dependency order. Returns whether any ran.
pub(crate) async fn migrate_nodes(&mut self, byte_store: Option<&dyn LoadResource>, host: Option<&dyn MigrationHost>) -> Result<bool, Error> {
let migrations = migration_core::registered_migrations();
if migrations.is_empty() {
return Ok(false);
}
let resolver = DocumentDeclarations::new(&migrations, self.session.peer());
let mut resolver = DocumentDeclarations::new(&migrations, self.session.peer());
let hot_ops = self.session.hot_log().iter().map(|hot_op| &hot_op.op);
let kinds: Vec<_> = self.session.history().map(|delta| &delta.kind).chain(hot_ops).collect();
let registry = self.session.registry();
let pending: Vec<Declaration> = migrations
let pending: Vec<&'static dyn NodeMigration> = migrations
.iter()
.map(|migration| migration.source())
.filter(|source| holds(registry, *source, &resolver) || kinds.iter().any(|kind| references(kind, *source, &resolver)))
.copied()
.filter(|migration| holds(registry, migration.source(), &resolver) || kinds.iter().any(|kind| references(kind, migration.source(), &resolver)))
.collect();
if pending.is_empty() {
return Ok(false);
}
// Only a document with a pending migration asking the compiler pays for loading its declarations
if host.is_some() && pending.iter().any(|migration| migration.asks_compiler()) {
resolver.stored = self.load_stored_declarations(byte_store).await;
}
// Hot ops join history first, so they migrate with it
self.session.retire_all()?;
let migrated = migrate_registry(&migrations, self.session.retired_registry(), &resolver)?;
(self.session, self.metadata) = match self.session_with_rewritten_history(&migrations, &migrated, &resolver) {
let migrated = migrate_registry(&migrations, self.session.retired_registry(), &resolver, host)?;
(self.session, self.metadata) = match self.session_with_rewritten_history(&migrations, &migrated, &resolver, host) {
Ok(rewritten) => rewritten,
Err(error) => {
log::warn!("Migrating this document's history failed, so undo can't reach before this point: {error}");
@@ -103,15 +109,57 @@ impl<L: Layout> Gdd<L> {
}
}
let names: Vec<String> = pending.iter().map(ToString::to_string).collect();
let names: Vec<String> = pending.iter().map(|migration| migration.source().to_string()).collect();
log::info!("Migrated nodes from {}", names.join(", "));
Ok(true)
}
/// Every declaration this document's nodes and history reference, from `byte_store` where it has them and otherwise from the container.
async fn load_stored_declarations(&self, byte_store: Option<&dyn LoadResource>) -> Declarations {
let mut declarations = Declarations::new();
for (id, hash) in self.session.all_declaration_resources() {
let Some(hash) = hash else { continue };
let cached = match byte_store {
Some(byte_store) => byte_store.load(hash).await,
None => None,
};
let stored = match cached {
Some(_) => None,
None => self.working.read(&self.layout.resource_path(&hash)).await.ok(),
};
let decoded = match (&cached, &stored) {
(Some(cached), _) => document_graph_storage::decode_declaration(cached.as_ref()),
(None, Some(stored)) => document_graph_storage::decode_declaration(stored.as_ref()),
(None, None) => {
log::warn!("Declaration bytes for {id} (hash {hash}) are missing, so what reads through it won't compile");
continue;
}
};
match decoded {
Ok(proto) => {
declarations.insert(id, proto);
}
Err(error) => log::warn!("Declaration {id} failed to decode: {error}"),
}
}
declarations
}
/// A session over the rewritten history, as long as replaying that history reaches `migrated`, which a history missing its beginning wouldn't.
fn session_with_rewritten_history(&self, migrations: &[&'static dyn NodeMigration], migrated: &Registry, resolver: &DocumentDeclarations) -> Result<(Session, HistoryMetadata), RunnerError> {
fn session_with_rewritten_history(
&self,
migrations: &[&'static dyn NodeMigration],
migrated: &Registry,
resolver: &DocumentDeclarations,
host: Option<&dyn MigrationHost>,
) -> Result<(Session, HistoryMetadata), RunnerError> {
let history: Vec<Delta> = self.session.history().cloned().collect();
let rewritten = migrate_history(migrations, history, resolver)?;
let cursors = self.session.head_rev().into_iter().chain(self.session.redo_stack().iter().copied());
let rewritten = migrate_history(migrations, history, resolver, host, cursors)?;
let remap = |rev: Rev| rewritten.revs.get(&rev).copied().flatten();
let head = self.session.head_rev().and_then(remap);
@@ -151,6 +199,8 @@ impl<L: Layout> Gdd<L> {
struct DocumentDeclarations {
known: HashMap<ResourceId, Declaration>,
encoded: HashMap<Declaration, EncodedDeclaration>,
/// The document's own declarations, loaded only for a migration asking the compiler.
stored: Declarations,
peer: PeerId,
}
@@ -173,7 +223,12 @@ impl DocumentDeclarations {
}
}
Self { known, encoded, peer }
Self {
known,
encoded,
stored: Declarations::new(),
peer,
}
}
}
@@ -196,4 +251,11 @@ impl DeclarationResolver for DocumentDeclarations {
let encoded = self.encoded.get(&declaration)?;
Some(ResourceEntry::embedded(encoded.hash, self.peer, TimeStamp::ORIGIN))
}
fn proto(&self, resource: ResourceId) -> Option<document_graph_storage::ProtoNode> {
if let Some(proto) = self.stored.get(&resource) {
return Some(proto.clone());
}
Some(self.encoded.get(self.known.get(&resource)?)?.proto.clone())
}
}
+4
View File
@@ -124,6 +124,10 @@ impl<L: Layout> Gdd<L> {
self.network.iter().flat_map(|replica| replica.peers())
}
pub fn mark_runtime_current(&mut self) {
self.session.mark_runtime_current();
}
pub fn poll_peers(&mut self) -> Vec<Event> {
let Some(mut replica) = self.network.take() else { return Vec::new() };
let events = replica.poll(self);
+168 -2
View File
@@ -6,7 +6,7 @@
use document_container::{AnyContainer, AsyncContainer};
#[cfg(feature = "conversion")]
use document_graph_storage::NodeMetadataSource;
use document_graph_storage::{HistoryMetadata, HotOp, MetadataFact, RegistryDelta, Rev, Sorted, Subject, TimeStamp, Value, WallStamp};
use document_graph_storage::{HistoryMetadata, HotOp, MetadataFact, PeerId, RegistryDelta, Rev, Sorted, Subject, TimeStamp, UserId, Value, WallStamp};
#[cfg(feature = "conversion")]
use graphene_resource::ResourceStorage;
@@ -65,6 +65,21 @@ impl<L: Layout> Gdd<L> {
Ok(rev)
}
/// Set the person using this device. `peer` must be unused, so the previous user keeps their steps. Refused while connected.
pub fn set_user(&mut self, user: UserId, peer: PeerId) -> Result<(), Error> {
if self.session.user() == user {
return Ok(());
}
#[cfg(feature = "network")]
if self.network.is_some() {
return Err(Error::UserChangeWhileConnected);
}
let closing = self.session.set_user(user, peer)?;
self.own_last_staged_ms = None;
self.persist_staged(&closing)?;
self.persist_session_state()
}
/// Edit the cached manifest and persist it. Always JSON, synchronous.
pub fn update_manifest(&mut self, edit: impl FnOnce(&mut Manifest)) -> Result<(), Error> {
edit(&mut self.manifest);
@@ -131,6 +146,9 @@ impl<L: Layout> Gdd<L> {
/// Append the frames of freshly staged hot ops, then broadcast them.
fn persist_staged(&mut self, hot_ops: &[HotOp]) -> Result<(), Error> {
if hot_ops.iter().any(|hot_op| !matches!(hot_op.op, RegistryDelta::Meta)) {
self.own_staged_since_tick = true;
}
for hot_op in hot_ops {
self.append_hot_frame(hot_op)?;
}
@@ -368,6 +386,13 @@ impl<L: Layout> Gdd<L> {
Ok(())
}
/// How many closed interactions wait before they retire. Retiring later merges more of a gesture into one delta.
pub const RETIRE_AFTER_INTERACTIONS: usize = 10;
/// Gives every peer time to see the whole interaction.
pub const RETIRE_MIN_AGE_MS: f64 = 2_000.0;
/// The longest anything waits, so quiet sessions and interactions with gaps still retire.
pub const RETIRE_MAX_AGE_MS: f64 = 60_000.0;
/// Close this peer's open interaction, if any, with a marker staged like any other hot op.
pub fn end_interaction(&mut self) -> Result<(), Error> {
let staged = self.session.end_interaction()?;
@@ -375,10 +400,149 @@ impl<L: Layout> Gdd<L> {
Ok(())
}
/// Undo this peer's latest hot interaction, here and on peers. `None` if it already retired.
pub fn retract_interaction(&mut self) -> Result<Option<Vec<RegistryDelta>>, Error> {
let Some(retraction) = self.session.retract_interaction()? else {
return Ok(None);
};
self.own_last_staged_ms = None;
self.rewrite_hot_log()?;
self.persist_registry_snapshot()?;
self.persist_session_state()?;
#[cfg(feature = "network")]
{
self.remote_changes.touched.extend(retraction.touched);
if let Some(replica) = &mut self.network {
replica.broadcast_retraction(&retraction.ids)?;
}
}
Ok(Some(retraction.ops))
}
#[cfg(feature = "network")]
pub fn undo_retired_step(&mut self) -> Result<Option<Rev>, Error> {
if !self.can_change_line() {
return Ok(None);
}
let Some(rev) = self.session.latest_own_interaction() else {
return Ok(None);
};
self.drop_step(rev)?;
Ok(Some(rev))
}
#[cfg(feature = "network")]
pub fn can_change_line(&self) -> bool {
self.retires_locally() || self.network.as_ref().is_some_and(|replica| replica.has_host())
}
/// Drop a retired interaction from the line. A non-retiring peer asks the retirer.
#[cfg(feature = "network")]
pub fn drop_step(&mut self, rev: Rev) -> Result<(), Error> {
if self.retires_locally() {
let (moved, touched) = self.session.drop_interaction(rev)?;
self.remote_changes.touched.extend(touched);
self.persist_rewritten_line()?;
if let Some(replica) = &mut self.network {
replica.broadcast_head_move(moved)?;
}
} else if let Some(replica) = &mut self.network {
replica.request_undo(rev, false)?;
}
Ok(())
}
/// Move the head back to an ancestor, keeping the later line as a branch. A non-retiring peer asks the retirer.
#[cfg(feature = "network")]
pub fn move_head(&mut self, rev: Rev) -> Result<(), Error> {
if self.retires_locally() {
let (moved, touched) = self.session.move_head_to(rev)?;
self.remote_changes.touched.extend(touched);
self.persist_registry_snapshot()?;
self.persist_session_state()?;
if let Some(replica) = &mut self.network {
replica.broadcast_head_move(moved)?;
}
} else if let Some(replica) = &mut self.network {
replica.request_move(rev)?;
}
Ok(())
}
/// Redo a dropped step as a copy on top of the line. A non-retiring peer asks the retirer.
#[cfg(feature = "network")]
pub fn redo_retired_step(&mut self, rev: Rev) -> Result<(), Error> {
if self.retires_locally() {
let deltas = self.restore_dropped_interaction(rev)?;
self.persist_rewritten_line()?;
if let Some(replica) = &mut self.network {
replica.broadcast_retired(&deltas, &[])?;
}
} else if let Some(replica) = &mut self.network {
replica.request_undo(rev, true)?;
}
Ok(())
}
#[cfg(feature = "network")]
fn persist_rewritten_line(&mut self) -> Result<(), Error> {
self.rewrite_history()?;
self.persist_registry_snapshot()?;
self.persist_session_state()
}
/// Stage retracted ops as a new interaction. They count as remote changes.
pub fn restage_ops(&mut self, ops: Vec<RegistryDelta>) -> Result<(), Error> {
#[cfg(feature = "network")]
for op in &ops {
self.remote_changes.touched.record(op);
}
self.stage_ops(ops)?;
Ok(())
}
/// Retire what is due at `now_ms`. Open interactions never retire. `idle` means the editor is between steps.
pub fn retire_due(&mut self, now_ms: f64, idle: bool) -> Result<Vec<Rev>, Error> {
self.wall_clock_ms = Some(now_ms);
// Close a quiet interaction only between steps, so a pause doesn't split a gesture
if self.own_staged_since_tick {
self.own_staged_since_tick = false;
self.own_last_staged_ms = Some(now_ms);
} else if idle && self.own_last_staged_ms.is_some_and(|last| now_ms - last >= Self::RETIRE_MIN_AGE_MS) {
self.end_interaction()?;
self.own_last_staged_ms = None;
}
if !self.retires_locally() {
return Ok(Vec::new());
}
let closed = self.session.closed_interactions();
let mut seen = std::mem::take(&mut self.interactions_seen);
let mut due = Vec::new();
let mut oldest_age: f64 = 0.0;
for interaction in &closed {
let Some(&marker) = interaction.ops.last() else { continue };
let age = now_ms - *seen.entry(marker).or_insert(now_ms);
if age >= Self::RETIRE_MIN_AGE_MS && (interaction.contiguous || age >= Self::RETIRE_MAX_AGE_MS) {
due.push(interaction.clone());
oldest_age = oldest_age.max(age);
}
}
seen.retain(|marker, _| closed.iter().any(|interaction| interaction.ops.last() == Some(marker)));
self.interactions_seen = seen;
if due.len() >= Self::RETIRE_AFTER_INTERACTIONS || oldest_age >= Self::RETIRE_MAX_AGE_MS {
self.retire_interactions(&due)
} else {
Ok(Vec::new())
}
}
/// Close this peer's open interaction and retire every closed one with no ops still on their way, whoever authored
/// it. A peer that does not retire only closes its own.
pub fn retire_pending_interaction(&mut self) -> Result<Vec<Rev>, Error> {
self.end_interaction()?;
self.own_last_staged_ms = None;
let closed = self.contiguous_interactions();
self.retire_interactions(&closed)
}
@@ -414,8 +578,10 @@ impl<L: Layout> Gdd<L> {
Ok(revs)
}
/// Publish and persist freshly retired deltas, then broadcast them with the hot ops they retired.
fn finish_retirement(&mut self, new_revs: &[Rev], retired_hot_ops: &[document_graph_storage::HotOpId]) -> Result<(), Error> {
if let Some(wall_ms) = self.wall_clock_ms {
self.session.stamp_retired_at(new_revs, wall_ms as u64);
}
// Deltas peers hold are published, so undo past them moves the shared head instead of rewinding.
#[cfg(feature = "network")]
if self.network.is_some()
+6
View File
@@ -137,6 +137,12 @@ impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
pub struct ResourceProxy<T: Layout>(AnyContainer, T);
impl<T: Layout + Clone> Clone for ResourceProxy<T> {
fn clone(&self) -> Self {
Self(self.0.clone(), self.1.clone())
}
}
impl<L: Layout + Send + Sync> LoadResource for ResourceProxy<L> {
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
Box::pin(async move {
+2 -2
View File
@@ -4,7 +4,7 @@
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{ExportFormat, ExportOptions, GddV1, GddV1Layout};
use document_graph_storage::{Implementation, Network, NetworkId, Node, NodeId, PeerId, Priority, RegistryDelta, ResourceId, SourceKey, TimeStamp, to_value};
use document_graph_storage::{Implementation, Network, NetworkId, Node, NodeId, PeerId, Priority, RegistryDelta, ResourceId, SourceKey, TimeStamp, UserId, to_value};
use graph_craft::application_io::resource::{HashMapResourceStorage, ResourceStorage};
use graphene_resource::DataSource;
use std::collections::BTreeMap;
@@ -16,7 +16,7 @@ const LATEST: TimeStamp = TimeStamp {
};
fn document(peer: u64) -> GddV1 {
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), 1, "editor".into(), "stdlib".into()).expect("create")
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), UserId(peer), 1, "editor".into(), "stdlib".into()).expect("create")
}
/// Networks and nodes, some of each removed again, plus link-only resources whose bytes sit in the byte store.
+127 -53
View File
@@ -1,13 +1,14 @@
// History metadata has its own file, travels in exports and merges across copies.
use document_container::backends::memory::MemoryBackend;
use document_container::{AnyContainer, AsyncContainer};
use document_format::{GddV1, GddV1Layout, Layout};
use document_graph_storage::{PeerId, Rev, Subject, UserId, rev_attr, user_attr};
use document_graph_storage::{Network, NetworkId, PeerId, RegistryDelta, Rev, Subject, TimeStamp, UserId, rev_attr, user_attr};
const NOW_MS: f64 = 1_700_000_000_000.;
const ADA: Subject = Subject::User(UserId(10));
fn document(peer: u64) -> GddV1 {
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), 1, "editor".into(), "stdlib".into()).expect("create")
fn document(peer: u64, user: u64) -> GddV1 {
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), UserId(user), 1, "editor".into(), "stdlib".into()).expect("create")
}
/// Let the room settle through greetings, the sync handshake and whatever was broadcast.
@@ -24,49 +25,76 @@ fn settle(network: &mut peer_transport::mock::MockNetwork, peers: &mut [&mut Gdd
}
}
fn document_naming_ada() -> GddV1 {
let mut gdd = document(1);
assert!(gdd.record(ADA, user_attr::NAME, "Ada".into(), NOW_MS).expect("record"));
gdd
}
#[test]
fn recorded_facts_survive_a_reopen() {
fn a_recorded_name_survives_a_reopen() {
futures::executor::block_on(async {
let mut gdd = document_naming_ada();
assert!(!gdd.record(ADA, user_attr::NAME, "Ada".into(), NOW_MS + 1.).expect("record"), "the same name is no change");
let step = Rev::new(7).expect("non-zero");
gdd.record(Subject::Rev(step), rev_attr::LABEL, "Fixed the eye".into(), NOW_MS).expect("record");
let mut gdd = document(1, 10);
assert!(gdd.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record"));
assert!(
!gdd.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS + 1.).expect("record"),
"the same name is no change"
);
let step = Rev::new(7).expect("non-zero");
assert!(gdd.record(Subject::Rev(step), rev_attr::LABEL, "Fixed the eye".into(), NOW_MS).expect("record"));
assert!(gdd.record(Subject::Rev(step), "tag:v1", true.into(), NOW_MS).expect("record"));
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.expect("open");
let mut reopened = GddV1::open_in(working, layout).await.expect("open");
assert_eq!(reopened.metadata().user_name(UserId(10)), Some("Ada"));
assert_eq!(reopened.metadata().rev_label(step), Some("Fixed the eye"));
reopened.record(Subject::User(UserId(11)), user_attr::NAME, "Bea".into(), NOW_MS).expect("record");
let (working, layout) = reopened.into_storage();
let reopened = GddV1::open_in(working, layout).await.expect("open");
assert_eq!(reopened.metadata().user_name(UserId(11)), Some("Bea"));
assert_eq!(reopened.metadata().rev_label(step), Some("Fixed the eye"), "a label appended after the name is folded back in");
assert_eq!(reopened.metadata().rev_tags(step), vec!["v1"]);
});
}
#[cfg(all(feature = "conversion", feature = "zip"))]
#[test]
fn an_export_carries_the_metadata_only_with_the_history() {
fn recording_an_unchanged_value_writes_nothing() {
futures::executor::block_on(async {
let gdd = document_naming_ada();
let byte_store = graph_craft::application_io::resource::HashMapResourceStorage::new();
for include_history in [true, false] {
let options = document_format::ExportOptions {
include_history,
..Default::default()
};
let archive = gdd.export_to_bytes(document_format::ExportFormat::Zip, options, &byte_store, None).await.expect("export");
let reopened = GddV1::open_from_archive(&archive, AnyContainer::Memory(MemoryBackend::new()), GddV1Layout).await.expect("open");
assert_eq!(reopened.metadata().user_name(UserId(10)), include_history.then_some("Ada"));
}
let mut gdd = document(1, 10);
gdd.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
let metadata = gdd.metadata().clone();
let (working, layout) = gdd.into_storage();
let path = document_format::io::path_for(layout.metadata_basename(), document_format::METADATA_CODEC);
let before = working.read(&path).await.expect("read").as_slice().to_vec();
let mut reopened = GddV1::open_in(working, layout).await.expect("open");
assert!(!reopened.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS + 1.).expect("record"));
assert_eq!(reopened.metadata(), &metadata);
let (working, _) = reopened.into_storage();
assert_eq!(working.read(&path).await.expect("read").as_slice().trim_ascii(), before.trim_ascii());
});
}
/// A line that doesn't decode is skipped, so a torn write can't block opening.
#[test]
fn an_unreadable_metadata_line_is_skipped() {
futures::executor::block_on(async {
let mut gdd = document(1, 10);
gdd.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
let (working, layout) = gdd.into_storage();
let path = document_format::io::path_for(layout.metadata_basename(), document_format::METADATA_CODEC);
working
.append_non_blocking(
&path,
b"{\"subject\":{\"Branch\":3},\"key\":\"name\",\"value\":1,\"stamp\":{\"ms\":1,\"peer\":1}}\n{\"subject\":{\"User\":",
)
.expect("append");
let reopened = GddV1::open_in(working, layout).await.expect("open");
assert_eq!(reopened.metadata().user_name(UserId(10)), Some("Ada"));
});
}
#[test]
fn a_torn_tail_is_skipped_and_the_next_fact_is_not_joined_to_it() {
futures::executor::block_on(async {
let (working, layout) = document_naming_ada().into_storage();
let mut gdd = document(1, 10);
gdd.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
let (working, layout) = gdd.into_storage();
let path = document_format::io::path_for(layout.metadata_basename(), document_format::METADATA_CODEC);
working.append_non_blocking(&path, b"{\"subject\":{\"User\":").expect("append");
@@ -82,29 +110,75 @@ fn a_torn_tail_is_skipped_and_the_next_fact_is_not_joined_to_it() {
#[cfg(feature = "network")]
#[test]
fn names_reach_the_room_with_the_sync_and_as_they_change() {
let mut host = document(1);
let mut guest = document(2);
host.record(ADA, user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
// A name given before joining travels with the joiner and reaches the host.
guest.record(Subject::User(UserId(20)), user_attr::NAME, "Bea".into(), NOW_MS).expect("record");
futures::executor::block_on(async {
let mut host = document(1, 10);
let mut guest = document(2, 20);
host.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
guest.record(Subject::User(UserId(20)), user_attr::NAME, "Bea".into(), NOW_MS).expect("record");
let mut network = peer_transport::mock::MockNetwork::new(1);
let host_endpoint = network.endpoint();
let guest_endpoint = network.endpoint();
let (host_id, guest_id) = (host_endpoint.id(), guest_endpoint.id());
host.share(host_endpoint, UserId(10)).expect("share");
guest.connect(guest_endpoint, UserId(20)).expect("connect");
network.connect(host_id);
network.connect(guest_id);
settle(&mut network, &mut [&mut host, &mut guest]);
let mut network = peer_transport::mock::MockNetwork::new(1);
let host_endpoint = network.endpoint();
let guest_endpoint = network.endpoint();
let (host_id, guest_id) = (host_endpoint.id(), guest_endpoint.id());
host.share(host_endpoint, UserId(10)).expect("share");
guest.connect(guest_endpoint, UserId(20)).expect("connect");
network.connect(host_id);
network.connect(guest_id);
settle(&mut network, &mut [&mut host, &mut guest]);
assert!(guest.is_synced());
assert_eq!(guest.metadata().user_name(UserId(10)), Some("Ada"), "the host's record came with the sync");
assert_eq!(host.metadata().user_name(UserId(20)), Some("Bea"), "the guest's record came back to the host");
assert!(guest.is_synced());
assert_eq!(guest.metadata().user_name(UserId(10)), Some("Ada"), "the host's record came with the sync");
assert_eq!(host.metadata().user_name(UserId(20)), Some("Bea"), "the guest's record came back to the host");
// A rename while in the room goes round on its own.
assert!(guest.record(Subject::User(UserId(20)), user_attr::NAME, "Beatrix".into(), NOW_MS + 5_000.).expect("record"));
settle(&mut network, &mut [&mut host, &mut guest]);
assert_eq!(host.metadata().user_name(UserId(20)), Some("Beatrix"));
assert_eq!(host.metadata(), guest.metadata(), "both copies hold the same record");
assert!(guest.record(Subject::User(UserId(20)), user_attr::NAME, "Beatrix".into(), NOW_MS + 5_000.).expect("record"));
settle(&mut network, &mut [&mut host, &mut guest]);
assert_eq!(host.metadata().user_name(UserId(20)), Some("Beatrix"));
assert_eq!(host.metadata(), guest.metadata(), "both copies hold the same record");
});
}
#[test]
fn a_retirement_records_when_it_happened() {
futures::executor::block_on(async {
let mut gdd = document(1, 10);
gdd.retire_due(NOW_MS, true).expect("tick");
gdd.stage_ops([RegistryDelta::AddNetwork {
id: NetworkId(9),
network: Network::default(),
}])
.expect("stage");
let everything = TimeStamp {
counter: u64::MAX,
peer: PeerId(u64::MAX),
};
let revs = gdd.retire(everything).expect("retire");
assert!(!revs.is_empty());
for rev in revs {
let delta = gdd.session().delta(rev).expect("retired delta");
assert_eq!(delta.retired_at(), Some(NOW_MS as u64));
}
});
}
/// An export without history carries no facts, since they'd name missing revs.
#[cfg(all(feature = "conversion", feature = "zip"))]
#[test]
fn an_export_carries_the_metadata_only_with_the_history() {
futures::executor::block_on(async {
let mut gdd = document(1, 10);
gdd.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
let byte_store = graph_craft::application_io::resource::HashMapResourceStorage::new();
for include_history in [true, false] {
let options = document_format::ExportOptions {
include_history,
..Default::default()
};
let archive = gdd.export_to_bytes(document_format::ExportFormat::Zip, options, &byte_store, None).await.expect("export");
let reopened = GddV1::open_from_archive(&archive, AnyContainer::Memory(MemoryBackend::new()), GddV1Layout).await.expect("open");
let expected = include_history.then_some("Ada");
assert_eq!(reopened.metadata().user_name(UserId(10)), expected, "include_history: {include_history}");
}
});
}
+185
View File
@@ -0,0 +1,185 @@
// Migrations asking the compiler run as part of opening, in order, and cost nothing to documents they don't apply to
#![cfg(feature = "migrations")]
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::{EncodedDeclaration, Implementation, NoMetadata, PeerId, Registry, UserId};
use futures::executor::block_on;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
use graph_craft::{ProtoNodeIdentifier, concrete};
use graphene_resource::{LoadResource, ResourceFuture, ResourceHash, ResourceRegistry, ResourceStorage};
use migration_core::{Compiler, DeclarationResolver, MigrationHost, Node, Target, ValueType, decl, migration};
use migration_formats as _;
use std::sync::atomic::{AtomicUsize, Ordering};
struct IsVector;
impl ValueType for IsVector {
fn element_name(&self) -> Option<&str> {
Some(std::any::type_name::<IsVector>())
}
}
struct FakeCompiler;
impl Compiler for FakeCompiler {
fn input_type(&self, _node: &Node, _slot: usize) -> Option<Box<dyn ValueType>> {
Some(Box::new(IsVector))
}
}
/// Picks by what the compiler says about the state.
#[migration("test_nodes::CopyNode"@1 => "test_nodes::FallbackNode"@2)]
pub fn by_compiler(node: &Node, compiler: Option<&dyn Compiler>, target: &mut Target) {
if compiler.and_then(|compiler| compiler.input_type(node, 0)).is_some_and(|value_type| value_type.element_is::<IsVector>()) {
target.set(decl!("test_nodes::VectorNode"@1));
}
}
/// Records that it was asked, and what the resolver knew when it was.
#[derive(Default)]
struct Host {
asked: AtomicUsize,
missing_declarations: AtomicUsize,
}
impl MigrationHost for Host {
fn compiler(&self, state: &Registry, resolver: &dyn DeclarationResolver) -> Option<Box<dyn Compiler + '_>> {
self.asked.fetch_add(1, Ordering::Relaxed);
for node in state.node_instances.values() {
if let Implementation::ProtoNode(resource) = node.implementation()
&& resolver.proto(*resource).is_none()
{
self.missing_declarations.fetch_add(1, Ordering::Relaxed);
}
}
Some(Box::new(FakeCompiler))
}
}
/// A byte store that has nothing, like a device's cache that has never seen this document, and counts what it's asked for.
#[derive(Default)]
struct EmptyStore {
loads: AtomicUsize,
}
impl LoadResource for EmptyStore {
fn load(&self, _hash: ResourceHash) -> ResourceFuture<'_> {
self.loads.fetch_add(1, Ordering::Relaxed);
Box::pin(async { None })
}
}
fn network_of(nodes: &[(u64, &'static str)]) -> NodeNetwork {
let node = |identifier: &'static str| DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
call_argument: concrete!(()),
..Default::default()
};
NodeNetwork {
nodes: nodes.iter().map(|(id, identifier)| (NodeId(*id), node(identifier))).collect(),
..Default::default()
}
}
fn stored(nodes: &[(u64, &'static str)]) -> AnyContainer {
stored_with_bytes_in(nodes, &HashMapResourceStorage::new())
}
/// A document whose declaration bytes went to `store`, as the editor sends them to its global cache.
fn stored_with_bytes_in(nodes: &[(u64, &'static str)], store: &HashMapResourceStorage) -> AnyContainer {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), UserId(7), 1, "editor".into(), "std".into()).unwrap();
gdd.commit_from_runtime(&network_of(nodes), &NoMetadata, &ResourceRegistry::new(), store).unwrap();
gdd.into_storage().0
}
fn implementation_of(identifier: &str, version: u32) -> Implementation {
Implementation::ProtoNode(EncodedDeclaration::new(identifier.to_string(), version).unwrap().id)
}
#[test]
fn a_document_without_the_node_pays_nothing() {
block_on(async {
let (host, store) = (Host::default(), EmptyStore::default());
let working = stored(&[(1, "test_nodes::OtherNode")]);
let gdd = GddV1::open_in_with(working, GddV1Layout, Some(&store), Some(&host)).await.unwrap();
assert!(!gdd.migrated());
assert_eq!(host.asked.load(Ordering::Relaxed), 0, "the compiler is never built");
assert_eq!(store.loads.load(Ordering::Relaxed), 0, "no declaration is loaded");
});
}
#[test]
fn opening_runs_it_in_one_pass_and_the_result_persists() {
block_on(async {
let host = Host::default();
let working = stored(&[(1, "test_nodes::CopyNode")]);
let gdd = GddV1::open_in_with(working, GddV1Layout, None, Some(&host)).await.unwrap();
let anchor = *gdd.registry().node_instances.keys().next().unwrap();
assert_eq!(*gdd.registry().node_instances[&anchor].implementation(), implementation_of("test_nodes::VectorNode", 1));
assert!(gdd.migrated());
let target = EncodedDeclaration::new("test_nodes::VectorNode".to_string(), 1).unwrap();
assert_eq!(gdd.declarations(&gdd).await[&target.id], target.proto, "the chosen declaration's bytes are stored");
let registry = gdd.registry().clone();
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.unwrap();
assert!(reopened.registry().value_equal(&registry));
assert!(!reopened.migrated());
});
}
#[test]
fn declarations_come_from_the_container_when_the_cache_lacks_them() {
block_on(async {
let (host, store) = (Host::default(), EmptyStore::default());
let nodes = [(1, "test_nodes::CopyNode"), (2, "test_nodes::OtherNode")];
// An archive carries its declarations in the container, which a device's cache hasn't seen yet
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), UserId(7), 1, "editor".into(), "std".into()).unwrap();
gdd.commit_from_runtime(&network_of(&nodes), &NoMetadata, &ResourceRegistry::new(), &HashMapResourceStorage::new())
.unwrap();
for (_, identifier) in nodes {
gdd.store(&EncodedDeclaration::new(identifier.to_string(), 1).unwrap().bytes);
}
let working = gdd.into_storage().0;
GddV1::open_in_with(working, GddV1Layout, Some(&store), Some(&host)).await.unwrap();
assert!(store.loads.load(Ordering::Relaxed) > 0, "the cache is asked first");
assert!(host.asked.load(Ordering::Relaxed) > 0);
assert_eq!(host.missing_declarations.load(Ordering::Relaxed), 0, "the container fills in what the cache lacks");
});
}
#[test]
fn declarations_come_from_the_cache_when_the_container_lacks_them() {
block_on(async {
let (host, store) = (Host::default(), HashMapResourceStorage::new());
let working = stored_with_bytes_in(&[(1, "test_nodes::CopyNode"), (2, "test_nodes::OtherNode")], &store);
GddV1::open_in_with(working, GddV1Layout, Some(&store), Some(&host)).await.unwrap();
assert!(host.asked.load(Ordering::Relaxed) > 0);
assert_eq!(host.missing_declarations.load(Ordering::Relaxed), 0);
});
}
#[test]
fn opening_without_a_host_takes_the_fallback() {
block_on(async {
let working = stored(&[(1, "test_nodes::CopyNode")]);
let gdd = GddV1::open_in(working, GddV1Layout).await.unwrap();
let node = gdd.registry().node_instances.values().next().unwrap();
assert_eq!(*node.implementation(), implementation_of("test_nodes::FallbackNode", 2));
});
}
+2 -2
View File
@@ -31,7 +31,7 @@ fn network_of(nodes: &[(u64, &'static str)]) -> NodeNetwork {
}
fn create() -> GddV1 {
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), 1, "editor".into(), "std".into()).unwrap()
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), UserId(7), 1, "editor".into(), "std".into()).unwrap()
}
fn commit(gdd: &mut GddV1, nodes: &[(u64, &'static str)], store: &HashMapResourceStorage) {
@@ -79,7 +79,7 @@ fn a_migration_on_disk_leaves_no_staging_behind() {
block_on(async {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("document");
let mut gdd = GddV1::create(&path, PeerId(7), 1, "editor".into(), "std".into()).unwrap();
let mut gdd = GddV1::create(&path, PeerId(7), UserId(7), 1, "editor".into(), "std".into()).unwrap();
commit(&mut gdd, &[(1, FADE)], &HashMapResourceStorage::new());
drop(gdd);
+2 -2
View File
@@ -4,7 +4,7 @@
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{Error, GddV1, GddV1Layout, manifest};
use document_graph_storage::{EncodedDeclaration, Implementation, NoMetadata, PeerId};
use document_graph_storage::{EncodedDeclaration, Implementation, NoMetadata, PeerId, UserId};
use futures::executor::block_on;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
@@ -28,7 +28,7 @@ fn network_of(nodes: &[(u64, &'static str)]) -> NodeNetwork {
}
fn create() -> GddV1 {
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), 1, "editor".into(), "std".into()).unwrap()
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), UserId(7), 1, "editor".into(), "std".into()).unwrap()
}
fn implementations(gdd: &GddV1) -> Vec<Implementation> {
+24 -24
View File
@@ -5,7 +5,7 @@
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{Codec, Error, GddV1, GddV1Layout, Layout, Manifest, io, manifest};
use document_graph_storage::{HotOp, HotSequence, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
use document_graph_storage::{HotOp, HotSequence, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp, UserId};
fn empty_container() -> AnyContainer {
AnyContainer::Memory(MemoryBackend::new())
@@ -44,7 +44,7 @@ fn create_in_round_trips_empty_document() {
futures::executor::block_on(async {
let container = empty_container();
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()) {
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), UserId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()) {
Ok(gdd) => gdd,
Err(error) => panic!("create_in failed: {error:?}"),
};
@@ -82,7 +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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), UserId(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,7 +99,7 @@ fn an_empty_registry_file_is_corrupt_rather_than_absent() {
use document_container::AsyncContainer;
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let codec = gdd.manifest().codecs.registry;
let (working, layout) = gdd.into_storage();
@@ -114,7 +114,7 @@ fn opening_a_registry_without_history_keeps_the_node_counter() {
use document_container::AsyncContainer;
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let codecs = gdd.manifest().codecs;
let (working, layout) = gdd.into_storage();
@@ -135,7 +135,7 @@ fn opening_a_registry_without_history_keeps_the_node_counter() {
#[test]
fn update_manifest_changes_visible_after_reopen() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(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:?}"));
@@ -150,7 +150,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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(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.
@@ -177,7 +177,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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(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 {
@@ -225,7 +225,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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(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 {
@@ -256,7 +256,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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), UserId(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");
@@ -284,7 +284,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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), UserId(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");
@@ -309,7 +309,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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(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");
@@ -332,7 +332,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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), UserId(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[..]);
@@ -362,7 +362,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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), UserId(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[..]);
@@ -391,7 +391,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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), UserId(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";
@@ -415,7 +415,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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), UserId(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[..]);
@@ -443,7 +443,7 @@ fn embed_all_resources_materializes_link_only_resource() {
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), 0xF00D, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), UserId(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.
@@ -508,7 +508,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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), UserId(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";
@@ -549,7 +549,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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), UserId(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[..]);
@@ -602,7 +602,7 @@ fn open_in_rejects_future_format_version() {
#[test]
fn create_in_records_default_codecs_in_manifest() {
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(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::Postcard);
@@ -623,7 +623,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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), UserId(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)],
@@ -665,7 +665,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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let hot_op = HotOp {
op: RegistryDelta::AddNetwork {
@@ -718,7 +718,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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(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();
@@ -746,7 +746,7 @@ fn an_export_without_history_drops_tombstones() {
use document_graph_storage::{Network, NetworkId, RegistryDelta};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xAC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xAC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let id = NetworkId(7);
gdd.stage_constructed_ops(vec![RegistryDelta::AddNetwork { id, network: Network::default() }], &Default::default(), &empty_byte_store())
.unwrap();
+54 -13
View File
@@ -4,7 +4,7 @@
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::{NoMetadata, PeerId, Registry};
use document_graph_storage::{NoMetadata, PeerId, Registry, UserId};
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
use graph_craft::{ProtoNodeIdentifier, concrete};
@@ -25,7 +25,7 @@ fn network_with_one_node() -> NodeNetwork {
/// A whole-document stage after a recorded batch stages nothing new: restating the batch would fail on the node it added.
#[test]
fn restaging_the_whole_document_after_a_batch_stages_nothing() {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(21), 1, "ed".into(), "std".into()).unwrap();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(21), UserId(21), 1, "ed".into(), "std".into()).unwrap();
let store = HashMapResourceStorage::new();
let resources = ResourceRegistry::new();
gdd.stage_runtime_snapshot(&NodeNetwork::default(), &NoMetadata, &resources, &store)
@@ -57,7 +57,7 @@ fn a_reopen_keeps_unretired_hot_ops_out_of_the_retired_snapshot() {
attributes: Default::default(),
};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(22), 1, "ed".into(), "std".into()).unwrap();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(22), UserId(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();
@@ -80,28 +80,69 @@ fn a_reopen_continues_the_hot_op_sequence() {
value: Some(Value::from(serde_json::json!(value))),
},
};
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 mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(23), UserId(23), 1, "ed".into(), "std".into()).unwrap();
gdd.stage_ops([set(1)]).unwrap();
let up_to = gdd.session().hot_log().last().unwrap().timestamp;
gdd.retire(up_to).unwrap();
let last = stage(&mut gdd, set(2));
let last = gdd.stage_ops([set(2)]).unwrap().last().unwrap().sequence;
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);
assert_eq!(reopened.stage_ops([set(3)]).unwrap()[0].sequence.0, last.0 + 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 last = reopened.session().last_hot_sequence();
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);
assert_eq!(reopened.stage_ops([set(4)]).unwrap()[0].sequence.0, last.0 + 1);
});
}
#[test]
fn a_user_change_survives_a_reopen() {
use document_graph_storage::{AttributeDelta, RegistryDelta, Value};
let set = |key: &str| RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta {
key: key.into(),
value: Some(Value::from(serde_json::json!(1))),
},
};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(24), UserId(240), 1, "ed".into(), "std".into()).unwrap();
gdd.stage_ops([set("a")]).unwrap();
gdd.retire_pending_interaction().unwrap();
gdd.stage_ops([set("b")]).unwrap();
gdd.set_user(UserId(250), PeerId(25)).unwrap();
let clock = gdd.session().clock_counter();
let (working, layout) = gdd.into_storage();
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
assert_eq!(reopened.session().peer(), PeerId(25));
assert_eq!(reopened.session().user(), UserId(250));
assert_eq!(reopened.session().clock_counter(), clock);
let staged = reopened.stage_ops([set("c")]).unwrap();
assert!(staged.iter().all(|hot_op| hot_op.timestamp.peer == PeerId(25) && hot_op.timestamp.counter > clock));
assert_eq!(staged[0].sequence.0, 1, "the new peer's run starts over");
reopened.retire_pending_interaction().unwrap();
let (working, layout) = reopened.into_storage();
let reopened = GddV1::open_in(working, layout).await.unwrap();
let session = reopened.session();
assert!(session.hot_log().is_empty(), "the previous user's open step closed and retired");
assert_eq!(session.user_of(PeerId(24)), Some(UserId(240)));
assert_eq!(session.user_of(PeerId(25)), Some(UserId(250)));
assert!(!session.is_mine(PeerId(24)));
assert!(session.is_mine(PeerId(25)));
let authors: Vec<PeerId> = session
.history()
.filter(|delta| matches!(delta.kind, RegistryDelta::ChangeDocumentAttribute { .. }))
.map(|delta| delta.author)
.collect();
assert_eq!(authors, [PeerId(24), PeerId(24), PeerId(25)]);
});
}
+11 -1
View File
@@ -9,7 +9,7 @@ use peer_transport::mock::MockNetwork;
use peer_transport::{Event, SyncTarget};
fn document(peer: u64) -> GddV1 {
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), 1, "editor".into(), "stdlib".into()).expect("create")
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), UserId(peer), 1, "editor".into(), "stdlib".into()).expect("create")
}
fn settle(network: &mut MockNetwork, peers: &mut [&mut GddV1]) {
@@ -110,3 +110,13 @@ fn an_interaction_past_a_gap_waits_to_retire() {
assert!(!host.retire_pending_interaction().expect("retire").is_empty());
assert!(host.session().hot_log().is_empty());
}
#[test]
fn the_user_cannot_change_while_connected() {
let mut host = document(1);
let mut network = MockNetwork::new(1);
host.share(network.endpoint(), UserId(1)).expect("share");
assert!(matches!(host.set_user(UserId(2), PeerId(2)), Err(document_format::Error::UserChangeWhileConnected)));
assert_eq!(host.session().peer(), PeerId(1));
assert_eq!(host.session().user(), UserId(1));
}
+27 -2
View File
@@ -1,5 +1,5 @@
use crate::{Attributes, NetworkId, NodeId, PeerId, Registry, ResourceId, ResourceStore, SourceKey, TimeStamp, Tombstone};
use std::collections::HashMap;
use crate::{Attributes, Implementation, NetworkId, NodeId, PeerId, ROOT_NETWORK, Registry, ResourceId, ResourceStore, SourceKey, TimeStamp, Tombstone};
use std::collections::{HashMap, HashSet};
impl Registry {
/// The node under `id`, live or as removed, for a reference to a node the runtime cannot hold.
@@ -25,6 +25,31 @@ impl Registry {
}
}
/// The registry as `to_runtime` renders it. A removed network the root still reaches counts as present.
pub(crate) fn as_rendered(&self) -> Registry {
let mut nodes_by_network: HashMap<NetworkId, Vec<&crate::Node>> = HashMap::new();
for node in self.node_instances.values() {
nodes_by_network.entry(node.network).or_default().push(node);
}
let mut rendered = self.clone();
let mut reached = HashSet::from([ROOT_NETWORK]);
let mut pending = vec![ROOT_NETWORK];
while let Some(network) = pending.pop() {
for node in nodes_by_network.get(&network).into_iter().flatten() {
if let Implementation::Network(id) = node.implementation
&& reached.insert(id)
{
pending.push(id);
if let Some(mark) = rendered.removed_networks.remove(&id) {
rendered.networks.insert(id, mark.content);
}
}
}
}
rendered
}
/// Whether both registries removed the same entities at the same times. Registries equal in value but not in their
/// removal marks resolve later ops differently.
pub fn removal_marks_equal(&self, other: &Self) -> bool {
@@ -10,7 +10,7 @@ use std::collections::BTreeMap;
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct SessionState {
/// This peer's identity for the document, stable per (device, document). Per-peer rather than
/// This peer's identity for the document, stable per (device, document, user). Per-peer rather than
/// document identity, so it lives with the cursor here, not in the manifest. Used for CRDT
/// tiebreaking and minting peer-scoped IDs.
#[serde(default)]
+83 -9
View File
@@ -19,6 +19,8 @@ pub struct Session {
/// leader-eligibility computation (lowest PeerId among peers whose tip matches the session max).
#[expect(dead_code, reason = "Populated once heartbeat/leader-election transport lands; held now so the field and constructors are in place.")]
remote_tips: HashMap<PeerId, Rev>,
/// The base of local diffs, so peers' edits to the working registry aren't diffed away.
runtime_base: Option<Registry>,
/// What the ops this peer took back named. A retirement racing the take-back may still name them, and this peer may
/// hold the only copy, so they stay garbage collection roots for the life of the session.
taken_back_resources: HashSet<ResourceHash>,
@@ -43,6 +45,7 @@ impl Session {
Self {
document: Document::empty(peer, user),
remote_tips: HashMap::new(),
runtime_base: None,
taken_back_resources: HashSet::new(),
}
}
@@ -55,6 +58,19 @@ impl Session {
self.document.user
}
/// Hand this device to `user` under `peer`, an unused id, so the old peer's ops keep their author.
pub fn set_user(&mut self, user: UserId, peer: PeerId) -> Result<Vec<HotOp>, CrdtError> {
let closing = self.end_interaction()?;
let mut clock = LamportClock::new(peer);
clock.counter = self.document.clock.counter;
self.document.clock = clock;
self.document.peer = peer;
self.document.user = user;
self.document.last_hot_sequence = HotSequence::NONE;
self.document.redo_stack.clear();
Ok(closing)
}
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)
@@ -91,11 +107,26 @@ impl Session {
resources: &graphene_resource::ResourceRegistry,
) -> 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)?;
let rendered;
let base = match &self.runtime_base {
Some(base) => base,
None => {
rendered = self.document.working_registry.as_rendered();
&rendered
}
};
let ops = crate::delta::compute_deltas(base, &conversion.registry);
// Lenient since a peer's concurrent write may have reshaped what the diff names.
let hot_ops = self.stage_ops_with(ops.into_iter().map(|op| (op, Attributes::new())), ApplyMode::Idempotent)?;
self.runtime_base = Some(conversion.registry.clone());
Ok((hot_ops, conversion))
}
pub fn mark_runtime_current(&mut self) {
self.runtime_base = Some(self.document.working_registry.as_rendered());
}
/// The stable [`NetworkId`] of each runtime network location for this document's peer, to key per-network view state in `session.json`.
/// It depends only on the network structure, not on resources or declarations.
#[cfg(any(feature = "conversion", test))]
@@ -169,10 +200,10 @@ impl Session {
/// `PeerId → UserId` mapping is established (and, under causal delivery, observed by other peers)
/// before any of its edits. A no-op batch doesn't register, since registration rides a real edit.
pub(crate) fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
self.stage_ops_with(ops.into_iter().map(|op| (op, Attributes::new())))
self.stage_ops_with(ops.into_iter().map(|op| (op, Attributes::new())), ApplyMode::Strict)
}
fn stage_ops_with(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Attributes)>) -> Result<Vec<HotOp>, CrdtError> {
fn stage_ops_with(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Attributes)>, mode: ApplyMode) -> Result<Vec<HotOp>, CrdtError> {
// A batch is staged whole or not at all.
let mut pending: Vec<(RegistryDelta, Attributes)> = ops.into_iter().collect();
if pending.is_empty() {
@@ -180,7 +211,10 @@ impl Session {
}
let (peer, user) = (self.document.peer, self.document.user);
if self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user) != Some(user) {
let carried = pending
.iter()
.any(|(op, _)| matches!(op, RegistryDelta::RegisterPeer { peer: named, user: naming } if *named == peer && *naming == user));
if !carried && self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user) != Some(user) {
pending.insert(0, (RegistryDelta::RegisterPeer { peer, user }, Attributes::new()));
}
@@ -199,7 +233,7 @@ impl Session {
sequence,
attributes,
};
if let Err(error) = self.document.stage_hot_op(hot_op.clone(), ApplyMode::Strict) {
if let Err(error) = self.document.stage_hot_op(hot_op.clone(), mode) {
// The run continues where it was, so no sequence goes unused.
self.document.last_hot_sequence = sequence_before;
if !staged.is_empty() {
@@ -213,9 +247,20 @@ impl Session {
self.document.last_hot_sequence = sequence;
staged.push(hot_op);
}
self.advance_runtime_base(&staged);
Ok(staged)
}
/// Keeps a later whole-document stage from restating a local batch.
fn advance_runtime_base(&mut self, staged: &[HotOp]) {
let Some(base) = self.runtime_base.take() else { return };
let working = std::mem::replace(&mut self.document.working_registry, base);
for hot_op in staged {
let _ = self.document.apply_op_with(RegistryTarget::Working, hot_op.op.clone(), hot_op.timestamp, ApplyMode::Idempotent);
}
self.runtime_base = Some(std::mem::replace(&mut self.document.working_registry, working));
}
/// Wrap each op as a `Delta`, apply it, and chain it onto the local history. One tick per op.
///
/// Operates on the retired snapshot, so each `reverse` holds the true pre-op state; the working registry already
@@ -289,6 +334,7 @@ impl Session {
..Document::empty(peer, user)
},
remote_tips: HashMap::new(),
runtime_base: None,
taken_back_resources: HashSet::new(),
}
}
@@ -314,6 +360,7 @@ impl Session {
/// Drop hot ops another peer retired, without retiring them here. Until their deltas arrive, the working registry
/// shows the snapshot plus what is still hot.
pub fn discard_hot_ops(&mut self, retired: &[HotOpId]) -> Touched {
self.runtime_base = None;
self.document.mark_retired(retired.iter().copied())
}
@@ -338,6 +385,7 @@ impl Session {
if ids.iter().any(|&id| retired.covers(id)) || !retired.took_back_all(peer, own[own.len() - 1].sequence, self.document.last_hot_sequence) {
return Ok(None);
}
self.runtime_base = None;
let (touched, taken) = self.document.retract_hot_ops(&ids);
self.taken_back_resources.extend(taken.iter().filter_map(|hot_op| hot_op.op.resource_hash()));
let ops = taken.into_iter().map(|hot_op| hot_op.op).filter(|op| !matches!(op, RegistryDelta::Meta)).collect();
@@ -346,6 +394,7 @@ impl Session {
/// Take back hot ops another peer retracted. See [`retract_interaction`](Self::retract_interaction).
pub fn retract_hot_ops(&mut self, ids: &[HotOpId]) -> Touched {
self.runtime_base = None;
self.document.retract_hot_ops(ids).0
}
@@ -408,6 +457,7 @@ impl Session {
self.document.redo_stack.clear();
self.document.rebuild_working();
self.runtime_base = None;
if let Some(head) = self.document.head {
self.publish_up_to(head);
}
@@ -435,6 +485,7 @@ impl Session {
self.document.retired_snapshot = snapshot;
self.document.redo_stack.clear();
self.document.rebuild_working();
self.runtime_base = None;
self.publish_up_to(target);
Ok((
HeadMove {
@@ -482,6 +533,7 @@ impl Session {
}
self.document.redo_stack.clear();
self.document.rebuild_working();
self.runtime_base = None;
if let Some(head) = moved.head {
self.publish_up_to(head);
}
@@ -528,6 +580,7 @@ impl Session {
}
self.document.history.canonical_sort();
self.document.rebuild_working();
self.runtime_base = None;
Ok(revs)
}
@@ -538,7 +591,11 @@ impl Session {
/// Take on a peer's marks, or this peer's persisted ones, dropping the hot ops they cover. Returns what those named.
pub fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Touched {
self.document.absorb_retired_marks(remote)
let touched = self.document.absorb_retired_marks(remote);
if !touched.is_empty() {
self.runtime_base = None;
}
touched
}
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
@@ -586,7 +643,7 @@ impl Session {
}
let mut closing = Attributes::new();
closing.set(crate::attr::delta::INTERACTION_END, Value::Bool(true), TimeStamp::ORIGIN);
self.stage_ops_with([(RegistryDelta::Meta, closing)])
self.stage_ops_with([(RegistryDelta::Meta, closing)], ApplyMode::Strict)
}
/// Every author's closed interactions in the hot log, the earliest closed first.
@@ -680,6 +737,7 @@ impl Session {
} else {
self.document.retired_snapshot = self.snapshot_from_history()?;
self.document.rebuild_working();
self.runtime_base = None;
}
if !self.document.history.extends_canonically(length_before) {
self.document.history.canonical_sort();
@@ -754,6 +812,7 @@ impl Session {
if refold {
self.document.retired_snapshot = self.snapshot_from_history()?;
self.document.rebuild_working();
self.runtime_base = None;
}
Ok(outcome)
@@ -829,6 +888,13 @@ impl Session {
self.document.history.mark_interaction_end(rev, timestamp);
}
/// Record the retirer's clock for these deltas. Not part of their revs and never used for ordering.
pub fn stamp_retired_at(&mut self, revs: &[Rev], wall_ms: u64) {
for &rev in revs {
self.document.history.set_retired_at(rev, wall_ms);
}
}
/// Give a minted copy the attributes and retirement time of the delta it stands for.
fn carry_attributes(&mut self, original: &Delta, copy: Rev) {
if let Some(wall_ms) = original.retired_at() {
@@ -884,6 +950,7 @@ impl Session {
pub fn undo(&mut self) -> Result<Rev, CrdtError> {
let checkpoint = self.document.head.ok_or(CrdtError::NothingToUndo)?;
let base = self.interaction_start_parent(checkpoint, true).ok_or(CrdtError::NothingToUndo)?;
self.runtime_base = None;
while let Some(rev) = self.document.head.filter(|&rev| rev != base) {
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
@@ -904,6 +971,7 @@ impl Session {
/// parents back from the checkpoint to `head` (the chain is linear in the silent solo zone).
pub fn redo(&mut self) -> Result<Rev, CrdtError> {
let checkpoint = self.document.redo_stack.pop().ok_or(CrdtError::NothingToRedo)?;
self.runtime_base = None;
let mut forward = Vec::new();
let mut cursor = Some(checkpoint);
@@ -935,7 +1003,13 @@ impl Session {
pub fn bootstrap_from_registry(peer: PeerId, user: UserId, registry: Registry) -> Result<Self, CrdtError> {
let ops = crate::delta::compute_deltas(&Registry::default(), &registry);
let mut session = Self::with_identity(peer, user);
session.commit_ops(ops, false)?;
let revs = session.commit_ops(ops, false)?;
// All of it is one step that undo can land on, with the first edit after it undoable as its own
if let Some(last) = revs.last() {
session.mark_interaction_end(*last);
}
// 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();
Ok(session)
@@ -281,7 +281,6 @@ fn newest_peer_registration_wins_in_any_order() {
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, so the next batch registers again.
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));
@@ -296,6 +295,56 @@ fn newest_peer_registration_wins_in_any_order() {
assert_eq!(other.user_of(PeerId(3)), None, "a peer never registered has no user");
}
#[test]
fn a_new_user_takes_a_fresh_peer_and_leaves_the_old_steps_to_their_maker() {
fn interaction(session: &mut Session, key: &str) {
session.stage_ops([set_attribute(key, 1)]).expect("stage");
session.end_interaction().expect("close");
for closed in session.closed_interactions() {
session.retire_interaction(&closed).expect("retire");
}
}
let mut device = Session::with_identity(PeerId(1), UserId(10));
for key in ["a", "b", "c"] {
interaction(&mut device, key);
}
device.undo().expect("undo c");
assert!(device.can_redo());
device.stage_ops([set_attribute("d", 1)]).expect("stage d, left open");
let clock_before = device.clock_counter();
let closing = device.set_user(UserId(20), PeerId(2)).expect("switch");
assert!(closing.iter().all(|hot_op| hot_op.timestamp.peer == PeerId(1)), "the old peer closes its own interaction");
assert!(closing.last().is_some_and(crate::HotOp::ends_interaction));
assert_eq!(device.peer(), PeerId(2));
assert!(device.clock_counter() >= clock_before);
assert!(!device.can_undo(), "the previous user's steps are not this person's to undo");
assert!(!device.can_redo());
assert_eq!(device.user_of(PeerId(1)), Some(UserId(10)));
assert!(!device.is_mine(PeerId(1)));
device.stage_ops([set_attribute("e", 1)]).expect("stage e");
device.end_interaction().expect("close e");
let new_ops: Vec<_> = device.hot_log().iter().filter(|hot_op| hot_op.timestamp.peer == PeerId(2)).collect();
assert_eq!(new_ops.first().map(|hot_op| hot_op.sequence), Some(crate::HotSequence(1)), "the new peer's run starts over");
assert!(new_ops.iter().all(|hot_op| hot_op.timestamp.counter > clock_before));
for closed in device.closed_interactions() {
device.retire_interaction(&closed).expect("retire");
}
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(10), "the old registration stands");
assert_eq!(device.user_of(PeerId(2)), Some(UserId(20)));
assert!(device.is_mine(PeerId(2)));
for delta in device.history().filter(|delta| !matches!(delta.kind, RegistryDelta::RegisterPeer { .. })) {
let expected = if delta.author == PeerId(1) { UserId(10) } else { UserId(20) };
assert_eq!(device.user_of(delta.author), Some(expected));
}
assert!(device.can_undo(), "the new user's own step undoes");
device.undo().expect("undo e");
assert!(!device.can_undo(), "but not past it into the previous user's");
}
#[test]
fn a_batch_past_the_last_sequence_is_refused_whole() {
let mut session = Session::with_peer(PeerId(1));
+207 -5
View File
@@ -1,8 +1,13 @@
//! Peers exchanging retired history, moving the shared head, and undoing against what other peers hold.
use core_types::uuid::NodeId as RuntimeNodeId;
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput as RuntimeInput, NodeNetwork};
use crate::{
AttributeDelta, CrdtError, Delta, History, HotOp, HotOpId, Implementation, InputSlot, MergeOutcome, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Registry, RegistryDelta, ResourceEntry,
ResourceHash, ResourceId, Rev, Session, TimeStamp, UserId, Value,
AttributeDelta, CrdtError, Delta, History, HotOp, HotOpId, Implementation, InputSlot, MergeOutcome, Network, NetworkId, NoMetadata, Node, NodeId, NodeInput, PeerId, Registry, RegistryDelta,
ResourceEntry, ResourceHash, ResourceId, Rev, Session, TimeStamp, UserId, Value,
};
use std::collections::HashSet;
@@ -397,6 +402,46 @@ fn rebuilt_working(session: &Session) -> Registry {
copy.document.working_registry
}
fn runtime_network(values: [u32; 2]) -> NodeNetwork {
NodeNetwork {
exports: vec![RuntimeInput::node(RuntimeNodeId(0), 0)],
nodes: [(
RuntimeNodeId(0),
DocumentNode {
inputs: values.iter().map(|&value| RuntimeInput::value(TaggedValue::Integer(value as i64), false)).collect(),
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
..Default::default()
},
)]
.into_iter()
.collect(),
..Default::default()
}
}
/// A stage past a peer's shrunken input list lands like a peer's write, so later stages don't fail.
#[test]
fn a_local_stage_after_a_peers_input_list_change_still_lands() {
let resources = graphene_resource::ResourceRegistry::new();
let mut a = Session::with_peer(PeerId(1));
a.stage_from_runtime(&runtime_network([1, 2]), &NoMetadata, &resources).expect("first stage");
let up_to = a.hot_log().last().unwrap().timestamp;
a.retire(up_to).unwrap();
let mut b = Session::with_peer(PeerId(2));
sync(&mut a, &mut b);
let (&id, node) = b.registry().node_instances.iter().find(|(_, node)| node.inputs().len() == 2).expect("the converted node");
let first = node.inputs()[0].clone();
let shrink = b.stage_ops([RegistryDelta::SetNodeInputs { id, inputs: vec![first] }]).unwrap();
for hot_op in shrink {
a.replay_hot_op(hot_op).unwrap();
}
let edit = a.stage_from_runtime(&runtime_network([1, 5]), &NoMetadata, &resources);
let later = a.stage_from_runtime(&runtime_network([9, 5]), &NoMetadata, &resources);
assert!(edit.is_ok() || later.is_ok(), "a later stage still lands: first {:?}, later {:?}", edit.err(), later.err());
}
struct Lcg(u64);
impl Lcg {
fn below(&mut self, bound: u64) -> u64 {
@@ -439,7 +484,11 @@ fn local_op(rng: &mut Lcg, registry: &Registry) -> Option<RegistryDelta> {
key: key.into(),
value: (rng.below(4) > 0).then(|| Value::from(serde_json::json!(rng.below(50)))),
};
Some(match rng.below(9) {
let source_key = |rng: &mut Lcg| crate::SourceKey {
priority: crate::Priority::new(rng.below(2) as f64).expect("finite"),
peer: PeerId(1 + rng.below(2)),
};
Some(match rng.below(17) {
0 | 1 => RegistryDelta::ChangeDocumentAttribute {
delta: {
let key = ["x", "y"][rng.below(2) as usize];
@@ -500,7 +549,7 @@ fn local_op(rng: &mut Lcg, registry: &Registry) -> Option<RegistryDelta> {
new_input: input(rng),
}
}
_ => {
8 => {
let id = pick(rng, seen_nodes.clone())?;
let inputs = (0..1 + rng.below(3))
.map(|_| InputSlot {
@@ -511,6 +560,55 @@ fn local_op(rng: &mut Lcg, registry: &Registry) -> Option<RegistryDelta> {
.collect();
RegistryDelta::SetNodeInputs { id: NodeId(id), inputs }
}
9 => RegistryDelta::SetNetworkExport {
id: NetworkId(pick(rng, seen_networks.clone())?),
index: rng.below(2) as u32,
export: (rng.below(3) > 0).then(|| input(rng)),
},
10 => RegistryDelta::ChangeNetworkAttribute {
id: NetworkId(pick(rng, seen_networks.clone())?),
delta: attribute(rng, "name"),
},
11 => RegistryDelta::SetNodeImplementation {
id: NodeId(pick(rng, seen_nodes.clone())?),
implementation: Implementation::Network(NetworkId(pick(rng, seen_networks.clone())?)),
},
12 => {
let mut entry = ResourceEntry {
hash: Some(ResourceHash::from([rng.below(2) as u8; 32])),
..Default::default()
};
entry.force_set_source(
source_key(rng),
crate::SourceValue {
source: Value::from(serde_json::json!(rng.below(9))),
timestamp: TimeStamp::ORIGIN,
deleted: false,
},
);
RegistryDelta::AddResource {
id: ResourceId::from(1 + rng.below(2)),
entry,
}
}
13 => {
let id = ResourceId::from(1 + rng.below(2));
let snapshot = registry.resources.get(&id)?.clone();
RegistryDelta::RemoveResource { id, snapshot }
}
14 => RegistryDelta::SetResourceHash {
id: ResourceId::from(1 + rng.below(2)),
hash: Some(ResourceHash::from([rng.below(2) as u8; 32])),
},
15 => RegistryDelta::AddSource {
id: ResourceId::from(1 + rng.below(2)),
key: source_key(rng),
source: Value::from(serde_json::json!(rng.below(9))),
},
_ => RegistryDelta::RemoveSource {
id: ResourceId::from(1 + rng.below(2)),
key: source_key(rng),
},
})
}
@@ -774,7 +872,7 @@ fn a_dropped_interaction_leaves_the_line_and_the_room_follows() {
host.commit_op_for_test(set_attribute("shared", 2)).expect("later step");
let later = host.head_rev().expect("rev");
host.mark_interaction_end(later);
host.document.history.set_retired_at(later, 1_234);
host.stamp_retired_at(&[later], 1_234);
catch_up(&mut guest, &host);
assert_eq!(guest.head_rev(), host.head_rev());
assert_eq!(guest.latest_own_interaction(), Some(undone));
@@ -1017,6 +1115,68 @@ fn discarded_hot_ops_leave_the_working_registry_at_the_snapshot() {
assert_eq!(session.registry(), session.retired_registry());
}
/// Staging a rebuilt runtime unchanged must not restore a network a peer removed while another kept writing to its owner.
#[test]
fn restaging_an_unchanged_runtime_does_not_revive_a_nested_network_removed_under_a_live_owner() {
let resources = graphene_resource::ResourceRegistry::new();
let outer = NodeNetwork {
exports: vec![RuntimeInput::node(RuntimeNodeId(0), 0)],
nodes: [(
RuntimeNodeId(0),
DocumentNode {
implementation: DocumentNodeImplementation::Definition(graph_craft::document::NetworkId(9)),
..Default::default()
},
)]
.into_iter()
.collect(),
definitions: [(graph_craft::document::NetworkId(9), runtime_network([1, 2]))].into_iter().collect(),
..Default::default()
};
let mut a = Session::with_peer(PeerId(1));
let (_, conversion) = a.stage_from_runtime(&outer, &NoMetadata, &resources).expect("first stage");
let up_to = a.hot_log().last().unwrap().timestamp;
a.retire(up_to).unwrap();
let mut b = Session::with_peer(PeerId(2));
sync(&mut a, &mut b);
let (&owner, owner_node) = b
.registry()
.node_instances
.iter()
.find(|(_, node)| matches!(node.implementation(), Implementation::Network(_)))
.expect("the owner");
let Implementation::Network(nested) = *owner_node.implementation() else { unreachable!() };
let mut removal = vec![RegistryDelta::RemoveNode {
id: owner,
snapshot: owner_node.clone(),
}];
for (&id, node) in b.registry().node_instances.iter().filter(|(_, node)| node.network() == nested) {
removal.push(RegistryDelta::RemoveNode { id, snapshot: node.clone() });
}
removal.push(RegistryDelta::RemoveNetwork {
id: nested,
snapshot: b.registry().networks[&nested].clone(),
});
let removal = b.stage_ops(removal).unwrap();
// A writes after the removal, so only the nested network goes.
for _ in 0..10 {
a.document.clock.tick();
}
a.stage_ops([change_node_attribute(owner, "tint", serde_json::json!(1))]).unwrap();
for hot_op in removal {
a.replay_hot_op(hot_op).unwrap();
}
assert!(a.registry().node_instances.contains_key(&owner));
assert!(!a.registry().networks.contains_key(&nested));
let (runtime, _) = a.registry().to_runtime_with_metadata(&conversion.declarations).expect("to runtime");
a.mark_runtime_current();
a.stage_from_runtime(&runtime, &NoMetadata, &resources).expect("restage");
assert!(!a.registry().networks.contains_key(&nested), "the removed network stays removed");
}
#[test]
fn a_drop_whose_copy_fails_leaves_the_session_unchanged() {
let mut session = Session::with_peer(PeerId(1));
@@ -1047,3 +1207,45 @@ fn a_drop_whose_copy_fails_leaves_the_session_unchanged() {
assert_eq!(session.retired_registry(), &retired);
assert_eq!(session.registry(), &registry);
}
#[test]
fn a_batch_carrying_its_registration_is_not_given_another() {
let mut session = Session::with_peer(crate::PeerId(1));
let register = RegistryDelta::RegisterPeer {
peer: crate::PeerId(1),
user: session.user(),
};
assert_eq!(session.stage_computed_ops(vec![register]).expect("stage").len(), 1);
}
/// Only what the root reaches renders, so a removal no rendered node undoes stays a removal.
#[test]
fn a_removed_network_counts_as_rendered_only_when_the_root_reaches_it() {
let (run_by_root, nested, run_by_stray, stray) = (NetworkId(1), NetworkId(2), NetworkId(3), NetworkId(4));
let node = |network, runs| crate::Node {
presence: TimeStamp::default(),
network,
network_timestamp: TimeStamp::default(),
implementation: Implementation::Network(runs),
implementation_timestamp: TimeStamp::default(),
inputs: Vec::new(),
inputs_timestamp: TimeStamp::default(),
attributes: Default::default(),
};
let mut registry = Registry::default();
for (id, network, runs) in [(1, crate::ROOT_NETWORK, run_by_root), (2, run_by_root, nested), (3, stray, run_by_stray)] {
registry.node_instances.insert(crate::NodeId(id), node(network, runs));
}
for id in [run_by_root, nested, run_by_stray] {
let mark = crate::Tombstone {
content: Network::default(),
timestamp: TimeStamp::default(),
placeholder: false,
};
registry.removed_networks.insert(id, mark);
}
let rendered = registry.as_rendered();
assert!(rendered.networks.contains_key(&run_by_root) && rendered.networks.contains_key(&nested));
assert!(!rendered.networks.contains_key(&run_by_stray) && rendered.removed_networks.contains_key(&run_by_stray));
}
+15
View File
@@ -190,6 +190,21 @@ impl RuntimeProjection<'_> {
(network == ROOT_NETWORK || self.reachable.contains(&network)).then(|| runtime_location(network))
}
pub fn definitions(&self) -> impl Iterator<Item = RuntimeNetworkId> + '_ {
self.reachable.iter().map(|&id| runtime_network_id(id))
}
pub fn network_nodes(&self, network: NetworkId) -> impl Iterator<Item = NodeId> + '_ {
self.context.nodes_by_network.get(&network).into_iter().flatten().map(|&(id, _)| id)
}
pub fn implemented_network(&self, id: NodeId) -> Option<NetworkId> {
match self.context.registry.node_instances.get(&id)?.implementation {
Implementation::Network(network) => Some(network),
_ => None,
}
}
/// The location of the node's network in the runtime, and the node's ID in that network.
pub fn node_address(&self, id: NodeId) -> Option<(NetworkLocation, RuntimeNodeId)> {
let node = self.context.registry.node_instances.get(&id)?;
+21
View File
@@ -0,0 +1,21 @@
[package]
name = "document-live"
description = "A memory-backed document following or hosting a collaborative session, for viewers and embedders"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
[dependencies]
document-container = { workspace = true }
document-format = { workspace = true, features = ["network"] }
document-graph-storage = { workspace = true }
peer-transport = { workspace = true }
graph-craft = { workspace = true }
thiserror = { workspace = true }
log = { workspace = true }
[lints]
workspace = true
+118
View File
@@ -0,0 +1,118 @@
//! A memory-backed document in a collaborative session. The caller spawns the transport driver.
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout, ResourceProxy};
use document_graph_storage::{PeerId, UserId};
use graph_craft::application_io::resource::ResourceHash;
use graph_craft::document::NodeNetwork;
use peer_transport::{Room, SyncTarget};
pub use document_format::Error as FormatError;
pub use document_graph_storage::to_runtime::ConversionError;
pub use peer_transport::{DEFAULT_SIGNALING_SERVER, Event, MessageLoopFuture, Role, SessionToken};
#[derive(Debug, thiserror::Error)]
pub enum LiveError {
#[error(transparent)]
Format(#[from] FormatError),
#[error(transparent)]
Conversion(#[from] ConversionError),
}
pub struct LiveDocument {
gdd: GddV1,
token: SessionToken,
}
impl LiveDocument {
/// Host an empty document under `token`. `spawn` must drive the returned future for the whole session.
pub async fn host(signaling_server: &str, token: SessionToken, peer: PeerId, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Result<Self, LiveError> {
let gdd = Self::empty_document(peer, user).await?;
Self::host_document(gdd, signaling_server, token, user, spawn)
}
pub fn host_document(mut gdd: GddV1, signaling_server: &str, token: SessionToken, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Result<Self, LiveError> {
gdd.share(Self::connect(signaling_server, token, spawn), user)?;
Ok(Self { gdd, token })
}
pub async fn join(signaling_server: &str, token: SessionToken, peer: PeerId, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Result<Self, LiveError> {
let mut gdd = Self::empty_document(peer, user).await?;
gdd.connect(Self::connect(signaling_server, token, spawn), user)?;
Ok(Self { gdd, token })
}
fn connect(signaling_server: &str, token: SessionToken, spawn: impl FnOnce(MessageLoopFuture)) -> Room {
let (room, driver) = Room::connect(&token.signaling_url(signaling_server));
spawn(driver);
room
}
async fn empty_document(peer: PeerId, user: UserId) -> Result<GddV1, FormatError> {
let version = env!("CARGO_PKG_VERSION").to_string();
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, peer, user, peer.0, version.clone(), version)
}
pub fn token(&self) -> SessionToken {
self.token
}
pub fn role(&self) -> Option<Role> {
self.gdd.role()
}
pub fn is_synced(&self) -> bool {
self.gdd.is_synced()
}
pub fn is_ready(&self) -> bool {
self.is_synced() && SyncTarget::missing_resources(&self.gdd).is_empty()
}
pub fn missing_resources(&self) -> Vec<ResourceHash> {
let mut missing: Vec<ResourceHash> = SyncTarget::missing_resources(&self.gdd).into_iter().collect();
missing.sort_unstable();
missing
}
/// Apply what peers sent and answer their requests. Call it regularly.
pub async fn poll(&mut self) -> Vec<Event> {
let events = self.gdd.poll_peers();
for event in &events {
let Event::ResourceRequested { from, hash } = event else { continue };
match self.gdd.read_resource(hash).await {
Ok(bytes) => {
if let Err(error) = self.gdd.send_resource(*from, *hash, bytes.as_slice().to_vec()) {
log::warn!("Failed to send resource {hash}: {error}");
}
}
Err(error) => log::warn!("Peer asked for resource {hash} which is not in this document: {error}"),
}
}
events
}
pub fn document(&self) -> &GddV1 {
&self.gdd
}
pub fn document_mut(&mut self) -> &mut GddV1 {
&mut self.gdd
}
/// Async because proto-node declarations are resources.
pub async fn network(&self) -> Result<NodeNetwork, LiveError> {
let declarations = self.gdd.declarations(&self.gdd).await;
let (network, _metadata) = self.gdd.registry().to_runtime_with_metadata(&declarations)?;
Ok(network)
}
pub fn resource_proxy(&self) -> ResourceProxy<GddV1Layout> {
self.gdd.resource_proxy()
}
pub fn leave(&mut self) {
self.gdd.leave();
}
}
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "migration-compiled"
description = "Node migrations of Graphite documents that ask the compiler, and the capability giving them access to it"
edition.workspace = true
version.workspace = true
license.workspace = true
authors.workspace = true
publish.workspace = true
[dependencies]
document-graph-storage = { workspace = true, features = ["conversion"] }
graph-craft = { workspace = true }
graphene-std = { workspace = true }
migration-core = { workspace = true, features = ["typed"] }
preprocessor = { workspace = true }
serde = { workspace = true }
[dev-dependencies]
migration-runner = { workspace = true, features = ["testing"] }
@@ -0,0 +1,72 @@
use document_graph_storage::{Declarations, Implementation, NodeId, Registry, ResourceId};
use graph_craft::Type;
use graph_craft::document::{NodeId as RuntimeNodeId, NodeNetwork};
use graphene_std::platform_application_io::ResourceHash;
use migration_core::{Compiler, DeclarationResolver, MigrationHost, Node, ValueType};
use preprocessor::Preprocessor;
use std::collections::HashMap;
use std::sync::OnceLock;
/// A value type from the live node registry.
struct LiveType(Type);
impl ValueType for LiveType {
fn element_name(&self) -> Option<&str> {
let element = match &self.0 {
Type::Item(element) | Type::List(element) => &**element,
other => other,
};
match element {
Type::Concrete(descriptor) => Some(&descriptor.name),
_ => None,
}
}
}
/// One state of a document, as the compiler sees it.
struct StateCompiler<'a> {
inlined: NodeNetwork,
local_ids: HashMap<NodeId, RuntimeNodeId>,
resource_hashes: HashMap<ResourceId, ResourceHash>,
preprocessor: &'a Preprocessor,
}
impl Compiler for StateCompiler<'_> {
fn input_type(&self, node: &Node, slot: usize) -> Option<Box<dyn ValueType>> {
let local_id = *self.local_ids.get(&node.id())?;
let resource_hash = |resource| self.resource_hashes.get(&resource).copied();
let value_type = self.preprocessor.input_type(&self.inlined, local_id, slot, &resource_hash)?;
Some(Box::new(LiveType(value_type)))
}
}
/// Offers migrations the compiler. Building it costs nothing, and only a document with a migration asking for it pays for what comes after.
#[derive(Default)]
pub struct CompilerHost {
preprocessor: OnceLock<Preprocessor>,
}
impl MigrationHost for CompilerHost {
fn compiler(&self, state: &Registry, resolver: &dyn DeclarationResolver) -> Option<Box<dyn Compiler + '_>> {
let mut declarations = Declarations::new();
for node in state.node_instances.values() {
if let Implementation::ProtoNode(resource) = node.implementation()
&& let Some(proto) = resolver.proto(*resource)
{
declarations.insert(*resource, proto);
}
}
// A state that doesn't convert answers nothing, so each migration asking takes its fallback
let (mut inlined, nodes, _) = state.to_runtime_with_full_metadata(&declarations).ok()?;
inlined.inline_definitions().ok()?;
Some(Box::new(StateCompiler {
inlined,
local_ids: nodes.into_iter().map(|node| (node.storage_id, node.local_id)).collect(),
resource_hashes: state.resources.iter().filter_map(|(id, entry)| Some((*id, entry.hash?))).collect(),
preprocessor: self.preprocessor.get_or_init(Preprocessor::new),
}))
}
}
+7
View File
@@ -0,0 +1,7 @@
//! Node migrations that ask the compiler about a document, and [`CompilerHost`], which the editor and CLI offer it through.
//! Unlike `migration-nodes`, these link the node crates and depend on the build they run in, so a document's peers can't all reach the same result.
mod compiler;
mod vary_nodes_from_copy_to_points;
pub use compiler::CompilerHost;
@@ -0,0 +1,272 @@
use document_graph_storage::attr::node::VISIBLE;
use graphene_std::Color;
use graphene_std::raster_types::{CPU, Raster};
use graphene_std::vector::Vector;
use graphene_std::vector::style::Gradient;
use migration_core::{Compiler, Inputs, MigrationError, NewNode, Node, NodeInput, Target, Upstream, decl, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const CONTENT: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration uses.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Integer(i64),
Bool(bool),
}
fn number(input: &NodeInput) -> Option<f64> {
match literal_of::<Tagged>(input) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
}
}
/// Copy to Points becomes Into Group, Repeat on Points, Vary Rotations, Vary Scales, and a flatten back to the content's element type, ending at the
/// anchor to keep its downstream wires. Grouping makes each copy one row for the vary nodes, and keeps the offsets of its content, whose translation
/// Repeat on Points overwrites. Content that doesn't compile takes Flatten Graphic, which can't make that state any worse. A hidden node only passes
/// its points through, so it needs nothing past the repeat, and its unused scale and rotation are dropped.
#[migration("core_types::vector::CopyToPointsNode"@1 => "transform_nodes::transform_nodes::VaryRotationsNode"@2)]
pub fn vary_nodes_from_copy_to_points(node: &Node, compiler: Option<&dyn Compiler>, inputs: &mut Inputs, upstream: &mut Upstream, target: &mut Target) -> Result<(), MigrationError> {
let slots: Vec<NodeInput> = node.inputs().iter().map(|slot| slot.input.clone()).collect();
let [points, content, scale_min, scale_max, scale_bias, scale_seed, rotation, rotation_seed] =
<[NodeInput; 8]>::try_from(slots).map_err(|_| MigrationError::invariant("Copy to Points has eight inputs"))?;
let repeat = decl!("repeat_nodes::repeat_nodes::RepeatOnPointsNode"@1);
let unset = || literal(Tagged::Bool(false));
let visible = node.attributes().get_or(VISIBLE, true);
if !visible {
target.set(repeat);
replace_inputs(inputs, vec![points, content, unset()]);
return Ok(());
}
let content_type = compiler.and_then(|compiler| compiler.input_type(node, CONTENT));
let fallback = decl!("graphic_nodes::graphic::FlattenGraphicNode"@1);
let flatten = match &content_type {
Some(content) if content.element_is::<Vector>() => decl!("graphic_nodes::graphic::FlattenVectorNode"@1),
Some(content) if content.element_is::<Raster<CPU>>() => decl!("graphic_nodes::graphic::FlattenRasterNode"@1),
Some(content) if content.element_is::<Color>() => decl!("graphic_nodes::graphic::FlattenColorNode"@1),
Some(content) if content.element_is::<Gradient>() => decl!("graphic_nodes::graphic::FlattenGradientNode"@1),
_ => fallback,
};
// Text has no group to go in, so its rows are repeated as they are
let groups = !content_type.as_ref().is_some_and(|content| content.element_is::<String>());
let group = groups.then(|| {
upstream.add_node(NewNode {
declaration: decl!("graphic_nodes::graphic::IntoGroupNode"@1),
inputs: vec![content.clone()],
})
});
let repeated_content = group.map_or(content, |group| NodeInput::Node { id: group, index: 0 });
let mut stages = vec![(repeat, vec![points, repeated_content, unset()])];
// The rotation range was centered on zero, so a wired one is halved to each side by Multiply nodes
if number(&rotation) != Some(0.) {
let mut half = |factor: f64, key: &str| match number(&rotation) {
Some(rotation) => literal(Tagged::Number(rotation * factor)),
None => {
let multiply = upstream.add_node_keyed(
NewNode {
declaration: decl!("math_nodes::MultiplyNode"@1),
inputs: vec![rotation.clone(), literal(Tagged::Number(factor))],
},
key,
);
NodeInput::Node { id: multiply, index: 0 }
}
};
let (min, max) = (half(-0.5, "min"), half(0.5, "max"));
stages.push((
decl!("transform_nodes::transform_nodes::VaryRotationsNode"@2),
vec![
unset(),
min,
max,
literal(Tagged::Number(0.5)),
unset(),
literal(Tagged::Bool(true)),
rotation_seed,
literal(Tagged::Integer(0)),
],
));
}
// A wired bias can't be converted, so it is left at the default
if number(&scale_min) != Some(1.) || number(&scale_max) != Some(1.) {
let bias = number(&scale_bias).map_or(0.5, bias_keeping_average_scale);
stages.push((
decl!("transform_nodes::transform_nodes::VaryScalesNode"@1),
vec![
unset(),
scale_min,
scale_max,
literal(Tagged::Number(bias)),
unset(),
literal(Tagged::Bool(true)),
scale_seed,
literal(Tagged::Integer(0)),
],
));
}
if groups {
let fully_flatten = (flatten == fallback).then(unset);
stages.push((flatten, std::iter::once(unset()).chain(fully_flatten).collect()));
}
// Each stage reads the one before it, up to the last, which is the anchor
let Some((last_declaration, mut last_inputs)) = stages.pop() else { return Ok(()) };
let mut previous = None;
for (declaration, mut stage_inputs) in stages {
if let Some(id) = previous {
stage_inputs[0] = NodeInput::Node { id, index: 0 };
}
previous = Some(upstream.add_node(NewNode { declaration, inputs: stage_inputs }));
}
if let Some(id) = previous {
last_inputs[0] = NodeInput::Node { id, index: 0 };
}
target.set(last_declaration);
replace_inputs(inputs, last_inputs);
Ok(())
}
fn replace_inputs(inputs: &mut Inputs, replacement: Vec<NodeInput>) {
inputs.truncate(0);
for input in replacement {
inputs.push(input);
}
}
/// The Vary Scales bias giving the same average scale, as a fraction of its range, that Copy to Points' random scale distribution had for its bias.
fn bias_keeping_average_scale(bias: f64) -> f64 {
if bias.abs() < 1e-6 {
return 0.5;
}
// Its bias curve `log2(1 + r (2^b - 1)) / b` averages `2^b / (2^b - 1) - 1 / (b ln 2)`, written with `x = b ln 2` to stay finite for a large bias
let x = bias * std::f64::consts::LN_2;
let average = -1. / (-x).exp_m1() - 1. / x;
// The new curve averages `k / (k + 1)` for `1 - (1 - t)^k` below a bias of 0.5, where `k = -log2(1 - bias)`, and `1 / (p + 1)` for `t^p` above it, where `p = -log2(bias)`
if average < 0.5 {
let k = average / (1. - average);
1. - (-k).exp2()
} else {
let p = 1. / average - 1.;
(-p).exp2()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::CompilerHost;
use migration_core::Declaration;
use migration_runner::testing::{Fixture, Random, SourceContract, check_commutation_with, check_undo_with};
const COPY_TO_POINTS: Declaration = decl!("core_types::vector::CopyToPointsNode"@1);
const STAR: Declaration = decl!("vector_nodes::generator_nodes::StarNode"@1);
const FLATTEN_VECTOR: Declaration = decl!("graphic_nodes::graphic::FlattenVectorNode"@1);
const FLATTEN_GRAPHIC: Declaration = decl!("graphic_nodes::graphic::FlattenGraphicNode"@1);
const VARY_ROTATIONS: Declaration = decl!("transform_nodes::transform_nodes::VaryRotationsNode"@2);
fn host() -> CompilerHost {
CompilerHost::default()
}
fn contract() -> SourceContract {
SourceContract::new(8, |random: &mut Random, slot| match slot {
2 | 3 | 4 | 6 => literal(Tagged::Number(random.below(3) as f64)),
_ => literal(Tagged::Integer(random.below(3) as i64)),
})
}
fn star_inputs() -> Vec<NodeInput> {
vec![literal(Tagged::None), literal(Tagged::Integer(5)), literal(Tagged::Number(50.)), literal(Tagged::Number(25.))]
}
fn inputs(content: NodeInput, scale: f64, rotation: f64) -> Vec<NodeInput> {
let number = |number| literal(Tagged::Number(number));
let integer = |integer| literal(Tagged::Integer(integer));
vec![literal(Tagged::Integer(0)), content, number(scale), number(scale), number(0.), integer(1), number(rotation), integer(2)]
}
#[test]
fn rewrites_history() {
let host = host();
check_commutation_with(&VaryNodesFromCopyToPoints, &contract(), Some(&host));
check_undo_with(&VaryNodesFromCopyToPoints, &contract(), Some(&host));
}
#[test]
fn typed_content_ends_in_the_flatten_of_its_element() {
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
let star = fixture.add(STAR, star_inputs());
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: star, index: 0 }, 1., 0.));
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
assert_eq!(fixture.declaration_of(&migrated, copies), Some(FLATTEN_VECTOR));
assert_eq!(fixture.inputs(&migrated, copies).len(), 1);
}
#[test]
fn content_that_does_not_compile_keeps_flatten_graphic() {
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
let unknown = fixture.add(decl!("migration_testing::unknown"@1), vec![]);
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: unknown, index: 0 }, 2., 0.));
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
assert_eq!(fixture.declaration_of(&migrated, copies), Some(FLATTEN_GRAPHIC));
assert_eq!(fixture.inputs(&migrated, copies).len(), 2);
}
#[test]
fn text_is_repeated_without_a_group() {
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
let text = fixture.add(decl!("text_nodes::AsStringNode"@1), vec![literal(Tagged::Number(1.))]);
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: text, index: 0 }, 1., 90.));
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
assert_eq!(fixture.declaration_of(&migrated, copies), Some(VARY_ROTATIONS));
let NodeInput::Node { id: repeat, .. } = fixture.inputs(&migrated, copies)[0] else {
panic!("the rotations read the repeat")
};
assert_eq!(fixture.inputs(&migrated, repeat)[1], NodeInput::Node { id: text, index: 0 });
}
#[test]
fn rotation_range_is_centered() {
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
let star = fixture.add(STAR, star_inputs());
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: star, index: 0 }, 1., 90.));
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
let NodeInput::Node { id: rotations, .. } = fixture.inputs(&migrated, copies)[0] else {
panic!("the flatten reads the last stage")
};
assert_eq!(fixture.declaration_of(&migrated, rotations), Some(VARY_ROTATIONS));
assert_eq!(number(&fixture.inputs(&migrated, rotations)[1]), Some(-45.));
assert_eq!(number(&fixture.inputs(&migrated, rotations)[2]), Some(45.));
}
#[test]
fn bias_keeps_its_average() {
assert_eq!(bias_keeping_average_scale(0.), 0.5);
assert!(bias_keeping_average_scale(-10.) < 0.5);
assert!(bias_keeping_average_scale(10.) > 0.5);
assert!(bias_keeping_average_scale(100.).is_finite());
}
}
@@ -0,0 +1,84 @@
//! The compiler host, on the real node registry.
use document_graph_storage::{NodeId, NodeInput};
use graphene_std::vector::Vector;
use migration_compiled::CompilerHost;
use migration_core::{Compiler, Declaration, Node, NodeMigration, Target, decl, literal, migration};
use migration_runner::testing::{Fixture, SourceContract, check_commutation_with};
use serde::Serialize;
const STAR: Declaration = decl!("vector_nodes::generator_nodes::StarNode"@1);
/// Frozen mirror of the `TaggedValue` variants these tests store.
#[derive(Serialize)]
enum Tagged {
None,
Integer(i64),
Number(f64),
}
/// Picks by the element type of its first input, with a fallback for what doesn't compile.
#[migration("test_nodes::anchor"@1 => "test_nodes::fallback"@2)]
pub fn by_compiler(node: &Node, compiler: Option<&dyn Compiler>, target: &mut Target) {
if compiler.and_then(|compiler| compiler.input_type(node, 0)).is_some_and(|value_type| value_type.element_is::<Vector>()) {
target.set(decl!("test_nodes::vector"@1));
}
}
fn star_inputs() -> Vec<NodeInput> {
vec![literal(Tagged::None), literal(Tagged::Integer(5)), literal(Tagged::Number(50.)), literal(Tagged::Number(25.))]
}
fn wire(id: NodeId) -> NodeInput {
NodeInput::Node { id, index: 0 }
}
#[test]
fn a_wire_from_a_real_node_gives_its_type() {
let mut fixture = Fixture::new(&ByCompiler);
let star = fixture.add(STAR, star_inputs());
let anchor = fixture.add(ByCompiler.source(), vec![wire(star)]);
let migrated = fixture.migrate_with(&ByCompiler, Some(&CompilerHost::default())).unwrap();
assert_eq!(fixture.declaration_of(&migrated, anchor), Some(decl!("test_nodes::vector"@1)));
}
#[test]
fn no_host_takes_the_fallback() {
let mut fixture = Fixture::new(&ByCompiler);
let star = fixture.add(STAR, star_inputs());
let anchor = fixture.add(ByCompiler.source(), vec![wire(star)]);
let migrated = fixture.migrate(&ByCompiler).unwrap();
assert_eq!(fixture.declaration_of(&migrated, anchor), Some(decl!("test_nodes::fallback"@2)));
}
#[test]
fn what_does_not_compile_takes_the_fallback() {
let mut fixture = Fixture::new(&ByCompiler);
let missing = fixture.add(decl!("test_nodes::not_a_node"@1), vec![]);
let anchor = fixture.add(ByCompiler.source(), vec![wire(missing)]);
let migrated = fixture.migrate_with(&ByCompiler, Some(&CompilerHost::default())).unwrap();
assert_eq!(fixture.declaration_of(&migrated, anchor), Some(decl!("test_nodes::fallback"@2)));
}
#[test]
fn a_literal_takes_the_fallback() {
let mut fixture = Fixture::new(&ByCompiler);
let anchor = fixture.add(ByCompiler.source(), vec![literal(Tagged::Number(1.))]);
let migrated = fixture.migrate_with(&ByCompiler, Some(&CompilerHost::default())).unwrap();
assert_eq!(fixture.declaration_of(&migrated, anchor), Some(decl!("test_nodes::fallback"@2)));
}
#[test]
fn asking_the_compiler_commutes() {
let host = CompilerHost::default();
let contract = SourceContract::new(1, |_, _| literal(Tagged::Number(0.)));
check_commutation_with(&ByCompiler, &contract, Some(&host));
}
+28
View File
@@ -0,0 +1,28 @@
use crate::{DeclarationResolver, Node};
use document_graph_storage::Registry;
/// A value type as the compiler reports it. Only ever compared within one run, so nothing about it is stored.
pub trait ValueType {
/// The `type_name` of the element an `Item` or `List` holds, or of the type itself when it's neither. `None` for what isn't concrete.
fn element_name(&self) -> Option<&str>;
}
impl dyn ValueType {
/// Whether the elements of this value type are `T`.
pub fn element_is<T: 'static>(&self) -> bool {
// The compiler's types carry no `TypeId`, and compare by this same name
self.element_name() == Some(std::any::type_name::<T>())
}
}
/// Answers what flows through one state of a document. A migration asks for it with an `Option<&dyn Compiler>` parameter, and handles `None`.
pub trait Compiler {
/// The value type slot `slot` of `node` carries, or `None` where what feeds it doesn't compile.
fn input_type(&self, node: &Node, slot: usize) -> Option<Box<dyn ValueType>>;
}
/// What the caller opening a document offers migrations beyond the stored data.
pub trait MigrationHost: Sync {
/// A compiler describing `state`, whose declarations `resolver` names. `None` runs the migrations asking for one on their fallback.
fn compiler(&self, state: &Registry, resolver: &dyn DeclarationResolver) -> Option<Box<dyn Compiler + '_>>;
}
+5 -1
View File
@@ -1,4 +1,4 @@
use document_graph_storage::{ResourceEntry, ResourceId};
use document_graph_storage::{ProtoNode, ResourceEntry, ResourceId};
use serde::Serialize;
/// A proto-node declaration at one version, written `identifier@version`.
@@ -38,4 +38,8 @@ pub trait DeclarationResolver {
fn resource_entry(&self, _declaration: Declaration) -> Option<ResourceEntry> {
None
}
/// What a resource this resolver knows decodes to, for converting a state to a runtime network.
fn proto(&self, _resource: ResourceId) -> Option<ProtoNode> {
None
}
}
+5 -1
View File
@@ -5,6 +5,8 @@
//! successor on the typed `Registry`. The `migration-runner` crate applies both. Design rationale
//! lives in `node-graph/rfcs/document-format-migrations.md`.
#[cfg(feature = "typed")]
mod compiler;
#[cfg(feature = "typed")]
mod connector;
#[cfg(feature = "typed")]
@@ -20,6 +22,8 @@ mod value;
#[cfg(feature = "typed")]
mod view;
#[cfg(feature = "typed")]
pub use compiler::{Compiler, MigrationHost, ValueType};
#[cfg(feature = "typed")]
pub use connector::{InputConnector, NewNode, OutputConnector};
#[cfg(feature = "typed")]
@@ -40,7 +44,7 @@ pub use registry::{register_migration, registered_migrations};
#[cfg(feature = "typed")]
pub use value::{encode, literal, literal_of};
#[cfg(feature = "typed")]
pub use view::{AddedNode, AnchorContext, Downstream, Edits, Graph, Inputs, InputsEdit, Node, Region, Upstream, View};
pub use view::{AddedNode, AnchorContext, Downstream, Edits, Graph, Inputs, InputsEdit, Node, Region, Target, Upstream, View};
// For the registration `#[migration]`, `rename!`, and `format_migration!` generate
#[doc(hidden)]
+5 -1
View File
@@ -4,12 +4,16 @@ use crate::{AnchorContext, Declaration, Edits, MigrationError, Region};
pub trait NodeMigration: Send + Sync {
/// The declaration whose nodes are anchors.
fn source(&self) -> Declaration;
/// The declaration the runner switches anchors to.
/// The declaration the runner switches anchors to, unless a run chooses one of its [`pins`](Self::pins) through [`Target`](crate::Target).
fn target(&self) -> Declaration;
/// Declarations the body names, which order it after the migration producing each and before the one consuming it.
fn pins(&self) -> &'static [Declaration] {
&[]
}
/// Whether the body takes an `Option<&dyn Compiler>`, which orders it as late as its dependencies allow.
fn asks_compiler(&self) -> bool {
false
}
/// The union of the regions the migration's parameters read and edit.
fn footprint(&self) -> Region;
/// Run on one anchor, returning what its views recorded.
+50 -1
View File
@@ -1,4 +1,4 @@
use crate::{Declaration, DeclarationResolver, InputConnector, MigrationError, NewNode, OutputConnector};
use crate::{Compiler, Declaration, DeclarationResolver, InputConnector, MigrationError, NewNode, OutputConnector};
use document_graph_storage::{InputSlot, NetworkId, NodeId, NodeInput, Registry, TimeStamp};
use std::ops::Deref;
@@ -19,6 +19,11 @@ impl Region {
Self(self.0 | other.0)
}
/// Whether a footprint reads the graph around its anchor, which needs a whole state rather than one in the middle of an interaction.
pub const fn reads_network(self) -> bool {
self.overlaps(Self::NETWORK)
}
const fn overlaps(self, other: Self) -> bool {
self.0 & other.0 != 0
}
@@ -69,6 +74,7 @@ pub struct AnchorContext<'a> {
source: Declaration,
target: Declaration,
resolver: &'a dyn DeclarationResolver,
compiler: Option<&'a dyn Compiler>,
}
impl<'a> AnchorContext<'a> {
@@ -82,9 +88,21 @@ impl<'a> AnchorContext<'a> {
source,
target,
resolver,
compiler: None,
})
}
/// Offer the run a `compiler` describing the state this context reads.
pub fn with_compiler(mut self, compiler: Option<&'a dyn Compiler>) -> Self {
self.compiler = compiler;
self
}
/// What a migration's `Option<&dyn Compiler>` parameter receives.
pub fn compiler(&self) -> Option<&'a dyn Compiler> {
self.compiler
}
pub fn source_node(&self) -> &Node<'a> {
&self.anchor
}
@@ -195,6 +213,8 @@ pub struct Edits {
pub added_nodes: Vec<AddedNode>,
pub removed_nodes: Vec<NodeId>,
pub connections: Vec<(OutputConnector, InputConnector)>,
/// The declaration this anchor switches to, when not the migration's target.
pub target: Option<Declaration>,
}
impl Edits {
@@ -205,6 +225,35 @@ impl Edits {
self.added_nodes.extend(other.added_nodes);
self.removed_nodes.extend(other.removed_nodes);
self.connections.extend(other.connections);
self.target = other.target.or(self.target);
}
}
/// Which declaration the anchor becomes, when that isn't the same for every anchor.
#[derive(Default)]
pub struct Target {
chosen: Option<Declaration>,
}
impl Target {
/// Switch this anchor to `declaration`, named with `decl!` in the migration's body, instead of the migration's target.
pub fn set(&mut self, declaration: Declaration) {
self.chosen = Some(declaration);
}
}
impl<'a> View<'a> for Target {
const REGION: Region = Region::ANCHOR;
fn extract(_context: &AnchorContext<'a>) -> Self {
Self::default()
}
fn into_edits(self) -> Result<Edits, MigrationError> {
Ok(Edits {
target: self.chosen,
..Default::default()
})
}
}
+21 -4
View File
@@ -14,8 +14,8 @@ use syn::{Error, FnArg, Ident, ItemFn, ReturnType, Type, parse_macro_input};
/// Turns a function into a node migration, named by its source and target declarations:
/// `#[migration("module::node"@1 => @2)]` for a version step, `#[migration("module::old"@1 => "module::new"@2)]` for a replacement.
///
/// Parameters state what the migration reads and writes: `&Node` and `&Graph` read the source state, and each `&mut` parameter is a
/// view (`Inputs`, `Upstream`, `Downstream`) recording edits to its region. The function may return `()` or `Result<(), MigrationError>`.
/// Parameters state what the migration reads and writes: `&Node` and `&Graph` read the source state, `Option<&dyn Compiler>` asks what only the
/// compiler can tell about it, and each `&mut` parameter is a view (`Inputs`, `Upstream`, `Downstream`, `Target`) recording edits to its region. The function may return `()` or `Result<(), MigrationError>`.
///
/// Generates a unit struct named after the function in Pascal case implementing `NodeMigration`, and registers it.
#[proc_macro_attribute]
@@ -57,6 +57,7 @@ pub fn format_migration(input: TokenStream) -> TokenStream {
enum Argument {
Node,
Graph,
Compiler,
View(Box<Type>),
}
@@ -80,6 +81,7 @@ fn expand_migration(step: Step, function: ItemFn) -> syn::Result<TokenStream2> {
})
.collect();
let reads_graph = arguments.iter().any(|argument| matches!(argument, Argument::Graph));
let asks_compiler = arguments.iter().any(|argument| matches!(argument, Argument::Compiler));
// Call the function with the source state and one extracted view per `&mut` parameter
let view_bindings: Vec<Ident> = (0..views.len()).map(|index| format_ident!("__view_{index}")).collect();
@@ -87,6 +89,7 @@ fn expand_migration(step: Step, function: ItemFn) -> syn::Result<TokenStream2> {
let call_arguments = arguments.iter().map(|argument| match argument {
Argument::Node => quote!(context.source_node()),
Argument::Graph => quote!(&__graph),
Argument::Compiler => quote!(context.compiler()),
Argument::View(_) => {
let binding = &view_bindings[view_index];
view_index += 1;
@@ -118,7 +121,14 @@ fn expand_migration(step: Step, function: ItemFn) -> syn::Result<TokenStream2> {
}
};
let network_region = reads_graph.then(|| quote!(.union(#core::Region::NETWORK)));
let network_region = (reads_graph || asks_compiler).then(|| quote!(.union(#core::Region::NETWORK)));
let asks_compiler = asks_compiler.then(|| {
quote! {
fn asks_compiler(&self) -> bool {
true
}
}
});
let footprint = quote! {
fn footprint(&self) -> #core::Region {
#core::Region::ANCHOR #(.union(<#views as #core::View>::REGION))* #network_region
@@ -166,6 +176,7 @@ fn expand_migration(step: Step, function: ItemFn) -> syn::Result<TokenStream2> {
#target
}
#pins
#asks_compiler
#footprint
#run
}
@@ -182,8 +193,14 @@ fn classify(argument: &FnArg) -> syn::Result<Argument> {
let FnArg::Typed(typed) = argument else {
return Err(Error::new(argument.span(), "migrations are free functions"));
};
if let Type::Path(path) = &*typed.ty
&& path.path.segments.last().is_some_and(|segment| segment.ident == "Option")
{
return Ok(Argument::Compiler);
}
let Type::Reference(reference) = &*typed.ty else {
return Err(Error::new(typed.ty.span(), "migration parameters are `&Node`, `&Graph`, or `&mut` views"));
return Err(Error::new(typed.ty.span(), "migration parameters are `&Node`, `&Graph`, `Option<&dyn Compiler>`, or `&mut` views"));
};
if reference.mutability.is_some() {
+1 -4
View File
@@ -12,8 +12,5 @@ migration-core = { workspace = true, features = ["typed"] }
serde = { workspace = true }
[dev-dependencies]
document-graph-storage = { workspace = true, default-features = false }
migration-runner = { workspace = true, features = ["testing"] }
[package.metadata.cargo-shear]
# Frozen mirrors of stored values, once a node migration needs one
ignored = ["serde"]
@@ -2,3 +2,4 @@
mod passthrough_from_upload_texture_node;
mod renames;
mod vary_colors_from_assign_colors;
@@ -0,0 +1,131 @@
use migration_core::{Declaration, Downstream, Inputs, MigrationError, NewNode, Node, NodeInput, OutputConnector, Target, decl, literal_of, migration};
use serde::{Deserialize, Serialize};
const FILL: u32 = 1;
const STROKE: u32 = 2;
/// Frozen mirror of the `TaggedValue` variant this migration reads.
#[derive(Serialize, Deserialize)]
enum Tagged {
Bool(bool),
}
/// Assign Colors splits by its Fill and Stroke toggles into Vary Fill Colors, Vary Stroke Colors, or both in a row, with the same parameters.
/// A wired toggle counts as enabled, and with both off it only ever passed its content through, which a Passthrough still does. With both on,
/// the stroke goes downstream of the anchor so toggling never rewires the content, since a wire written to a removed node would revive it.
#[migration("graphene_core::vector::AssignColorsNode"@1 => "graphene_core::vector::VaryFillColorsNode"@2)]
pub fn vary_colors_from_assign_colors(node: &Node, inputs: &mut Inputs, downstream: &mut Downstream, target: &mut Target) -> Result<(), MigrationError> {
let slots: Vec<NodeInput> = node.inputs().iter().map(|slot| slot.input.clone()).collect();
if slots.len() != 8 {
return Err(MigrationError::invariant("Assign Colors has eight inputs"));
}
let enabled = |slot: u32| !matches!(literal_of::<Tagged>(&slots[slot as usize]), Some(Tagged::Bool(false)));
let (fill, stroke) = (enabled(FILL), enabled(STROKE));
let vary_fill: Declaration = decl!("graphene_core::vector::VaryFillColorsNode"@2);
let vary_stroke: Declaration = decl!("graphene_core::vector::VaryStrokeColorsNode"@1);
if !fill && !stroke {
target.set(decl!("graphene_core::ops::PassthroughNode"@2));
inputs.truncate(1);
return Ok(());
}
inputs.remove(STROKE);
inputs.remove(FILL);
if !fill {
target.set(vary_stroke);
return Ok(());
}
target.set(vary_fill);
if stroke {
let consumers = downstream.consumers(0);
let mut stroke_inputs = vec![NodeInput::Node { id: node.id(), index: 0 }];
stroke_inputs.extend(slots[3..].iter().cloned());
let strokes = downstream.add_node(NewNode {
declaration: vary_stroke,
inputs: stroke_inputs,
});
for consumer in consumers {
downstream.connect(OutputConnector { node: strokes, output: 0 }, consumer);
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
const ASSIGN_COLORS: Declaration = decl!("graphene_core::vector::AssignColorsNode"@1);
fn contract() -> SourceContract {
// Only the content can read another Assign Colors, since the other inputs don't take its output type
SourceContract {
reads_own_output: |slot| slot == 0,
..SourceContract::new(8, |random, slot| match slot {
1 | 2 => literal(Tagged::Bool(random.below(2) == 0)),
_ => literal(random.below(4) as f64),
})
}
}
fn node(fill: bool, stroke: bool) -> Vec<NodeInput> {
let parameter = |number: u32| literal(f64::from(number));
vec![
parameter(0),
literal(Tagged::Bool(fill)),
literal(Tagged::Bool(stroke)),
parameter(3),
parameter(4),
parameter(5),
parameter(6),
parameter(7),
]
}
fn migrated_declaration(fill: bool, stroke: bool) -> (Option<Declaration>, usize) {
let mut fixture = Fixture::new(&VaryColorsFromAssignColors);
let anchor = fixture.add(ASSIGN_COLORS, node(fill, stroke));
let migrated = fixture.migrate(&VaryColorsFromAssignColors).unwrap();
(fixture.declaration_of(&migrated, anchor), fixture.inputs(&migrated, anchor).len())
}
#[test]
fn rewrites_history() {
check_commutation(&VaryColorsFromAssignColors, &contract());
check_undo(&VaryColorsFromAssignColors, &contract());
}
#[test]
fn each_toggle_chooses_its_node() {
assert_eq!(migrated_declaration(true, false), (Some(decl!("graphene_core::vector::VaryFillColorsNode"@2)), 6));
assert_eq!(migrated_declaration(false, true), (Some(decl!("graphene_core::vector::VaryStrokeColorsNode"@1)), 6));
assert_eq!(migrated_declaration(false, false), (Some(decl!("graphene_core::ops::PassthroughNode"@2)), 1));
}
#[test]
fn both_toggles_chain_fill_into_stroke() {
let mut fixture = Fixture::new(&VaryColorsFromAssignColors);
let anchor = fixture.add(ASSIGN_COLORS, node(true, true));
fixture.export(NodeInput::Node { id: anchor, index: 0 });
let migrated = fixture.migrate(&VaryColorsFromAssignColors).unwrap();
assert_eq!(fixture.declaration_of(&migrated, anchor), Some(decl!("graphene_core::vector::VaryFillColorsNode"@2)));
assert_eq!(fixture.inputs(&migrated, anchor)[0], literal(0.));
let export = migrated.networks[&document_graph_storage::ROOT_NETWORK].exports[0].target.clone();
let Some(NodeInput::Node { id: strokes, .. }) = export else {
panic!("the export reads the stroke")
};
assert_eq!(fixture.declaration_of(&migrated, strokes), Some(decl!("graphene_core::vector::VaryStrokeColorsNode"@1)));
assert_eq!(fixture.inputs(&migrated, strokes)[0], NodeInput::Node { id: anchor, index: 0 });
}
}
+2
View File
@@ -27,6 +27,8 @@ pub enum RunnerError {
Format { from: u32, error: MigrationError },
#[error("migration from {migration} failed on node {anchor:?}: {error}")]
Migration { migration: Declaration, anchor: NodeId, error: MigrationError },
#[error("node {anchor:?} chose {target}, which the migration from {migration} doesn't name")]
UnnamedTarget { migration: Declaration, anchor: NodeId, target: Declaration },
#[error("node {anchor:?} adds two nodes of {declaration} under the key {key:?}")]
DuplicateAddedNode { anchor: NodeId, declaration: Declaration, key: String },
#[error("added node {0:?} already exists")]
+129 -18
View File
@@ -2,8 +2,8 @@
use crate::RunnerError;
use document_graph_storage::delta::compute_deltas;
use document_graph_storage::{Delta, Implementation, Node, NodeId, Registry, RegistryDelta, ResourceHash, ResourceId, Rev, apply_retired_op};
use migration_core::{AnchorContext, Declaration, DeclarationResolver, Edits, InputConnector, InputsEdit, NodeMigration, OutputConnector};
use document_graph_storage::{Delta, Implementation, NetworkId, Node, NodeId, NodeInput, ProtoNode, Registry, RegistryDelta, ResourceHash, ResourceId, Rev, apply_retired_op};
use migration_core::{AnchorContext, Compiler, Declaration, DeclarationResolver, Edits, InputConnector, InputsEdit, MigrationHost, NodeMigration, OutputConnector};
use std::collections::{HashMap, HashSet};
/// A [`DeclarationResolver`] over a fixed set of declarations for tests, whose resource IDs derive from `identifier@version` rather than the encoded declarations documents store.
@@ -49,17 +49,99 @@ impl DeclarationResolver for DeclarationTable {
fn resource(&self, declaration: Declaration) -> ResourceId {
Self::resource_id(declaration)
}
fn proto(&self, resource: ResourceId) -> Option<ProtoNode> {
let declaration = self.declaration(resource)?;
Some(ProtoNode {
identifier: declaration.identifier.to_string(),
version: declaration.version,
attributes: Default::default(),
})
}
}
/// `M`: run `migration` on every anchor in `source` and apply the edits. Every run reads `source`, so no run observes another's edits.
pub(crate) fn apply_migration(migration: &dyn NodeMigration, source: &Registry, resolver: &dyn DeclarationResolver) -> Result<Registry, RunnerError> {
/// A migration asking the compiler runs upstream anchors first instead, in rounds, since the compiler can't describe what's still in the old shape.
pub(crate) fn apply_migration(migration: &dyn NodeMigration, source: &Registry, resolver: &dyn DeclarationResolver, host: Option<&dyn MigrationHost>) -> Result<Registry, RunnerError> {
let anchors = anchors(migration.source(), source, resolver);
if anchors.is_empty() {
return Ok(source.clone());
}
let Some(host) = host.filter(|_| migration.asks_compiler()) else {
return apply_runs(migration, source, &anchors, resolver, None);
};
let mut state = source.clone();
let mut remaining = anchors;
while !remaining.is_empty() {
let ready = upstream_most(&state, &remaining);
let compiler = host.compiler(&state, resolver);
state = apply_runs(migration, &state, &ready, resolver, compiler.as_deref())?;
remaining.retain(|anchor| !ready.contains(anchor));
}
Ok(state)
}
/// The `anchors` with no other of them upstream, or all of them if they form a cycle. O(registry) per anchor.
fn upstream_most(registry: &Registry, anchors: &[NodeId]) -> Vec<NodeId> {
let mut callers: HashMap<NetworkId, Vec<&Node>> = HashMap::new();
for node in registry.node_instances.values() {
if let Implementation::Network(network) = node.implementation() {
callers.entry(*network).or_default().push(node);
}
}
let others: HashSet<NodeId> = anchors.iter().copied().collect();
let reads_another = |anchor: NodeId| {
let mut visited = HashSet::from([anchor]);
let mut pending = vec![anchor];
while let Some(id) = pending.pop() {
let Some(node) = registry.node_instances.get(&id) else { continue };
let mut read = |input: &NodeInput| {
if let NodeInput::Node { id, .. } = input
&& visited.insert(*id)
{
pending.push(*id);
}
};
for slot in node.inputs() {
read(&slot.input);
if let NodeInput::Import { index } = slot.input {
for caller in callers.get(&node.network()).into_iter().flatten() {
if let Some(slot) = caller.inputs().get(index as usize) {
read(&slot.input);
}
}
}
}
if let Implementation::Network(network) = node.implementation()
&& let Some(network) = registry.networks.get(network)
{
for target in network.exports.iter().filter_map(|export| export.target.as_ref()) {
read(target);
}
}
}
visited.iter().any(|id| *id != anchor && others.contains(id))
};
let ready: Vec<NodeId> = anchors.iter().copied().filter(|anchor| !reads_another(*anchor)).collect();
if ready.is_empty() { anchors.to_vec() } else { ready }
}
/// Run `migration` on `anchors` and apply the edits, with every run reading `source`.
fn apply_runs(migration: &dyn NodeMigration, source: &Registry, anchors: &[NodeId], resolver: &dyn DeclarationResolver, compiler: Option<&dyn Compiler>) -> Result<Registry, RunnerError> {
let mut target = source.clone();
let mut runs = Vec::new();
for anchor in anchors(migration.source(), source, resolver) {
for anchor in anchors.iter().copied() {
let Some(context) = AnchorContext::new(source, anchor, migration.source(), migration.target(), resolver) else {
continue;
};
let context = context.with_compiler(compiler);
let edits = migration.run(&context).map_err(|error| RunnerError::Migration {
migration: migration.source(),
anchor,
@@ -91,15 +173,24 @@ pub(crate) fn apply_migration(migration: &dyn NodeMigration, source: &Registry,
}
}
let target_implementation = Implementation::ProtoNode(resolver.resource(migration.target()));
for (anchor, _) in &runs {
if let Some(node) = target.node_instances.get_mut(anchor) {
*node.implementation_mut() = target_implementation.clone();
let mut used_declarations = vec![migration.target()];
for (anchor, edits) in &runs {
let chosen = edits.target.unwrap_or(migration.target());
if chosen != migration.target() && !migration.pins().contains(&chosen) {
return Err(RunnerError::UnnamedTarget {
migration: migration.source(),
anchor: *anchor,
target: chosen,
});
}
}
let added_declarations = runs.iter().flat_map(|(_, edits)| edits.added_nodes.iter().map(|added| added.node.declaration));
for declaration in std::iter::once(migration.target()).chain(added_declarations) {
if let Some(node) = target.node_instances.get_mut(anchor) {
*node.implementation_mut() = Implementation::ProtoNode(resolver.resource(chosen));
}
used_declarations.push(chosen);
used_declarations.extend(edits.added_nodes.iter().map(|added| added.node.declaration));
}
for declaration in used_declarations {
if let Some(entry) = resolver.resource_entry(declaration) {
target.resources.entry(resolver.resource(declaration)).or_insert(entry);
}
@@ -197,14 +288,34 @@ struct Branch {
/// Undoing and then editing leaves an abandoned branch, which rewrites like any other since each delta only depends on its ancestors.
/// Fails on a delta that merges branches, or whose parent isn't in `history`.
///
/// A migration reading the graph or asking the compiler needs whole states, so it only runs at the boundaries undo can land on, the end of an interaction,
/// and rewrites everything since the last one as a single chain. Each delta inside maps to the boundary before it, and `kept` names further states to keep.
///
/// Each delta costs one full evaluation of `M` and one full diff, so this is O(history × registry), until the RFC's footprint-scoped
/// evaluation lands. A state is only copied where history branches.
pub(crate) fn rewrite_history(migration: &dyn NodeMigration, history: &[Delta], resolver: &dyn DeclarationResolver) -> Result<RewrittenHistory, RunnerError> {
pub(crate) fn rewrite_history(
migration: &dyn NodeMigration,
history: &[Delta],
resolver: &dyn DeclarationResolver,
host: Option<&dyn MigrationHost>,
kept: &HashSet<Rev>,
) -> Result<RewrittenHistory, RunnerError> {
let mut children: HashMap<Option<Rev>, usize> = HashMap::new();
let mut child_authors: HashMap<Rev, HashSet<_>> = HashMap::new();
for delta in history {
*children.entry(delta.parent).or_default() += 1;
if let Some(parent) = delta.parent {
child_authors.entry(parent).or_default().insert(delta.author);
}
}
let child_counts = children.clone();
let whole_states_only = migration.footprint().reads_network();
let is_boundary = |delta: &Delta| {
let continues_alone = child_counts.get(&Some(delta.id)) == Some(&1) && child_authors.get(&delta.id).is_some_and(|authors| authors.contains(&delta.author));
delta.is_interaction_end() || !continues_alone || kept.contains(&delta.id)
};
let mut branches = HashMap::from([(
None,
Branch {
@@ -234,12 +345,12 @@ pub(crate) fn rewrite_history(migration: &dyn NodeMigration, history: &[Delta],
apply_retired_op(&mut branch.original, delta.kind.clone(), delta.timestamp)?;
let chain = if passes_through(&delta.kind) {
vec![delta.kind.clone()]
} else {
let migrated = apply_migration(migration, &branch.original, resolver)?;
compute_deltas(&branch.rewritten, &migrated)
};
let passes = passes_through(&delta.kind);
let mut chain = if passes { vec![delta.kind.clone()] } else { Vec::new() };
if if whole_states_only { is_boundary(delta) } else { !passes } {
let migrated = apply_migration(migration, &branch.original, resolver, host)?;
chain.extend(compute_deltas(&branch.rewritten, &migrated));
}
check_single_writes(&chain)?;
// Every op of the chain shares the original's timestamp, which orders it after everything the original saw
+19 -8
View File
@@ -3,12 +3,12 @@
use crate::node::{apply_migration, rewrite_history};
use crate::{RewrittenHistory, RunnerError};
use document_graph_storage::{Delta, Implementation, Node, Registry, RegistryDelta, Rev};
use migration_core::{Declaration, DeclarationResolver, NodeMigration};
use std::collections::{BTreeSet, HashMap};
use migration_core::{Declaration, DeclarationResolver, MigrationHost, NodeMigration};
use std::collections::{BTreeSet, HashMap, HashSet};
/// Order `migrations` so each runs after the one producing its source and before the one consuming its target, and pinned
/// declarations exist in exactly the version the body names. Unrelated migrations order by source declaration, so the result
/// doesn't depend on registration order. Kahn's algorithm, O(n²) in the number of migrations to find edges.
/// doesn't depend on registration order, except that those asking the compiler go last, so what they ask about is in its current shape. Kahn's algorithm, O(n²) in the number of migrations to find edges.
pub fn order_migrations(migrations: &[&'static dyn NodeMigration]) -> Result<Vec<&'static dyn NodeMigration>, RunnerError> {
let mut migrations = migrations.to_vec();
migrations.sort_by_key(|migration| (migration.source(), migration.target()));
@@ -25,6 +25,8 @@ pub fn order_migrations(migrations: &[&'static dyn NodeMigration]) -> Result<Vec
});
}
migrations.sort_by_key(|migration| (migration.asks_compiler(), migration.source(), migration.target()));
let consumer = |declaration: Declaration| migrations.iter().position(|migration| migration.source() == declaration);
// `successors[a]` holds every migration that must run after `a`
@@ -73,8 +75,16 @@ pub fn order_migrations(migrations: &[&'static dyn NodeMigration]) -> Result<Vec
}
/// Rewrite `history` through every migration whose source declaration it references, in dependency order. A migration is pending
/// even when no live node uses its source, since a removed node keeps its old shape in history and undo can bring it back.
pub fn migrate_history(migrations: &[&'static dyn NodeMigration], history: Vec<Delta>, resolver: &dyn DeclarationResolver) -> Result<RewrittenHistory, RunnerError> {
/// even when no live node uses its source, since a removed node keeps its old shape in history and undo can bring it back. `kept` names the
/// states a cursor rests on, which even a migration only running at interaction boundaries has to keep.
pub fn migrate_history(
migrations: &[&'static dyn NodeMigration],
history: Vec<Delta>,
resolver: &dyn DeclarationResolver,
host: Option<&dyn MigrationHost>,
kept: impl IntoIterator<Item = Rev>,
) -> Result<RewrittenHistory, RunnerError> {
let mut kept: HashSet<Rev> = kept.into_iter().collect();
let mut revs: HashMap<Rev, Option<Rev>> = history.iter().map(|delta| (delta.id, Some(delta.id))).collect();
let mut deltas = history;
@@ -83,7 +93,8 @@ pub fn migrate_history(migrations: &[&'static dyn NodeMigration], history: Vec<D
continue;
}
let step = rewrite_history(migration, &deltas, resolver)?;
let step = rewrite_history(migration, &deltas, resolver, host, &kept)?;
kept = kept.iter().filter_map(|rev| step.revs.get(rev).copied().flatten()).collect();
for rev in revs.values_mut() {
*rev = rev.and_then(|rev| step.revs.get(&rev).copied().flatten());
}
@@ -94,10 +105,10 @@ pub fn migrate_history(migrations: &[&'static dyn NodeMigration], history: Vec<D
}
/// `M` of every migration on one state, for a document whose history can't be rewritten. Undo can't cross the result.
pub fn migrate_registry(migrations: &[&'static dyn NodeMigration], registry: &Registry, resolver: &dyn DeclarationResolver) -> Result<Registry, RunnerError> {
pub fn migrate_registry(migrations: &[&'static dyn NodeMigration], registry: &Registry, resolver: &dyn DeclarationResolver, host: Option<&dyn MigrationHost>) -> Result<Registry, RunnerError> {
let mut migrated = registry.clone();
for migration in order_migrations(migrations)? {
migrated = apply_migration(migration, &migrated, resolver)?;
migrated = apply_migration(migration, &migrated, resolver, host)?;
}
Ok(migrated)
}
+22 -7
View File
@@ -4,7 +4,8 @@
use crate::node::{apply_migration, rewrite_history};
use crate::{DeclarationTable, RunnerError, references, registry_at};
use document_graph_storage::{Delta, ExportSlot, Implementation, Network, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Session, UserId, apply_retired_op};
use migration_core::{Declaration, DeclarationResolver, NodeMigration, decl, literal, registered_migrations};
use migration_core::{Declaration, DeclarationResolver, MigrationHost, NodeMigration, decl, literal, registered_migrations};
use std::collections::HashSet;
/// A root network built node by node, for running one migration on.
pub struct Fixture {
@@ -47,7 +48,11 @@ impl Fixture {
}
pub fn migrate(&self, migration: &dyn NodeMigration) -> Result<Registry, RunnerError> {
apply_migration(migration, &self.registry, &self.table)
self.migrate_with(migration, None)
}
pub fn migrate_with(&self, migration: &dyn NodeMigration, host: Option<&dyn MigrationHost>) -> Result<Registry, RunnerError> {
apply_migration(migration, &self.registry, &self.table, host)
}
pub fn declaration_of(&self, registry: &Registry, node: NodeId) -> Option<Declaration> {
@@ -262,15 +267,20 @@ pub fn replay(deltas: &[Delta]) -> Registry {
/// `replay(rewrite(H)) == M(replay(H))` at every delta of generated histories, abandoned branches included, which also proves the rewrite
/// leaves none of the old shape behind.
pub fn check_commutation(migration: &dyn NodeMigration, contract: &SourceContract) {
check_commutation_with(migration, contract, None);
}
/// [`check_commutation`] for a migration asking `host`'s compiler.
pub fn check_commutation_with(migration: &dyn NodeMigration, contract: &SourceContract, host: Option<&dyn MigrationHost>) {
for seed in 1..50 {
let (session, table) = generate(migration, contract, seed, 40);
let history: Vec<Delta> = session.history().cloned().collect();
let rewritten = rewrite_history(migration, &history, &table).unwrap_or_else(|error| panic!("seed {seed}: rewrite failed: {error}"));
let rewritten = rewrite_history(migration, &history, &table, host, &HashSet::new()).unwrap_or_else(|error| panic!("seed {seed}: rewrite failed: {error}"));
for delta in &history {
let original = registry_at(&history, Some(delta.id)).unwrap_or_else(|error| panic!("seed {seed}: {error}"));
let expected = apply_migration(migration, &original, &table).unwrap_or_else(|error| panic!("seed {seed}: M failed: {error}"));
let expected = apply_migration(migration, &original, &table, host).unwrap_or_else(|error| panic!("seed {seed}: M failed: {error}"));
let replayed = registry_at(&rewritten.deltas, rewritten.revs[&delta.id]).unwrap_or_else(|error| panic!("seed {seed}: {error}"));
assert!(
replayed.value_equal(&expected),
@@ -292,10 +302,15 @@ pub fn check_commutation(migration: &dyn NodeMigration, contract: &SourceContrac
/// Undo walks the rewritten deltas' reverse priors, so undoing in rewritten history must land on `M` of the undone original.
pub fn check_undo(migration: &dyn NodeMigration, contract: &SourceContract) {
check_undo_with(migration, contract, None);
}
/// [`check_undo`] for a migration asking `host`'s compiler.
pub fn check_undo_with(migration: &dyn NodeMigration, contract: &SourceContract, host: Option<&dyn MigrationHost>) {
for seed in 1..20 {
let (session, table) = generate(migration, contract, seed, 30);
let history: Vec<Delta> = session.history().cloned().collect();
let rewritten = rewrite_history(migration, &history, &table).unwrap_or_else(|error| panic!("seed {seed}: rewrite failed: {error}"));
let rewritten = rewrite_history(migration, &history, &table, host, &HashSet::new()).unwrap_or_else(|error| panic!("seed {seed}: rewrite failed: {error}"));
let head = session.head_rev();
let migrated_head = head.and_then(|head| rewritten.revs[&head]);
@@ -305,13 +320,13 @@ pub fn check_undo(migration: &dyn NodeMigration, contract: &SourceContract) {
let mut original = Session::load(PeerId(1), UserId(1), original_registry, history, head, Vec::new(), 0);
let mut migrated = Session::load(PeerId(1), UserId(1), migrated_registry, rewritten.deltas, migrated_head, Vec::new(), 0);
let mut previous = apply_migration(migration, original.registry(), &table).unwrap_or_else(|error| panic!("seed {seed}: M failed: {error}"));
let mut previous = apply_migration(migration, original.registry(), &table, host).unwrap_or_else(|error| panic!("seed {seed}: M failed: {error}"));
for undo in 0..5 {
// An interaction that only touched what `M` drops left no delta in the rewrite, so undo there passes over it
let mut expected = previous.clone();
while expected.value_equal(&previous) && original.can_undo() {
original.undo().expect("can_undo said so");
expected = apply_migration(migration, original.registry(), &table).unwrap_or_else(|error| panic!("seed {seed}, undo {undo}: M failed: {error}"));
expected = apply_migration(migration, original.registry(), &table, host).unwrap_or_else(|error| panic!("seed {seed}, undo {undo}: M failed: {error}"));
}
if expected.value_equal(&previous) {
break;
@@ -0,0 +1,269 @@
//! Migrations choosing a target per anchor, and asking the compiler, which only run on whole states.
use document_graph_storage::{Implementation, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Session, UserId};
use migration_core::{Compiler, DeclarationResolver, Graph, MigrationError, MigrationHost, NodeMigration, Target, ValueType, decl, literal, literal_of, migration};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_commutation_with, check_undo, check_undo_with};
use migration_runner::{DeclarationTable, RunnerError, migrate_history, order_migrations};
use std::any::type_name;
use std::sync::atomic::{AtomicUsize, Ordering};
/// Chooses by a literal toggle, at the version each target already has, rather than stepping them all.
#[migration("choice::toggle"@1 => "choice::on"@2)]
pub fn choice_by_toggle(node: &migration_core::Node, target: &mut Target) {
if literal_of::<bool>(&node.inputs()[0].input) == Some(false) {
target.set(decl!("choice::off"@5));
}
}
/// Names a target only at runtime, which the runner can't order against anything.
#[migration("choice::unnamed"@1 => "choice::named"@2)]
pub fn choice_unnamed(target: &mut Target) {
target.set(migration_core::Declaration::new("choice::elsewhere", 1));
}
/// A fake value type, whose element stands for how many nodes are alive in the state the compiler describes.
struct Crowded(bool);
struct Many;
struct Few;
impl ValueType for Crowded {
fn element_name(&self) -> Option<&str> {
Some(if self.0 { type_name::<Many>() } else { type_name::<Few>() })
}
}
struct FakeCompiler(usize);
impl Compiler for FakeCompiler {
fn input_type(&self, _node: &migration_core::Node, _slot: usize) -> Option<Box<dyn ValueType>> {
Some(Box::new(Crowded(self.0 > 3)))
}
}
/// Chooses by what the compiler says, and only sees whole states.
#[migration("compiler::anchor"@1 => "compiler::few"@2)]
pub fn by_compiler(node: &migration_core::Node, compiler: Option<&dyn Compiler>, target: &mut Target) {
if compiler.and_then(|compiler| compiler.input_type(node, 0)).is_some_and(|value_type| value_type.element_is::<Many>()) {
target.set(decl!("compiler::many"@1));
}
}
/// Asks the compiler, and sorts before `order::static_late` by source, so only the runner's rule can put it after.
#[migration("order::asking"@1 => "order::asked"@2)]
pub fn order_asking(_compiler: Option<&dyn Compiler>) {}
#[migration("order::static_late"@1 => @2)]
pub fn order_static_late() {}
/// Asks the compiler, but `order::inspector` inspects what it produces, so it has to run first after all.
#[migration("order::pinned_asking"@1 => "order::produced"@2)]
pub fn order_pinned_asking(_compiler: Option<&dyn Compiler>) {}
#[migration("order::inspector"@1 => @2)]
pub fn order_inspector() {
let _ = decl!("order::produced"@2);
}
/// Reads the graph, which doesn't ask the host but still only sees whole states.
#[migration("compiler::graph_reader"@1 => @2)]
pub fn graph_reader(_graph: &Graph) -> Result<(), MigrationError> {
GRAPH_READS.fetch_add(1, Ordering::Relaxed);
Ok(())
}
static GRAPH_READS: AtomicUsize = AtomicUsize::new(0);
#[derive(Default)]
pub struct AnswerHost {
asked: AtomicUsize,
}
impl MigrationHost for AnswerHost {
fn compiler(&self, state: &Registry, _resolver: &dyn DeclarationResolver) -> Option<Box<dyn Compiler + '_>> {
self.asked.fetch_add(1, Ordering::Relaxed);
Some(Box::new(FakeCompiler(state.node_instances.len())))
}
}
fn wire(id: NodeId) -> NodeInput {
NodeInput::Node { id, index: 0 }
}
/// A history of one interaction per entry in `interactions`, each adding that many nodes implementing the `source` of `migration`.
fn history_of(migration: &dyn NodeMigration, table: &mut DeclarationTable, interactions: &[usize]) -> Session {
table.register_migration(migration);
let resource = table.register(migration.source());
let mut session = Session::with_identity(PeerId(1), UserId(1));
session
.stage_computed_ops(vec![RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Default::default(),
}])
.unwrap();
session.retire_all().unwrap();
for nodes in interactions {
let mut last = None;
for _ in 0..*nodes {
let id = session.next_node_id();
let node = Node::new(ROOT_NETWORK, Implementation::ProtoNode(resource), 0);
session.stage_computed_ops(vec![RegistryDelta::AddNode { id, node }]).unwrap();
last = session.retire_all().unwrap().last().copied();
}
session.mark_interaction_end(last.expect("an interaction adds nodes"));
}
session
}
#[test]
fn each_anchor_chooses_its_target() {
let mut fixture = Fixture::new(&ChoiceByToggle);
let on = fixture.add(ChoiceByToggle.source(), vec![literal(true)]);
let off = fixture.add(ChoiceByToggle.source(), vec![literal(false)]);
let migrated = fixture.migrate(&ChoiceByToggle).unwrap();
assert_eq!(fixture.declaration_of(&migrated, on), Some(decl!("choice::on"@2)));
assert_eq!(fixture.declaration_of(&migrated, off), Some(decl!("choice::off"@5)));
}
#[test]
fn a_choice_changing_across_history_commutes() {
let contract = SourceContract::new(1, |random, _| literal(random.below(2) == 0));
check_commutation(&ChoiceByToggle, &contract);
check_undo(&ChoiceByToggle, &contract);
}
#[test]
fn a_target_the_body_does_not_name_fails() {
let mut fixture = Fixture::new(&ChoiceUnnamed);
fixture.add(ChoiceUnnamed.source(), vec![]);
assert!(matches!(fixture.migrate(&ChoiceUnnamed), Err(RunnerError::UnnamedTarget { .. })));
}
#[test]
fn the_compiler_decides_per_state() {
let host = AnswerHost::default();
let mut few = Fixture::new(&ByCompiler);
let anchor = few.add(ByCompiler.source(), vec![]);
let migrated = few.migrate_with(&ByCompiler, Some(&host)).unwrap();
assert_eq!(few.declaration_of(&migrated, anchor), Some(decl!("compiler::few"@2)));
let mut many = Fixture::new(&ByCompiler);
let anchor = many.add(ByCompiler.source(), vec![]);
for _ in 0..3 {
many.add(decl!("compiler::other"@1), vec![]);
}
let migrated = many.migrate_with(&ByCompiler, Some(&host)).unwrap();
assert_eq!(many.declaration_of(&migrated, anchor), Some(decl!("compiler::many"@1)));
}
#[test]
fn without_a_host_it_takes_the_fallback() {
let mut fixture = Fixture::new(&ByCompiler);
let anchor = fixture.add(ByCompiler.source(), vec![]);
for _ in 0..3 {
fixture.add(decl!("compiler::other"@1), vec![]);
}
let migrated = fixture.migrate(&ByCompiler).unwrap();
assert_eq!(fixture.declaration_of(&migrated, anchor), Some(decl!("compiler::few"@2)));
}
#[test]
fn asking_the_compiler_goes_last_unless_a_dependency_says_otherwise() {
let position = |ordered: &[&'static dyn NodeMigration], source: migration_core::Declaration| ordered.iter().position(|migration| migration.source() == source).unwrap();
let ordered = order_migrations(&[&OrderAsking, &OrderStaticLate]).unwrap();
assert!(position(&ordered, OrderStaticLate.source()) < position(&ordered, OrderAsking.source()));
let ordered = order_migrations(&[&OrderPinnedAsking, &OrderInspector]).unwrap();
assert!(position(&ordered, OrderPinnedAsking.source()) < position(&ordered, OrderInspector.source()));
}
#[test]
fn upstream_anchors_run_before_those_reading_them() {
let host = AnswerHost::default();
let mut fixture = Fixture::new(&ByCompiler);
let first = fixture.add(ByCompiler.source(), vec![]);
let second = fixture.add(ByCompiler.source(), vec![wire(first)]);
fixture.add(ByCompiler.source(), vec![wire(second)]);
fixture.migrate_with(&ByCompiler, Some(&host)).unwrap();
assert_eq!(host.asked.load(Ordering::Relaxed), 3, "one round per level of nesting");
}
#[test]
fn unrelated_anchors_share_one_round() {
let host = AnswerHost::default();
let mut fixture = Fixture::new(&ByCompiler);
for _ in 0..3 {
fixture.add(ByCompiler.source(), vec![]);
}
fixture.migrate_with(&ByCompiler, Some(&host)).unwrap();
assert_eq!(host.asked.load(Ordering::Relaxed), 1);
}
#[test]
fn the_compiler_is_only_asked_at_interaction_boundaries() {
let mut table = DeclarationTable::default();
let session = history_of(&ByCompiler, &mut table, &[4, 3]);
let history: Vec<_> = session.history().cloned().collect();
let host = AnswerHost::default();
let rewritten = migrate_history(&[&ByCompiler], history.clone(), &table, Some(&host), session.head_rev()).unwrap();
// The root network's interaction has no anchors yet, so it never asks, and each of the other two asks once for its one round of unrelated anchors
assert_eq!(host.asked.load(Ordering::Relaxed), 2);
// A delta inside an interaction has no state of its own, and an interaction end does
let ends: Vec<_> = history.iter().filter(|delta| delta.is_interaction_end()).collect();
assert_eq!(ends.len(), 2);
for end in ends {
assert!(rewritten.revs[&end.id].is_some());
let rev = rewritten.revs[&end.id].unwrap();
assert!(rewritten.deltas.iter().any(|delta| delta.id == rev && delta.is_interaction_end()));
}
}
#[test]
fn a_cursor_inside_an_interaction_keeps_its_state() {
let mut table = DeclarationTable::default();
let session = history_of(&ByCompiler, &mut table, &[4]);
let history: Vec<_> = session.history().cloned().collect();
let inside = history[history.len() - 2].id;
let host = AnswerHost::default();
let rewritten = migrate_history(&[&ByCompiler], history, &table, Some(&host), [inside]).unwrap();
assert_eq!(host.asked.load(Ordering::Relaxed), 2, "the cursor and the interaction's end");
assert!(rewritten.revs[&inside].is_some());
}
#[test]
fn reading_the_graph_also_only_sees_whole_states() {
let mut table = DeclarationTable::default();
let session = history_of(&GraphReader, &mut table, &[5]);
let history: Vec<_> = session.history().cloned().collect();
let before = GRAPH_READS.load(Ordering::Relaxed);
migrate_history(&[&GraphReader], history, &table, None, session.head_rev()).unwrap();
// All five anchors exist at the one boundary, and the anchorless root network's boundary reads nothing
assert_eq!(GRAPH_READS.load(Ordering::Relaxed) - before, 5);
}
#[test]
fn asking_the_compiler_commutes() {
let host = AnswerHost::default();
let contract = SourceContract::new(1, |_, _| literal(0.));
check_commutation_with(&ByCompiler, &contract, Some(&host));
check_undo_with(&ByCompiler, &contract, Some(&host));
}
@@ -1,3 +1,4 @@
mod compiler;
mod examples;
mod registration;
mod rewrite;
@@ -1,5 +1,6 @@
//! What `#[migration]` and `rename!` generate and register, and how the runner orders and chains the registry.
use crate::compiler;
use crate::examples::{ExtractXyToSplit, OpacityToggles, ROTATION, Tagged, TransformDegrees};
use document_graph_storage::{Delta, Implementation, Network, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, RegistryDelta, Session, UserId};
use migration_core::{AnchorContext, Declaration, DeclarationResolver, Edits, MigrationError, NodeMigration, Region, decl, literal, registered_migrations};
@@ -13,8 +14,16 @@ fn every_migration_registers_once() {
let mut expected = vec![
decl!("blending_nodes::opacity"@1),
decl!("compiler::anchor"@1),
decl!("compiler::graph_reader"@1),
decl!("choice::toggle"@1),
decl!("choice::unnamed"@1),
decl!("graphene_core::ops::AddNode"@1),
decl!("math_nodes::multiply"@1),
decl!("order::asking"@1),
decl!("order::inspector"@1),
decl!("order::pinned_asking"@1),
decl!("order::static_late"@1),
decl!("transform_nodes::transform"@1),
decl!("vector_nodes::angle_between"@1),
decl!("vector_nodes::extract_xy"@1),
@@ -198,7 +207,7 @@ fn migrate_history_chains_every_pending_migration() {
});
let history: Vec<Delta> = session.history().cloned().collect();
let migrated = migrate_history(&registered_migrations(), history.clone(), &table).unwrap();
let migrated = migrate_history(&registered_migrations(), history.clone(), &table, Some(&compiler::AnswerHost::default()), None).unwrap();
let registry = replay(&migrated.deltas);
let declaration_of = |id: NodeId| match registry.node_instances[&id].implementation() {
+3 -3
View File
@@ -1,8 +1,8 @@
//! Compares every node's API against a baseline commit, to find changes that need a version bump or a migration.
use crate::lineage::{MigrationStep, find_migrations};
use crate::lineage::{MigrationStep, find_all_migrations};
use crate::nodes::{NodeSource, find_nodes};
use crate::scaffold::{MIGRATIONS, NODE_CRATES};
use crate::scaffold::{MIGRATION_CRATES, NODE_CRATES};
use std::collections::HashMap;
use std::path::Path;
use std::process::{Command, Stdio};
@@ -10,7 +10,7 @@ use std::process::{Command, Stdio};
/// Fail if the nodes at the git ref `baseline` differ from the working tree's in a way documents would notice.
pub(crate) fn check_against(workspace: &Path, baseline: &str) -> Result<(), String> {
let current = find_nodes(&workspace.join(NODE_CRATES))?;
let migrations = find_migrations(&workspace.join(MIGRATIONS))?;
let migrations = find_all_migrations(workspace, &MIGRATION_CRATES)?;
let directory = std::env::temp_dir().join(format!("migration-api-baseline-{}", std::process::id()));
let baseline_nodes = extract_baseline(workspace, baseline, &directory).and_then(|()| find_nodes(&directory.join(NODE_CRATES)));
@@ -39,6 +39,18 @@ pub(crate) fn find_migrations(directory: &Path) -> Result<Vec<MigrationStep>, St
Ok(steps)
}
/// Every migration step of the crates at `directories` under `workspace`, leaving out those that don't exist.
pub(crate) fn find_all_migrations(workspace: &Path, directories: &[&str]) -> Result<Vec<MigrationStep>, String> {
let mut steps = Vec::new();
for directory in directories {
let directory = workspace.join(directory);
if directory.exists() {
steps.extend(find_migrations(&directory)?);
}
}
Ok(steps)
}
/// `file` is a module whose `mod child;` declarations live in `children`.
fn read_module(file: &Path, children: &Path, steps: &mut Vec<MigrationStep>) -> Result<(), String> {
let source = std::fs::read_to_string(file).map_err(|error| format!("{}: {error}", file.display()))?;
+1 -1
View File
@@ -119,7 +119,7 @@ fn check(workspace: &Path) -> Result<(), String> {
.into_iter()
.map(|node| (node.identifier, node.version))
.collect();
let migrations = lineage::find_migrations(&workspace.join(scaffold::MIGRATIONS))?;
let migrations = lineage::find_all_migrations(workspace, &scaffold::MIGRATION_CRATES)?;
let problems = lineage::lineage_problems(&nodes, &migrations);
if !problems.is_empty() {
return Err(problems.join("\n"));
@@ -7,6 +7,8 @@ use std::path::{Path, PathBuf};
pub(crate) const NODE_CRATES: &str = "node-graph";
pub(crate) const MIGRATIONS: &str = "document/migrations/nodes/src";
/// Every crate holding migrations, including those asking for a capability, which `new` doesn't scaffold.
pub(crate) const MIGRATION_CRATES: [&str; 2] = [MIGRATIONS, "document/migrations/compiled/src"];
/// `new` scaffolds every step missing between a node's newest migration and its version, `new <identifier>` does so for one node,
/// `new <old>@<version> <identifier>` replaces a node by another, and `rename <old>@<version> <identifier>` registers a finished rename.
+4
View File
@@ -124,6 +124,10 @@ impl Replica {
Some(Role::Host)
}
pub fn has_host(&self) -> bool {
self.current_host().is_some()
}
/// The link and id of the peer greeting as host. While two coexist this is the one with the lower id, which keeps
/// the role once they meet.
fn current_host(&self) -> Option<(TransportPeerId, PeerId)> {
+3 -1
View File
@@ -22,11 +22,13 @@ gpu = ["interpreted-executor/gpu", "dep:wgpu-executor"]
# Local dependencies
graphite-proc-macros = { workspace = true }
graph-craft = { workspace = true }
document-format = { workspace = true, features = ["migrations"] }
document-format = { workspace = true, features = ["migrations", "network"] }
migration-formats = { workspace = true }
migration-compiled = { workspace = true }
migration-nodes = { workspace = true }
document-graph-storage = { workspace = true, features = ["conversion"] }
document-container = { workspace = true }
peer-transport = { workspace = true }
graphene-hash = { workspace = true }
blake3 = { workspace = true }
interpreted-executor = { workspace = true }
+11 -28
View File
@@ -2,7 +2,7 @@ use crate::application::{Editor, Environment};
use crate::dispatcher::Dispatcher;
use crate::messages::prelude::*;
use crate::node_graph_executor::{NodeGraphExecutor, NodeRuntime};
use crate::task::{Clock, Scheduling, Spawn, Spawner};
use crate::task::{Spawn, Spawner};
use document_container::store::DocumentStore;
use graph_craft::application_io::PlatformApplicationIo;
use graph_craft::application_io::resource::ResourceStorage;
@@ -96,8 +96,6 @@ impl Builder<ReadyEditorBuilder, ReadyRuntimeBuilder, Spawner, u64> {
let RuntimeBuilder {
wake: runtime_wake,
mut application_io,
scheduling,
clock,
} = runtime;
graphene_std::uuid::set_uuid_seed(random_seed);
@@ -109,8 +107,7 @@ impl Builder<ReadyEditorBuilder, ReadyRuntimeBuilder, Spawner, u64> {
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
node_runtime.replace_application_io(application_io);
node_runtime.replace_task_executor(spawner, runtime_wake, clock);
node_runtime.set_scheduling(scheduling);
node_runtime.replace_task_executor(spawner, runtime_wake);
(Editor { dispatcher }, node_runtime)
}
@@ -187,18 +184,17 @@ impl<W, E, R> EditorBuilder<W, E, R, ()> {
pub struct RuntimeBuilder<W = (), A = ()> {
wake: W,
application_io: A,
clock: Arc<dyn Clock>,
scheduling: Scheduling,
}
impl RuntimeBuilder {
pub fn new(clock: Arc<dyn Clock>) -> Self {
Self {
wake: (),
application_io: (),
clock,
scheduling: Scheduling::default(),
}
pub fn new() -> Self {
Self { wake: (), application_io: () }
}
}
impl Default for RuntimeBuilder {
fn default() -> Self {
Self::new()
}
}
@@ -208,25 +204,12 @@ impl<A> RuntimeBuilder<(), A> {
RuntimeBuilder {
wake: Arc::new(wake),
application_io: self.application_io,
clock: self.clock,
scheduling: self.scheduling,
}
}
}
impl<W> RuntimeBuilder<W, ()> {
pub fn with_application_io(self, application_io: PlatformApplicationIo) -> RuntimeBuilder<W, PlatformApplicationIo> {
RuntimeBuilder {
wake: self.wake,
application_io,
clock: self.clock,
scheduling: self.scheduling,
}
}
}
impl<W, A> RuntimeBuilder<W, A> {
pub fn with_scheduling(self, scheduling: Scheduling) -> Self {
Self { scheduling, ..self }
RuntimeBuilder { wake: self.wake, application_io }
}
}
+3
View File
@@ -291,6 +291,7 @@ impl Dispatcher {
preferences: &self.message_handlers.preferences_message_handler,
current_tool: &self.message_handlers.tool_message_handler.tool_state.tool_data.active_tool_type,
tool_edit_target: &self.message_handlers.tool_message_handler.edit_target,
tools: &self.message_handlers.tool_message_handler,
reset_node_definitions_on_open: self.message_handlers.portfolio_message_handler.reset_node_definitions_on_open,
timing_information: self.message_handlers.animation_message_handler.timing_information(),
animation: &self.message_handlers.animation_message_handler,
@@ -305,6 +306,8 @@ impl Dispatcher {
menu_bar_message_handler.focus_document = self.message_handlers.portfolio_message_handler.workspace.panel_layout.focus_document;
let layout = &self.message_handlers.portfolio_message_handler.workspace.panel_layout;
menu_bar_message_handler.data_panel_open = layout.is_panel_present(PanelType::Data);
menu_bar_message_handler.session_panel_open = layout.is_panel_present(PanelType::Session);
menu_bar_message_handler.history_panel_open = layout.is_panel_present(PanelType::History);
menu_bar_message_handler.layers_panel_open = layout.is_panel_present(PanelType::Layers);
menu_bar_message_handler.inspector_open = layout.is_panel_present(PanelType::Inspector);
menu_bar_message_handler.message_logging_verbosity = self.message_handlers.debug_message_handler.message_logging_verbosity;
+1
View File
@@ -25,5 +25,6 @@ pub mod utility_types;
pub use document_container::store as document_store;
// Referenced so the linker keeps their self-registering migrations, which run as documents open
use migration_compiled as _;
use migration_formats as _;
use migration_nodes as _;
@@ -3,7 +3,8 @@ use crate::messages::prelude::*;
/// Lists the stored documents that stayed closed because another tab has them open.
pub struct DocumentsOpenElsewhereDialog {
pub documents: Vec<(DocumentId, String)>,
/// Id, name and whether it is in a live session.
pub documents: Vec<(DocumentId, String, bool)>,
}
impl DialogLayoutHolder for DocumentsOpenElsewhereDialog {
@@ -24,19 +25,23 @@ impl LayoutHolder for DocumentsOpenElsewhereDialog {
let mut rows = vec![
LayoutGroup::row(vec![TextLabel::new(format!("{count} {documents} open in another tab.")).bold(true).multiline(true).widget_instance()]),
LayoutGroup::row(vec![
TextLabel::new(format!("{are} closed here so the two tabs don't overwrite each other.\nA copy opens here as a separate document."))
.multiline(true)
.widget_instance(),
TextLabel::new(format!(
"{are} closed here so the two tabs don't overwrite each other.\nA copy is a separate document, while joining a session edits it live."
))
.multiline(true)
.widget_instance(),
]),
];
rows.extend(self.documents.iter().cloned().map(|(source, name)| {
rows.extend(self.documents.iter().cloned().map(|(source, name, shared)| {
let label = TextLabel::new(name.clone()).widget_instance();
let button = TextButton::new("Open a Copy")
let button = TextButton::new(if shared { "Join in This Tab" } else { "Open a Copy" })
.on_update(move |_| {
DialogMessage::CloseAndThen {
followups: vec![PortfolioMessage::OpenDocumentCopy { source, document_name: name.clone() }.into()],
}
.into()
let followup = if shared {
PortfolioMessage::JoinStoredSession { source }
} else {
PortfolioMessage::OpenDocumentCopy { source, document_name: name.clone() }
};
DialogMessage::CloseAndThen { followups: vec![followup.into()] }.into()
})
.widget_instance();
LayoutGroup::row(vec![label, Separator::new(SeparatorStyle::Unrelated).widget_instance(), button])
@@ -6,7 +6,7 @@ use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::utility_types::{
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, NodeGraphErrorDiagnostic,
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
};
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
@@ -140,6 +140,9 @@ pub enum FrontendMessage {
url: String,
},
TriggerClipboardRead,
TriggerSessionLinkCopy {
token: String,
},
TriggerClipboardWrite {
content: String,
},
@@ -190,6 +193,15 @@ pub enum FrontendMessage {
#[serde(rename = "box")]
box_selection: Option<BoxSelection>,
},
UpdateDocumentCursors {
cursors: Vec<FrontendRemoteCursor>,
},
UpdateHistoryPanel {
state: crate::messages::portfolio::history::utility_types::HistoryPanelState,
},
UpdateNodeGraphCursors {
cursors: Vec<FrontendRemoteCursor>,
},
UpdateContextMenuInformation {
#[serde(rename = "contextMenuInformation")]
context_menu_information: Option<ContextMenuInformation>,
@@ -12,6 +12,17 @@ pub struct DocumentInfo {
#[serde(default)]
pub path: Option<PathBuf>,
pub is_saved: bool,
/// `None` when not shared.
#[serde(default)]
pub session: Option<SessionStatus>,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum SessionStatus {
Connected,
/// The transport is down or the document isn't mounted. It reconnects on mount.
Disconnected,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints, from_wasm_abi))]
@@ -76,6 +76,7 @@ define_layout_target!(
NodeGraphControlBar,
/// The body of the Inspector containing many collapsable sections.
Inspector,
SessionPanel,
/// The contextual input key/mouse combination shortcuts shown in the status bar at the bottom of the window.
StatusBarHints,
/// The version information shown in the status bar at the bottom right of the window.
@@ -24,6 +24,8 @@ pub struct MenuBarMessageHandler {
pub show_storage_preferences: bool,
pub make_path_editable_is_allowed: bool,
pub data_panel_open: bool,
pub session_panel_open: bool,
pub history_panel_open: bool,
pub layers_panel_open: bool,
pub inspector_open: bool,
pub focus_document: bool,
@@ -687,6 +689,16 @@ impl LayoutHolder for MenuBarMessageHandler {
.tooltip_shortcut(action_shortcut!(WorkspaceMessageDiscriminant::ToggleDataPanelOpen))
.on_commit(|_| WorkspaceMessage::ToggleDataPanelOpen.into())
.disabled(self.focus_document),
MenuListEntry::new("Session")
.label("Session")
.icon(if self.session_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
.on_commit(|_| WorkspaceMessage::ToggleSessionPanelOpen.into())
.disabled(self.focus_document),
MenuListEntry::new("History")
.label("History")
.icon(if self.history_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
.on_commit(|_| WorkspaceMessage::ToggleHistoryPanelOpen.into())
.disabled(self.focus_document),
],
])
.widget_instance(),
@@ -2,7 +2,7 @@ use std::collections::VecDeque;
use std::collections::{BTreeMap, HashSet};
use document_graph_storage::{Declarations, Registry, Value};
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry, ResourceStorage};
use graph_craft::application_io::resource::{ResourceHash, ResourceId, ResourceRegistry, ResourceStorage};
use super::utility_types::network_interface::NodeNetworkInterface;
use super::utility_types::network_interface::editor_delta::{EditorDelta, StagingError, construct_batch};
@@ -35,6 +35,18 @@ pub struct DocumentHistory {
/// 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,
/// How storage undid each step on the legacy redo stack, aligned with its top.
undo_notes: Vec<UndoNote>,
}
#[derive(Clone, Debug)]
enum UndoNote {
/// The step was hot and got taken back.
Retracted(Vec<document_graph_storage::RegistryDelta>),
/// The step had retired and was dropped from the shared line.
Dropped(document_graph_storage::Rev),
/// The storage cursor moved back over the step.
Cursor,
}
/// Why [`DocumentHistory::move_cursor`] produced no interface.
@@ -77,6 +89,7 @@ impl DocumentHistory {
/// Clear the redo stack, called when a fresh edit invalidates the redo future.
pub fn clear_redo(&mut self) {
self.legacy_redo_stack.clear();
self.undo_notes.clear();
}
/// Add the resources referenced by every snapshot in both history stacks into `resources`, so
@@ -99,6 +112,10 @@ impl DocumentHistory {
self.storage.as_mut()
}
pub fn declarations(&self) -> &Declarations {
&self.declarations
}
/// 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();
@@ -112,9 +129,124 @@ impl DocumentHistory {
self.needs_whole_document_stage = true;
}
/// Retire the pending staged hot ops into durable Gdd history as one undo unit. Called at each undo-step
/// boundary (a new `StartTransaction`) and before undo/redo, so the per-`CommitTransaction` staging
/// coalesces into one interaction aligned with the legacy step. No-op while unmounted.
pub fn end_storage_interaction(&mut self) {
let Some(storage) = self.storage.as_mut() else { return };
if let Err(error) = storage.end_interaction() {
log::error!("Closing the storage interaction failed: {error}");
}
}
/// Undoes the latest step in storage alone. Returns whether storage undid it.
pub fn undo_in_storage(&mut self, in_session: bool) -> bool {
if self.legacy_undo_stack.is_empty() {
return false;
}
let note = if let Some(ops) = self.retract_storage_interaction() {
UndoNote::Retracted(ops)
} else if in_session && let Some(rev) = self.undo_retired_step() {
UndoNote::Dropped(rev)
} else {
return false;
};
if let Some(snapshot) = self.pop_undo() {
self.push_redo(snapshot);
}
self.note_undo(note);
true
}
/// Reverses [`undo_in_storage`](Self::undo_in_storage). Returns whether the next redo step was undone there.
pub fn redo_in_storage(&mut self) -> bool {
if self.legacy_redo_stack.is_empty() {
return false;
}
let reachable = self.storage.as_ref().is_some_and(|storage| storage.can_change_line());
let Some(note) = self
.undo_notes
.pop_if(|note| matches!(note, UndoNote::Retracted(_)) || (reachable && matches!(note, UndoNote::Dropped(_))))
else {
return false;
};
if let Some(snapshot) = self.pop_redo() {
self.push_undo(snapshot);
}
match note {
UndoNote::Retracted(ops) => self.restage_ops(ops),
UndoNote::Dropped(rev) => {
self.redo_retired_step(rev);
}
UndoNote::Cursor => {}
}
true
}
pub fn note_cursor_undo(&mut self) {
self.note_undo(UndoNote::Cursor);
}
pub fn forget_undo_note(&mut self) {
self.undo_notes.pop();
}
fn note_undo(&mut self, note: UndoNote) {
self.undo_notes.push(note);
let evicted = self.undo_notes.len().saturating_sub(self.legacy_redo_stack.len());
self.undo_notes.drain(..evicted);
}
fn retract_storage_interaction(&mut self) -> Option<Vec<document_graph_storage::RegistryDelta>> {
self.storage.as_mut()?.retract_interaction().unwrap_or_else(|error| {
log::error!("Taking the storage interaction back failed: {error}");
None
})
}
fn restage_ops(&mut self, ops: Vec<document_graph_storage::RegistryDelta>) {
let Some(storage) = self.storage.as_mut() else { return };
if let Err(error) = storage.restage_ops(ops) {
log::error!("Staging the redone step failed: {error}");
}
}
fn undo_retired_step(&mut self) -> Option<document_graph_storage::Rev> {
self.storage.as_mut()?.undo_retired_step().unwrap_or_else(|error| {
log::error!("Undoing the retired step failed: {error}");
None
})
}
pub fn resource_gc_roots(&self) -> HashSet<ResourceHash> {
self.storage.as_ref().map(|storage| storage.resource_gc_roots()).unwrap_or_default()
}
pub fn redo_retired_step(&mut self, rev: document_graph_storage::Rev) -> bool {
self.change_line(|storage| storage.redo_retired_step(rev), "Redoing the dropped step failed")
}
pub fn drop_step(&mut self, rev: document_graph_storage::Rev) -> bool {
self.change_line(|storage| storage.drop_step(rev), "Removing the step failed")
}
pub fn move_head_to(&mut self, rev: document_graph_storage::Rev) -> bool {
self.change_line(|storage| storage.move_head(rev), "Moving the head failed")
}
fn change_line(&mut self, change: impl FnOnce(&mut document_format::GddV1) -> Result<(), document_format::Error>, failure: &str) -> bool {
let Some(storage) = self.storage.as_mut().filter(|storage| storage.can_change_line()) else {
return false;
};
change(storage).inspect_err(|error| log::error!("{failure}: {error}")).is_ok()
}
/// Forgets the legacy snapshots once the head has moved off their line.
pub fn clear_legacy(&mut self) {
self.legacy_undo_stack.clear();
self.legacy_redo_stack.clear();
self.undo_notes.clear();
}
pub fn retire_storage_interaction(&mut self) {
let Some(storage) = self.storage.as_mut() else { return };
if let Err(error) = storage.retire_pending_interaction() {
@@ -124,10 +256,19 @@ impl DocumentHistory {
/// Stage a `CommitTransaction` into the `Gdd` working copy: the first commit writes the whole document,
/// every later one stages the `deltas` the store recorded. No-op while unmounted. Proto-node declaration
/// bytes go into `byte_store` (the app-global resource cache). The staged hot ops are retired by
/// [`retire_storage_interaction`](Self::retire_storage_interaction) at undo-step boundaries.
/// bytes go into `byte_store` (the app-global resource cache). The staged hot ops are closed into one
/// interaction by [`end_storage_interaction`](Self::end_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 Some(storage) = self.storage.as_mut() else { return };
if !self.stage_graph(deltas, interface, registry, byte_store) {
return;
}
self.persist_view_state(interface, view_settings);
}
/// [`stage_snapshot`](Self::stage_snapshot) without the view state. Returns whether the working copy took the batch.
pub fn stage_graph(&mut self, deltas: &[EditorDelta], interface: &NodeNetworkInterface, registry: &ResourceRegistry, byte_store: &dyn ResourceStorage) -> bool {
let Some(storage) = self.storage.as_mut() else { return false };
let staged = match self.needs_whole_document_stage {
true => Self::stage_whole_document(storage, interface, registry, byte_store),
@@ -148,14 +289,13 @@ impl DocumentHistory {
Ok(declarations) => {
self.declarations.extend(declarations);
self.needs_whole_document_stage = false;
true
}
Err(error) => {
log::error!("Storage snapshot staging failed: {error}");
return;
false
}
}
self.persist_view_state(interface, view_settings);
}
/// Converts the whole document and stages the difference from what the working copy holds.
@@ -235,15 +375,60 @@ impl DocumentHistory {
return Err(CursorMoveError::NotMoved);
}
self.rebuild_interface().ok_or(CursorMoveError::RebuildFailed)
}
/// Build a new interface from the working registry and cached declarations. `None` when it doesn't convert.
pub fn rebuild_interface(&self) -> Option<NodeNetworkInterface> {
let storage = self.storage.as_ref()?;
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
})
.inspect_err(|error| log::error!("Storage interface rebuild failed: {error}"))
.ok()
}
pub fn undecoded_declaration_hashes(&self) -> Vec<ResourceHash> {
let Some(storage) = self.storage.as_ref() else { return Vec::new() };
let mut hashes: Vec<ResourceHash> = storage
.session()
.all_declaration_resources()
.into_iter()
.filter_map(|(id, hash)| hash.filter(|_| !self.declarations.contains_key(&id)))
.collect();
hashes.sort_unstable();
hashes.dedup();
hashes
}
/// Cache a peer's resource as a declaration if one names its hash. Returns false when the bytes don't decode.
pub fn cache_declaration_bytes(&mut self, hash: ResourceHash, bytes: &[u8]) -> bool {
let Some(storage) = self.storage.as_ref() else { return true };
let referencing: Vec<ResourceId> = storage
.session()
.all_declaration_resources()
.into_iter()
.filter_map(|(id, declaration_hash)| (declaration_hash == Some(hash)).then_some(id))
.collect();
if referencing.is_empty() {
return true;
}
match document_graph_storage::decode_declaration(bytes) {
Ok(declaration) => {
self.declarations.extend(referencing.into_iter().map(|id| (id, declaration.clone())));
true
}
Err(error) => {
log::error!("Failed to deserialize a received ProtoNode declaration: {error}");
false
}
}
}
/// Step the cursor back the other way, undoing a [`move_cursor`](Self::move_cursor) in the `undo`
@@ -56,6 +56,17 @@ pub enum DocumentMessage {
DeselectAllLayers,
DocumentHistoryBackward,
DocumentHistoryForward,
/// Moves the shared head to an earlier interaction and keeps the later steps as a branch.
HistoryMoveHead {
rev: document_graph_storage::Rev,
},
/// Drops a retired interaction and mints the later ones again on its parent.
HistoryRemoveStep {
rev: document_graph_storage::Rev,
},
HistoryRestoreStep {
rev: document_graph_storage::Rev,
},
DocumentStructureChanged,
DrawArtboardOverlays {
context: OverlayContext,
@@ -23,7 +23,7 @@ use crate::messages::portfolio::document::overlays::grid_overlays::{grid_overlay
use crate::messages::portfolio::document::overlays::utility_types::{OverlaysType, OverlaysVisibilitySettings, Pivot};
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, PTZ};
use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, ChainNodeCopy, FlowType, InputConnector, NodeTemplate, OutputConnector};
use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, ChainNodeCopy, FlowType, InputConnector, NodeTemplate, OutputConnector, ReconcileError, Reconciled};
use crate::messages::portfolio::utility_types::PanelType;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::edit_target::EditTarget;
@@ -37,7 +37,7 @@ 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::resource::{ResourceHash, ResourceId, ResourceStorage};
use graph_craft::document::value::{TaggedValue, deserialize_replacing_null_floats_with_zero};
use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork};
use graph_craft::list;
@@ -53,8 +53,12 @@ use graphene_std::vector::style::{GradientStops, RenderMode};
use kurbo::{Affine, BezPath, Line, PathSeg, Shape};
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
/// The document attribute holding its name, shared so renames reach peers.
pub const DOCUMENT_NAME_ATTRIBUTE: &str = "name";
#[derive(ExtractField)]
pub struct DocumentMessageContext<'a> {
pub document_id: DocumentId,
@@ -172,6 +176,9 @@ pub struct DocumentMessageHandler {
#[serde(skip)]
#[derivative(Debug = "ignore")]
pub(crate) container: Option<AnyContainer>,
/// Peer changes not yet applied, held until their declarations are cached.
#[serde(skip)]
pub(crate) pending_remote: document_format::network::RemoteChanges,
/// Hash of the document snapshot that was most recently saved to disk by the user.
#[serde(skip)]
saved_hash: Option<u64>,
@@ -235,6 +242,7 @@ impl Default for DocumentMessageHandler {
selection_network_path: Vec::new(),
history: DocumentHistory::default(),
container: None,
pending_remote: Default::default(),
saved_hash: None,
auto_saved_hash: None,
layer_range_selection_reference: None,
@@ -465,6 +473,27 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
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::HistoryMoveHead { rev } => self.apply_history_action(
document_id,
|history| history.move_head_to(rev),
&resource_storage.resources_mut(),
preferences.validate_storage_round_trip,
responses,
),
DocumentMessage::HistoryRemoveStep { rev } => self.apply_history_action(
document_id,
|history| history.drop_step(rev),
&resource_storage.resources_mut(),
preferences.validate_storage_round_trip,
responses,
),
DocumentMessage::HistoryRestoreStep { rev } => self.apply_history_action(
document_id,
|history| history.redo_retired_step(rev),
&resource_storage.resources_mut(),
preferences.validate_storage_round_trip,
responses,
),
DocumentMessage::DocumentStructureChanged => {
if layers_panel_open {
self.network_interface.load_structure();
@@ -1147,6 +1176,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.path = None;
self.set_save_state(false);
self.set_auto_save_state(false);
self.stage_name_attribute();
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(NodeGraphMessage::UpdateNewNodeGraph);
@@ -1253,7 +1283,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
DocumentMessage::SaveDocumentAs => None,
_ => self.path.clone().map(|path| path.with_extension(extension)),
};
if path.is_some() {
if path.is_some() || environment.is_web() {
responses.add(DocumentMessage::MarkAsSaved);
}
let folder = self.path.as_ref().and_then(|path| path.parent()).map(|parent| parent.to_path_buf());
@@ -1659,7 +1689,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
// Note: A transaction should never be started in a scope that mutates the network interface, since it will only be run after that scope ends.
DocumentMessage::StartTransaction => {
self.stage_edits_outside_transaction(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
self.retire_storage_interaction();
self.end_storage_interaction();
self.network_interface.start_transaction();
self.history.push_undo(self.network_interface.clone());
@@ -2177,7 +2207,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
impl DocumentMessageHandler {
/// Build a document handler from a `.gdd` working copy.
pub fn from_storage(interface: NodeNetworkInterface, storage: document_format::GddV1, declarations: Declarations, name: String, path: Option<std::path::PathBuf>) -> Self {
pub fn from_storage(
interface: NodeNetworkInterface,
storage: document_format::GddV1,
declarations: Declarations,
byte_store: Arc<dyn ResourceStorage>,
name: String,
path: Option<std::path::PathBuf>,
) -> Self {
let mut document = Self {
network_interface: interface,
name,
@@ -2186,11 +2223,7 @@ impl DocumentMessageHandler {
};
document.apply_stored_document_settings(storage.view_settings());
match storage.registry().to_resource_registry() {
Ok(resource_registry) => document.resources.registry = resource_registry,
Err(error) => log::error!("Opening .gdd: failed to rebuild resource registry: {error}"),
}
document.history.set_storage(storage, declarations);
document.set_storage(storage, declarations, byte_store);
document
}
@@ -2373,6 +2406,40 @@ impl DocumentMessageHandler {
self.network_interface.document_metadata()
}
pub fn breadcrumb_network_path(&self) -> &[NodeId] {
&self.breadcrumb_network_path
}
fn stored_name(&self) -> Option<&str> {
let attribute = self.storage()?.registry().attributes.get(DOCUMENT_NAME_ATTRIBUTE).filter(|attribute| !attribute.deleted)?;
match &attribute.value {
document_graph_storage::Value::Str(name) => Some(name),
_ => None,
}
}
pub fn stage_name_attribute(&mut self) {
if self.stored_name() == Some(self.name.as_str()) {
return;
}
let delta = document_graph_storage::AttributeDelta {
key: DOCUMENT_NAME_ATTRIBUTE.to_string(),
value: Some(document_graph_storage::Value::Str(self.name.clone())),
};
let Some(gdd) = self.storage_mut() else { return };
if let Err(error) = gdd.stage_ops([document_graph_storage::RegistryDelta::ChangeDocumentAttribute { delta }]) {
log::error!("Staging the document name failed: {error}");
}
}
pub fn adopt_name_from_storage(&mut self) -> bool {
let Some(name) = self.stored_name().filter(|name| *name != self.name).map(str::to_string) else {
return false;
};
self.name = name;
true
}
/// Path to the subnetwork that the user's selection is currently scoped to.
/// Empty when the selection lives in the root document network.
pub fn selection_network_path(&self) -> &[NodeId] {
@@ -2390,8 +2457,14 @@ impl DocumentMessageHandler {
}
/// 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) {
pub fn set_storage(&mut self, mut storage: document_format::GddV1, declarations: Declarations, byte_store: Arc<dyn ResourceStorage>) {
storage.set_byte_store(byte_store);
self.history.set_storage(storage, declarations);
self.refresh_resource_registry();
}
pub(crate) fn end_storage_interaction(&mut self) {
self.history.end_storage_interaction();
}
/// Retire the pending staged hot ops into durable Gdd history as one undo unit.
@@ -2420,7 +2493,8 @@ impl DocumentMessageHandler {
let view_settings = self.storage_view_settings();
self.history.stage_snapshot(&deltas, &self.network_interface, &self.resources.registry, view_settings, byte_store);
if validate {
// The interface lags the registry until peer changes are applied
if validate && self.pending_remote.is_empty() {
self.history.verify_round_trip(&self.network_interface, &self.resources.registry);
}
}
@@ -2495,6 +2569,93 @@ impl DocumentMessageHandler {
}
}
/// Rebuild the resource registry from storage, or keep it on failure. `Resource` inputs resolve through it.
fn refresh_resource_registry(&mut self) {
let Some(storage) = self.history.storage() else { return };
match storage.registry().to_resource_registry() {
Ok(resource_registry) => self.resources.registry = resource_registry,
Err(error) => log::error!("Failed to rebuild the resource registry from storage: {error}"),
}
}
pub(crate) fn stage_pending_edits(&mut self, byte_store: &dyn ResourceStorage) {
let deltas = self.network_interface.take_deltas();
if deltas.is_empty() {
return;
}
self.history.stage_graph(&deltas, &self.network_interface, &self.resources.registry, byte_store);
}
/// Updates the interface with peer changes, in place unless a rebuild is needed. Returns false and keeps what it can't apply.
pub(crate) fn apply_remote_changes(&mut self, responses: &mut VecDeque<Message>) -> bool {
let changes = std::mem::take(&mut self.pending_remote);
if changes.is_empty() {
return true;
}
if !changes.rebuilt
&& let Some(gdd) = self.history.storage()
{
let peer = gdd.session().peer();
match self.network_interface.reconcile_remote(gdd.registry(), self.history.declarations(), &changes.touched, peer) {
Ok(reconciled) => {
self.finish_remote_reconcile(reconciled, changes.touched.resources, responses);
return true;
}
Err(ReconcileError::DeclarationMissing(id)) => {
log::debug!("Remote changes wait for declaration {id}");
self.pending_remote = changes;
return false;
}
Err(error) => log::warn!("Reconciling remote changes failed, rebuilding the interface instead: {error}"),
}
}
match self.history.rebuild_interface() {
Some(rebuilt) => {
self.apply_gdd_cursor_rebuild(rebuilt, false, false, responses);
true
}
None => {
self.pending_remote = changes;
false
}
}
}
fn finish_remote_reconcile(&mut self, reconciled: Reconciled, resources_changed: bool, responses: &mut VecDeque<Message>) {
for path in self.network_interface.paths_reaching(&reconciled.networks) {
self.network_interface.unload_stack_dependents(&path);
self.network_interface.unload_import_export_ports(&path);
self.network_interface.unload_all_nodes_bounding_box(&path);
self.network_interface.unload_outward_wires(&path);
self.network_interface.unload_all_nodes_click_targets(&path);
}
self.network_interface.load_structure();
if let Some(gdd) = self.history.storage_mut() {
gdd.mark_runtime_current();
}
if resources_changed {
self.refresh_resource_registry();
}
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(NodeGraphMessage::SelectedNodesUpdated);
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::SendWires);
}
pub(crate) fn cache_declaration_bytes(&mut self, hash: ResourceHash, bytes: &[u8]) -> bool {
self.history.cache_declaration_bytes(hash, bytes)
}
pub(crate) fn undecoded_declaration_hashes(&self) -> Vec<ResourceHash> {
self.history.undecoded_declaration_hashes()
}
/// Swap in the interface rebuilt from the `Gdd` cursor. Always overwrites the interface.
fn apply_gdd_cursor_rebuild(&mut self, mut rebuilt: NodeNetworkInterface, had_oracle: bool, validate: bool, responses: &mut VecDeque<Message>) {
rebuilt.copy_all_transient_view_state(&self.network_interface);
@@ -2506,6 +2667,11 @@ impl DocumentMessageHandler {
}
self.network_interface = rebuilt;
self.pending_remote = Default::default();
if let Some(gdd) = self.history.storage_mut() {
gdd.mark_runtime_current();
}
self.refresh_resource_registry();
if validate {
let current_resources: std::collections::HashSet<_> = self.used_resources(false).iter().copied().collect();
@@ -2827,16 +2993,73 @@ impl DocumentMessageHandler {
}
pub fn undo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
// The storage path skips `undo`, which settles a glide before the snapshot moves
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
// The legacy snapshot predates peers' writes, so follow only what storage changed
let stored_name = self.stored_name().map(str::to_string);
if self.history.undo_in_storage(self.is_in_session()) {
self.follow_storage_changes(stored_name, responses);
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
return;
}
// A session's history is shared, so no legacy snapshot may be installed
if self.is_in_session() {
return;
}
let legacy_applied = if let Some(previous_network) = self.undo(viewport, responses) {
self.history.push_redo(previous_network);
self.history.note_cursor_undo();
true
} else {
false
};
self.drive_storage_undo_redo(document_id, legacy_applied, true, validate, responses);
}
/// Performs a History panel action in storage and drops the legacy snapshots, which are off the head's line.
fn apply_history_action(
&mut self,
document_id: DocumentId,
action: impl FnOnce(&mut DocumentHistory) -> bool,
byte_store: &dyn ResourceStorage,
validate: bool,
responses: &mut VecDeque<Message>,
) {
if self.network_interface.transaction_status() != TransactionStatus::Finished {
return;
}
responses.add(EventMessage::ToolAbort);
self.stage_edits_outside_transaction(byte_store, validate);
self.history.retire_storage_interaction();
let stored_name = self.stored_name().map(str::to_string);
if !action(&mut self.history) {
return;
}
self.history.clear_legacy();
self.follow_storage_changes(stored_name, responses);
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
responses.add(OverlaysMessage::Draw);
responses.add(EventMessage::SelectionChanged);
}
/// Reconciles the interface with storage. The tab takes the stored name only if it changed from `name_before`.
fn follow_storage_changes(&mut self, name_before: Option<String>, responses: &mut VecDeque<Message>) {
if let Some(gdd) = self.history.storage_mut() {
let changes = gdd.take_remote_changes();
self.pending_remote.extend(changes);
}
self.apply_remote_changes(responses);
if self.stored_name() != name_before.as_deref() && self.adopt_name_from_storage() {
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
}
}
pub(crate) fn is_in_session(&self) -> bool {
self.storage().is_some_and(|gdd| gdd.role().is_some())
}
/// Installs a history snapshot as the active network interface, carrying over the current view state and structure load, and returns the replaced interface.
fn install_history_snapshot(&mut self, mut network_interface: NodeNetworkInterface, viewport: &ViewportMessageHandler) -> NodeNetworkInterface {
// Set the previous network navigation metadata to the current navigation metadata
@@ -2871,13 +3094,25 @@ impl DocumentMessageHandler {
Some(previous_network)
}
pub fn redo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
let stored_name = self.stored_name().map(str::to_string);
if self.history.redo_in_storage() {
self.follow_storage_changes(stored_name, responses);
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
return;
}
if self.is_in_session() {
return;
}
let legacy_applied = if let Some(previous_network) = self.redo(viewport, responses) {
self.history.push_undo(previous_network);
self.history.forget_undo_note();
true
} else {
false
};
self.drive_storage_undo_redo(document_id, legacy_applied, false, validate, responses);
}
@@ -4111,6 +4346,10 @@ impl DocumentMessageHandler {
self.resources.collect_garbage(&used_resources);
}
pub fn resource_gc_roots(&self) -> HashSet<ResourceHash> {
self.history.resource_gc_roots()
}
pub fn used_resources(&self, include_history: bool) -> Box<[ResourceId]> {
let mut resources = HashSet::new();
self.network_interface.collect_used_resources(&mut resources);
@@ -4695,6 +4934,7 @@ mod document_message_handler_tests {
.executor
.submit_node_graph_evaluation(document, document_id, glam::UVec2::ONE, 1., Default::default(), merged, true, DVec2::ZERO)
.unwrap();
editor.runtime.update();
editor.runtime.run().await;
let frontend_messages = editor.editor.handle_message(Message::Wake);
@@ -5115,4 +5355,20 @@ mod document_message_handler_tests {
nudge(&mut editor, DVec2::new(NUDGE_AMOUNT, 0.)).await;
assert_bounds(&editor, rectangle, [DVec2::new(105., 32.), DVec2::new(165., 76.)]);
}
#[tokio::test]
async fn remote_changes_that_neither_reconcile_nor_rebuild_are_kept_for_a_retry() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
let document = editor.active_document_mut();
let storage = document.storage().expect("the document has a working copy").clone();
document.history.set_storage(storage, Declarations::default());
assert!(document.history.rebuild_interface().is_none(), "the registry should not convert without its declarations");
document.pending_remote.rebuilt = true;
document.apply_remote_changes(&mut VecDeque::new());
assert!(document.pending_remote.rebuilt, "the changes should be kept when the interface could not be rebuilt");
}
}
@@ -1234,33 +1234,50 @@ fn static_input_inspector() -> InputInspector {
}),
);
map.insert(
"assign_colors_gradient".to_string(),
"vary_fill_colors_gradient".to_string(),
Box::new(|node_id, index, context| {
let gradient_row = node_inspector::color_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context), ColorInput::default().allow_none(false));
Ok(vec![gradient_row])
}),
);
map.insert(
"assign_colors_seed".to_string(),
"vary_fill_colors_seed".to_string(),
Box::new(|node_id, index, context| node_inspector::vary_seed_widget(node_id, index, context, vector::vary_fill_colors::RandomizeInput)),
);
map.insert(
"vary_fill_colors_repeat_every".to_string(),
Box::new(|node_id, index, context| node_inspector::vary_repeat_every_widget(node_id, index, context, vector::vary_fill_colors::RandomizeInput)),
);
map.insert(
"vary_stroke_colors_gradient".to_string(),
Box::new(|node_id, index, context| {
let randomize_enabled = node_inspector::query_assign_colors_randomize(node_id, context)?;
let seed_row = node_inspector::number_widget(
ParameterWidgetsInfo::at_index(node_id, index, true, context),
NumberInput::default().min(0.).int().disabled(!randomize_enabled),
);
Ok(vec![seed_row.into()])
let gradient_row = node_inspector::color_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context), ColorInput::default().allow_none(false));
Ok(vec![gradient_row])
}),
);
map.insert(
"assign_colors_repeat_every".to_string(),
Box::new(|node_id, index, context| {
let randomize_enabled = node_inspector::query_assign_colors_randomize(node_id, context)?;
let repeat_every_row = node_inspector::number_widget(
ParameterWidgetsInfo::at_index(node_id, index, true, context),
NumberInput::default().min(0.).int().disabled(randomize_enabled),
);
Ok(vec![repeat_every_row.into()])
}),
"vary_stroke_colors_seed".to_string(),
Box::new(|node_id, index, context| node_inspector::vary_seed_widget(node_id, index, context, vector::vary_stroke_colors::RandomizeInput)),
);
map.insert(
"vary_stroke_colors_repeat_every".to_string(),
Box::new(|node_id, index, context| node_inspector::vary_repeat_every_widget(node_id, index, context, vector::vary_stroke_colors::RandomizeInput)),
);
map.insert(
"vary_rotations_seed".to_string(),
Box::new(|node_id, index, context| node_inspector::vary_seed_widget(node_id, index, context, transform_nodes::vary_rotations::RandomizeInput)),
);
map.insert(
"vary_rotations_repeat_every".to_string(),
Box::new(|node_id, index, context| node_inspector::vary_repeat_every_widget(node_id, index, context, transform_nodes::vary_rotations::RandomizeInput)),
);
map.insert(
"vary_scales_seed".to_string(),
Box::new(|node_id, index, context| node_inspector::vary_seed_widget(node_id, index, context, transform_nodes::vary_scales::RandomizeInput)),
);
map.insert(
"vary_scales_repeat_every".to_string(),
Box::new(|node_id, index, context| node_inspector::vary_repeat_every_widget(node_id, index, context, transform_nodes::vary_scales::RandomizeInput)),
);
map.insert(
"transform_rotation".to_string(),
@@ -1637,17 +1637,35 @@ pub fn query_noise_pattern_state(node_id: NodeId, context: &NodeInspectorContext
))
}
pub fn query_assign_colors_randomize(node_id: NodeId, context: &NodeInspectorContext) -> Result<bool, String> {
use graphene_std::vector::assign_colors::*;
fn query_vary_randomize(node_id: NodeId, context: &NodeInspectorContext, randomize: impl NodeParameter) -> Result<bool, String> {
let document_node = get_document_node(node_id, context)?;
// This is safe since the node is a proto node and the implementation cannot be changed.
Ok(match document_node.input(RandomizeInput).and_then(|input| input.as_value()) {
Ok(match document_node.input(randomize).and_then(|input| input.as_value()) {
Some(TaggedValue::Bool(randomize_enabled)) => *randomize_enabled,
_ => false,
})
}
/// The seed of a vary node (like Vary Fill Colors), which applies only while its given Randomize parameter is enabled.
pub fn vary_seed_widget(node_id: NodeId, index: usize, context: &mut NodeInspectorContext, randomize: impl NodeParameter) -> Result<Vec<LayoutGroup>, String> {
let randomize_enabled = query_vary_randomize(node_id, context, randomize)?;
let seed_row = number_widget(
ParameterWidgetsInfo::at_index(node_id, index, true, context),
NumberInput::default().min(0.).int().disabled(!randomize_enabled),
);
Ok(vec![seed_row.into()])
}
/// The repeat count of a vary node (like Vary Fill Colors), which applies only while its given Randomize parameter is disabled.
pub fn vary_repeat_every_widget(node_id: NodeId, index: usize, context: &mut NodeInspectorContext, randomize: impl NodeParameter) -> Result<Vec<LayoutGroup>, String> {
let randomize_enabled = query_vary_randomize(node_id, context, randomize)?;
let repeat_every_row = number_widget(
ParameterWidgetsInfo::at_index(node_id, index, true, context),
NumberInput::default().min(0.).int().disabled(randomize_enabled),
);
Ok(vec![repeat_every_row.into()])
}
/// 2-stop black-to-white gradient track for sliders that map a value to a grayscale axis.
fn bw_track() -> Gradient {
Gradient::from(vec![Color::BLACK, Color::WHITE])
@@ -233,3 +233,16 @@ pub enum Direction {
Left,
Right,
}
/// Another peer's pointer over the node graph, in viewport pixels.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FrontendRemoteCursor {
pub x: f64,
pub y: f64,
pub name: String,
/// A stand-in name, shown in italics.
pub anonymous: bool,
pub color: String,
pub tool: Option<String>,
}
@@ -173,6 +173,8 @@ async fn unchanged_content_keeps_cursor_and_redo_across_restart() {
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 });
// Undoing a hot step takes it back instead of moving the cursor
editor.active_document_mut().retire_storage_interaction();
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(editor.active_document().document_network(), &network_before);
@@ -4,11 +4,13 @@
//! 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 crate::messages::resource_storage::ResourcesHandle;
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::{NodeMetadataSource, PeerId, to_value};
use document_graph_storage::{NodeMetadataSource, PeerId, UserId, to_value};
use graph_craft::application_io::resource::HashMapResourceStorage;
use std::sync::Arc;
use super::test_support::{RoundTrip, node_locations, node_paths, round_trip_through_gdd};
use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler;
@@ -158,9 +160,9 @@ async fn edit_after_open_commits_cleanly() {
// Persist the document into a fresh Gdd and reopen it, then build a runtime document from the
// reopened registry: the editor's .gdd-open path.
let byte_store = HashMapResourceStorage::new();
let byte_store = ResourcesHandle::new(Arc::new(HashMapResourceStorage::new()));
let source = editor.active_document();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(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 +178,7 @@ async fn edit_after_open_commits_cleanly() {
{
let document = editor.active_document_mut();
document.network_interface = rebuilt;
document.set_storage(reopened, declarations);
document.set_storage(reopened, declarations, byte_store.storage());
document.finalize_storage_load();
}
@@ -210,7 +212,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()).expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(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) {
@@ -261,7 +263,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()).expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(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();
@@ -383,7 +385,7 @@ async fn gdd_archive_round_trips_view_settings() {
use document_graph_storage::attr::session::doc;
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(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();
@@ -431,7 +433,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()).expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(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);
@@ -664,10 +666,11 @@ fn assert_cursor_matches_runtime(document: &DocumentMessageHandler, at: &str) {
/// Mount a fresh in-memory `Gdd` onto the active document so `commit_storage_snapshot` (the real
/// autosave path) runs against it. Returns the byte store the document's resources resolve through.
fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> HashMapResourceStorage {
let gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0x5EED, "test".into(), "test".into()).expect("create_in");
editor.active_document_mut().set_storage(gdd, Default::default());
HashMapResourceStorage::new()
fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> ResourcesHandle {
let gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0x5EED, "test".into(), "test".into()).expect("create_in");
let byte_store = ResourcesHandle::new(Arc::new(HashMapResourceStorage::new()));
editor.active_document_mut().set_storage(gdd, Default::default(), byte_store.storage());
byte_store
}
/// Open a real demo artwork, mount storage, edit it, and trigger autosave. The autosave runs
@@ -701,8 +704,8 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
let after_edit = editor.active_document().network_interface.document_network().clone();
assert_ne!(before_edit, after_edit, "drawing a rectangle should change the document network");
// Second autosave: again verifies the round-trip, and the edit must produce new retired history.
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.active_document_mut().retire_storage_interaction();
let history_after_edit = editor.active_document().storage().unwrap().session().history().count();
assert!(
history_after_edit > history_after_open,
@@ -936,3 +939,40 @@ async fn eight_input_fill_migrates_the_spread_input_into_the_ramp() {
"the transform input should shift down intact, but became {transform:?}"
);
}
#[tokio::test]
async fn undoing_a_hot_step_takes_it_back_and_redo_stages_it_again() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let byte_store = mount_in_memory_storage(&mut editor);
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.active_document_mut().retire_storage_interaction();
let history_base = editor.active_document().storage().unwrap().session().history().count();
let before_edit = editor.active_document().network_interface.document_network().clone();
editor.draw_rect(64., 64., 192., 192.).await;
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let after_edit = editor.active_document().network_interface.document_network().clone();
assert_ne!(after_edit, before_edit);
assert!(!editor.active_document().storage().unwrap().session().hot_log().is_empty(), "the step is hot");
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(editor.active_document().network_interface.document_network(), &before_edit, "undo restores the pre-edit network");
let storage = editor.active_document().storage().unwrap();
assert!(storage.session().hot_log().is_empty(), "the step was taken back, not retired: {:?}", storage.session().hot_log());
assert_eq!(storage.session().history().count(), history_base, "nothing entered history");
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
// The step held for redo keeps its declaration bytes from collection
let storage = editor.active_document().storage().unwrap();
assert!(
!editor.active_document().resource_gc_roots().is_subset(&storage.all_referenced_resource_hashes()),
"the retracted step names its declaration resource"
);
editor.handle_message(DocumentMessage::Redo).await;
assert_eq!(editor.active_document().network_interface.document_network(), &after_edit, "redo restores the edit");
let storage = editor.active_document().storage().unwrap();
assert!(!storage.session().hot_log().is_empty(), "the redone step is staged afresh");
assert_eq!(storage.session().history().count(), history_base);
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
}
@@ -5,7 +5,7 @@
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::PeerId;
use document_graph_storage::{PeerId, UserId};
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NetworkLocation, NodeId, NodeNetwork};
@@ -110,7 +110,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()).expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
@@ -17,6 +17,7 @@ mod layout;
mod memo_network;
mod mutations;
mod queries;
mod reconcile;
mod resolved_types;
pub mod storage_metadata;
mod store;
@@ -28,6 +29,7 @@ mod validation;
mod view;
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
pub use reconcile::{ReconcileError, Reconciled};
use store::Guarded;
pub use store::NodeLocator;
pub use template::*;
@@ -8,7 +8,6 @@ impl NodeNetworkInterface {
/// 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);
@@ -1,6 +1,7 @@
use super::template::NodeTemplateImplementation;
use super::{InputConnector, OutputConnector, catalog};
use crate::messages::portfolio::document::node_graph::document_node_definitions::{network_node_identifiers, resolve_network_node_type};
use crate::messages::portfolio::document::storage_tests::test_support::round_trip_through_gdd;
use crate::test_utils::test_prelude::*;
use graph_craft::document::{DocumentNodeImplementation, NetworkId, NodeInput};
use graphene_std::uuid::NodeId;
@@ -148,3 +149,14 @@ async fn an_entry_that_diverged_under_a_catalog_id_gets_a_fresh_id_on_open() {
assert!(!network.definitions.contains_key(&shipped));
assert!(network.definitions[&renamed].exports.len() > catalog::entry(shipped).expect("shipped").network.exports.len());
}
#[tokio::test]
async fn a_reopened_document_keeps_its_catalog_entries() {
let (editor, blends) = editor_with_blends(1).await;
let shipped = entry_of(&editor, blends[0]);
let mut reopened = round_trip_through_gdd(editor.active_document()).await.rebuilt;
reopened.give_diverged_catalog_entries_new_ids();
assert!(reopened.document_network().definitions.contains_key(&shipped));
}
@@ -1,7 +1,7 @@
use super::DocumentNodePersistentMetadata;
use super::InputConnector;
use super::editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange, construct_batch, ui_attribute_writes};
use super::storage_metadata::StorageMetadataView;
use super::{InputConnector, NodeTemplate};
use crate::test_utils::test_prelude::*;
use document_graph_storage::delta::compute_deltas;
use document_graph_storage::{PeerId, Registry, RegistryDelta, Session};
@@ -660,6 +660,251 @@ async fn swapping_an_implementation_leaves_the_node_in_place() {
}
}
fn conversion(editor: &EditorTestUtils) -> document_graph_storage::RuntimeConversion {
let document = editor.active_document();
Registry::convert_from_runtime(
document.network_interface.document_network(),
&StorageMetadataView::new(&document.network_interface),
&document.resources.registry,
PEER,
)
.expect("conversion should succeed")
}
/// Checks that a clone reconciled from `edit`'s storage ops equals the edited interface.
async fn assert_remote_reconcile_reproduces(edit: impl FnOnce(&mut EditorTestUtils)) {
use document_graph_storage::Touched;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: crate::messages::portfolio::document::utility_types::misc::GroupFolderType::Layer,
})
.await;
editor.active_document_mut().network_interface.discard_deltas();
editor.active_document_mut().network_interface.pin_storage_identities(PEER);
let mut mirror = editor.active_document().network_interface.clone();
let baseline = conversion(&editor);
let mut peer = Session::with_peer(PeerId(8));
peer.stage_computed_ops(compute_deltas(&Registry::default(), &baseline.registry)).expect("the peer takes the baseline");
let mut declarations = baseline.declarations;
edit(&mut editor);
editor.active_document_mut().network_interface.settle_definitions();
editor.active_document_mut().network_interface.pin_storage_identities(PEER);
let recorded = editor.active_document_mut().network_interface.take_deltas();
assert!(!recorded.is_empty(), "the edit should have recorded something to send");
let constructed = {
let document = editor.active_document();
construct_batch(
&recorded,
&baseline.registry,
&document.resources.registry,
&StorageMetadataView::new(&document.network_interface),
PEER,
)
.expect("construction")
};
declarations.extend(constructed.declarations.decoded);
let mut touched = Touched::default();
for op in &constructed.ops {
touched.record(op);
}
peer.stage_computed_ops(constructed.ops).expect("the peer applies the batch");
mirror.reconcile_remote(peer.registry(), &declarations, &touched, PEER).expect("reconcile");
let edited = &editor.active_document().network_interface;
assert!(
mirror.document_network() == edited.document_network(),
"reconciling {} recorded deltas did not reproduce the edited graph:\n{}",
recorded.len(),
crate::messages::portfolio::document::document_diff::diff_networks(edited.document_network(), mirror.document_network())
);
let metadata = |interface: &super::NodeNetworkInterface| serde_json::to_value(interface.document_network_metadata()).expect("metadata serializes");
let (reconciled_metadata, edited_metadata) = (metadata(&mirror), metadata(edited));
assert!(
reconciled_metadata == edited_metadata,
"reconciling {} recorded deltas did not reproduce the edited metadata:\n{}",
recorded.len(),
json_diff(&edited_metadata, &reconciled_metadata, "")
);
let converted = Registry::convert_from_runtime(mirror.document_network(), &StorageMetadataView::new(&mirror), &editor.active_document().resources.registry, PEER)
.expect("the reconciled interface converts")
.registry;
assert!(
peer.registry().value_equal(&converted),
"the reconciled interface must convert back to the registry it was reconciled from\nresidual: {:#?}",
compute_deltas(&converted, peer.registry())
);
}
fn json_diff(expected: &serde_json::Value, actual: &serde_json::Value, path: &str) -> String {
use serde_json::Value;
match (expected, actual) {
(Value::Object(expected), Value::Object(actual)) => {
let keys: std::collections::BTreeSet<_> = expected.keys().chain(actual.keys()).collect();
keys.into_iter()
.map(|key| match (expected.get(key), actual.get(key)) {
(Some(expected), Some(actual)) => json_diff(expected, actual, &format!("{path}/{key}")),
(Some(expected), None) => format!("{path}/{key}: missing, expected {expected}\n"),
(None, Some(actual)) => format!("{path}/{key}: unexpected {actual}\n"),
(None, None) => String::new(),
})
.collect()
}
(Value::Array(expected), Value::Array(actual)) if expected.len() == actual.len() => expected
.iter()
.zip(actual)
.enumerate()
.map(|(index, (expected, actual))| json_diff(expected, actual, &format!("{path}[{index}]")))
.collect(),
_ if expected == actual => String::new(),
_ => format!("{path}: expected {expected}\n{path}: actual {actual}\n"),
}
}
fn rectangle_template() -> NodeTemplate {
crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition())
.expect("rectangle definition")
.default_node_template()
}
#[tokio::test]
async fn reconciling_metadata_edits_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_display_name(&group, "Renamed".to_string(), &[]);
network_interface.set_locked(&group, &[], true);
network_interface.set_pinned(&group, &[], true);
network_interface.set_visibility(&group, &[], false);
network_interface.shift_node(&group, glam::IVec2::new(3, 5), &[]);
})
.await;
}
#[tokio::test]
async fn reconciling_an_arity_change_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
editor
.active_document_mut()
.network_interface
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
})
.await;
}
#[tokio::test]
async fn reconciling_a_node_insertion_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
editor.active_document_mut().network_interface.insert_node(NodeId(0xDE17A), rectangle_template(), &[]);
})
.await;
}
#[tokio::test]
async fn reconciling_a_node_insertion_inside_a_group_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
editor.active_document_mut().network_interface.insert_node(NodeId(0xDE17B), rectangle_template(), &[group]);
})
.await;
}
#[tokio::test]
async fn reconciling_a_new_instance_of_a_shared_network_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
insert_shared_copy(editor, group);
})
.await;
}
#[tokio::test]
async fn reconciling_an_edit_inside_a_shared_network_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
insert_shared_copy(editor, group);
editor
.active_document_mut()
.network_interface
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
})
.await;
}
#[tokio::test]
async fn reconciling_a_group_removal_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
editor.active_document_mut().network_interface.delete_nodes(vec![group], true, &[]);
})
.await;
}
#[tokio::test]
async fn reconciling_an_implementation_swap_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
let interface = &mut editor.active_document_mut().network_interface;
let Some(mut cursor) = interface.node_mut(super::NodeLocator::new(group, &[])) else {
panic!("the group should resolve")
};
cursor.replace_implementation(graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER));
})
.await;
}
#[tokio::test]
async fn reconciling_an_input_value_edit_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
let interface = &mut editor.active_document_mut().network_interface;
let (inner, index) = interface
.nested_network(&[group])
.expect("the group's network")
.nodes
.iter()
.find_map(|(id, node)| Some((*id, node.inputs.iter().position(|input| input.as_value().is_some())?)))
.expect("a node with a value input inside the group");
interface.set_input(&InputConnector::node_at_index(inner, index), NodeInput::value(TaggedValue::Number(42.), false), &[group]);
})
.await;
}
#[tokio::test]
async fn reconciling_an_untouched_node_changes_nothing() {
use document_graph_storage::Touched;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
editor.active_document_mut().network_interface.pin_storage_identities(PEER);
let baseline = conversion(&editor);
let mut touched = Touched::default();
touched.nodes.extend(baseline.registry.node_instances.keys().copied());
touched.networks.extend(baseline.registry.networks.keys().copied());
let before = editor.active_document().network_interface.clone();
let reconciled = editor
.active_document_mut()
.network_interface
.reconcile_remote(&baseline.registry, &baseline.declarations, &touched, PEER)
.expect("reconcile");
assert!(reconciled.networks.is_empty(), "nothing differed, so nothing should have been applied: {:?}", reconciled.networks);
assert_eq!(editor.active_document().network_interface, before);
}
/// A `ui::` key the registry already holds as deleted is not cleared again on every snapshot.
#[test]
fn a_deleted_ui_key_is_not_cleared_again() {
@@ -0,0 +1,382 @@
//! Updates the interface from the registry for the entities peers touched, through `EditorDelta`s it doesn't record.
//! The touched set may be too large. An unchanged entity compares equal and emits nothing.
use std::collections::{BTreeSet, HashMap};
use document_graph_storage::to_runtime::ConversionError;
use document_graph_storage::{Declarations, NetworkId as StorageNetworkId, NodeId as StorageNodeId, Registry, RuntimeProjection, Touched};
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NetworkId, NetworkLocation, NodeId, NodeInput, NodeNetwork};
use graph_craft::runtime_delta::RuntimeDelta;
use super::storage_metadata::{InterfaceRebuildError, input_metadata_entry_to_runtime, node_metadata_from_projection};
use super::{DocumentNodePersistentMetadata, EditorDelta, NetworkMetadataChange, NodeMetadataChange, NodeNetworkInterface};
#[derive(Debug, thiserror::Error)]
pub enum ReconcileError {
/// A declaration the touched nodes need is not cached yet.
#[error("waiting for proto-node declaration {0}")]
DeclarationMissing(document_graph_storage::ResourceId),
#[error("the interface lacks the network at {0:?} that the registry places a node in")]
NetworkMissing(NetworkLocation),
/// No delta writes a held network's scope injections.
#[error("the scope injections of the network at {0:?} changed")]
ScopeInjectionsChanged(NetworkLocation),
#[error(transparent)]
Conversion(ConversionError),
#[error(transparent)]
Metadata(#[from] InterfaceRebuildError),
}
impl From<ConversionError> for ReconcileError {
fn from(error: ConversionError) -> Self {
match error {
ConversionError::DeclarationNotFound(id) => Self::DeclarationMissing(id),
other => Self::Conversion(other),
}
}
}
#[derive(Debug, Default)]
pub struct Reconciled {
pub networks: BTreeSet<NetworkLocation>,
}
type StorageIndex = HashMap<StorageNodeId, (NetworkLocation, NodeId)>;
impl NodeNetworkInterface {
/// Applies what the registry holds differently for the touched entities. Can fail part-way, and a retry is safe.
pub(crate) fn reconcile_remote(&mut self, registry: &Registry, declarations: &Declarations, touched: &Touched, peer: document_graph_storage::PeerId) -> Result<Reconciled, ReconcileError> {
let projection = registry.runtime_projection(declarations);
let index = self.pin_storage_identities(peer);
let mut reconciled = Reconciled::default();
let mut nodes = touched.nodes.clone();
let mut networks = touched.networks.clone();
networks.extend(nodes.iter().filter_map(|&node| projection.implemented_network(node)));
self.add_newly_reached_networks(&projection, &mut nodes, &mut networks, &mut reconciled)?;
let mut items: Vec<(NetworkLocation, NodeId, StorageNodeId)> = nodes
.into_iter()
.filter_map(|id| {
let (location, local_id) = projection.node_address(id).or_else(|| index.get(&id).copied())?;
Some((location, local_id, id))
})
.collect();
items.sort();
for (location, local_id, id) in items {
self.reconcile_node(&projection, &index, location, local_id, id, &mut reconciled)?;
}
for &network in &networks {
if projection.network_location(network).is_some() {
self.reconcile_network(&projection, network, &mut reconciled)?;
}
}
self.remove_unreached_networks(&projection, &mut reconciled);
Ok(reconciled)
}
/// Adds each table entry the touched entities newly reach, and queues everything under it as touched.
fn add_newly_reached_networks(
&mut self,
projection: &RuntimeProjection,
nodes: &mut BTreeSet<StorageNodeId>,
networks: &mut BTreeSet<StorageNetworkId>,
reconciled: &mut Reconciled,
) -> Result<(), ReconcileError> {
let mut pending: Vec<StorageNetworkId> = networks.iter().copied().collect();
while let Some(network) = pending.pop() {
let Some(location) = projection.network_location(network) else { continue };
let Some(id) = location else { continue };
if self.holds_network(location) {
continue;
}
let target = projection.network_entry(network)?;
let added = NodeNetwork {
exports: target.exports,
scope_injections: target.scope_injections,
..Default::default()
};
self.apply_reconciled(location, vec![EditorDelta::Graph(RuntimeDelta::AddNetwork { id, network: Box::new(added) })], reconciled);
networks.insert(network);
for node in projection.network_nodes(network) {
nodes.insert(node);
pending.extend(projection.implemented_network(node));
}
}
Ok(())
}
fn remove_unreached_networks(&mut self, projection: &RuntimeProjection, reconciled: &mut Reconciled) {
let reached: BTreeSet<NetworkId> = projection.definitions().collect();
let unreached: Vec<NetworkId> = self.document_network().definitions.keys().copied().filter(|id| !reached.contains(id)).collect();
for id in unreached {
self.apply_reconciled(Some(id), vec![EditorDelta::Graph(RuntimeDelta::RemoveNetwork { id })], reconciled);
}
}
fn reconcile_network(&mut self, projection: &RuntimeProjection, network: StorageNetworkId, reconciled: &mut Reconciled) -> Result<(), ReconcileError> {
let target = projection.network_entry(network)?;
let location = target.network;
let (Some(current), Some(current_metadata)) = (
self.document_network().located_network(location),
self.network_metadata.nested_metadata(location).map(|metadata| &metadata.persistent_metadata),
) else {
return Err(ReconcileError::NetworkMissing(location));
};
if current.scope_injections != target.scope_injections {
return Err(ReconcileError::ScopeInjectionsChanged(location));
}
let mut deltas = Vec::new();
export_deltas(location, &current.exports, &target.exports, &mut deltas);
// An export slot write resizes the names and descriptions, so restate them
let resized = current.exports.len() != target.exports.len();
let change = |change| EditorDelta::NetworkMetadata { network: location, change };
if current_metadata.reference != target.metadata.reference {
deltas.push(change(NetworkMetadataChange::Reference(target.metadata.reference.clone())));
}
if current_metadata.pinned_node_order != target.metadata.pinned_order {
deltas.push(change(NetworkMetadataChange::PinnedOrder(target.metadata.pinned_order.clone())));
}
// An empty list states nothing, since an older document keeps its interface on the instances
let import_metadata: Vec<_> = target.metadata.import_metadata.iter().cloned().map(input_metadata_entry_to_runtime).collect();
if !import_metadata.is_empty() && current_metadata.import_metadata != import_metadata {
deltas.push(change(NetworkMetadataChange::ImportMetadata(import_metadata)));
}
if !target.metadata.export_names.is_empty() && (resized || current_metadata.export_names != target.metadata.export_names) {
deltas.push(change(NetworkMetadataChange::ExportNames(target.metadata.export_names.clone())));
}
if !target.metadata.export_names.is_empty() && (resized || current_metadata.export_descriptions != target.metadata.export_descriptions) {
deltas.push(change(NetworkMetadataChange::ExportDescriptions(target.metadata.export_descriptions.clone())));
}
self.apply_reconciled(location, deltas, reconciled);
Ok(())
}
fn reconcile_node(
&mut self,
projection: &RuntimeProjection,
index: &StorageIndex,
location: NetworkLocation,
local_id: NodeId,
id: StorageNodeId,
reconciled: &mut Reconciled,
) -> Result<(), ReconcileError> {
// A copy held under another id or in another network goes first
if let Some(&(held_location, held_id)) = index.get(&id)
&& (held_location != location || held_id != local_id)
&& self.holds_node(held_location, held_id)
{
self.apply_reconciled(held_location, vec![remove_node(held_location, held_id)], reconciled);
}
let stored = projection.node_address(id).is_some();
match (stored, self.holds_node(location, local_id)) {
(false, false) => {}
(false, true) => self.apply_reconciled(location, vec![remove_node(location, local_id)], reconciled),
(true, false) => {
if !self.holds_network(location) {
return Err(ReconcileError::NetworkMissing(location));
}
let (node, metadata) = node_metadata_from_projection(projection.node(id)?)?;
let deltas = vec![
EditorDelta::Graph(RuntimeDelta::AddNode {
network: location,
node_id: local_id,
node: Box::new(node),
}),
EditorDelta::NodeMetadataSnapshot {
network: location,
node_id: local_id,
metadata: Box::new(metadata),
},
];
self.apply_reconciled(location, deltas, reconciled);
}
(true, true) => {
let (node, metadata) = node_metadata_from_projection(projection.node(id)?)?;
self.diff_node(location, local_id, node, metadata, reconciled);
}
}
Ok(())
}
fn diff_node(&mut self, location: NetworkLocation, local_id: NodeId, target: DocumentNode, target_metadata: DocumentNodePersistentMetadata, reconciled: &mut Reconciled) {
let Some(current) = self.document_network().located_network(location).and_then(|network| network.nodes.get(&local_id)) else {
return;
};
let Some(current_metadata) = self
.network_metadata
.nested_metadata(location)
.and_then(|network| network.persistent_metadata.node_metadata.get(&local_id))
.map(|node| &node.persistent_metadata)
else {
return;
};
let deltas = if current.implementation == target.implementation && current.skip_deduplication == target.skip_deduplication {
field_deltas(location, local_id, (current, current_metadata), (&target, &target_metadata))
} else {
vec![
EditorDelta::Graph(RuntimeDelta::ReplaceNode {
network: location,
node_id: local_id,
node: Box::new(target),
}),
EditorDelta::NodeMetadataSnapshot {
network: location,
node_id: local_id,
metadata: Box::new(target_metadata),
},
]
};
self.apply_reconciled(location, deltas, reconciled);
}
fn apply_reconciled(&mut self, location: NetworkLocation, deltas: Vec<EditorDelta>, reconciled: &mut Reconciled) {
if deltas.is_empty() {
return;
}
for delta in &deltas {
self.apply(delta);
}
reconciled.networks.insert(location);
}
/// Every document path to one of `locations`. A shared network has one per instance.
pub(crate) fn paths_reaching(&self, locations: &BTreeSet<NetworkLocation>) -> Vec<Vec<NodeId>> {
let root = self.document_network();
let mut paths = Vec::new();
let mut pending = vec![(Vec::new(), root)];
while let Some((path, network)) = pending.pop() {
for (&node_id, node) in &network.nodes {
if let Some(nested) = root.implementation_network(&node.implementation) {
pending.push(([path.as_slice(), &[node_id]].concat(), nested));
}
}
if root.locate(&path).is_some_and(|location| locations.contains(&location)) {
paths.push(path);
}
}
paths
}
fn holds_node(&self, location: NetworkLocation, local_id: NodeId) -> bool {
self.document_network().located_network(location).is_some_and(|network| network.nodes.contains_key(&local_id))
&& self
.network_metadata
.nested_metadata(location)
.is_some_and(|network| network.persistent_metadata.node_metadata.contains_key(&local_id))
}
fn holds_network(&self, location: NetworkLocation) -> bool {
self.document_network().located_network(location).is_some() && self.network_metadata.nested_metadata(location).is_some()
}
}
fn field_deltas(
location: NetworkLocation,
local_id: NodeId,
(current, current_metadata): (&DocumentNode, &DocumentNodePersistentMetadata),
(target, target_metadata): (&DocumentNode, &DocumentNodePersistentMetadata),
) -> Vec<EditorDelta> {
let mut deltas = Vec::new();
let metadata = |change: NodeMetadataChange| EditorDelta::NodeMetadata {
network: location,
node_id: local_id,
change,
};
let input_metadata = || EditorDelta::NodeInputMetadata {
network: location,
node_id: local_id,
input_metadata: target_metadata.input_metadata.clone(),
};
// An instance's input metadata belongs to its implementing network
let instance = matches!(target.implementation, DocumentNodeImplementation::Definition(_));
// Slots first, so the metadata indexing them finds the right length
if current.inputs.len() != target.inputs.len() {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetInputs {
network: location,
node_id: local_id,
inputs: target.inputs.clone(),
}));
if !instance {
deltas.push(input_metadata());
}
} else {
for (input_index, (held, wanted)) in current.inputs.iter().zip(&target.inputs).enumerate() {
if held != wanted {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetInput {
network: location,
node_id: local_id,
input_index,
input: wanted.clone(),
}));
}
}
if !instance && current_metadata.input_metadata != target_metadata.input_metadata {
deltas.push(input_metadata());
}
}
if current.visible != target.visible {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetVisibility {
network: location,
node_id: local_id,
visible: target.visible,
}));
}
if current.call_argument != target.call_argument {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetCallArgument {
network: location,
node_id: local_id,
call_argument: target.call_argument.clone(),
}));
}
if current_metadata.node_type_metadata != target_metadata.node_type_metadata {
deltas.push(metadata(NodeMetadataChange::NodeType(target_metadata.node_type_metadata.clone())));
}
if current_metadata.display_name != target_metadata.display_name {
deltas.push(metadata(NodeMetadataChange::DisplayName(target_metadata.display_name.clone())));
}
if current_metadata.locked != target_metadata.locked {
deltas.push(metadata(NodeMetadataChange::Locked(target_metadata.locked)));
}
if current_metadata.pinned != target_metadata.pinned {
deltas.push(metadata(NodeMetadataChange::Pinned(target_metadata.pinned)));
}
if current_metadata.output_names != target_metadata.output_names {
deltas.push(metadata(NodeMetadataChange::OutputNames(target_metadata.output_names.clone())));
}
if current_metadata.output_descriptions != target_metadata.output_descriptions {
deltas.push(metadata(NodeMetadataChange::OutputDescriptions(target_metadata.output_descriptions.clone())));
}
deltas
}
fn remove_node(location: NetworkLocation, local_id: NodeId) -> EditorDelta {
EditorDelta::Graph(RuntimeDelta::RemoveNode { network: location, node_id: local_id })
}
fn export_deltas(location: NetworkLocation, current: &[NodeInput], target: &[NodeInput], deltas: &mut Vec<EditorDelta>) {
let set_export = |export_index, input| {
EditorDelta::Graph(RuntimeDelta::SetExport {
network: location,
export_index,
input,
})
};
let changed = target.iter().enumerate().filter(|&(export_index, input)| current.get(export_index) != Some(input));
deltas.extend(changed.map(|(export_index, input)| set_export(export_index, Some(input.clone()))));
deltas.extend((target.len()..current.len()).map(|_| set_export(target.len(), None)));
}
@@ -10,7 +10,7 @@ use std::collections::{BTreeMap, HashMap};
use document_graph_storage::attr::session;
use document_graph_storage::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry, NodeMetadataSource, Position, Value, from_value, to_value};
use glam::IVec2;
use graph_craft::document::{NetworkLocation, NodeId, NodeNetwork};
use graph_craft::document::{DocumentNodeImplementation, NetworkLocation, NodeId, NodeNetwork};
use graphene_std::vector::style::RenderMode;
use super::{
@@ -210,6 +210,28 @@ pub fn build_interface_from_storage(network: NodeNetwork, node_entries: Vec<Node
Ok(NodeNetworkInterface::from_trees(network, network_metadata))
}
/// The node and its metadata from a single-node projection, patched like a whole rebuild's entry.
pub(super) fn node_metadata_from_projection(projected: document_graph_storage::ProjectedNode) -> Result<(graph_craft::document::DocumentNode, DocumentNodePersistentMetadata), InterfaceRebuildError> {
let document_graph_storage::ProjectedNode { local_id, node, metadata: entry, .. } = projected;
let entry = NodeMetadataEntry { network: None, ..entry };
let mut scratch = NodeNetwork::default();
scratch.nodes.insert(local_id, node);
let mut metadata = NodeNetworkMetadata::default();
seed_metadata_tree(&scratch, &mut metadata);
apply_entries_into_tree(&scratch, &mut metadata, vec![entry])?;
let mut persistent = metadata.persistent_metadata.node_metadata.remove(&local_id).map(|node| node.persistent_metadata).unwrap_or_default();
let node = scratch.nodes.remove(&local_id).expect("inserted above");
if matches!(node.implementation, DocumentNodeImplementation::Definition(_)) {
persistent.input_metadata.clear();
persistent.output_names.clear();
persistent.output_descriptions.clear();
}
Ok((node, persistent))
}
/// Maps each runtime network location to its stable `NetworkId`, from the entries `to_runtime_with_full_metadata` returns.
pub fn network_ids_from_entries(network_entries: &[NetworkMetadataEntry]) -> HashMap<NetworkLocation, document_graph_storage::NetworkId> {
network_entries.iter().map(|entry| (entry.network, entry.network_id)).collect()
@@ -423,7 +445,7 @@ pub(super) fn input_metadata_entry_from_runtime(input_metadata: &InputMetadata)
}
/// Storage-side `None` restores as `""` (the runtime's "unset" sentinel for `input_name` / `input_description`).
fn input_metadata_entry_to_runtime(entry: InputMetadataEntry) -> InputMetadata {
pub(super) fn input_metadata_entry_to_runtime(entry: InputMetadataEntry) -> InputMetadata {
InputMetadata {
persistent_metadata: InputPersistentMetadata {
input_name: entry.input_name.unwrap_or_default(),
@@ -567,9 +567,11 @@ impl NodeNetworkInterface {
return false;
};
let Some(network) = self.document_network().definitions.get(&id).cloned() else { return false };
let Some(metadata) = self.network_metadata.persistent_metadata.definitions.get(&id).cloned() else {
let Some(mut metadata) = self.network_metadata.persistent_metadata.definitions.get(&id).cloned() else {
return false;
};
// The copy's nodes are new and can't keep the originals' storage identities
clear_storage_ids(&mut metadata.persistent_metadata);
let unique = NetworkId::new();
self.insert_definition(unique, network, metadata);
@@ -658,6 +660,42 @@ impl NodeNetworkInterface {
self.dots_that_lost_a_wire.clear();
}
/// Pins each unpinned node to the identity a conversion derives from its location, and returns where each identity is held.
pub(crate) fn pin_storage_identities(&mut self, peer: document_graph_storage::PeerId) -> HashMap<document_graph_storage::NodeId, (NetworkLocation, NodeId)> {
let mut index = HashMap::new();
let mut unpinned = Vec::new();
{
let view = super::storage_metadata::StorageMetadataView::new(self);
let resolver = document_graph_storage::PathResolver::new(Some(&view), peer);
let definitions = self.network_metadata.persistent_metadata.definitions.iter().map(|(id, metadata)| (Some(*id), metadata));
for (location, metadata) in definitions.chain([(None, &*self.network_metadata)]) {
for (&local_id, node) in &metadata.persistent_metadata.node_metadata {
let storage_id = match node.persistent_metadata.storage_id {
Some(pinned) => document_graph_storage::NodeId(pinned),
None => {
let derived = resolver.node_id(location, local_id);
unpinned.push((location, local_id, derived));
derived
}
};
index.insert(storage_id, (location, local_id));
}
}
}
for (location, local_id, storage_id) in unpinned {
if let Some(node) = self
.network_metadata
.get_mut()
.nested_metadata_mut(location)
.and_then(|network| network.persistent_metadata.node_metadata.get_mut(&local_id))
{
node.persistent_metadata.storage_id = Some(storage_id.0);
}
}
index
}
/// Records the open transaction's bookkeeping, so writes that are undone before [`Self::restore_transaction_checkpoint`] don't count toward it.
pub fn transaction_checkpoint(&mut self) -> TransactionCheckpoint {
self.scan_transaction_edited_nodes();
@@ -726,6 +764,15 @@ impl NodeNetworkInterface {
}
}
fn clear_storage_ids(metadata: &mut NodeNetworkPersistentMetadata) {
for node in metadata.node_metadata.values_mut() {
node.persistent_metadata.storage_id = None;
if let Some(nested) = &mut node.persistent_metadata.network_metadata {
clear_storage_ids(&mut nested.persistent_metadata);
}
}
}
/// Whether any of `descriptions` says anything, since storage keeps the whole list then, but not a list that's all empty.
fn has_description(descriptions: &[String]) -> bool {
descriptions.iter().any(|description| !description.is_empty())
@@ -504,7 +504,7 @@ impl<'de> serde::Deserialize<'de> for Previewing {
}
}
/// Whether two networks' metadata match, ignoring view state.
/// Whether two networks' metadata match, ignoring view state and storage identities.
pub(crate) fn same_content(first: &NodeNetworkPersistentMetadata, second: &NodeNetworkPersistentMetadata) -> bool {
let content = |metadata: &NodeNetworkPersistentMetadata| {
let mut content = metadata.clone();
@@ -519,6 +519,9 @@ fn clear_view_state(metadata: &mut NodeNetworkPersistentMetadata) {
metadata.navigation_metadata = NavigationMetadata::default();
metadata.selection_undo_history.clear();
metadata.selection_redo_history.clear();
for node in metadata.node_metadata.values_mut() {
node.persistent_metadata.storage_id = None;
}
let nested_networks = metadata
.node_metadata
@@ -4,7 +4,7 @@
use crate::messages::portfolio::document::graph_operation::utility_types::set_stroke_paint_order;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type, resolve_network_node_type, resolve_proto_node_type};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeTemplate, NodeTemplateImplementation, OutputConnector};
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate, NodeTemplateImplementation, OutputConnector};
use crate::messages::prelude::DocumentMessageHandler;
use glam::{DVec2, IVec2};
use graph_craft::application_io::resource::{DataSource, Resource, ResourceHash, ResourceId};
@@ -786,10 +786,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::vector::area::IDENTIFIER,
aliases: &["graphene_core::vector::AreaNode"],
},
NodeReplacement {
node: graphene_std::vector::assign_colors::IDENTIFIER,
aliases: &["graphene_core::vector::AssignColorsNode"],
},
NodeReplacement {
node: graphene_std::vector::smooth_anchors::IDENTIFIER,
aliases: &[
@@ -919,10 +915,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::repeat::repeat_on_points::IDENTIFIER,
aliases: &["graphene_core::vector::InstanceOnPointsNode", "core_types::vector::InstanceOnPointsNode"],
},
NodeReplacement {
node: graphene_std::vector::copy_to_points::IDENTIFIER,
aliases: &["graphene_core::vector::CopyToPointsNode", "core_types::vector::CopyToPointsNode"],
},
NodeReplacement {
node: graphene_std::vector::jitter_points::IDENTIFIER,
aliases: &["graphene_core::vector::JitterPointsNode"],
@@ -1861,6 +1853,11 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::value(TaggedValue::Integer(integer), exposed), &network_path);
}
migrate_assign_colors_nodes(document);
// Last, so the rest of the graph is upgraded enough to compile when each Copy to Points node's content type is resolved
migrate_copy_to_points_nodes(document);
// Bringing an old document up to date is not a set of edits on it, it is how the document arrives.
// The upgrades run through the ordinary mutators, so the store records them; dropping what they
// recorded leaves the opened document as the baseline rather than as a pile of changes to itself.
@@ -3843,6 +3840,322 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
Some(())
}
/// Splits each removed Assign Colors node into the Vary Fill Colors and Vary Stroke Colors nodes its Fill and Stroke toggles call for.
fn migrate_assign_colors_nodes(document: &mut DocumentMessageHandler) {
let assign_colors_nodes: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter(|(_, node, _)| node.inputs.len() == 8 && matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if identifier.as_str().ends_with("::AssignColorsNode")))
.map(|(node_id, _, path)| (*node_id, path))
.collect();
for (node_id, network_path) in assign_colors_nodes {
migrate_assign_colors(&node_id, &network_path, document);
}
}
/// Rebuilds a removed Assign Colors node as Vary Fill Colors, Vary Stroke Colors, or both in a row ending at the original node to keep its downstream wires.
/// A wired toggle counts as enabled, and a node with both toggles disabled is hidden so it still passes its content through unchanged.
fn migrate_assign_colors(node_id: &NodeId, network_path: &[NodeId], document: &mut DocumentMessageHandler) -> Option<()> {
use graphene_std::vector::{vary_fill_colors, vary_stroke_colors};
let enabled = |input: &NodeInput| !matches!(input.as_value(), Some(TaggedValue::Bool(false)));
let old_node = document.network_interface.document_node(node_id, network_path)?;
let (fill, stroke) = (enabled(&old_node.inputs[1]), enabled(&old_node.inputs[2]));
let identifier = if stroke { vary_stroke_colors::IDENTIFIER } else { vary_fill_colors::IDENTIFIER };
let mut node_template = resolve_proto_node_type(identifier)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
reset_default_display_name(document, node_id, network_path, "Assign Colors");
// The content and color parameters carry over in the same order, without the toggles
let [content, _, _, gradient, reverse, randomize, seed, repeat_every] = <[NodeInput; 8]>::try_from(old_inputs).ok()?;
let carried_inputs = [content, gradient, reverse, randomize, seed, repeat_every];
for (index, input) in carried_inputs.iter().enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
}
// Styling both gets a Vary Fill Colors node with the same parameters inserted before the Vary Stroke Colors one
if fill && stroke {
let fill_id = NodeId::new();
document
.network_interface
.insert_node(fill_id, resolve_proto_node_type(vary_fill_colors::IDENTIFIER)?.default_node_template(), network_path);
for (index, input) in carried_inputs.iter().enumerate().skip(1) {
document.network_interface.set_input(&InputConnector::node_at_index(fill_id, index), input.clone(), network_path);
}
document.network_interface.insert_node_before_input(&fill_id, &InputConnector::node_at_index(*node_id, 0), network_path);
}
if !fill && !stroke {
document.network_interface.set_visibility(node_id, network_path, false);
}
Some(())
}
/// Rebuilds each removed Copy to Points node, with any feeding another's content rebuilt first so that content compiles when its type is resolved.
fn migrate_copy_to_points_nodes(document: &mut DocumentMessageHandler) {
let copy_to_points_nodes: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter(|(_, node, _)| node.inputs.len() == 8 && matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if identifier.as_str().ends_with("::CopyToPointsNode")))
.map(|(node_id, _, path)| (*node_id, path))
.collect();
if copy_to_points_nodes.is_empty() {
return;
}
// A node feeding another's content has fewer of these nodes upstream of its own content, so sorting by that count puts it first
let mut ordered = copy_to_points_nodes.clone();
ordered.sort_by_cached_key(|(node_id, network_path)| {
let Some(NodeInput::Node { node_id: content_source, .. }) = document.network_interface.document_node(node_id, network_path).and_then(|node| node.inputs.get(1)) else {
return 0;
};
document
.network_interface
.upstream_flow_back_from_nodes(vec![*content_source], network_path, FlowType::UpstreamFlow)
.filter(|upstream| copy_to_points_nodes.iter().any(|(other, other_path)| other == upstream && other_path == network_path))
.count()
});
let preprocessor = preprocessor::Preprocessor::new();
let mut content_types: HashMap<(Vec<NodeId>, NodeId, usize), Option<Type>> = HashMap::new();
for (node_id, network_path) in ordered {
let Some(node) = document.network_interface.document_node(&node_id, &network_path).cloned() else {
continue;
};
let content_type = match &node.inputs[1] {
NodeInput::Node { node_id: source, output_index, .. } => content_types
.entry((network_path.clone(), *source, *output_index))
.or_insert_with(|| resolved_output_type(document, &preprocessor, &node.inputs[1], &network_path))
.clone(),
_ => None,
};
migrate_copy_to_points(&node_id, &node, &network_path, content_type, document);
}
}
/// The compile-time type of the node output an input is wired to, resolved by compiling only that output's upstream.
/// It is `None` where that copy doesn't compile, such as for content reading a scope only the runtime provides.
fn resolved_output_type(document: &DocumentMessageHandler, preprocessor: &preprocessor::Preprocessor, input: &NodeInput, network_path: &[NodeId]) -> Option<Type> {
let NodeInput::Node { node_id, .. } = input else { return None };
// A hidden node passes its primary input through rather than giving the output its type describes
if !document.network_interface.is_visible(node_id, network_path) {
return None;
}
// Subnetworks stored as shared definitions are inlined so the type can be followed through them
let mut network = document.network_interface.document_network().clone();
network.inline_definitions().ok()?;
let resources = &document.resources.registry;
preprocessor.type_of_input(&network, network_path.to_vec(), input.clone(), &|resource_id| resources.hash(&resource_id))
}
/// Rebuilds a removed Copy to Points node as a Repeat on Points, then Vary Rotations and Vary Scales, ending at the original node to keep its downstream wires.
/// The points stay on the primary input so tools still edit them. List content other than a lone layer (or content of an unknown type) is grouped into one item to be repeated, then flattened back out with the node for its type.
fn migrate_copy_to_points(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId], content_type: Option<Type>, document: &mut DocumentMessageHandler) -> Option<()> {
use graphene_std::graphic::{flatten_color, flatten_gradient, flatten_graphic, flatten_raster, flatten_vector, into_group};
use graphene_std::math_nodes::multiply;
use graphene_std::raster_types::{CPU, Raster};
use graphene_std::repeat::repeat_on_points;
use graphene_std::transform_nodes::{vary_rotations, vary_scales};
use graphene_std::vector::Vector;
use graphene_std::vector::style::Gradient;
let number = |input: &NodeInput| match input.as_value() {
Some(TaggedValue::Number(number)) => Some(*number),
_ => None,
};
// A layer with nothing stacked below it gives one group, which is repeated as it is like a single item
let lone_layer = match &node.inputs[1] {
NodeInput::Node { node_id: source, .. } => {
document.network_interface.is_layer(source, network_path)
&& document
.network_interface
.document_node(source, network_path)
.is_some_and(|layer| matches!(layer.inputs.first(), Some(NodeInput::Value { .. })))
}
_ => false,
};
let flatten = match content_type {
_ if lone_layer => None,
Some(Type::Item(_)) => None,
Some(content_type) if content_type == list!(Vector) => Some(flatten_vector::IDENTIFIER),
Some(content_type) if content_type == list!(Raster<CPU>) => Some(flatten_raster::IDENTIFIER),
Some(content_type) if content_type == list!(Color) => Some(flatten_color::IDENTIFIER),
Some(content_type) if content_type == list!(Gradient) => Some(flatten_gradient::IDENTIFIER),
_ => Some(flatten_graphic::IDENTIFIER),
};
// The vary nodes are left out where they would leave every copy unchanged
let rotates = number(&node.inputs[6]) != Some(0.);
let scales = number(&node.inputs[2]) != Some(1.) || number(&node.inputs[3]) != Some(1.);
let mut stages = vec![repeat_on_points::IDENTIFIER];
if rotates {
stages.push(vary_rotations::IDENTIFIER);
}
if scales {
stages.push(vary_scales::IDENTIFIER);
}
stages.extend(flatten.clone());
let last_stage = stages.pop()?;
// Note the nodes laid out along a layer's chain through this one, since rewiring breaks that chain
let position = document.network_interface.position(node_id, network_path).unwrap_or_default();
let chained: Vec<NodeId> = if document.network_interface.is_chain(node_id, network_path) {
document
.network_interface
.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::HorizontalFlow)
.take_while(|upstream| document.network_interface.is_chain(upstream, network_path))
.collect()
} else {
Vec::new()
};
let mut last_stage_template = resolve_proto_node_type(last_stage)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut last_stage_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut last_stage_template)?;
reset_default_display_name(document, node_id, network_path, "Copy to Points");
let [points, content, scale_min, scale_max, scale_bias, scale_seed, rotation, rotation_seed] = <[NodeInput; 8]>::try_from(old_inputs).ok()?;
let insert = |document: &mut DocumentMessageHandler, identifier: ProtoNodeIdentifier, position: IVec2| -> Option<NodeId> {
let id = NodeId::new();
document.network_interface.insert_node(id, resolve_proto_node_type(identifier)?.default_node_template(), network_path);
document.network_interface.set_absolute_position(&id, position, network_path);
Some(id)
};
// Wire the points through each stage in turn, in a row leading up to the original node
let mut stage_ids = Vec::new();
for (index, identifier) in stages.iter().enumerate() {
stage_ids.push(insert(document, identifier.clone(), position - IVec2::new(7 * (stages.len() - index) as i32, 0))?);
}
stage_ids.push(*node_id);
let points_source = points.as_node();
document
.network_interface
.set_input(&InputConnector::node(stage_ids[0], repeat_on_points::PointsInput), points, network_path);
for pair in stage_ids.windows(2) {
document
.network_interface
.set_input(&InputConnector::node_at_index(pair[1], 0), NodeInput::node(pair[0], 0), network_path);
}
// A hidden node passed its points through, so its stages are hidden to keep doing that
if !node.visible {
for stage_id in &stage_ids {
document.network_interface.set_visibility(stage_id, network_path, false);
}
}
// The stages join the layer's chain if there is one, and the other nodes feeding the row move left to make room
if !chained.is_empty() {
for chain_node_id in stage_ids.iter().chain(&chained) {
document.network_interface.set_chain_position(chain_node_id, network_path);
}
}
let mut upstream = points_source;
while let Some(upstream_id) = upstream
&& !document.network_interface.is_layer(&upstream_id, network_path)
{
if !document.network_interface.is_chain(&upstream_id, network_path)
&& let Some(upstream_position) = document.network_interface.position(&upstream_id, network_path)
{
let shifted = upstream_position - IVec2::new(7 * stages.len() as i32, 0);
document.network_interface.set_absolute_position(&upstream_id, shifted, network_path);
}
upstream = document.network_interface.document_node(&upstream_id, network_path).and_then(|node| node.inputs.first()?.as_node());
}
let offset_from_stage = |document: &DocumentMessageHandler, stage_id: &NodeId, offset: IVec2| document.network_interface.position(stage_id, network_path).unwrap_or(position) + offset;
// Repeat the content at each point, grouped if it's flattened back out at the end
let repeated_content = match flatten {
Some(_) => {
let group_id = insert(document, into_group::IDENTIFIER, offset_from_stage(document, &stage_ids[0], IVec2::new(-7, 3)))?;
document.network_interface.set_input(&InputConnector::node(group_id, into_group::ContentInput), content, network_path);
NodeInput::node(group_id, 0)
}
None => content,
};
document
.network_interface
.set_input(&InputConnector::node(stage_ids[0], repeat_on_points::ContentInput), repeated_content, network_path);
// The rotation range was centered on zero, so a wired one is halved to each side by Multiply nodes
if rotates {
let rotations_id = stage_ids[1];
document
.network_interface
.set_input(&InputConnector::node(rotations_id, vary_rotations::SeedInput), rotation_seed, network_path);
let ends = [
(InputConnector::node(rotations_id, vary_rotations::MinInput), -0.5),
(InputConnector::node(rotations_id, vary_rotations::MaxInput), 0.5),
];
for (index, (end, factor)) in ends.into_iter().enumerate() {
let half_rotation = match number(&rotation) {
Some(rotation) => NodeInput::value(TaggedValue::Number(rotation * factor), false),
None => {
let multiply_id = insert(document, multiply::IDENTIFIER, offset_from_stage(document, &rotations_id, IVec2::new(-7, 3 + 3 * index as i32)))?;
document
.network_interface
.set_input(&InputConnector::node(multiply_id, multiply::MultiplierInput), rotation.clone(), network_path);
document.network_interface.set_input(
&InputConnector::node(multiply_id, multiply::MultiplicandInput),
NodeInput::value(TaggedValue::Number(factor), false),
network_path,
);
NodeInput::node(multiply_id, 0)
}
};
document.network_interface.set_input(&end, half_rotation, network_path);
}
}
// The bias is converted to the one that keeps its average scale, though a wired bias can't be converted and is left at the default
if scales {
let scales_id = stage_ids[1 + rotates as usize];
document.network_interface.set_input(&InputConnector::node(scales_id, vary_scales::MinInput), scale_min, network_path);
document.network_interface.set_input(&InputConnector::node(scales_id, vary_scales::MaxInput), scale_max, network_path);
document.network_interface.set_input(&InputConnector::node(scales_id, vary_scales::SeedInput), scale_seed, network_path);
if let Some(bias) = number(&scale_bias) {
let bias = NodeInput::value(TaggedValue::Number(vary_scales_bias_from_copy_to_points(bias)), false);
document.network_interface.set_input(&InputConnector::node(scales_id, vary_scales::BiasInput), bias, network_path);
}
}
Some(())
}
/// The Vary Scales bias giving the same average scale, as a fraction of its range, that the removed Copy to Points node's random scale distribution had for the scale bias it was given.
fn vary_scales_bias_from_copy_to_points(bias: f64) -> f64 {
if bias.abs() < 1e-6 {
return 0.5;
}
// Its bias curve `log2(1 + r (2^b - 1)) / b` averages `2^b / (2^b - 1) - 1 / (b ln 2)`, written with `x = b ln 2` to stay finite for a large bias
let x = bias * std::f64::consts::LN_2;
let average = -1. / (-x).exp_m1() - 1. / x;
// The new curve averages `k / (k + 1)` for `1 - (1 - t)^k` below a bias of 0.5, where `k = -log2(1 - bias)`, and `1 / (p + 1)` for `t^p` above it, where `p = -log2(bias)`
if average < 0.5 {
let k = average / (1. - average);
1. - (-k).exp2()
} else {
let p = 1. / average - 1.;
(-p).exp2()
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -5186,4 +5499,402 @@ mod tests {
assert_eq!(interface.display_name(&node_id, &[]), "Image", "node {node_id}");
}
}
#[tokio::test]
async fn copy_to_points_opens_as_a_chain_that_compiles() {
use crate::messages::portfolio::ingest::utility_types::IngestAction;
use crate::test_utils::test_prelude::*;
use graphene_std::NodeParameter;
use graphene_std::graphic::{flatten_graphic, flatten_vector, into_group};
use graphene_std::math_nodes::multiply;
use graphene_std::repeat::repeat_on_points;
use graphene_std::transform_nodes::{vary_rotations, vary_scales};
use graphene_std::vector::generator_nodes::{circle, rectangle};
let default_template = |identifier| {
resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier))
.expect("the definition should exist")
.default_node_template()
};
let number = |value| NodeInput::value(TaggedValue::Number(value), false);
let integer = |value| NodeInput::value(TaggedValue::Integer(value), false);
let copy_to_points = |[scale_min, scale_max, scale_bias]: [f64; 3], scale_seed, rotation, rotation_seed| {
let wired = || NodeInput::value(TaggedValue::None, false);
let inputs = vec![
wired(),
wired(),
number(scale_min),
number(scale_max),
number(scale_bias),
integer(scale_seed),
number(rotation),
integer(rotation_seed),
];
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::vector::CopyToPointsNode")),
input_metadata: inputs.iter().map(|_| ("Value", "").into()).collect(),
inputs,
display_name: "Copy to Points".to_string(),
..Default::default()
}
};
let (points, content, rotation, layer) = (NodeId(1), NodeId(2), NodeId(3), NodeId(4));
let (stored, wired, unchanged) = (NodeId(5), NodeId(6), NodeId(7));
let (lone_layer, single, layer_below) = (NodeId(8), NodeId(9), NodeId(10));
// Chain the variants so each is evaluated and rebuilt after those it depends on: a vector item with stored values, a list of vectors
// with a wired rotation, then a lone layer and a hidden stack of layers with settings that change nothing
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let interface = &mut editor.active_document_mut().network_interface;
interface.insert_node(unchanged, copy_to_points([1., 1., 0.], 0, 0., 0), &[]);
interface.insert_node(single, copy_to_points([1., 1., 0.], 0, 0., 0), &[]);
interface.insert_node(wired, copy_to_points([1., 1., 0.], 0, 0., 4), &[]);
interface.insert_node(stored, copy_to_points([0.5, 2., -10.], 7, 90., 3), &[]);
interface.insert_node(points, default_template(rectangle::IDENTIFIER), &[]);
interface.insert_node(content, default_template(circle::IDENTIFIER), &[]);
interface.insert_node(rotation, default_template(graphene_std::math_nodes::number_value::IDENTIFIER), &[]);
let merge = resolve_document_node_type(&DefinitionIdentifier::Network("Merge".into())).expect("the Merge definition should exist");
for layer_id in [layer, lone_layer, layer_below] {
interface.insert_node(layer_id, merge.default_node_template(), &[]);
}
interface.set_input(&InputConnector::node_at_index(layer, 1), NodeInput::node(wired, 0), &[]);
interface.set_input(&InputConnector::node_at_index(layer, 0), NodeInput::node(layer_below, 0), &[]);
interface.set_input(&InputConnector::node_at_index(layer_below, 1), NodeInput::node(single, 0), &[]);
for (node_id, content_source) in [(stored, content), (wired, stored), (single, lone_layer), (unchanged, layer)] {
interface.set_input(&InputConnector::node_at_index(node_id, 0), NodeInput::node(points, 0), &[]);
interface.set_input(&InputConnector::node_at_index(node_id, 1), NodeInput::node(content_source, 0), &[]);
}
interface.set_input(&InputConnector::node_at_index(wired, 6), NodeInput::node(rotation, 0), &[]);
interface.create_wire(&OutputConnector::primary_output(unchanged), &InputConnector::Export(0), &[]);
interface.set_visibility(&unchanged, &[], false);
let serialized = editor.active_document().serialize_document();
// Opening migrates the document, then evaluates its graph and checks the interface, failing on any error
editor
.handle_message(IngestMessage::Ingest {
data: serialized.into_bytes(),
action: IngestAction::Open,
mime_type: String::new(),
path: Some("copy-to-points.graphite".into()),
})
.await;
let interface = &editor.active_document().network_interface;
let node = |node_id| interface.document_node(&node_id, &[]).expect("the node should exist");
let upstream = |node_id, index: usize| match &node(node_id).inputs[index] {
NodeInput::Node { node_id, .. } => *node_id,
input => panic!("input {index} of node {node_id} should be wired, found {input:?}"),
};
let proto = DocumentNodeImplementation::ProtoNode;
// The points stay on the primary input, where tools look for the path to edit
let assert_repeats_on_points = |repeat_id, content_source, grouped: bool| {
assert_eq!(node(repeat_id).implementation, proto(repeat_on_points::IDENTIFIER));
assert_eq!(upstream(repeat_id, repeat_on_points::PointsInput::INDEX), points);
let repeated_content = upstream(repeat_id, repeat_on_points::ContentInput::INDEX);
if grouped {
assert_eq!(node(repeated_content).implementation, proto(into_group::IDENTIFIER));
assert_eq!(upstream(repeated_content, 0), content_source);
} else {
assert_eq!(repeated_content, content_source);
}
};
// One item is copied as it is, with the stored rotation range centered on zero and the bias kept as the average scale
assert_eq!(node(stored).implementation, proto(vary_scales::IDENTIFIER));
assert_ne!(interface.display_name(&stored, &[]), "Copy to Points");
assert_eq!(node(stored).input_value(vary_scales::MinInput), Some(&TaggedValue::Number(0.5)));
assert_eq!(node(stored).input_value(vary_scales::MaxInput), Some(&TaggedValue::Number(2.)));
assert_eq!(node(stored).input_value(vary_scales::SeedInput), Some(&TaggedValue::Integer(7)));
assert_eq!(node(stored).input_value(vary_scales::BiasInput), Some(&TaggedValue::Number(vary_scales_bias_from_copy_to_points(-10.))));
let rotations = upstream(stored, 0);
assert_eq!(node(rotations).implementation, proto(vary_rotations::IDENTIFIER));
assert_eq!(node(rotations).input_value(vary_rotations::MinInput), Some(&TaggedValue::Number(-45.)));
assert_eq!(node(rotations).input_value(vary_rotations::MaxInput), Some(&TaggedValue::Number(45.)));
assert_eq!(node(rotations).input_value(vary_rotations::SeedInput), Some(&TaggedValue::Integer(3)));
assert_repeats_on_points(upstream(rotations, 0), content, false);
// A list of vectors is grouped and flattened back out as vectors, a wired rotation is halved to each side of zero, and a scale range of 1 drops Vary Scales
assert_eq!(node(wired).implementation, proto(flatten_vector::IDENTIFIER));
let wired_rotations = upstream(wired, 0);
assert_eq!(node(wired_rotations).implementation, proto(vary_rotations::IDENTIFIER));
assert_eq!(node(wired_rotations).input_value(vary_rotations::SeedInput), Some(&TaggedValue::Integer(4)));
for (end, factor) in [(vary_rotations::MinInput::INDEX, -0.5), (vary_rotations::MaxInput::INDEX, 0.5)] {
let half_rotation = upstream(wired_rotations, end);
assert_eq!(node(half_rotation).implementation, proto(multiply::IDENTIFIER));
assert_eq!(upstream(half_rotation, 0), rotation);
assert_eq!(node(half_rotation).input_value(multiply::MultiplicandInput), Some(&TaggedValue::Number(factor)));
}
assert_repeats_on_points(upstream(wired_rotations, 0), stored, true);
// Feeding the layer, its stages join the layer's chain
assert!(interface.is_chain(&wired, &[]));
assert!(interface.is_chain(&wired_rotations, &[]));
assert!(interface.is_chain(&upstream(wired_rotations, 0), &[]));
// A lone layer is one group, repeated as it is
assert_repeats_on_points(single, lone_layer, false);
// A stack of layers is flattened back out as graphics, with only the Repeat on Points between since the settings change nothing
assert_eq!(node(unchanged).implementation, proto(flatten_graphic::IDENTIFIER));
assert_repeats_on_points(upstream(unchanged, 0), layer, true);
// Its stages are hidden with it, so the row still passes the points through
assert!(!interface.is_visible(&upstream(unchanged, 0), &[]));
}
#[tokio::test]
async fn copy_to_points_in_a_subnetwork_resolves_its_content_type() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkTemplate;
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use crate::test_utils::test_prelude::*;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graphene_std::repeat::repeat_on_points;
use graphene_std::vector::generator_nodes::{circle, rectangle};
let default_template = |identifier| {
resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier))
.expect("the definition should exist")
.default_node_template()
};
let number = |value| NodeInput::value(TaggedValue::Number(value), false);
let integer = |value| NodeInput::value(TaggedValue::Integer(value), false);
// A subnetwork copying a circle onto a rectangle's corners
let (points, content, copy_to_points, subnetwork) = (NodeId(1), NodeId(2), NodeId(3), NodeId(4));
let copy_to_points_template = NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::vector::CopyToPointsNode")),
inputs: vec![
NodeInput::node(points, 0),
NodeInput::node(content, 0),
number(1.),
number(1.),
number(0.),
integer(0),
number(0.),
integer(0),
],
..Default::default()
};
let subnetwork_template = NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(copy_to_points, 0)],
nodes: [
(points, default_template(rectangle::IDENTIFIER)),
(content, default_template(circle::IDENTIFIER)),
(copy_to_points, copy_to_points_template),
]
.into_iter()
.collect(),
..Default::default()
}),
..Default::default()
};
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let interface = &mut editor.active_document_mut().network_interface;
interface.insert_node(subnetwork, subnetwork_template, &[]);
interface.create_wire(&OutputConnector::primary_output(subnetwork), &InputConnector::Export(0), &[]);
assert!(!interface.document_network().definitions.is_empty(), "the subnetwork should be stored as a shared definition");
let serialized = editor.active_document().serialize_document();
// The circle is one vector item, so it's repeated as it is rather than grouped and flattened back out as graphics
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
let migrated = opened.network_interface.document_node(&copy_to_points, &[subnetwork]).expect("the node should exist");
assert_eq!(migrated.implementation, DocumentNodeImplementation::ProtoNode(repeat_on_points::IDENTIFIER));
}
#[tokio::test]
async fn copy_to_points_content_from_a_secondary_output_resolves_its_type() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkTemplate;
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use crate::test_utils::test_prelude::*;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graphene_std::NodeParameter;
use graphene_std::repeat::repeat_on_points;
use graphene_std::vector::generator_nodes::{circle, rectangle};
let default_template = |identifier| {
resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier))
.expect("the definition should exist")
.default_node_template()
};
let number = |value| NodeInput::value(TaggedValue::Number(value), false);
let integer = |value| NodeInput::value(TaggedValue::Integer(value), false);
// A subnetwork exporting a list of circles repeated on a rectangle's corners first, then a lone circle
let (subnetwork_points, subnetwork_content, subnetwork_repeat) = (NodeId(1), NodeId(2), NodeId(3));
let mut repeat_template = default_template(repeat_on_points::IDENTIFIER);
repeat_template.inputs[repeat_on_points::PointsInput::INDEX] = NodeInput::node(subnetwork_points, 0);
repeat_template.inputs[repeat_on_points::ContentInput::INDEX] = NodeInput::node(subnetwork_content, 0);
let subnetwork_template = NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(subnetwork_repeat, 0), NodeInput::node(subnetwork_content, 0)],
nodes: [
(subnetwork_points, default_template(rectangle::IDENTIFIER)),
(subnetwork_content, default_template(circle::IDENTIFIER)),
(subnetwork_repeat, repeat_template),
]
.into_iter()
.collect(),
..Default::default()
}),
..Default::default()
};
// Copy the subnetwork's lone circle onto another rectangle's corners
let (points, subnetwork, copy_to_points) = (NodeId(4), NodeId(5), NodeId(6));
let copy_to_points_template = NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::vector::CopyToPointsNode")),
inputs: vec![
NodeInput::value(TaggedValue::None, false),
NodeInput::value(TaggedValue::None, false),
number(1.),
number(1.),
number(0.),
integer(0),
number(0.),
integer(0),
],
..Default::default()
};
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let interface = &mut editor.active_document_mut().network_interface;
interface.insert_node(points, default_template(rectangle::IDENTIFIER), &[]);
interface.insert_node(subnetwork, subnetwork_template, &[]);
interface.insert_node(copy_to_points, copy_to_points_template, &[]);
interface.set_input(&InputConnector::node_at_index(copy_to_points, 0), NodeInput::node(points, 0), &[]);
interface.set_input(&InputConnector::node_at_index(copy_to_points, 1), NodeInput::node(subnetwork, 1), &[]);
interface.create_wire(&OutputConnector::primary_output(copy_to_points), &InputConnector::Export(0), &[]);
let serialized = editor.active_document().serialize_document();
// The second output is one vector item, so it's repeated as it is rather than grouped and flattened back out
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
let migrated = opened.network_interface.document_node(&copy_to_points, &[]).expect("the node should exist");
assert_eq!(migrated.implementation, DocumentNodeImplementation::ProtoNode(repeat_on_points::IDENTIFIER));
}
#[tokio::test]
async fn assign_colors_splits_by_its_fill_and_stroke_toggles() {
use crate::messages::portfolio::ingest::utility_types::IngestAction;
use crate::test_utils::test_prelude::*;
use graphene_std::NodeParameter;
use graphene_std::vector::generator_nodes::rectangle;
use graphene_std::vector::{vary_fill_colors, vary_stroke_colors};
let default_template = |identifier| {
resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier))
.expect("the definition should exist")
.default_node_template()
};
let gradient = default_template(vary_fill_colors::IDENTIFIER).inputs[vary_fill_colors::GradientInput::INDEX].clone();
let assign_colors = |fill, stroke, seed| {
let boolean = |value| NodeInput::value(TaggedValue::Bool(value), false);
let integer = |value| NodeInput::value(TaggedValue::Integer(value), false);
let inputs = vec![
NodeInput::value(TaggedValue::None, false),
boolean(fill),
boolean(stroke),
gradient.clone(),
boolean(false),
boolean(true),
integer(seed),
integer(0),
];
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::vector::AssignColorsNode")),
input_metadata: inputs.iter().map(|_| ("Value", "").into()).collect(),
inputs,
display_name: "Assign Colors".to_string(),
..Default::default()
}
};
// Chain every combination of the toggles after a rectangle, so the whole row is evaluated
let (shape, fill_only, stroke_only, both, neither) = (NodeId(1), NodeId(2), NodeId(3), NodeId(4), NodeId(5));
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let interface = &mut editor.active_document_mut().network_interface;
interface.insert_node(shape, default_template(rectangle::IDENTIFIER), &[]);
for (node_id, fill, stroke, seed) in [(fill_only, true, false, 1), (stroke_only, false, true, 2), (both, true, true, 3), (neither, false, false, 4)] {
interface.insert_node(node_id, assign_colors(fill, stroke, seed), &[]);
}
for pair in [shape, fill_only, stroke_only, both, neither].windows(2) {
interface.set_input(&InputConnector::node_at_index(pair[1], 0), NodeInput::node(pair[0], 0), &[]);
}
interface.create_wire(&OutputConnector::primary_output(neither), &InputConnector::Export(0), &[]);
let serialized = editor.active_document().serialize_document();
// Opening migrates the document, then evaluates its graph and checks the interface, failing on any error
editor
.handle_message(IngestMessage::Ingest {
data: serialized.into_bytes(),
action: IngestAction::Open,
mime_type: String::new(),
path: Some("assign-colors.graphite".into()),
})
.await;
let interface = &editor.active_document().network_interface;
let node = |node_id| interface.document_node(&node_id, &[]).expect("the node should exist");
let upstream = |node_id| match &node(node_id).inputs[0] {
NodeInput::Node { node_id, .. } => *node_id,
input => panic!("the content of node {node_id} should be wired, found {input:?}"),
};
let proto = DocumentNodeImplementation::ProtoNode;
assert_eq!(node(fill_only).implementation, proto(vary_fill_colors::IDENTIFIER));
assert_eq!(node(fill_only).input_value(vary_fill_colors::SeedInput), Some(&TaggedValue::Integer(1)));
assert_ne!(interface.display_name(&fill_only, &[]), "Assign Colors");
assert_eq!(node(stroke_only).implementation, proto(vary_stroke_colors::IDENTIFIER));
assert_eq!(node(stroke_only).input_value(vary_stroke_colors::SeedInput), Some(&TaggedValue::Integer(2)));
// Styling both puts a Vary Fill Colors node with the same parameters in front of the Vary Stroke Colors node
assert_eq!(node(both).implementation, proto(vary_stroke_colors::IDENTIFIER));
let inserted_fill = upstream(both);
assert_eq!(node(inserted_fill).implementation, proto(vary_fill_colors::IDENTIFIER));
assert_eq!(node(inserted_fill).input_value(vary_fill_colors::SeedInput), Some(&TaggedValue::Integer(3)));
assert_eq!(upstream(inserted_fill), stroke_only);
// Styling neither is kept as a hidden node, which passes its content through as before
assert_eq!(node(neither).implementation, proto(vary_fill_colors::IDENTIFIER));
assert!(!interface.is_visible(&neither, &[]));
}
#[test]
fn copy_to_points_bias_keeps_its_average() {
use graphene_std::core_types::math::midpoint::apply_midpoint_inverse;
// The removed node's bias curve, mapping a uniform random draw to a fraction of its scale range
let legacy_bias_curve = |random: f64, bias: f64| (1. - random * (1. - 2_f64.powf(bias))).log2() / bias;
// Averages a curve over evenly spaced draws from 0 to 1
fn average(curve: impl Fn(f64) -> f64) -> f64 {
const SAMPLES: usize = 100_000;
(0..SAMPLES).map(|i| curve((i as f64 + 0.5) / SAMPLES as f64)).sum::<f64>() / SAMPLES as f64
}
assert_eq!(vary_scales_bias_from_copy_to_points(0.), 0.5);
for bias in [-100., -10., -1., 1., 10., 100.] {
let converted = vary_scales_bias_from_copy_to_points(bias);
let legacy_average = average(|random| legacy_bias_curve(random, bias));
let migrated_average = average(|random| apply_midpoint_inverse(random, converted));
assert!(
(migrated_average - legacy_average).abs() < 1e-4,
"bias {bias} became {converted}, averaging {migrated_average} rather than {legacy_average}"
);
}
for bias in [-2000., 2000.] {
let converted = vary_scales_bias_from_copy_to_points(bias);
assert!(converted > 0. && converted < 1., "bias {bias} became {converted}");
}
}
}
@@ -11,13 +11,16 @@ use super::document_locks;
use super::document_migration::*;
use super::portfolio_message::PortfolioMessage;
use crate::application::{GRAPHITE_GIT_COMMIT_HASH, generate_uuid};
use crate::messages::dialog::DialogMessage;
use crate::messages::message::Message;
use crate::messages::portfolio::document::utility_types::misc::DocumentId;
use crate::messages::portfolio::sync::SyncMessage;
use crate::messages::resource_storage::ResourcesHandle;
use document_container::store::{DocumentKey, DocumentStore, MemoryStore};
use document_container::{AnyContainer, AsyncContainer};
use document_format::{Error as DocumentFormatError, GddV1, GddV1Layout, Layout, ReadError};
use document_graph_storage::{Declarations, PeerId};
use document_graph_storage::{Declarations, PeerId, UserId};
use graph_craft::application_io::resource::LoadResource;
use graph_craft::application_io::resource::{DataSource, ResourceHash, ResourceStorage};
use std::collections::HashSet;
use std::path::PathBuf;
@@ -118,7 +121,7 @@ pub(super) async fn attach_container(store: DocumentStoreHandle, document_id: Do
.into();
}
};
let gdd = open_storage_or_fallback_to_legacy(container.clone(), document_id).await;
let gdd = open_storage_or_fallback_to_legacy(container.clone(), document_id, &resources).await;
let declarations = load_declarations(gdd.as_ref(), &resources, document_id).await;
PortfolioMessage::StorageAttached {
document_id,
@@ -137,6 +140,26 @@ pub(super) async fn remove_stored_document(store: DocumentStoreHandle, document_
Message::NoOp
}
/// Joins the session of a stored document another tab holds, as a document and peer of this tab's own.
pub(super) async fn join_stored_session(store: DocumentStoreHandle, source: DocumentId) -> Message {
let manifest = async {
let container = store.open(document_key(source)).await.map_err(|error| error.to_string())?;
GddV1::read_manifest(&container, &GddV1Layout).await.map_err(|error| error.to_string())
}
.await;
match manifest {
Ok(manifest) => SyncMessage::Join {
token: peer_transport::SessionToken::for_document(manifest.document_id).to_string(),
}
.into(),
Err(error) => DialogMessage::DisplayDialogError {
title: "Failed to join the session".into(),
description: format!("The session's document could not be read: {error}"),
}
.into(),
}
}
/// Opens a copy of a stored document that another tab may be writing. Its fresh manifest id separates it from the original.
pub(super) async fn copy_stored_document(store: DocumentStoreHandle, source: DocumentId, document_id: DocumentId, document_name: String, resources: ResourcesHandle, reset_nodes: bool) -> Message {
document_locks::claim(document_id).await;
@@ -181,12 +204,14 @@ pub(super) async fn copy_stored_document(store: DocumentStoreHandle, source: Doc
}
/// Materializes a `.gdd` archive into a fresh store container and loads it like a stored document.
#[allow(clippy::too_many_arguments)]
pub(super) async fn open_document_file(
store: DocumentStoreHandle,
document_id: DocumentId,
document_name: Option<String>,
document_path: Option<PathBuf>,
content: Vec<u8>,
fresh_identity: bool,
resources: ResourcesHandle,
reset_nodes: bool,
) -> Message {
@@ -197,13 +222,21 @@ pub(super) async fn open_document_file(
Ok::<_, String>(container)
}
.await;
let (document, gdd) = match materialized {
let (mut document, mut gdd) = match materialized {
Ok(container) => load_from_container(container, document_id, &resources, reset_nodes).await,
Err(error) => {
log::error!("Opening the document archive for {document_id:?} failed: {error}");
(None, None)
}
};
// The room derives from the manifest's document id, so a fresh id is a fresh room
if fresh_identity
&& let Some(storage) = gdd.as_mut().or_else(|| document.as_mut().and_then(|document| document.storage_mut()))
&& let Err(error) = storage.update_manifest(|manifest| manifest.document_id = generate_uuid())
{
log::error!("Giving the copy of {document_id:?} its own id failed: {error}");
(document, gdd) = (None, None);
}
let declarations = load_declarations(gdd.as_ref(), &resources, document_id).await;
PortfolioMessage::DocumentFileLoaded {
document_id,
@@ -228,11 +261,11 @@ async fn load_from_container(container: AnyContainer, document_id: DocumentId, r
Ok(mut document) => {
document.set_auto_save_state(true);
document.container = Some(container.clone());
let gdd = open_storage_or_fallback_to_legacy(container, document_id).await;
let gdd = open_storage_or_fallback_to_legacy(container, document_id, resources).await;
(Some(document), gdd)
}
Err(legacy_error) => {
let gdd = match GddV1::open_in(container.clone(), GddV1Layout).await {
let gdd = match open_migrating(container.clone(), resources).await {
Ok(gdd) => gdd,
Err(storage_error) => {
log::error!("Loading {document_id:?} failed. Legacy: {legacy_error}. Storage: {storage_error}");
@@ -249,8 +282,14 @@ async fn load_from_container(container: AnyContainer, document_id: DocumentId, r
}
}
async fn open_storage_or_fallback_to_legacy(container: AnyContainer, document_id: DocumentId) -> Option<GddV1> {
match GddV1::open_in(container.clone(), GddV1Layout).await {
/// Open a document's storage, offering its migrations the compiler and the global cache's declarations.
async fn open_migrating(container: AnyContainer, resources: &dyn LoadResource) -> Result<GddV1, DocumentFormatError> {
let host = migration_compiled::CompilerHost::default();
GddV1::open_in_with(container, GddV1Layout, Some(resources), Some(&host)).await
}
async fn open_storage_or_fallback_to_legacy(container: AnyContainer, document_id: DocumentId, resources: &dyn LoadResource) -> Option<GddV1> {
match open_migrating(container.clone(), resources).await {
Ok(gdd) => return Some(gdd),
Err(DocumentFormatError::MissingManifest) => {}
// Container I/O, newer-format, and migration errors keep the existing files, since a later build can still read them. Anything else is broken data the legacy document replaces.
@@ -267,7 +306,8 @@ async fn open_storage_or_fallback_to_legacy(container: AnyContainer, document_id
container.remove(&path).await?;
}
}
GddV1::create_in(container, GddV1Layout, PeerId(generate_uuid()), document_id.0, version.clone(), version)
let peer = PeerId(generate_uuid());
GddV1::create_in(container, GddV1Layout, peer, UserId(peer.0), document_id.0, version.clone(), version)
}
.await;
match created {
@@ -332,7 +372,7 @@ async fn build_document_from_storage(gdd: GddV1, byte_store: &ResourcesHandle, d
interface.give_diverged_catalog_entries_new_ids();
// TODO: Run document upgrades here once this format has a versioned migration
let mut document = DocumentMessageHandler::from_storage(interface, gdd, declarations, String::new(), None);
let mut document = DocumentMessageHandler::from_storage(interface, gdd, declarations, byte_store.storage(), String::new(), None);
document.finalize_storage_load();
Some(document)
}
@@ -421,13 +461,17 @@ mod tests {
#[tokio::test]
async fn a_failed_migration_keeps_the_stored_document() {
let container = AnyContainer::Memory(MemoryBackend::new());
let mut gdd = GddV1::create_in(container.clone(), GddV1Layout, PeerId(1), 1, "editor".into(), "std".into()).unwrap();
let mut gdd = GddV1::create_in(container.clone(), GddV1Layout, PeerId(1), UserId(1), 1, "editor".into(), "std".into()).unwrap();
// No format step starts from version 0, so the migration fails
gdd.update_manifest(|manifest| manifest.format_version = 0).unwrap();
let files = container.list("").await.unwrap();
assert!(open_storage_or_fallback_to_legacy(container.clone(), DocumentId(1)).await.is_none());
assert!(
open_storage_or_fallback_to_legacy(container.clone(), DocumentId(1), &graph_craft::application_io::resource::HashMapResourceStorage::new())
.await
.is_none()
);
assert_eq!(container.list("").await.unwrap(), files, "the document's files should survive for a build that can migrate them");
let manifest = container
.read(&document_format::io::path_for(GddV1Layout.manifest_basename(), document_format::MANIFEST_CODEC))
@@ -229,6 +229,7 @@ mod tests {
name: name.to_string(),
path: None,
is_saved: true,
session: None,
});
let names: HashSet<_> = recovery_file_names(infos.iter()).into_iter().map(|(_, name)| name).collect();
@@ -0,0 +1,16 @@
use crate::messages::prelude::*;
#[impl_message(Message, PortfolioMessage, History)]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum HistoryMessage {
Refresh,
Tick,
Expand { id: String, expanded: bool },
LoadMore,
GoBack { id: String },
RemoveStep { id: String },
BringBack { id: String },
Follow { id: Option<String> },
Rename { id: String, label: String },
Tag { id: String, tag: String, on: bool },
}
@@ -0,0 +1,508 @@
use super::utility_types::{HistoryBranch, HistoryDeltaRow, HistoryPanelState, HistoryProgressRow, HistoryRow};
use crate::messages::portfolio::document::DocumentMessageHandler;
use crate::messages::portfolio::sync::identity::{anonymous_name, user_color};
use crate::messages::portfolio::sync::now_ms;
use crate::messages::prelude::*;
use document_format::GddV1;
use document_graph_storage::{Delta, HistoryMetadata, HotOpId, PeerId, RegistryDelta, Rev, Session, Subject, UserId, rev_attr};
use peer_transport::RemotePeer;
use std::collections::{HashMap, HashSet};
use std::hash::{Hash, Hasher};
#[derive(ExtractField)]
pub struct HistoryMessageContext<'a> {
pub documents: &'a mut HashMap<DocumentId, DocumentMessageHandler>,
pub active_document_id: Option<DocumentId>,
pub panel_open: bool,
}
/// Sends the History panel the active document's history and turns its actions into head moves.
#[derive(Debug, Default, ExtractField)]
pub struct HistoryMessageHandler {
ticking: bool,
expanded: HashSet<Rev>,
limit: usize,
following: Option<Rev>,
last_sent: Option<u64>,
}
/// How many interactions each request adds.
const PAGE: usize = 100;
#[message_handler_data]
impl MessageHandler<HistoryMessage, HistoryMessageContext<'_>> for HistoryMessageHandler {
fn process_message(&mut self, message: HistoryMessage, responses: &mut VecDeque<Message>, mut context: HistoryMessageContext) {
match message {
HistoryMessage::Refresh => {
if !self.ticking {
self.ticking = true;
responses.add(BroadcastMessage::SubscribeEvent {
on: EventMessage::AnimationFrame,
send: Box::new(HistoryMessage::Tick.into()),
});
}
self.send(&context, responses, true);
}
HistoryMessage::Tick => {
if context.panel_open {
self.send(&context, responses, false);
}
}
HistoryMessage::Expand { id, expanded } => {
if let Some(rev) = parse_rev(&id) {
match expanded {
true => self.expanded.insert(rev),
false => self.expanded.remove(&rev),
};
}
self.send(&context, responses, true);
}
HistoryMessage::LoadMore => {
self.limit = self.limit.max(PAGE) + PAGE;
self.send(&context, responses, true);
}
HistoryMessage::Follow { id } => {
self.following = id.as_deref().and_then(parse_rev);
self.send(&context, responses, true);
}
HistoryMessage::GoBack { id } => {
let Some((gdd, rev)) = active_storage(&context).zip(parse_rev(&id)) else { return };
match place(gdd.session(), rev) {
Some(Place::Undone(steps)) => (0..steps).for_each(|_| responses.add(DocumentMessage::Redo)),
Some(Place::Line(0)) => {}
// A session moves the head for everyone at once. Alone, undo each interaction to keep undo in step
Some(Place::Line(steps)) => match gdd.role().is_some() {
true => responses.add(DocumentMessage::HistoryMoveHead { rev }),
false => (0..steps).for_each(|_| responses.add(DocumentMessage::Undo)),
},
None => log::warn!("The History panel asked to go to {rev:?}, which is not on the head's line"),
}
}
HistoryMessage::RemoveStep { id } => {
if let Some(rev) = parse_rev(&id) {
responses.add(DocumentMessage::HistoryRemoveStep { rev });
}
}
HistoryMessage::BringBack { id } => {
let Some((gdd, rev)) = active_storage(&context).zip(parse_rev(&id)) else { return };
match place(gdd.session(), rev) {
Some(Place::Undone(steps)) => (0..steps).for_each(|_| responses.add(DocumentMessage::Redo)),
Some(Place::Line(_)) => {}
None => responses.add(DocumentMessage::HistoryRestoreStep { rev }),
}
}
HistoryMessage::Rename { id, label } => {
let Some((gdd, rev)) = active_storage_mut(&mut context).zip(parse_rev(&id)) else { return };
if let Err(error) = gdd.record(Subject::Rev(rev), rev_attr::LABEL, serde_json::Value::from(label.trim()), now_ms()) {
log::warn!("Naming the step failed: {error}");
}
self.send(&context, responses, true);
}
HistoryMessage::Tag { id, tag, on } => {
let tag = tag.trim();
if tag.is_empty() {
return;
}
let Some((gdd, rev)) = active_storage_mut(&mut context).zip(parse_rev(&id)) else { return };
if let Err(error) = gdd.record(Subject::Rev(rev), &format!("{}{tag}", rev_attr::TAG_PREFIX), serde_json::Value::Bool(on), now_ms()) {
log::warn!("Tagging the step failed: {error}");
}
self.send(&context, responses, true);
}
}
}
advertise_actions!(HistoryMessageDiscriminant;);
}
impl HistoryMessageHandler {
fn send(&mut self, context: &HistoryMessageContext, responses: &mut VecDeque<Message>, force: bool) {
let Some(gdd) = active_storage(context) else {
if force || self.last_sent.is_some() {
self.last_sent = None;
responses.add(FrontendMessage::UpdateHistoryPanel { state: HistoryPanelState::default() });
}
return;
};
if self.following.is_some_and(|tip| gdd.session().delta(tip).is_none()) {
self.following = None;
}
let limit = self.limit.max(PAGE);
let fingerprint = fingerprint(context.active_document_id, gdd, limit, &self.expanded, self.following);
if !force && self.last_sent == Some(fingerprint) {
return;
}
self.last_sent = Some(fingerprint);
let state = panel_state(gdd, limit, &self.expanded, self.following);
responses.add(FrontendMessage::UpdateHistoryPanel { state });
}
}
fn active_storage<'a>(context: &'a HistoryMessageContext) -> Option<&'a GddV1> {
context.active_document_id.and_then(|id| context.documents.get(&id)).and_then(|document| document.storage())
}
fn active_storage_mut<'a>(context: &'a mut HistoryMessageContext) -> Option<&'a mut GddV1> {
context.active_document_id.and_then(|id| context.documents.get_mut(&id)).and_then(|document| document.storage_mut())
}
fn parse_rev(id: &str) -> Option<Rev> {
id.parse::<u128>().ok().and_then(Rev::new)
}
/// Where an interaction sits relative to the head.
enum Place {
/// On the head's line, this many interactions back.
Line(usize),
/// Undone above the head, this many redos forward.
Undone(usize),
}
fn place(session: &Session, rev: Rev) -> Option<Place> {
let head = session.head_rev();
let (kept, _) = line(session, head, None, usize::MAX);
if let Some(steps) = interactions(&kept).iter().position(|group| group[0].id == rev) {
return Some(Place::Line(steps));
}
// The stack's first entry is the farthest undone, so its line holds every undone step
let checkpoint = *session.redo_stack().first()?;
let (undone, _) = line(session, Some(checkpoint), head, usize::MAX);
let groups = interactions(&undone);
let index = groups.iter().position(|group| group[0].id == rev)?;
Some(Place::Undone(groups.len() - index))
}
/// A hash of the panel's inputs, cheap enough for every frame.
fn fingerprint(document_id: Option<DocumentId>, gdd: &GddV1, limit: usize, expanded: &HashSet<Rev>, following: Option<Rev>) -> u64 {
let session = gdd.session();
let mut hasher = std::collections::hash_map::DefaultHasher::new();
document_id.hash(&mut hasher);
session.history_len().hash(&mut hasher);
session.head_rev().hash(&mut hasher);
session.redo_stack().hash(&mut hasher);
session.hot_log().len().hash(&mut hasher);
gdd.role().is_some().hash(&mut hasher);
for remote in gdd.peers() {
remote.user.hash(&mut hasher);
remote.name.hash(&mut hasher);
}
for fact in gdd.metadata().facts() {
fact.subject.hash(&mut hasher);
fact.key.hash(&mut hasher);
fact.stamp.hash(&mut hasher);
}
limit.hash(&mut hasher);
expanded.len().hash(&mut hasher);
following.hash(&mut hasher);
hasher.finish()
}
fn panel_state(gdd: &GddV1, limit: usize, expanded: &HashSet<Rev>, following: Option<Rev>) -> HistoryPanelState {
let session = gdd.session();
let people = People {
session,
metadata: gdd.metadata(),
peers: gdd.peers().collect(),
};
let mut children: HashMap<Rev, Vec<Rev>> = HashMap::new();
for delta in session.history() {
for parent in delta.all_parents() {
children.entry(parent).or_default().push(delta.id);
}
}
let head = session.head_rev();
let (head_line, _) = line(session, head, None, usize::MAX);
let head_line_revs: HashSet<Rev> = head_line.iter().map(|delta| delta.id).collect();
let undone = match (following, session.redo_stack().first()) {
(None, Some(&checkpoint)) => line(session, Some(checkpoint), head, usize::MAX).0,
_ => Vec::new(),
};
let (shown, more) = line(session, following.or(head), None, limit);
let on_line: HashSet<Rev> = undone.iter().chain(&shown).map(|delta| delta.id).collect();
let view = View {
children: &children,
on_line: &on_line,
head_line: &head_line_revs,
head,
people: &people,
expanded,
session,
metadata: gdd.metadata(),
};
let undone_rows = interactions(&undone).into_iter().map(|group| view.row(&group, true));
let shown_rows = interactions(&shown).into_iter().map(|group| view.row(&group, false));
let rows = undone_rows.chain(shown_rows).collect();
// Open interactions first, then closed ones waiting to retire, newest first
let hot_log = session.hot_log();
let closed = session.closed_interactions();
let in_closed: HashSet<HotOpId> = closed.iter().flat_map(|interaction| interaction.ops.iter().copied()).collect();
let mut open_by_peer: Vec<(PeerId, Vec<&RegistryDelta>)> = Vec::new();
for hot_op in hot_log.iter().filter(|hot_op| !in_closed.contains(&hot_op.id())) {
match open_by_peer.iter_mut().find(|(peer, _)| *peer == hot_op.timestamp.peer) {
Some((_, ops)) => ops.push(&hot_op.op),
None => open_by_peer.push((hot_op.timestamp.peer, vec![&hot_op.op])),
}
}
let mut progress: Vec<HistoryProgressRow> = open_by_peer.into_iter().map(|(peer, ops)| progress_row(&people, peer, &ops, true)).collect();
for interaction in closed.iter().rev() {
let ids: HashSet<HotOpId> = interaction.ops.iter().copied().collect();
let ops: Vec<&RegistryDelta> = hot_log.iter().filter(|hot_op| ids.contains(&hot_op.id())).map(|hot_op| &hot_op.op).collect();
progress.push(progress_row(&people, interaction.author, &ops, false));
}
HistoryPanelState {
rows,
progress,
more,
following: following.map(|tip| tip.to_string()),
session: gdd.role().is_some(),
}
}
/// The deltas from `from` back along first parents to `until` (exclusive) or the root, newest first. Stops after
/// `limit` interaction ends, and the flag says whether it did.
fn line(session: &Session, from: Option<Rev>, until: Option<Rev>, limit: usize) -> (Vec<Delta>, bool) {
let mut deltas = Vec::new();
let mut ends = 0;
let mut current = from;
while let Some(rev) = current
&& Some(rev) != until
{
let Some(delta) = session.delta(rev) else { break };
if delta.is_interaction_end() {
if ends == limit {
return (deltas, true);
}
ends += 1;
}
deltas.push(delta.clone());
current = delta.parent;
}
(deltas, false)
}
/// Groups a newest-first line into interactions. Newest deltas without an end, retired mid-interaction, form their own.
fn interactions(deltas: &[Delta]) -> Vec<Vec<&Delta>> {
let mut groups: Vec<Vec<&Delta>> = Vec::new();
for delta in deltas {
match groups.last_mut() {
Some(group) if !delta.is_interaction_end() => group.push(delta),
_ => groups.push(vec![delta]),
}
}
groups
}
struct View<'a> {
children: &'a HashMap<Rev, Vec<Rev>>,
on_line: &'a HashSet<Rev>,
head_line: &'a HashSet<Rev>,
head: Option<Rev>,
people: &'a People<'a>,
expanded: &'a HashSet<Rev>,
session: &'a Session,
metadata: &'a HistoryMetadata,
}
impl View<'_> {
fn row(&self, group: &[&Delta], undone: bool) -> HistoryRow {
let closing = group[0];
let person = self.people.person(closing.author);
let branches = group
.iter()
.flat_map(|delta| self.children.get(&delta.id).into_iter().flatten())
.filter(|child| !self.on_line.contains(child))
.map(|&child| self.branch(child))
.collect();
let is_expanded = self.expanded.contains(&closing.id);
let details = match is_expanded {
true => group
.iter()
.map(|delta| {
let author = self.people.person(delta.author);
HistoryDeltaRow {
id: delta.id.to_string(),
label: describe(&delta.kind),
author: author.name,
color: author.color,
time: delta.retired_at().map(|ms| ms as f64),
}
})
.collect(),
false => Vec::new(),
};
let given = self.metadata.rev_label(closing.id);
HistoryRow {
id: closing.id.to_string(),
label: given.map(str::to_string).unwrap_or_else(|| summarize(group.iter().map(|delta| &delta.kind))),
named: given.is_some(),
tags: self.metadata.rev_tags(closing.id).into_iter().map(str::to_string).collect(),
author: person.name,
anonymous: person.anonymous,
mine: person.mine,
color: person.color,
time: group.iter().find_map(|delta| delta.retired_at()).map(|ms| ms as f64),
deltas: group.len(),
branches,
undone,
abandoned: !undone && !self.head_line.contains(&closing.id),
head: Some(closing.id) == self.head,
expanded: is_expanded,
details,
}
}
fn branch(&self, first: Rev) -> HistoryBranch {
let mut tip = first;
while let Some(&next) = self.children.get(&tip).and_then(|children| children.first()) {
tip = next;
}
let (newest, _) = line(self.session, Some(tip), None, 1);
let label = self
.metadata
.rev_label(tip)
.map(str::to_string)
.unwrap_or_else(|| interactions(&newest).first().map(|group| summarize(group.iter().map(|delta| &delta.kind))).unwrap_or_default());
HistoryBranch { id: tip.to_string(), label }
}
}
fn progress_row(people: &People, peer: PeerId, ops: &[&RegistryDelta], open: bool) -> HistoryProgressRow {
let person = people.person(peer);
HistoryProgressRow {
label: summarize(ops.iter().copied()),
author: person.name,
anonymous: person.anonymous,
mine: person.mine,
color: person.color,
ops: ops.len(),
open,
}
}
/// One line for a run of changes, most frequent kind first. Peer registrations and markers are named only when alone.
fn summarize<'a>(kinds: impl IntoIterator<Item = &'a RegistryDelta>) -> String {
let is_bookkeeping = |kind: &RegistryDelta| matches!(kind, RegistryDelta::RegisterPeer { .. } | RegistryDelta::Meta);
let mut kinds: Vec<&RegistryDelta> = kinds.into_iter().collect();
if kinds.iter().any(|kind| !is_bookkeeping(kind)) {
kinds.retain(|kind| !is_bookkeeping(kind));
}
let mut counts: Vec<(String, usize)> = Vec::new();
for kind in kinds {
let label = describe(kind);
match counts.iter_mut().find(|(known, _)| *known == label) {
Some((_, count)) => *count += 1,
None => counts.push((label, 1)),
}
}
counts.sort_by_key(|(_, count)| std::cmp::Reverse(*count));
let mut parts: Vec<String> = counts
.iter()
.take(2)
.map(|(label, count)| match count {
1 => label.clone(),
count => format!("{label} ×{count}"),
})
.collect();
if counts.len() > 2 {
parts.push(format!("{} more", counts.len() - 2));
}
parts.join(", ")
}
fn describe(kind: &RegistryDelta) -> String {
match kind {
RegistryDelta::AddNode { .. } => "Added a node".into(),
RegistryDelta::RemoveNode { .. } => "Removed a node".into(),
RegistryDelta::ChangeNodeInput { .. } => "Changed an input".into(),
RegistryDelta::SetNodeInputs { .. } => "Set a node's inputs".into(),
RegistryDelta::SetNodeImplementation { .. } => "Changed what a node does".into(),
RegistryDelta::ChangeNodeAttribute { delta, .. } => format!("Set node {}", delta.key),
RegistryDelta::ChangeNodeInputAttribute { delta, .. } => format!("Set input {}", delta.key),
RegistryDelta::SetNetworkExport { .. } => "Changed an export".into(),
RegistryDelta::ChangeNetworkAttribute { delta, .. } => format!("Set network {}", delta.key),
RegistryDelta::AddNetwork { .. } => "Added a network".into(),
RegistryDelta::RemoveNetwork { .. } => "Removed a network".into(),
RegistryDelta::AddResource { .. } => "Added a resource".into(),
RegistryDelta::SetResourceHash { .. } => "Updated a resource".into(),
RegistryDelta::RemoveResource { .. } => "Removed a resource".into(),
RegistryDelta::AddSource { .. } | RegistryDelta::RemoveSource { .. } => "Changed where a resource comes from".into(),
RegistryDelta::RegisterPeer { .. } => "Joined the document".into(),
RegistryDelta::ChangeDocumentAttribute { delta } => format!("Set document {}", delta.key),
RegistryDelta::Merge { .. } => "Joined two lines of work".into(),
RegistryDelta::Meta => "Marked a step".into(),
RegistryDelta::Other(_) => "Changed something".into(),
}
}
/// Names and colours authors by user id. The document's record wins, then the announced name, then the stand-in.
struct People<'a> {
session: &'a Session,
metadata: &'a HistoryMetadata,
peers: Vec<&'a RemotePeer>,
}
struct Person {
name: String,
anonymous: bool,
mine: bool,
color: String,
}
impl People<'_> {
fn person(&self, peer: PeerId) -> Person {
// A peer that never registered is its own user
let user = self.session.user_of(peer).unwrap_or(UserId(peer.0));
let recorded = self.metadata.user_name(user).map(str::to_string);
let announced = || self.peers.iter().find(|remote| remote.user == user && !remote.name.is_empty()).map(|remote| remote.name.clone());
let (name, anonymous) = match recorded.or_else(announced) {
Some(name) => (name, false),
None => (anonymous_name(user), true),
};
Person {
name,
anonymous,
mine: self.session.is_mine(peer),
color: user_color(user),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Undoing pushes each step's head, so undone steps must be read from the first entry.
#[test]
fn every_undone_step_stays_on_the_panel() {
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::GddV1Layout;
use document_graph_storage::{Network, NetworkId};
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 1, "editor".into(), "stdlib".into()).expect("create");
for id in 1..=3 {
let network = Network::default();
gdd.stage_ops([RegistryDelta::AddNetwork { id: NetworkId(id), network }]).expect("stage");
gdd.retire_pending_interaction().expect("retire");
}
gdd.undo().expect("undo");
gdd.undo().expect("undo");
assert_eq!(panel_state(&gdd, PAGE, &HashSet::new(), None).rows.len(), 3);
}
#[test]
fn a_run_of_only_markers_is_named_by_them() {
let register = RegistryDelta::RegisterPeer { peer: PeerId(1), user: UserId(1) };
let merge = RegistryDelta::Merge { extra_parents: Vec::new() };
assert_eq!(summarize([&RegistryDelta::Meta, &RegistryDelta::Meta]), "Marked a step ×2");
assert_eq!(summarize([&register, &RegistryDelta::Meta]), "Joined the document, Marked a step");
assert_eq!(summarize([&RegistryDelta::Meta, &merge, &register]), "Joined two lines of work");
}
}
@@ -0,0 +1,8 @@
mod history_message;
mod history_message_handler;
pub mod utility_types;
#[doc(inline)]
pub use history_message::{HistoryMessage, HistoryMessageDiscriminant};
#[doc(inline)]
pub use history_message_handler::{HistoryMessageContext, HistoryMessageHandler};
@@ -0,0 +1,72 @@
//! What the History panel shows, as the frontend receives it.
/// The panel's content, newest first. The head's line with undone interactions above it, or a followed branch's line.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HistoryPanelState {
pub rows: Vec<HistoryRow>,
/// Work not yet in history. One row per person's open work and per closed interaction waiting to retire.
pub progress: Vec<HistoryProgressRow>,
pub more: bool,
pub following: Option<String>,
/// In a session, a head move affects everyone.
pub session: bool,
}
/// One interaction, a run of deltas that undo takes back together.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HistoryRow {
/// The rev closing the interaction, in decimal.
pub id: String,
pub label: String,
pub named: bool,
pub tags: Vec<String>,
pub author: String,
/// `author` is a stand-in.
pub anonymous: bool,
pub mine: bool,
pub color: String,
/// Milliseconds since the Unix epoch, if the retirer recorded it.
pub time: Option<f64>,
pub deltas: usize,
/// Branches off the shown line, each by its tip.
pub branches: Vec<HistoryBranch>,
pub undone: bool,
/// On a followed branch, off the head's line.
pub abandoned: bool,
pub head: bool,
pub expanded: bool,
pub details: Vec<HistoryDeltaRow>,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HistoryBranch {
pub id: String,
pub label: String,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HistoryDeltaRow {
pub id: String,
pub label: String,
pub author: String,
pub color: String,
pub time: Option<f64>,
}
/// A person with unretired work in the room's hot log.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HistoryProgressRow {
pub label: String,
pub author: String,
pub anonymous: bool,
pub mine: bool,
pub color: String,
pub ops: usize,
/// Still being made, not closed and waiting.
pub open: bool,
}
@@ -49,6 +49,7 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
IngestMessage::Ingest { data, action, mime_type, path } => {
let data_type = DataType::detect(&data, &mime_type, path.as_deref());
let fresh_identity = matches!(action, IngestAction::OpenDemo);
let placement = match action {
IngestAction::ResourceInput {
document_id,
@@ -80,7 +81,7 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
}
return;
}
IngestAction::Open => None,
IngestAction::Open | IngestAction::OpenDemo => None,
IngestAction::Import | IngestAction::Paste => Some((None, None)),
IngestAction::DropOnCanvas { mouse } => Some((Some(mouse), None)),
IngestAction::DropOnLayers { parent, insert_index } => Some((None, Some((parent, insert_index as usize)))),
@@ -109,6 +110,7 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
document_name: name,
document_path,
content: data,
fresh_identity,
});
return;
}
@@ -16,6 +16,8 @@ const SNIFFED_TEXT_LENGTH: usize = 4096;
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
pub enum IngestAction {
Open,
/// Open a distributed file such as a demo artwork as a copy with its own session room.
OpenDemo,
Import,
Paste,
DropOnCanvas {
+2
View File
@@ -7,8 +7,10 @@ pub mod document_migration;
pub mod document_storage_io;
pub mod failed_documents;
pub mod fonts;
pub mod history;
pub mod ingest;
pub mod persistent_state;
pub mod sync;
pub mod utility_types;
pub mod workspace;
@@ -1,5 +1,7 @@
use super::document::utility_types::document_metadata::LayerNodeIdentifier;
use super::history::HistoryMessage;
use super::persistent_state::PersistentStateMessage;
use super::sync::SyncMessage;
use crate::messages::frontend::utility_types::{ExportBounds, FileType, PersistedState};
use crate::messages::prelude::*;
use document_container::AnyContainer;
@@ -21,6 +23,10 @@ pub enum PortfolioMessage {
#[child]
PersistentState(PersistentStateMessage),
#[child]
History(HistoryMessage),
#[child]
Sync(SyncMessage),
#[child]
Workspace(WorkspaceMessage),
// Messages
@@ -64,6 +70,9 @@ pub enum PortfolioMessage {
source: DocumentId,
document_name: String,
},
JoinStoredSession {
source: DocumentId,
},
CollectResources,
StoredDocumentLoaded {
document_id: DocumentId,
@@ -80,6 +89,11 @@ pub enum PortfolioMessage {
NewDocumentWithName {
name: String,
},
/// Creates the document under a given id, so the sender can recognize it on mount.
NewDocumentWithId {
name: String,
document_id: DocumentId,
},
OpenLegacyDocumentFile {
document_name: Option<String>,
document_path: Option<PathBuf>,
@@ -89,6 +103,7 @@ pub enum PortfolioMessage {
document_name: Option<String>,
document_path: Option<PathBuf>,
content: Vec<u8>,
fresh_identity: bool,
},
DocumentFileLoaded {
document_id: DocumentId,
@@ -6,7 +6,7 @@ use crate::application::{Environment, generate_uuid};
use crate::consts::DEFAULT_DOCUMENT_NAME;
use crate::messages::animation::TimingInformation;
use crate::messages::dialog::simple_dialogs;
use crate::messages::frontend::utility_types::{DocumentInfo, PersistedState};
use crate::messages::frontend::utility_types::{DocumentInfo, PersistedState, SessionStatus};
use crate::messages::input_mapper::utility_types::keyboard::{Key, KeysGroup, LabeledShortcut};
use crate::messages::input_mapper::utility_types::macros::action_shortcut;
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
@@ -15,7 +15,8 @@ use crate::messages::portfolio::document::DocumentMessageContext;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions;
use crate::messages::portfolio::document_storage_io::{
DocumentStoreHandle, attach_container, copy_stored_document, legacy_path, list_stored_documents, load_legacy_document, load_stored_document, open_document_file, remove_stored_document,
DocumentStoreHandle, attach_container, copy_stored_document, join_stored_session, legacy_path, list_stored_documents, load_legacy_document, load_stored_document, open_document_file,
remove_stored_document,
};
use crate::messages::preferences::SelectionMode;
use crate::messages::prelude::*;
@@ -42,6 +43,7 @@ pub struct PortfolioMessageContext<'a> {
pub animation: &'a AnimationMessageHandler,
pub current_tool: &'a ToolType,
pub tool_edit_target: &'a EditTarget,
pub tools: &'a ToolMessageHandler,
pub reset_node_definitions_on_open: bool,
pub timing_information: TimingInformation,
pub viewport: &'a ViewportMessageHandler,
@@ -58,6 +60,8 @@ pub struct PortfolioMessageHandler {
persistent_state: PersistentStateMessageHandler,
pub fonts: FontsMessageHandler,
ingest: IngestMessageHandler,
history: HistoryMessageHandler,
sync: SyncMessageHandler,
pub executor: NodeGraphExecutor,
pub selection_mode: SelectionMode,
pub reset_node_definitions_on_open: bool,
@@ -80,6 +84,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
animation,
current_tool,
tool_edit_target,
tools,
reset_node_definitions_on_open,
timing_information,
viewport,
@@ -134,6 +139,26 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
};
self.ingest.process_message(message, responses, context);
}
PortfolioMessage::History(message) => {
let context = HistoryMessageContext {
documents: &mut self.documents,
active_document_id: self.active_document_id,
panel_open: self.workspace.panel_layout.is_panel_visible(PanelType::History) && !self.workspace.panel_layout.focus_document,
};
self.history.process_message(message, responses, context);
}
PortfolioMessage::Sync(message) => {
let context = SyncMessageContext {
documents: &mut self.documents,
active_document_id: self.active_document_id,
resource_storage,
preferences,
ipp,
viewport,
tools,
};
self.sync.process_message(message, responses, context);
}
PortfolioMessage::Workspace(message) => {
let context = WorkspaceMessageContext {
has_active_document: self.active_document_id.is_some(),
@@ -385,10 +410,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
for document in self.documents.values_mut() {
document.garbage_collect_resources();
used_resources.extend(document.resources.registry.resolved().filter_map(|info| info.hash.cloned()));
if let Some(storage) = document.storage() {
used_resources.extend(storage.all_referenced_resource_hashes());
}
used_resources.extend(document.resource_gc_roots());
}
used_resources.extend(self.fonts.used_resources());
responses.add(ResourceStorageMessage::GarbageCollect {
@@ -409,6 +431,14 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
PortfolioMessage::LoadPersistedState { state } => {
if let Some(layout) = state.workspace_layout {
self.workspace.panel_layout = layout;
// Add the Session panel beside the Inspector, unless the user closed it
let panel_layout = &mut self.workspace.panel_layout;
if !panel_layout.is_panel_present(PanelType::Session) && !panel_layout.was_closed(PanelType::Session) {
match panel_layout.find_panel(PanelType::Inspector).and_then(|group_id| panel_layout.panel_group_mut(group_id)) {
Some(group) => group.tabs.push(PanelType::Session),
None => panel_layout.restore_panel(PanelType::Session),
}
}
responses.add(WorkspaceMessage::UpdatePanelsLayout);
// Refill panels whose content was lost when the layout load remounted their frontend components
@@ -443,12 +473,9 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
let elsewhere = held
.iter()
.map(|&document_id| {
let name = restoring
.iter()
.find(|info| info.id == document_id)
.map(|info| info.name.clone())
.filter(|name| !name.trim().is_empty());
(document_id, name.unwrap_or_else(|| DEFAULT_DOCUMENT_NAME.to_string()))
let info = restoring.iter().find(|info| info.id == document_id);
let name = info.map(|info| info.name.clone()).filter(|name| !name.trim().is_empty());
(document_id, name.unwrap_or_else(|| DEFAULT_DOCUMENT_NAME.to_string()), info.is_some_and(|info| info.session.is_some()))
})
.collect::<Vec<_>>();
for info in restoring {
@@ -474,6 +501,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
name: String::new(),
path: None,
is_saved: false,
session: None,
},
);
}
@@ -514,7 +542,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document.path = info.path;
document.set_save_state(info.is_saved);
self.load_document(document, document_id, resource_storage.resources_mut(), responses);
self.attach_storage(document_id, gdd, declarations, resource_storage, preferences);
self.attach_storage(document_id, gdd, declarations, resource_storage, preferences, responses);
}
None => {
self.document_ids.retain(|id| *id != document_id);
@@ -534,12 +562,17 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
}
PortfolioMessage::NewDocumentWithName { name } => {
responses.add_front(PortfolioMessage::NewDocumentWithId {
name,
document_id: DocumentId(generate_uuid()),
});
}
PortfolioMessage::NewDocumentWithId { name, document_id } => {
let mut new_document = DocumentMessageHandler::default();
new_document.name = self.resolve_document_name(name, None);
responses.add(DocumentMessage::PTZUpdate);
let document_id = DocumentId(generate_uuid());
if self.active_document().is_some() {
responses.add(EventMessage::ToolAbort);
responses.add(NavigationMessage::CanvasPan { delta: (0., 0.).into() });
@@ -583,6 +616,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document_name,
document_path,
content,
fresh_identity,
} => {
if let Some(path) = &document_path
&& let Some(&document_id) = self.document_ids.iter().find(|&&id| self.document_details(id).is_some_and(|info| info.path.as_ref() == Some(path)))
@@ -603,6 +637,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document_name,
document_path,
content,
fresh_identity,
resource_storage.resources_mut(),
reset_node_definitions_on_open,
));
@@ -622,6 +657,9 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
reset_node_definitions_on_open,
));
}
PortfolioMessage::JoinStoredSession { source } => {
responses.add(join_stored_session(self.document_store.clone(), source));
}
PortfolioMessage::DocumentFileLoaded {
document_id,
document_name,
@@ -643,7 +681,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document.path = document_path;
self.load_document(document, document_id, resource_storage.resources_mut(), responses);
self.attach_storage(document_id, gdd, declarations, resource_storage, preferences);
self.attach_storage(document_id, gdd, declarations, resource_storage, preferences, responses);
responses.add(PortfolioMessage::SelectDocument { document_id });
}
PortfolioMessage::StorageAttached {
@@ -662,7 +700,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
return;
};
document.container = Some(container);
self.attach_storage(document_id, gdd, declarations, resource_storage, preferences);
self.attach_storage(document_id, gdd, declarations, resource_storage, preferences, responses);
self.save_if_needed(document_id, responses);
}
PortfolioMessage::NextDocument => {
@@ -914,6 +952,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(FrontendMessage::UpdateActiveDocument { document_id });
responses.add(ToolMessage::InitTools);
responses.add(SyncMessage::RefreshPanel);
responses.add(NodeGraphMessage::Init);
responses.add(OverlaysMessage::Draw);
responses.add(EventMessage::ToolAbort);
@@ -1162,6 +1201,8 @@ impl PortfolioMessageHandler {
persistent_state: Default::default(),
fonts: Default::default(),
ingest: Default::default(),
history: Default::default(),
sync: Default::default(),
executor,
selection_mode: Default::default(),
reset_node_definitions_on_open: Default::default(),
@@ -1293,12 +1334,33 @@ impl PortfolioMessageHandler {
declarations: Declarations,
resource_storage: &ResourceStorageMessageHandler,
preferences: &PreferencesMessageHandler,
responses: &mut VecDeque<Message>,
) {
let (Some(document), Some(gdd)) = (self.documents.get_mut(&document_id), gdd) else { return };
document.set_storage(*gdd, declarations);
document.require_whole_document_stage();
document.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
document.retire_storage_interaction();
let Some(document) = self.documents.get_mut(&document_id) else { return };
// The person at this device authors the working copy, whoever wrote it last
let set_user = |gdd: &mut GddV1| {
let user = document_graph_storage::UserId(preferences.user_id);
if gdd.session().user() != user
&& let Err(error) = gdd.set_user(user, document_graph_storage::PeerId(generate_uuid()))
{
log::error!("Setting the user of {document_id:?} failed: {error}");
}
};
match gdd {
Some(mut gdd) => {
set_user(&mut gdd);
let resources = resource_storage.resources_mut();
document.set_storage(*gdd, declarations, resources.storage());
document.require_whole_document_stage();
document.commit_storage_snapshot(&resources, preferences.validate_storage_round_trip);
document.retire_storage_interaction();
}
None => {
let Some(storage) = document.storage_mut() else { return };
set_user(storage);
}
}
responses.add(SyncMessage::StorageMounted { document_id });
}
/// The resources of documents that are not loaded yet are unknown, so GC waits for every load and for a successful store listing.
@@ -1352,6 +1414,11 @@ impl PortfolioMessageHandler {
name: document.name.clone(),
path: document.path.clone(),
is_saved: document.is_saved(),
session: document.storage().and_then(|gdd| match (gdd.role().is_some(), gdd.is_shared()) {
(true, _) => Some(SessionStatus::Connected),
(false, true) => Some(SessionStatus::Disconnected),
(false, false) => None,
}),
})
} else {
self.loading_documents.get(&document_id).cloned()
@@ -1423,6 +1490,7 @@ mod tests {
name: "Elsewhere".into(),
path: None,
is_saved: true,
session: None,
};
editor.portfolio_message_handler_mut().restoring_documents.push(info);
editor
@@ -1441,6 +1509,18 @@ mod tests {
assert_eq!(editor.active_document().network_interface.document_network().nodes.len(), nodes);
}
#[tokio::test]
async fn a_held_session_is_joined_through_its_manifest_id() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let source = editor.portfolio_message_handler().active_document_id().unwrap();
let document_id = editor.active_document().storage().unwrap().manifest().document_id;
let token = peer_transport::SessionToken::for_document(document_id).to_string();
let message = join_stored_session(editor.portfolio_message_handler().document_store(), source).await;
assert_eq!(message, SyncMessage::Join { token }.into());
}
#[tokio::test]
async fn resources_stay_uncollected_while_a_stored_document_is_not_open() {
use graph_craft::application_io::resource::ResourceStorage;
@@ -0,0 +1,97 @@
//! A person's colour and stand-in name. Both derive from the user id, so all peers show the same ones.
use document_graph_storage::UserId;
fn scramble(user: UserId) -> u64 {
user.0.wrapping_mul(0x9E37_79B9_7F4A_7C15)
}
pub(crate) fn anonymous_name(user: UserId) -> String {
let index = (scramble(user) >> 40) as usize % ANONYMOUS_ANIMALS.len();
format!("Anonymous {}", ANONYMOUS_ANIMALS[index])
}
const ANONYMOUS_ANIMALS: [&str; 64] = [
"Alligator",
"Anteater",
"Armadillo",
"Axolotl",
"Badger",
"Bat",
"Beaver",
"Buffalo",
"Camel",
"Capybara",
"Chameleon",
"Cheetah",
"Chinchilla",
"Chipmunk",
"Cormorant",
"Coyote",
"Crow",
"Dingo",
"Dolphin",
"Duck",
"Elephant",
"Ferret",
"Fox",
"Frog",
"Giraffe",
"Gopher",
"Grizzly",
"Hedgehog",
"Heron",
"Hippo",
"Hyena",
"Ibex",
"Iguana",
"Jackal",
"Jaguar",
"Kangaroo",
"Koala",
"Kraken",
"Lemur",
"Leopard",
"Liger",
"Llama",
"Manatee",
"Mink",
"Monkey",
"Moose",
"Narwhal",
"Nyan Cat",
"Orangutan",
"Otter",
"Panda",
"Penguin",
"Platypus",
"Python",
"Quagga",
"Rabbit",
"Raccoon",
"Rhino",
"Sheep",
"Shrew",
"Skunk",
"Squirrel",
"Tiger",
"Turtle",
];
pub(crate) fn user_color(user: UserId) -> String {
let hue = (scramble(user) >> 32) % 360;
let (h, s, l): (f64, f64, f64) = (hue as f64 / 60., 0.65, 0.5);
let c = (1. - (2. * l - 1.).abs()) * s;
let x = c * (1. - (h % 2. - 1.).abs());
let m = l - c / 2.;
let (r, g, b) = match h as u32 {
0 => (c, x, 0.),
1 => (x, c, 0.),
2 => (0., c, x),
3 => (0., x, c),
4 => (x, 0., c),
_ => (c, 0., x),
};
let channel = |value: f64| ((value + m) * 255.).round() as u8;
format!("#{:02x}{:02x}{:02x}", channel(r), channel(g), channel(b))
}
@@ -0,0 +1,9 @@
pub(crate) mod identity;
mod sync_message;
mod sync_message_handler;
#[doc(inline)]
pub use sync_message::{SyncMessage, SyncMessageDiscriminant};
pub(crate) use sync_message_handler::now_ms;
#[doc(inline)]
pub use sync_message_handler::{SyncMessageContext, SyncMessageHandler};
@@ -0,0 +1,35 @@
use crate::messages::prelude::*;
use graph_craft::application_io::resource::ResourceHash;
use peer_transport::TransportPeerId;
#[impl_message(Message, PortfolioMessage, Sync)]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum SyncMessage {
/// Host the active document and give the frontend a link.
Share,
/// Open a new document that follows the session behind `token`.
Join { token: String },
/// Disconnect the active document. Editing continues alone.
Leave,
/// Host the active document as a new session with its own link. The others stay in the old room.
Fork,
/// Send the Session panel's layout.
RefreshPanel,
/// Apply what peers sent, once per frame.
Poll,
/// A packet arrived, so poll now. A stale `generation` is ignored.
Wake { document_id: DocumentId, generation: u32 },
/// A document's working copy mounted.
StorageMounted { document_id: DocumentId },
/// A transport loop ended. A stale `generation` is ignored.
Disconnected { document_id: DocumentId, generation: u32 },
/// `None` when the byte store lacks the declaration.
DeclarationLoaded { document_id: DocumentId, hash: ResourceHash, bytes: Option<Vec<u8>> },
/// A resource a peer asked for was read from the byte store.
ResourceLoaded {
document_id: DocumentId,
to: TransportPeerId,
hash: ResourceHash,
bytes: Vec<u8>,
},
}
Loaded 100 of 169 files, more files were not shown because too many files have changed in this diff. Show more