Compare commits

..
Author SHA1 Message Date
Timon 6a463712a4 Make every registry op a timestamped, commuting write with presence stamps and tombstones, undo by restoring each step's exact prior state, record the user behind each peer, and persist settled hot op marks and the clock 2026-10-01 22:30:53 +00:00
James Lindsay 39158dec4b Improve time complexity of identity node removal (#4625)
* Improve time complexity of identity node removal

* Code review

* Ensure all passthrough nodes are removed

* Fix double test with invalid passthrough node
2026-09-30 21:35:40 +00:00
Timon 28ed22824f Update rust-gpu (#4629) 2026-09-30 12:55:10 +00:00
Dennis Kobert d10ccbedac Update Rust to version 1.98 (#4628)
* Update rust version 1.98

* Use consts::GOLDEN_RATIO
2026-09-30 13:17:46 +02:00
Shubh Pingale 55c4e6689b Fix overflow in unsaved document list in Close All dialog (#4617)
* Fix #4601: Limit unsaved document list in Close All dialog to prevent overflow

* Truncate individual long document names in Close All dialog

* Address review comments: move dialog constants to consts.rs and use write! macro

* Use Cow and iterator chaining in Close All dialog layout
2026-09-30 01:05:59 -07:00
Keavon Chambers 0c983566f6 Keep the outward wire cache exact through node input and output replacement/insertion/deletion and validate it after every test message (#4593)
Keep the outward wire cache exact through node input and output replacement, insertion, and deletion, and validate it after every test message
2026-09-30 01:05:59 -07:00
Keavon Chambers 68c3c759d5 Add a smoothstep function to the math expression language (#4623)
* Add `smoothstep(x, R)` to the math expression language

* Evaluate a smoothstep's continuity after its range, and document the trailing argument
2026-09-28 18:00:13 -07:00
Keavon Chambers ac5be43448 Add where-keyword bindings to the math expression language (#4622)
Add where bindings to the math expression language
2026-09-28 16:13:34 -07:00
James Lindsay d24919c2c3 Improve support for importing SVGs with a viewbox (#4606)
* Improve support for importing SVGs with a viewbox

* Swap fill and stroke for SVG imports
2026-09-28 18:53:36 +00:00
James Lindsay 34a9aa9a48 Update glam and enforce unchecked preconditions (#4603)
* Update glam

* More work to avoid panics

* Clean up with new FallibleVec2Operations extension trait

* Fix compile error

* Fix typo

* Fix Nix compiling rust-gpu (#4621)
2026-09-28 18:53:36 +00:00
Keavon Chambers ae321b3409 Add a warning icon to Math node expressions with errors as tooltips (#4614)
* Add a warning icon to Math node expressions with errors as tooltips

* Point at a parse error with carets under a repeat of the expression, as a compiler does

* Render fenced code blocks in tooltips and put the parse error snippet in one

* Quote tokens as code in chumsky's parse messages and in custom parser errors

* Report the parse error past an operator rather than the operator itself
2026-09-27 02:13:28 -07:00
Timon c2fb97cc81 Switch binary document format to postcard (#4608)
* Load preferences before persisted state

* Custom Value enum

* Add to_value and from_value over serde_json::Value

* Review
2026-09-27 01:09:11 +00:00
Keavon Chambers aa27f55ab5 Add matrices, with swizzle and range literals, to the math expression parser (#4611)
* Add matrices to the math expression parser as a second sort beside values

* Add Transform input and output to the Math f(x) node

* Add ranges and boxes to the math expression parser with inside, clamp, and remap over them

* Add Transform lists to the Math f(…) node with reducers composing, averaging, and counting them

* Lex a number's trailing e as Euler's number unless an exponent's digits follow it

* Fix matrix inversion scaling, exact matrix powers, infinite shears, matrix means, kept axes, and the Transform default

* Make shared box parts flat, give composed regions their inner map's axes, and fix lone logic items, spaced ranges, and the Math f(…) tooltip

* Transpose across spaces, name fractional matrix powers, check matrix builtin arities when parsing, read range literals by their corners, and let host functions shadow matrix builtins

* Make inside and clamp hold a region's uncovered parts at zero, so a box contains only the points between its corners

* Require hosts to declare the functions they provide, name the region functions' syntax node after its builtin, and remap onto ranges with equal infinite corners

* Apply a matrix to the whole product after it, so M 2 v is M (2 v)

* Pin prefix NOT's precedence above products, comparisons, and AND with tests

* Rename inside to within, since a range's ends count and the geometry predicates with a point first use that name

* Keep a range's corners as written, so clamp orders an integer past the reals' limit exactly

* Give within a tolerance of a billionth of the region's scale, so a point a float error off an edge or a flat side counts

* Write a unit part as its basis alone, so the identity displays as [1;i;j;k]

* Add tests for product folds, mixed chains, remap, and rejected inputs

* Evaluate matrix operands, builder arguments, regions, and comparison chains on the stack instead of the heap

* Build the expression parsers once per thread, since building the combinator tree cost as much as parsing a short expression

* Compare a chain reducer's items by their order directly, and reject an item with no order rather than reading it as false

* Send a host-built list of builder arguments or regions past the stack buffers to the heap instead of rejecting it
2026-09-26 15:11:16 -07:00
Kulcode 8f5d500459 Fix Alt-drag node duplication not removing the new one on right-click abort (#3782)
Fix
2026-09-26 12:16:14 -07:00
James Lindsay f7562b6fd7 Use workspace for repository, readme, homepage, and lints (#4598)
* Use workspace for repository, readme, homepage, and lints

* Use proper README for graphite-wasm-wrapper
2026-09-26 14:31:34 +00:00
James Lindsay fdcbdd1646 Avoid unused dependency warnings (#4599)
* Avoid unused dependency warnings

* Update comment
2026-09-26 14:30:39 +00:00
Keavon Chambers 2ef9c11cd3 Add piecewise expressions to the math parser (#4610)
* Fix the math expression parser giving a valid direction between multiple infinite vector parts

* Replace the math expression parser's if() with piecewise cases like {a if x > 0, b otherwise}

* Fix the math expression parser's error spans starting before whitespace and infinities displaying as inf
2026-09-25 17:33:46 -07:00
Keavon Chambers 46c84c21fe Add Vec2 input/output in the Math nodes with quaternion support in the math expression parser (#4609)
* Extend the math expression parser's value ladder past complex numbers to quaternions

* Add a vector function family (dot, cross, rotate, slerp, and more) to the math expression parser

* Let hosts read a math expression result as a 1D to 3D vector or weighted particle

* Let the 'Math f(x)' and 'Math f(…)' nodes take and output Vec2 values

* Remove unfulfillable dead_code expectations from methods reached only through replay
2026-09-25 16:06:23 -07:00
Timon b1b372f1d6 Move all documents into platform-provided document store (#4573)
* Migrate autosaves to document store

* Review
2026-09-25 01:40:03 +00:00
Keavon Chambers 907b7d5ce3 Make the math expression parser use ints instead of floats for exact whole-number math (#4596)
Make the math expression parser store whole numbers exactly as integers and classify each value by its minimal rung
2026-09-24 17:44:25 -07:00
Keavon Chambers ddafaaa757 Add an "Output Type" parameter to the 'Math f(x)' and 'Math f(…)' nodes (#4591)
Add an 'Output Type' choice to the 'Math f(x)' and 'Math f(…)' nodes
2026-09-23 20:26:51 -07:00
Keavon Chambers 2c1cca7e99 Rename the TaggedValue I64/F64/F64Array variants to Integer/Number/Numbers (#4590)
Rename the TaggedValue F64/I64/F64Array variants to Number/Integer/Numbers
2026-09-23 18:02:06 -07:00
Keavon Chambers c91d0cd5a3 Update all node parameters with appropriate attributes of #[unit(...)], bounds, etc., deprecating the type alias units pattern (#4589)
Replace the node parameter typedefs with unit and widget attributes
2026-09-23 17:08:05 -07:00
Dennis Kobert 84ed60a404 Route every network interface write through a single-writer store (#4586)
* Route every network interface write through a single-writer store

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

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

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

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

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

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

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

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

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

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

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

* Round half away from zero on every Number to Integer conversion instead of truncating
2026-09-22 18:22:24 -07:00
Keavon Chambers 60bba681d3 Have the math expression nodes each use #[data] to cache its parsed expression input (#4577)
Parse each expression node's source once, reusing the tree across list items and frames
2026-09-22 17:44:18 -07:00
Keavon Chambers f868aadd8d Retire the 'Math' node and migrate its documents to 'Math f(x)' and 'Math f(…)' (#4576)
Retire the Math node and migrate its documents to Math f(x) and Math f(…)
2026-09-22 17:14:47 -07:00
Keavon Chambers b610d9bc23 Extend the math expression parser's combinatorics, statistics, roots, powers, and division past the reals (#4574) 2026-09-22 16:00:08 -07:00
Dennis Kobert 69398a6703 Make GDD based undo syncronous by caching protonode declarations (#4571)
* Make gdd based undo syncronous by caching protonode declarations

* Address review comments
2026-09-22 11:32:12 +00:00
279 changed files with 17653 additions and 7400 deletions

No files matched your search

+6 -5
View File
@@ -1,7 +1,7 @@
{ pkgs, ... }:
let
toolchain = pkgs.rust-bin.nightly."2026-04-11".default.override {
toolchain = pkgs.rust-bin.nightly."2026-07-03".default.override {
extensions = [
"rust-src"
"rust-analyzer"
@@ -32,11 +32,12 @@ let
(finalAttrs: {
pname = "rustc_codegen_spirv";
version = "0.10.0-alpha.1";
src = pkgs.fetchCrate {
inherit (finalAttrs) pname version;
sha256 = "sha256-zJEpExkPgYzwo7fR4ge4GxJNj7H5yo4bJ4eTOw36+7c=";
src = pkgs.fetchgit {
url = "https://github.com/Rust-GPU/rust-gpu";
rev = "2fff75a21a1909945ac85f5818843dd9960004d7";
sha256 = "sha256-clUt4jUh4D9EmoXZFgur1RrMYob4X5jti2e2hvBnAx8=";
};
cargoHash = "sha256-J1rtbfGqrL2NJ7Bu2pYfDwCdUmnECB/kzxrpYluA0kY=";
cargoHash = "sha256-9dGb+RDYpJKaIhkMPkZAx1M1VGE3gMfCD2T84i1VtV8=";
cargoBuildFlags = [
"-p"
"rustc_codegen_spirv"
Generated
+163 -154
View File
File diff suppressed because it is too large. Load diff
+11 -6
View File
@@ -53,7 +53,7 @@ default-members = [
resolver = "2"
[workspace.package]
rust-version = "1.88"
rust-version = "1.98"
edition = "2024"
authors = ["Graphite Authors <[email protected]>"]
homepage = "https://graphite.art"
@@ -114,7 +114,7 @@ rustc-hash = "2.0"
bytemuck = { version = "1.13", features = ["derive", "min_const_generics"] }
serde = { version = "1.0", features = ["derive", "rc"] }
serde_json = "1.0"
rmp-serde = "1.3"
postcard = { version = "1.1", default-features = false, features = ["use-std"] }
serde_bytes = "0.11"
serde-wasm-bindgen = "0.6"
reqwest = { version = "0.13", features = ["blocking", "json"] }
@@ -172,7 +172,6 @@ tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-mult
kurbo = { version = "0.13", features = ["serde"] }
vello = "0.10"
vello_encoding = "0.10"
resvg = "0.47"
usvg = "0.47"
simplecss = "0.2"
parley = { version = "0.9", default-features = false, features = ["std"] }
@@ -182,10 +181,12 @@ color = "0.3"
# Linebender ecosystem (END)
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
rand_chacha = "0.9"
glam = { version = "0.32.1", default-features = false, features = [
glam = { version = "0.33", default-features = false, features = [
"nostd-libm",
"scalar-math",
"bytemuck",
"debug-glam-assert",
"all-types",
] }
base64 = "0.22"
blake3 = "1.5"
@@ -239,8 +240,12 @@ rfd = "0.17"
open = "5.3"
spin = "0.10"
clap = "4.5"
spirv-std = { version = "0.10.0-alpha.1", features = ["bytemuck"] }
cargo-gpu-install = { version = "0.10.0-alpha.1", default-features = false }
# Ensure these are kept in sync with .nix/deps/rust-gpu.nix
# Git commit required for glam=0.33 support (TODO: use release when new version is published. Last publish was Apr 17)
spirv-std = { git = "https://github.com/Rust-GPU/rust-gpu.git", rev = "2fff75a21a1909945ac85f5818843dd9960004d7", features = ["bytemuck"] }
cargo-gpu-install = { git = "https://github.com/Rust-GPU/rust-gpu.git", rev = "2fff75a21a1909945ac85f5818843dd9960004d7", default-features = false }
qrcodegen = "1.8"
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
scraper = "0.25"
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":fLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":fLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[194878846429432339,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[194878846429432339,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"I64":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"I64":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_vaLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"outLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"outLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_Line truncated
+6
View File
@@ -5,9 +5,15 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[[bin]]
name = "graphite"
path = "src/main.rs"
+6
View File
@@ -5,9 +5,15 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[dependencies]
cef-dll-sys = { workspace = true }
+3
View File
@@ -7,6 +7,9 @@ mod mac;
#[cfg(target_os = "windows")]
mod win;
// Avoid incorrect warnings about an unused dependency (this crate sets `DEP_CEF_DLL_WRAPPER_CEF_DIR` which is used in `build.rs`)
use cef_dll_sys as _;
fn main() {
#[cfg(target_os = "linux")]
linux::main().unwrap();
+3
View File
@@ -5,6 +5,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
+6
View File
@@ -5,9 +5,15 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[[bin]]
name = "graphite"
path = "src/main.rs"
+6
View File
@@ -5,9 +5,15 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
main = ["dep:graphite-desktop"]
helper = ["dep:graphite-desktop-ui"]
+6
View File
@@ -5,9 +5,15 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[[bin]]
name = "graphite"
path = "src/main.rs"
+8 -15
View File
@@ -25,7 +25,7 @@ use crate::render::{RenderError, RenderState};
use crate::ui::{InputEvent, UiCommand, UiInstance};
use crate::window::Window;
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, IngestAction, Preferences};
use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
use crate::wrapper::{DesktopWrapper, FolderStore, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
pub(crate) struct App {
render_state: Option<RenderState>,
@@ -99,7 +99,13 @@ impl App {
let wake = Arc::new(move || {
wake_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Wake));
});
let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), dirs::app_autosave_documents_dir(), wgpu_context.clone(), wake);
let desktop_wrapper = DesktopWrapper::new(
rand::rng().random(),
Arc::new(resource_storage),
Arc::new(FolderStore::new(dirs::app_autosave_documents_dir())),
wgpu_context.clone(),
wake,
);
Self {
render_state: None,
@@ -307,19 +313,6 @@ impl App {
DesktopFrontendMessage::PersistenceReadState => {
responses.push(DesktopWrapperMessage::LoadPersistedState { state: persist::read_state() });
}
DesktopFrontendMessage::PersistenceReadDocument { id } => {
if let Some(document) = persist::read_document_content(&id) {
responses.push(DesktopWrapperMessage::LoadDocumentContent { id, document });
} else {
tracing::error!("Failed to read document content for {id:?}");
}
}
DesktopFrontendMessage::PersistenceWriteDocument { id, document_serialized_content } => {
persist::write_document_content(id, document_serialized_content);
}
DesktopFrontendMessage::PersistenceDeleteDocument { id } => {
persist::delete_document(&id);
}
DesktopFrontendMessage::PersistenceWritePreferences { preferences } => {
preferences::write(preferences);
}
+50 -52
View File
@@ -1,6 +1,9 @@
use crate::wrapper::messages::{DocumentId, PersistedState};
use crate::wrapper::messages::PersistedState;
pub(crate) fn read_state() -> PersistedState {
if let Err(error) = migrate_documents() {
tracing::error!("Autosave migration failed: {error}");
}
let path = state_file_path();
let data = match std::fs::read_to_string(&path) {
Ok(d) => d,
@@ -13,16 +16,13 @@ pub(crate) fn read_state() -> PersistedState {
return PersistedState::default();
}
};
let loaded = match ron::from_str(&data) {
match ron::from_str(&data) {
Ok(d) => d,
Err(e) => {
tracing::error!("Failed to deserialize persistent data: {e}");
return PersistedState::default();
PersistedState::default()
}
};
garbage_collect_document_files(&loaded);
loaded
}
}
pub(crate) fn write_state(state: PersistedState) {
@@ -37,47 +37,6 @@ pub(crate) fn write_state(state: PersistedState) {
if let Err(e) = std::fs::write(state_file_path(), data) {
tracing::error!("Failed to write persistent data to disk: {e}");
}
garbage_collect_document_files(state);
}
pub(crate) fn write_document_content(id: DocumentId, document_content: String) {
if let Err(e) = std::fs::write(document_content_path(&id), document_content) {
tracing::error!("Failed to write document {id:?} to disk: {e}");
}
}
pub(crate) fn read_document_content(id: &DocumentId) -> Option<String> {
std::fs::read_to_string(document_content_path(id)).ok()
}
pub(crate) fn delete_document(id: &DocumentId) {
if let Err(e) = std::fs::remove_file(document_content_path(id)) {
tracing::error!("Failed to delete document {id:?} from disk: {e}");
}
}
fn garbage_collect_document_files(state: &PersistedState) {
let valid_paths: std::collections::HashSet<_> = state.documents.iter().map(|doc| document_content_path(&doc.id)).collect();
let directory = crate::dirs::app_autosave_documents_dir();
let entries = match std::fs::read_dir(&directory) {
Ok(entries) => entries,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
Err(e) => {
tracing::error!("Failed to read autosave documents directory: {e}");
return;
}
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_file()
&& !valid_paths.contains(&path)
&& let Err(e) = std::fs::remove_file(&path)
{
tracing::error!("Failed to remove orphaned document file {path:?}: {e}");
}
}
}
fn state_file_path() -> std::path::PathBuf {
@@ -86,8 +45,47 @@ fn state_file_path() -> std::path::PathBuf {
path
}
fn document_content_path(id: &DocumentId) -> std::path::PathBuf {
let mut path = crate::dirs::app_autosave_documents_dir();
path.push(format!("{:x}.{}", id.0, graphite_desktop_wrapper::FILE_EXTENSION));
path
// TODO: Remove this migration code
fn migrate_documents() -> std::io::Result<()> {
let root = crate::dirs::app_autosave_documents_dir();
let entries = match std::fs::read_dir(&root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error),
};
for entry in entries {
let entry = match entry {
Ok(entry) => entry,
Err(error) => {
tracing::error!("Skipping an unreadable autosave entry: {error}");
continue;
}
};
if let Err(error) = migrate_document(&root, &entry) {
tracing::error!("Autosave migration of {} failed: {error}", entry.path().display());
}
}
Ok(())
}
fn migrate_document(root: &std::path::Path, entry: &std::fs::DirEntry) -> std::io::Result<()> {
let path = entry.path();
if !entry.file_type()?.is_file() || path.extension().and_then(|s| s.to_str()) != Some(graphite_desktop_wrapper::FILE_EXTENSION) {
return Ok(());
}
let Some(id) = path.file_stem().and_then(|s| s.to_str()).and_then(|s| u64::from_str_radix(s, 16).ok()) else {
return Ok(());
};
let destination = root.join(format!("{id:016x}"));
if !destination.join("legacy.graphite").exists() && !destination.join("manifest.json").exists() {
std::fs::create_dir_all(&destination)?;
let staging = destination.join("legacy.graphite.migrating");
std::fs::copy(&path, &staging)?;
std::fs::rename(staging, destination.join("legacy.graphite"))?;
}
let backup = path.with_extension(format!("{}.migrated", graphite_desktop_wrapper::FILE_EXTENSION));
if backup.exists() {
return Ok(());
}
std::fs::rename(path, backup)
}
+6
View File
@@ -5,9 +5,15 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
default = []
embedded_resources = ["dep:graphite-desktop-embedded-resources"]
+6
View File
@@ -5,9 +5,15 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
@@ -44,10 +44,6 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
let message = FrontendMessage::UpdateFullscreen { fullscreen };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::LoadDocumentContent { id, document } => {
let message = PersistentStateMessage::LoadDocument { document_id: id, document };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::LoadPersistedState { state } => {
let message = PersistentStateMessage::LoadState { state };
dispatcher.queue_editor_message(message);
@@ -69,18 +69,6 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
FrontendMessage::TriggerPersistenceWriteState { state } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteState { state });
}
FrontendMessage::TriggerPersistenceReadDocument { document_id } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceReadDocument { id: document_id });
}
FrontendMessage::TriggerPersistenceDeleteDocument { document_id } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceDeleteDocument { id: document_id });
}
FrontendMessage::TriggerPersistenceWriteDocument { document_id, document } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteDocument {
id: document_id,
document_serialized_content: document,
});
}
FrontendMessage::TriggerOpenLaunchDocuments => {
dispatcher.respond(DesktopFrontendMessage::OpenLaunchDocuments);
}
+3 -2
View File
@@ -10,6 +10,7 @@ use std::sync::Arc;
pub use graph_craft::application_io::resource::MmapResourceStorage;
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
pub use graphite_editor::document_store::{DocumentStore, FolderStore};
pub use wgpu_executor::Texture;
pub use wgpu_executor::WgpuBackends;
pub use wgpu_executor::WgpuContext;
@@ -32,7 +33,7 @@ pub struct DesktopWrapper {
}
impl DesktopWrapper {
pub fn new(uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, working_copy_root: std::path::PathBuf, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self {
pub fn new(uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, document_store: Arc<dyn DocumentStore>, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self {
#[cfg(target_os = "windows")]
let host = Host::Windows;
#[cfg(target_os = "macos")]
@@ -43,7 +44,7 @@ impl DesktopWrapper {
let application_io = PlatformApplicationIo::new_with_context(wgpu_context);
Self {
editor: Editor::new(env, uuid_random_seed, resource_storage, Some(working_copy_root), application_io, schedule_wake),
editor: Editor::new(env, uuid_random_seed, resource_storage, document_store, application_io, schedule_wake),
}
}
+1 -1
View File
@@ -47,7 +47,7 @@ impl<'a> DesktopWrapperMessageDispatcher<'a> {
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses)
&& e != "No active document"
{
tracing::error!("Error poling node graph: {}", e);
tracing::error!("Error polling node graph: {}", e);
}
while let Some(message) = responses.pop_front() {
self.queue_editor_message(message);
-11
View File
@@ -44,13 +44,6 @@ pub enum DesktopFrontendMessage {
enabled: bool,
},
UpdateOverlays(vello::Scene),
PersistenceWriteDocument {
id: DocumentId,
document_serialized_content: String,
},
PersistenceDeleteDocument {
id: DocumentId,
},
PersistenceWritePreferences {
preferences: Preferences,
},
@@ -59,9 +52,6 @@ pub enum DesktopFrontendMessage {
state: PersistedState,
},
PersistenceReadState,
PersistenceReadDocument {
id: DocumentId,
},
UpdateMenu {
entries: Vec<MenuItem>,
},
@@ -92,7 +82,6 @@ pub enum DesktopWrapperMessage {
PollNodeGraphEvaluation,
UpdateMaximized { maximized: bool },
UpdateFullscreen { fullscreen: bool },
LoadDocumentContent { id: DocumentId, document: String },
LoadPersistedState { state: PersistedState },
LoadPreferences { preferences: Preferences },
MenuEvent { id: String },
+7
View File
@@ -5,9 +5,15 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
default = []
zip = ["dep:zip"]
@@ -34,6 +40,7 @@ web-sys = { workspace = true, features = [
"FileSystemFileHandle",
"FileSystemGetFileOptions",
"FileSystemGetDirectoryOptions",
"FileSystemRemoveOptions",
"FileSystemHandle",
"FileSystemHandleKind",
"FileSystemWritableFileStream",
@@ -6,6 +6,7 @@ use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
#[derive(Clone)]
pub struct FolderBackend {
root: PathBuf,
}
+3 -3
View File
@@ -2,11 +2,11 @@
use crate::{ByteHolder, Container, ContainerError, Result, validate_path, validate_prefix, with_trailing_slash};
use std::collections::{HashMap, HashSet};
use std::sync::Mutex;
use std::sync::{Arc, Mutex};
#[derive(Default)]
#[derive(Clone, Default)]
pub struct MemoryBackend {
files: Mutex<HashMap<String, Vec<u8>>>,
files: Arc<Mutex<HashMap<String, Vec<u8>>>>,
}
impl MemoryBackend {
+67 -11
View File
@@ -3,6 +3,7 @@
use crate::{AsyncContainer, ByteHolder, ContainerError, Result, validate_path, validate_prefix, with_trailing_slash};
use futures::channel::oneshot;
use js_sys::Uint8Array;
use std::cell::Cell;
use std::collections::{HashSet, VecDeque};
use std::sync::{Arc, Mutex};
use wasm_bindgen::JsCast;
@@ -40,6 +41,33 @@ struct Inner {
worker_active: bool,
}
thread_local! {
static LAST_WRITE_FAILURE_ALERT: Cell<Option<f64>> = const { Cell::new(None) };
}
fn report_write_error(operation: &str, path: &str, error: &JsValue) {
if is_not_found(error) {
log::warn!("OPFS {operation} on {path} dropped: the container no longer exists");
return;
}
log::error!("OPFS {operation} failure on {path}:\n{error:?}");
let now = js_sys::Date::now();
// Debounce alerts to avoid spamming the user
if LAST_WRITE_FAILURE_ALERT.get().is_some_and(|last| now - last < 60. * 1000.) {
return;
}
LAST_WRITE_FAILURE_ALERT.set(Some(now));
if let Some(window) = web_sys::window() {
let message = format!(
"Autosave is not working. Save your documents manually to avoid losing changes.\n\n\
Please report it at https://github.com/GraphiteEditor/Graphite/issues/new and include this error:\n\n\
{operation} {path}: {error:?}"
);
let _ = window.alert_with_message(&message);
}
}
#[derive(Clone)]
pub struct OpfsBackend {
inner: Arc<Mutex<Inner>>,
}
@@ -77,8 +105,6 @@ impl OpfsBackend {
guard.queue.push_back(Mutation::Barrier(sender));
kick_worker(&self.inner, &mut guard);
}
// The sender is only dropped without sending if the worker is torn down mid-drain; either way
// there is nothing left to wait for, so a receive error is treated as "already flushed".
let _ = receiver.await;
}
}
@@ -239,12 +265,12 @@ async fn drain_queue(inner: Arc<Mutex<Inner>>) {
match mutation {
Mutation::Write { path, bytes } => {
if let Err(error) = write_file(&directory, &path, &bytes).await {
log::error!("OPFS background write for {path} failed: {error:?}");
report_write_error("write", &path, &error);
}
}
Mutation::Append { path, bytes } => {
if let Err(error) = append_file(&directory, &path, &bytes).await {
log::error!("OPFS background append for {path} failed: {error:?}");
report_write_error("append", &path, &error);
}
}
Mutation::Delete { path } => {
@@ -252,7 +278,7 @@ async fn drain_queue(inner: Arc<Mutex<Inner>>) {
if let Err(error) = remove_file(&directory, &path).await
&& !is_not_found(&error)
{
log::error!("OPFS background delete for {path} failed: {error:?}");
report_write_error("delete", &path, &error);
}
}
// A receive error on the waiter side just means the reader gave up; nothing to apply.
@@ -263,16 +289,11 @@ async fn drain_queue(inner: Arc<Mutex<Inner>>) {
}
}
fn js_err(error: JsValue) -> ContainerError {
ContainerError::Backend(format!("{error:?}"))
}
/// Resolve `directory_path` (a `/`-separated relative path) under the OPFS root, creating each
/// segment. OPFS rejects directory names containing `/`, so a multi-segment path like
/// `documents/<id>` must be descended one segment at a time rather than passed whole.
async fn open_directory(directory_path: &str) -> std::result::Result<FileSystemDirectoryHandle, JsValue> {
let storage = web_sys::window().ok_or_else(|| JsValue::from_str("no window"))?.navigator().storage();
let mut current: FileSystemDirectoryHandle = JsFuture::from(storage.get_directory()).await?.dyn_into()?;
let mut current = opfs_root().await?;
for segment in directory_path.split('/').filter(|segment| !segment.is_empty()) {
let options = FileSystemGetDirectoryOptions::new();
@@ -283,6 +304,37 @@ async fn open_directory(directory_path: &str) -> std::result::Result<FileSystemD
Ok(current)
}
/// List the subdirectories directly under `directory_path`.
pub async fn list_directories(directory_path: &str) -> Result<Vec<String>> {
crate::validate_prefix(directory_path)?;
let root = opfs_root().await.map_err(js_err)?;
list_entries(&root, directory_path, EntryKind::Directory).await.map_err(|error| list_error(directory_path, error))
}
/// Remove `directory_path` recursively.
pub async fn remove_directory(directory_path: &str) -> Result<()> {
validate_path(directory_path)?;
let root = opfs_root().await.map_err(js_err)?;
let removed = async {
let (parent, name) = descend(&root, directory_path, false).await?;
let options = web_sys::FileSystemRemoveOptions::new();
options.set_recursive(true);
JsFuture::from(parent.remove_entry_with_options(name, &options)).await
}
.await;
match removed {
Ok(_) => Ok(()),
Err(error) if is_not_found(&error) => Ok(()),
Err(error) => Err(js_err(error)),
}
}
async fn opfs_root() -> std::result::Result<FileSystemDirectoryHandle, JsValue> {
let storage = web_sys::window().ok_or_else(|| JsValue::from_str("no window"))?.navigator().storage();
JsFuture::from(storage.get_directory()).await?.dyn_into()
}
/// Descend the `/`-separated path against `root` and return the directory handle plus the final segment.
async fn descend<'a>(root: &FileSystemDirectoryHandle, relative: &'a str, create_dirs: bool) -> std::result::Result<(FileSystemDirectoryHandle, &'a str), JsValue> {
let mut current = root.clone();
@@ -473,3 +525,7 @@ fn list_error(prefix: &str, error: JsValue) -> ContainerError {
js_err(error)
}
}
fn js_err(error: JsValue) -> ContainerError {
ContainerError::Backend(format!("{error:?}"))
}
+2
View File
@@ -12,6 +12,7 @@
pub mod archive;
pub mod backends;
pub mod store;
pub enum ByteHolder {
/// Bytes synthesized in memory (decompressed from an archive, produced by serialization).
@@ -350,6 +351,7 @@ impl<C: Container + ?Sized> AsyncContainer for C {
/// `AsyncContainer::read` returns `impl Future`, so `dyn AsyncContainer` is not object-safe.
/// `AnyContainer` is the workaround: `Gdd` holds one of these by value, and the `AsyncContainer`
/// impl forwards to the active variant.
#[derive(Clone)]
pub enum AnyContainer {
Memory(backends::memory::MemoryBackend),
#[cfg(not(target_family = "wasm"))]
+145
View File
@@ -0,0 +1,145 @@
use crate::backends::memory::MemoryBackend;
use crate::{AnyContainer, Result};
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Mutex;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DocumentKey(pub u64);
#[cfg(not(target_family = "wasm"))]
pub type StoreFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T>> + Send + 'a>>;
#[cfg(target_family = "wasm")]
pub type StoreFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T>> + 'a>>;
pub trait DocumentStore: Send + Sync {
fn list(&self) -> StoreFuture<'_, Vec<DocumentKey>>;
fn open(&self, key: DocumentKey) -> StoreFuture<'_, AnyContainer>;
fn remove(&self, key: DocumentKey) -> StoreFuture<'_, ()>;
}
fn directory_name(key: DocumentKey) -> String {
format!("{:016x}", key.0)
}
fn parse_directory_name(name: &str) -> Option<DocumentKey> {
(name.len() == 16 && name.bytes().all(|byte| byte.is_ascii_hexdigit()))
.then(|| u64::from_str_radix(name, 16).ok().map(DocumentKey))
.flatten()
}
#[derive(Default)]
pub struct MemoryStore {
documents: Mutex<HashMap<DocumentKey, MemoryBackend>>,
}
impl DocumentStore for MemoryStore {
fn list(&self) -> StoreFuture<'_, Vec<DocumentKey>> {
let mut keys: Vec<_> = self.documents.lock().unwrap().keys().copied().collect();
keys.sort();
Box::pin(async move { Ok(keys) })
}
fn open(&self, key: DocumentKey) -> StoreFuture<'_, AnyContainer> {
let backend = self.documents.lock().unwrap().entry(key).or_default().clone();
Box::pin(async move { Ok(AnyContainer::Memory(backend)) })
}
fn remove(&self, key: DocumentKey) -> StoreFuture<'_, ()> {
self.documents.lock().unwrap().remove(&key);
Box::pin(async { Ok(()) })
}
}
#[cfg(not(target_family = "wasm"))]
pub struct FolderStore {
root: std::path::PathBuf,
}
#[cfg(not(target_family = "wasm"))]
impl FolderStore {
pub fn new(root: impl Into<std::path::PathBuf>) -> Self {
Self { root: root.into() }
}
}
#[cfg(not(target_family = "wasm"))]
impl DocumentStore for FolderStore {
fn list(&self) -> StoreFuture<'_, Vec<DocumentKey>> {
Box::pin(async {
let entries = match std::fs::read_dir(&self.root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(error) => return Err(error.into()),
};
let mut keys: Vec<_> = entries
.filter_map(|entry| entry.ok())
.filter(|entry| entry.file_type().is_ok_and(|file_type| file_type.is_dir()))
.filter_map(|entry| parse_directory_name(&entry.file_name().to_string_lossy()))
.collect();
keys.sort();
Ok(keys)
})
}
fn open(&self, key: DocumentKey) -> StoreFuture<'_, AnyContainer> {
Box::pin(async move {
let backend = crate::backends::folder::FolderBackend::create(self.root.join(directory_name(key)))?;
Ok(AnyContainer::Folder(backend))
})
}
fn remove(&self, key: DocumentKey) -> StoreFuture<'_, ()> {
Box::pin(async move {
match std::fs::remove_dir_all(self.root.join(directory_name(key))) {
Ok(()) => Ok(()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error.into()),
}
})
}
}
#[cfg(target_family = "wasm")]
pub struct OpfsStore {
root: String,
}
#[cfg(target_family = "wasm")]
impl OpfsStore {
pub fn new(root: impl Into<String>) -> Self {
Self {
root: root.into().trim_matches('/').to_string(),
}
}
fn document_path(&self, key: DocumentKey) -> String {
let name = directory_name(key);
if self.root.is_empty() { name } else { format!("{}/{name}", self.root) }
}
}
#[cfg(target_family = "wasm")]
impl DocumentStore for OpfsStore {
fn list(&self) -> StoreFuture<'_, Vec<DocumentKey>> {
Box::pin(async {
let paths = crate::backends::opfs::list_directories(&self.root).await?;
let mut keys: Vec<_> = paths.iter().filter_map(|path| parse_directory_name(path.rsplit('/').next()?)).collect();
keys.sort();
Ok(keys)
})
}
fn open(&self, key: DocumentKey) -> StoreFuture<'_, AnyContainer> {
Box::pin(async move {
let backend = crate::backends::opfs::OpfsBackend::open(&self.document_path(key)).await?;
Ok(AnyContainer::Opfs(backend))
})
}
fn remove(&self, key: DocumentKey) -> StoreFuture<'_, ()> {
Box::pin(async move { crate::backends::opfs::remove_directory(&self.document_path(key)).await })
}
}
+12
View File
@@ -176,3 +176,15 @@ fn folder_backend_write_sized_fills_via_mmap() {
let read_back = backend.read("resources/sized").unwrap();
assert_eq!(read_back.as_slice(), payload);
}
#[test]
fn memory_backend_clones_share_the_store() {
let backend = MemoryBackend::new();
let clone = backend.clone();
backend.write("file", b"through the original").unwrap();
assert_eq!(clone.read("file").unwrap().as_slice(), b"through the original");
clone.remove("file").unwrap();
assert!(!backend.exists("file"));
}
+7 -1
View File
@@ -5,9 +5,15 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
# Runtime bridge: the editor <-> storage conversion methods (stage/commit from a `NodeNetwork`,
# `network_ids`, `declarations`). Off lets a standalone migration tool build without `graph-craft`
@@ -27,7 +33,7 @@ graphene-resource = { workspace = true }
core-types = { workspace = true, optional = true }
serde = { workspace = true }
serde_json = { workspace = true }
rmp-serde = { workspace = true }
postcard = { workspace = true }
futures = { workspace = true }
thiserror = "2.0"
log = { workspace = true }
+33 -51
View File
@@ -8,18 +8,16 @@ pub enum Codec {
Json,
/// Newline-delimited compact JSON, one value per line.
JsonLines,
/// A single MessagePack blob. `append` to a non-empty buffer errors.
MessagePack,
/// Length-prefixed MessagePack frames: `[u32 big-endian length][MessagePack bytes]` per value.
MessagePackFrames,
/// A single postcard blob. `append` to a non-empty buffer errors.
Postcard,
/// Length-prefixed postcard frames: `[u32 big-endian length][postcard bytes]` per value.
PostcardFrames,
}
#[derive(Debug, thiserror::Error)]
pub enum CodecError {
#[error("MessagePack encode error: {0}")]
MessagePackEncode(#[from] rmp_serde::encode::Error),
#[error("MessagePack decode error: {0}")]
MessagePackDecode(#[from] rmp_serde::decode::Error),
#[error("postcard error: {0}")]
Postcard(#[from] postcard::Error),
#[error("JSON error: {0}")]
Json(#[from] serde_json::Error),
#[error("frame length {0} exceeds u32")]
@@ -41,8 +39,8 @@ impl Codec {
match self {
Codec::Json => "json",
Codec::JsonLines => "jsonl",
Codec::MessagePack => "bin",
Codec::MessagePackFrames => "frames",
Codec::Postcard => "bin",
Codec::PostcardFrames => "frames",
}
}
@@ -62,15 +60,15 @@ impl Codec {
output.push(b'\n');
Ok(())
}
Codec::MessagePack => {
Codec::Postcard => {
if !output.is_empty() {
return Err(CodecError::SingleValueAlreadyWritten);
}
rmp_serde::encode::write(output, value)?;
postcard::to_io(value, &mut *output)?;
Ok(())
}
Codec::MessagePackFrames => {
let payload = rmp_serde::to_vec(value)?;
Codec::PostcardFrames => {
let payload = postcard::to_stdvec(value)?;
let length = u32::try_from(payload.len()).map_err(|_| CodecError::FrameTooLarge(payload.len()))?;
output.extend_from_slice(&length.to_be_bytes());
output.extend_from_slice(&payload);
@@ -91,11 +89,11 @@ impl Codec {
remaining: bytes,
_marker: std::marker::PhantomData,
}),
Codec::MessagePack => {
let single = rmp_serde::from_slice::<T>(bytes).map_err(CodecError::from);
Codec::Postcard => {
let single = postcard::from_bytes::<T>(bytes).map_err(CodecError::from);
Box::new(std::iter::once(single))
}
Codec::MessagePackFrames => Box::new(MessagePackFrameIter {
Codec::PostcardFrames => Box::new(PostcardFrameIter {
remaining: bytes,
_marker: std::marker::PhantomData,
}),
@@ -153,12 +151,12 @@ impl<T: DeserializeOwned> Iterator for JsonLineIter<'_, T> {
}
}
struct MessagePackFrameIter<'a, T> {
struct PostcardFrameIter<'a, T> {
remaining: &'a [u8],
_marker: std::marker::PhantomData<fn() -> T>,
}
impl<T: DeserializeOwned> Iterator for MessagePackFrameIter<'_, T> {
impl<T: DeserializeOwned> Iterator for PostcardFrameIter<'_, T> {
type Item = Result<T, CodecError>;
fn next(&mut self) -> Option<Self::Item> {
@@ -183,7 +181,7 @@ impl<T: DeserializeOwned> Iterator for MessagePackFrameIter<'_, T> {
let (frame, after) = tail.split_at(length);
self.remaining = after;
Some(rmp_serde::from_slice(frame).map_err(CodecError::from))
Some(postcard::from_bytes(frame).map_err(CodecError::from))
}
}
@@ -224,31 +222,20 @@ mod tests {
}
#[test]
fn message_pack_round_trip_single() {
fn postcard_round_trip_single() {
let frame = Frame { id: 99, label: "blob".into() };
let bytes = Codec::MessagePack.write_single(&frame).unwrap();
let decoded: Frame = Codec::MessagePack.read_single(&bytes).unwrap();
let bytes = Codec::Postcard.write_single(&frame).unwrap();
let decoded: Frame = Codec::Postcard.read_single(&bytes).unwrap();
assert_eq!(decoded, frame);
}
#[test]
fn message_pack_append_to_non_empty_errors() {
fn postcard_append_to_non_empty_errors() {
let mut buffer = vec![0xAB];
let result = Codec::MessagePack.append(&mut buffer, &Frame { id: 1, label: "x".into() });
let result = Codec::Postcard.append(&mut buffer, &Frame { id: 1, label: "x".into() });
assert!(matches!(result, Err(CodecError::SingleValueAlreadyWritten)), "got {result:?}");
}
/// A type-erased `serde_json::Value` round-trips through the binary codec: the property postcard
/// could not satisfy (it raises `WontImplement` on self-describing values), which is why the
/// resource/attribute deltas that carry `serde_json::Value` bodies need a self-describing codec.
#[test]
fn message_pack_round_trips_serde_json_value() {
let value = serde_json::json!({ "kind": "embedded", "priority": 1.5, "tags": ["a", "b"] });
let bytes = Codec::MessagePack.write_single(&value).unwrap();
let decoded: serde_json::Value = Codec::MessagePack.read_single(&bytes).unwrap();
assert_eq!(decoded, value);
}
#[test]
fn json_lines_round_trip_and_skip_blanks() {
let frames = [Frame { id: 1, label: "alpha".into() }, Frame { id: 2, label: "beta".into() }];
@@ -263,13 +250,13 @@ mod tests {
}
#[test]
fn message_pack_frames_round_trip() {
fn postcard_frames_round_trip() {
let frames = frames();
let mut buffer = Vec::new();
for frame in &frames {
Codec::MessagePackFrames.append(&mut buffer, frame).unwrap();
Codec::PostcardFrames.append(&mut buffer, frame).unwrap();
}
let decoded: Vec<Frame> = Codec::MessagePackFrames.iter(&buffer).collect::<Result<_, _>>().unwrap();
let decoded: Vec<Frame> = Codec::PostcardFrames.iter(&buffer).collect::<Result<_, _>>().unwrap();
assert_eq!(decoded, frames);
}
@@ -277,27 +264,27 @@ mod tests {
/// deterministically (declared length exceeds the bytes that actually made it to disk) rather
/// than decoding a partial value into a plausible-but-wrong one.
#[test]
fn message_pack_frames_detect_truncation() {
fn postcard_frames_detect_truncation() {
let mut buffer = Vec::new();
Codec::MessagePackFrames.append(&mut buffer, &Frame { id: 7, label: "ok".into() }).unwrap();
Codec::PostcardFrames.append(&mut buffer, &Frame { id: 7, label: "ok".into() }).unwrap();
buffer.truncate(buffer.len() - 1);
let last = Codec::MessagePackFrames.iter::<Frame>(&buffer).last().unwrap();
let last = Codec::PostcardFrames.iter::<Frame>(&buffer).last().unwrap();
assert!(matches!(last, Err(CodecError::TruncatedFrame { .. })), "got {last:?}");
}
/// A buffer whose first record's length prefix itself is incomplete (fewer than 4 bytes) is
/// reported as a truncated prefix rather than mis-read as a zero-length frame.
#[test]
fn message_pack_frames_detect_truncated_length_prefix() {
fn postcard_frames_detect_truncated_length_prefix() {
let buffer = vec![0x00, 0x00];
let last = Codec::MessagePackFrames.iter::<Frame>(&buffer).last().unwrap();
let last = Codec::PostcardFrames.iter::<Frame>(&buffer).last().unwrap();
assert!(matches!(last, Err(CodecError::TruncatedLengthPrefix(2))), "got {last:?}");
}
#[test]
fn write_single_then_read_with_iter_yields_one() {
let frame = Frame { id: 5, label: "one".into() };
for codec in [Codec::Json, Codec::JsonLines, Codec::MessagePack, Codec::MessagePackFrames] {
for codec in [Codec::Json, Codec::JsonLines, Codec::Postcard, Codec::PostcardFrames] {
let bytes = codec.write_single(&frame).unwrap();
let collected: Vec<Frame> = codec.iter(&bytes).collect::<Result<_, _>>().unwrap();
assert_eq!(collected, vec![Frame { id: 5, label: "one".into() }], "codec {codec:?}");
@@ -315,12 +302,7 @@ mod tests {
#[test]
fn extensions_are_distinct() {
let exts = [
Codec::Json.extension(),
Codec::JsonLines.extension(),
Codec::MessagePack.extension(),
Codec::MessagePackFrames.extension(),
];
let exts = [Codec::Json.extension(), Codec::JsonLines.extension(), Codec::Postcard.extension(), Codec::PostcardFrames.extension()];
let unique: std::collections::HashSet<_> = exts.iter().collect();
assert_eq!(unique.len(), exts.len(), "extensions collide: {exts:?}");
}
+3
View File
@@ -35,6 +35,9 @@ pub enum Error {
#[cfg(feature = "conversion")]
#[error("commit error: {0}")]
Commit(#[from] CommitError),
/// The container has no manifest, cannot be opened.
#[error("container has no manifest")]
MissingManifest,
/// The manifest's `format` field is not the `.gdd` magic, so this is not a `.gdd` document.
#[error("not a .gdd document (manifest format = {found:?}, expected {expected:?})")]
WrongFormat { found: String, expected: &'static str },
+4
View File
@@ -146,10 +146,14 @@ impl<L: Layout> Gdd<L> {
// Carry the per-peer cursor + view settings so a `.gdd` reopened elsewhere restores the viewport.
let session_state = SessionState {
peer_id: self.session.peer(),
user_id: self.session.user(),
head_rev: self.session.head_rev(),
last_broadcast_rev: self.session.last_broadcast_rev(),
redo_stack: self.session.redo_stack().to_vec(),
next_node_counter: self.session.next_node_counter(),
last_hot_sequence: self.session.last_hot_sequence(),
settled: self.session.settled_marks().clone(),
clock: self.session.clock_counter(),
view_settings: self.view_settings.clone(),
network_view_settings: self.network_view_settings.clone(),
};
+49 -59
View File
@@ -6,7 +6,6 @@
//!
//! See the "On-disk container" section of `node-graph/rfcs/document-format.md` for the format spec.
use std::sync::Arc;
// `Path` and `FolderBackend` are only used by the native-only path-based open/create, so they're
// gated off wasm to avoid unused-import warnings.
#[cfg(not(target_family = "wasm"))]
@@ -14,10 +13,10 @@ use std::path::Path;
#[cfg(not(target_family = "wasm"))]
use document_container::backends::folder::FolderBackend;
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
use document_container::{AnyContainer, AsyncContainer, ByteHolder};
#[cfg(feature = "conversion")]
use document_graph_storage::{CommitError, NodeMetadataSource};
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session};
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session, UserId};
#[cfg(feature = "conversion")]
use graphene_resource::LoadResource;
use graphene_resource::ResourceHash;
@@ -49,30 +48,28 @@ pub type GddV1 = Gdd<GddV1Layout>;
pub const MANIFEST_CODEC: Codec = Codec::Json;
/// Working-copy codecs. The working copy lives in appdata, not under VCS — these defaults
/// optimize for size and write cost. MessagePack is self-describing, so it round-trips the
/// type-erased `serde_json::Value` bodies that resource and attribute deltas carry (a non-self-
/// describing format like postcard cannot). JSON/JSONL is opt-in via `ExportFormat::Folder` for
/// users who want a diffable on-disk representation. Recorded in the manifest at create time and
/// read back on open (see [`manifest::PayloadCodecs`]), so the persist path never probes the filesystem.
/// optimize for size and write cost. JSON/JSONL is opt-in via `ExportFormat::Folder` for users who
/// want a diffable on-disk representation. Recorded in the manifest at create time and read back on
/// open (see [`manifest::PayloadCodecs`]), so the persist path never probes the filesystem.
pub const DEFAULT_SESSION_CODEC: Codec = Codec::Json;
pub const DEFAULT_REGISTRY_CODEC: Codec = Codec::MessagePack;
pub const DEFAULT_HISTORY_CODEC: Codec = Codec::MessagePackFrames;
pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::MessagePackFrames;
pub const DEFAULT_REGISTRY_CODEC: Codec = Codec::Postcard;
pub const DEFAULT_HISTORY_CODEC: Codec = Codec::PostcardFrames;
pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::PostcardFrames;
/// Editor-facing handle. Owns the `Session` and the working-copy container; mutations are mirrored
/// to disk continuously (every retirement appends to the history file and re-snapshots the registry).
///
/// The per-edit persist path (`commit_from_runtime`, `apply_hot_op`, `retire`) is synchronous and
/// read-free: the manifest is cached in memory (so payload codecs need no disk read), and writes go
/// through the container's sync write surface. Only `open` / `create` / `export` are async, since they
/// through the container's sync write surface. Only `open` / `export` are async, since they
/// read.
/// `Clone` shares the working-copy container (`Arc<AnyContainer>`) so a cloned handle reads and writes
/// `Clone` shares the working-copy container (`AnyContainer` is a handle) so a cloned handle reads and writes
/// the *same* on-disk/OPFS working copy — including any writes still queued on the OPFS backend. The
/// `Session` is cloned (a snapshot copy); the container is shared.
#[derive(Clone)]
pub struct Gdd<L: Layout = GddV1Layout> {
pub(crate) session: Session,
pub(crate) working: Arc<AnyContainer>,
pub(crate) working: AnyContainer,
pub(crate) layout: L,
/// In-memory copy of the manifest, kept authoritative since `Gdd` is its sole writer. Holds the
/// per-payload codecs so the persist path never probes the filesystem, keeping it fully read-free
@@ -80,10 +77,10 @@ pub struct Gdd<L: Layout = GddV1Layout> {
pub(crate) manifest: Manifest,
/// Per-peer view settings (PTZ, rulers, etc.), persisted in `session.json` not the registry, so
/// they stay out of the CRDT/history. Opaque to the storage layer; the editor owns the keys/values.
pub(crate) view_settings: std::collections::BTreeMap<String, serde_json::Value>,
pub(crate) view_settings: std::collections::BTreeMap<String, document_graph_storage::Value>,
/// Per-network view settings (node-graph nav + previewing), keyed by stable [`NetworkId`]. Same per-peer
/// `session.json` treatment as [`view_settings`](Self::view_settings), but scoped per network.
pub(crate) network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>>,
pub(crate) network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, document_graph_storage::Value>>,
}
/// Native folder-backed convenience constructors. On wasm the editor builds an OPFS-backed
@@ -101,10 +98,10 @@ impl<L: Layout + Default> Gdd<L> {
/// Create a fresh, empty working copy at `path` bound to `peer`. Writes a default manifest
/// and session state; the caller fills in editor metadata via [`Gdd::update_manifest`].
pub async fn create(path: &Path, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
pub fn create(path: &Path, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
let working = AnyContainer::Folder(FolderBackend::create(path)?);
let layout = L::default();
Self::create_in(working, layout, peer, document_uuid, editor_version, stdlib_version).await
Self::create_in(working, layout, peer, document_uuid, editor_version, stdlib_version)
}
}
@@ -124,10 +121,14 @@ impl<L: Layout> Gdd<L> {
/// Backend-agnostic open. Splits out so tests can supply a [`document_container::backends::memory::MemoryBackend`].
///
/// # Errors
/// [`Error::WrongFormat`] / [`Error::UnsupportedVersion`] if the manifest fails validation, plus
/// the usual [`Error::Read`] / [`Error::Codec`] / [`Error::Crdt`] if a payload is malformed.
/// [`Error::MissingManifest`] if the container holds no manifest, [`Error::WrongFormat`] / [`Error::UnsupportedVersion`]
/// if it fails validation, plus the usual [`Error::Read`] / [`Error::Codec`] / [`Error::Crdt`] if a payload is malformed.
pub async fn open_in(working: AnyContainer, layout: L) -> Result<Self, Error> {
let manifest: Manifest = io::read_single(&working, layout.manifest_basename(), MANIFEST_CODEC).await?;
let manifest: Manifest = match io::read_single(&working, layout.manifest_basename(), MANIFEST_CODEC).await {
Ok(manifest) => manifest,
Err(io::ReadError::NotFound { .. }) => return Err(Error::MissingManifest),
Err(error) => return Err(error.into()),
};
validate_manifest(&manifest)?;
let codecs = manifest.codecs;
@@ -140,18 +141,19 @@ impl<L: Layout> Gdd<L> {
let has_history = io::exists(&working, layout.history_basename(), codecs.history).await;
let peer = session_state.peer_id;
let user = session_state.user_id;
let mut session = match (has_registry, has_history) {
(true, true) => {
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
let history = load_history(&working, &layout, codecs.history).await?;
Session::load(peer, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
Session::load(peer, user, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
}
(true, false) => {
// Registry-only export: synthesize a history that reproduces this state.
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
Session::bootstrap_from_registry(peer, registry)?
Session::bootstrap_from_registry(peer, user, registry)?
}
(false, _) => Session::replay_from_history(peer, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
(false, _) => Session::replay_from_history(peer, user, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
};
// Restore the published frontier (silent/published undo boundary) regardless of which load arm ran.
@@ -159,11 +161,15 @@ impl<L: Layout> Gdd<L> {
session.publish_up_to(rev);
}
session.restore_hot_sequence(session_state.last_hot_sequence);
session.restore_clock(session_state.clock);
// Before the hot log replays, so a settled op in it is dropped rather than staged again.
session.absorb_settled_marks(&session_state.settled);
replay_hot_log(&working, &layout, codecs.hot_log, &mut session).await?;
Ok(Self {
session,
working: Arc::new(working),
working,
layout,
manifest,
view_settings: session_state.view_settings,
@@ -173,11 +179,15 @@ impl<L: Layout> Gdd<L> {
/// Backend-agnostic create. Records the working-copy default codecs (see `DEFAULT_*_CODEC`) in
/// the manifest and writes each payload with its recorded codec.
pub async fn create_in(working: AnyContainer, layout: L, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
pub fn create_in(working: AnyContainer, layout: L, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
let manifest = Manifest::new(document_uuid, editor_version, stdlib_version);
let codecs = manifest.codecs;
io::write_single(&working, layout.manifest_basename(), MANIFEST_CODEC, &manifest)?;
let session_state = SessionState { peer_id: peer, ..Default::default() };
let session_state = SessionState {
peer_id: peer,
user_id: UserId(peer.0),
..Default::default()
};
io::write_single(&working, layout.session_basename(), codecs.session, &session_state)?;
let session = Session::with_peer(peer);
@@ -185,7 +195,7 @@ impl<L: Layout> Gdd<L> {
Ok(Self {
session,
working: Arc::new(working),
working,
layout,
manifest,
view_settings: std::collections::BTreeMap::new(),
@@ -256,13 +266,13 @@ impl<L: Layout> Gdd<L> {
/// The per-peer view settings read from `session.json` (PTZ, rulers, overlays, snapping, collapse).
/// Opaque `ui::doc::*` blobs; the editor decodes them. Empty for a fresh document.
pub fn view_settings(&self) -> &std::collections::BTreeMap<String, serde_json::Value> {
pub fn view_settings(&self) -> &std::collections::BTreeMap<String, document_graph_storage::Value> {
&self.view_settings
}
/// The per-network view settings read from `session.json` (node-graph nav + previewing), keyed by
/// [`NetworkId`](document_graph_storage::NetworkId). Opaque `ui::nav::*` / `ui::previewing` blobs the editor decodes.
pub fn network_view_settings(&self) -> &std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>> {
pub fn network_view_settings(&self) -> &std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, document_graph_storage::Value>> {
&self.network_view_settings
}
@@ -285,31 +295,20 @@ impl<L: Layout> Gdd<L> {
}
/// Drop the session and return the working-copy container + layout.
/// Intended for test code that needs to reopen against the same container; panics if the container
/// is still shared by a `Gdd` clone (tests don't clone before calling this).
pub fn into_storage(self) -> (AnyContainer, L) {
let working = Arc::try_unwrap(self.working).unwrap_or_else(|_| panic!("into_storage called while the working-copy container is still shared by a Gdd clone"));
(working, self.layout)
(self.working, self.layout)
}
/// Resolve the proto-node declarations referenced by the registry into a [`document_graph_storage::Declarations`]
/// map, loading each `ProtoNode`'s bytes from `byte_store` (the global cache in the editor, the
/// working-copy container for standalone). Only resources referenced by `Implementation::ProtoNode`
/// are visited, so image/font resources are skipped. Cold-path (open / `to_runtime`); async
/// because resource loads are.
/// Resolve every proto-node declaration referenced by the registry or its history into a
/// [`document_graph_storage::Declarations`] map, loading each `ProtoNode`'s bytes from `byte_store`
/// (the global cache in the editor, the working-copy container for standalone). Covers history so
/// the map can serve any undo/redo target. Cold-path (mount / open); async because resource loads are.
#[cfg(feature = "conversion")]
pub async fn declarations(&self, byte_store: &dyn LoadResource) -> document_graph_storage::Declarations {
use document_graph_storage::Implementation;
let registry = self.session.registry();
let mut declarations = document_graph_storage::Declarations::new();
for node in registry.node_instances.values() {
let Implementation::ProtoNode(id) = node.implementation() else { continue };
if declarations.contains_key(id) {
continue;
}
let Some(hash) = registry.resources.get(id).and_then(|entry| entry.hash) else {
for (id, hash) in self.session.all_declaration_resources() {
let Some(hash) = hash else {
log::error!("Declaration resource {id} has no resolved hash; cannot load ProtoNode");
continue;
};
@@ -319,7 +318,7 @@ impl<L: Layout> Gdd<L> {
};
match document_graph_storage::decode_declaration(resource.as_ref()) {
Ok(proto) => {
declarations.insert(*id, proto);
declarations.insert(id, proto);
}
Err(error) => log::error!("Failed to deserialize ProtoNode for {id}: {error}"),
}
@@ -328,16 +327,7 @@ impl<L: Layout> Gdd<L> {
declarations
}
/// Store the legacy `.graphite` document bytes verbatim inside the working copy (dual-write soak).
/// Synchronous (hot-path safe via `write_non_blocking`): called at the autosave boundary alongside
/// the registry snapshot. The bytes are opaque to `Gdd` — it never deserializes them.
// TODO: Add feature gate for legacy embedding
pub fn store_legacy_document(&self, bytes: &[u8]) -> Result<(), ContainerError> {
self.working.write_non_blocking(self.layout.legacy_path(), bytes)
}
/// Read back the embedded legacy `.graphite` document, if present. The compare-on-open oracle and
/// the recovery fallback both go through here. `None` when no legacy blob was ever written.
/// Read the embedded legacy `.graphite` document, if present.
pub async fn read_legacy_document(&self) -> Option<ByteHolder> {
self.working.read(self.layout.legacy_path()).await.ok()
}
+16 -14
View File
@@ -6,7 +6,7 @@
use document_container::AsyncContainer;
#[cfg(feature = "conversion")]
use document_graph_storage::NodeMetadataSource;
use document_graph_storage::{HotOp, Rev, TimeStamp};
use document_graph_storage::{HotOp, Rev, TimeStamp, Value};
#[cfg(feature = "conversion")]
use graphene_resource::ResourceStorage;
@@ -47,7 +47,7 @@ impl<L: Layout> Gdd<L> {
/// declaration bytes. The working registry reflects the edit immediately, but nothing enters durable
/// retired history until [`retire_pending_interaction`](Self::retire_pending_interaction). Staging on
/// every edit while retiring only at interaction boundaries lets several edits coalesce into one retired
/// interaction.
/// interaction. Returns the decoded declarations the snapshot references, for the caller's cache.
///
/// # Errors
/// [`Error::Commit`] if the runtime diff is rejected by the session. On an [`Error::Container`] /
@@ -60,8 +60,8 @@ impl<L: Layout> Gdd<L> {
metadata: &M,
resources: &graphene_resource::ResourceRegistry,
byte_store: &dyn ResourceStorage,
) -> Result<(), Error> {
let (hot_ops, declaration_bytes) = self.session.stage_from_runtime(network, metadata, resources)?;
) -> Result<document_graph_storage::Declarations, Error> {
let (hot_ops, conversion) = self.session.stage_from_runtime(network, metadata, resources)?;
for hot_op in &hot_ops {
self.append_hot_frame(hot_op)?;
@@ -70,10 +70,10 @@ impl<L: Layout> Gdd<L> {
// Persist proto-node declaration content to the byte store (the global cache in the editor,
// the working-copy container for standalone export). Content-addressed, so re-storing
// identical bytes on every commit is an idempotent no-op.
for bytes in declaration_bytes.values() {
for bytes in conversion.declaration_bytes.values() {
byte_store.store(bytes);
}
Ok(())
Ok(conversion.declarations)
}
/// Stage ops the caller built from what the editor recorded, rather than deriving them by converting
@@ -173,7 +173,7 @@ impl<L: Layout> Gdd<L> {
/// Unlike the per-interaction marker written inline at retire, this targets an already-written delta, so
/// the whole history file is rewritten in topological order. O(history) — fine for occasional user
/// labeling, not for per-interaction marking (which uses the inline path). No-op if `rev` is unknown.
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: serde_json::Value) -> Result<(), Error> {
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: Value) -> Result<(), Error> {
if self.session.annotate_delta(rev, key, value) {
self.rewrite_history()?;
}
@@ -194,10 +194,14 @@ impl<L: Layout> Gdd<L> {
fn persist_session_state(&mut self) -> Result<(), Error> {
let state = SessionState {
peer_id: self.session.peer(),
user_id: self.session.user(),
head_rev: self.session.head_rev(),
last_broadcast_rev: self.session.last_broadcast_rev(),
redo_stack: self.session.redo_stack().to_vec(),
next_node_counter: self.session.next_node_counter(),
last_hot_sequence: self.session.last_hot_sequence(),
settled: self.session.settled_marks().clone(),
clock: self.session.clock_counter(),
view_settings: self.view_settings.clone(),
network_view_settings: self.network_view_settings.clone(),
};
@@ -205,18 +209,16 @@ impl<L: Layout> Gdd<L> {
Ok(())
}
/// Re-snapshot the materialized working registry to `registry.bin`. `Session::load` trusts the stored
/// registry to match the persisted `head`, so any cursor move (undo/redo) that rewinds the working
/// registry without retiring must re-persist it or a reopen would read a registry inconsistent with
/// `head`. Synchronous and hot-path-safe (`write_non_blocking`).
/// Re-snapshot the retired registry to `registry.bin`. `Session::load` trusts it to match the persisted `head`
/// and replays the hot log on top, so it must hold no hot op, and any cursor move must re-persist it.
fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.registry())?;
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.retired_registry())?;
Ok(())
}
/// Replace the per-peer view settings and persist them to `session.json`. Called by the editor when
/// the viewport or a document-level toggle changes; never enters the registry, history, or CRDT.
pub fn set_view_settings(&mut self, view_settings: std::collections::BTreeMap<String, serde_json::Value>) -> Result<(), Error> {
pub fn set_view_settings(&mut self, view_settings: std::collections::BTreeMap<String, document_graph_storage::Value>) -> Result<(), Error> {
self.view_settings = view_settings;
self.persist_session_state()
}
@@ -232,7 +234,7 @@ impl<L: Layout> Gdd<L> {
/// enters the registry, history, or CRDT.
pub fn set_network_view_settings(
&mut self,
network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>>,
network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, document_graph_storage::Value>>,
) -> Result<(), Error> {
self.network_view_settings = network_view_settings;
self.persist_session_state()
+2 -3
View File
@@ -4,7 +4,6 @@
#[cfg(not(target_family = "wasm"))]
use std::path::Path;
use std::sync::Arc;
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
use graphene_resource::ResourceFuture;
@@ -39,7 +38,7 @@ impl<L: Layout> Gdd<L> {
#[cfg(not(target_family = "wasm"))]
pub fn add_resource_from_path(&mut self, id: document_graph_storage::ResourceId, hash: ResourceHash, src: &Path) -> Result<(), Error> {
let dest_path = self.layout.resource_path(&hash);
if let AnyContainer::Folder(folder) = self.working.as_ref() {
if let AnyContainer::Folder(folder) = &self.working {
let full = folder.root().join(&dest_path);
if let Some(parent) = full.parent() {
std::fs::create_dir_all(parent).map_err(ContainerError::Io)?;
@@ -102,7 +101,7 @@ impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
}
}
pub struct ResourceProxy<T: Layout>(Arc<AnyContainer>, T);
pub struct ResourceProxy<T: Layout>(AnyContainer, T);
impl<L: Layout + Send + Sync> LoadResource for ResourceProxy<L> {
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
+22 -6
View File
@@ -4,7 +4,7 @@
//!
//! Lives in `session.json`. Rewritten on retirement.
use document_graph_storage::{NetworkId, PeerId, Rev};
use document_graph_storage::{HotSequence, NetworkId, PeerId, Rev, SettledHotOps, UserId, Value};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
@@ -15,13 +15,17 @@ pub struct SessionState {
/// tiebreaking and minting peer-scoped IDs.
#[serde(default)]
pub peer_id: PeerId,
/// The person using this device, which the peer registers as, so authorship and undo follow the person
/// across the peer ids they accumulate.
#[serde(default)]
pub user_id: UserId,
/// Local-chain cursor. Points at the most recently applied retired delta, or `None` on an empty
/// document (no commits yet).
#[serde(default)]
pub head_rev: Option<Rev>,
/// Published frontier: the latest retired commit broadcast to a peer. Commits after it are silently
/// rewritable on undo; commits at or before it are published. `None` until broadcast transport lands.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[serde(default)]
pub last_broadcast_rev: Option<Rev>,
/// Revs the user has undone past, so redo survives a reopen. (The legacy `VecDeque` redo history
/// is not persisted, so within the shadow phase this is strictly more capable than the live editor.)
@@ -31,12 +35,24 @@ pub struct SessionState {
/// collide on minted IDs.
#[serde(default)]
pub next_node_counter: u64,
/// The sequence of the last hot op this peer authored, feeding [`document_graph_storage::HotOp::sequence`], so a
/// reopen never reuses a spent sequence.
#[serde(default)]
pub last_hot_sequence: HotSequence,
/// Per-peer view settings (PTZ, rulers, overlays, snapping, panel collapse). Local to the viewer,
/// so kept out of the CRDT/history. Editor owns the keys/values (opaque `ui::doc::*` blobs).
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub view_settings: BTreeMap<String, serde_json::Value>,
#[serde(default)]
pub view_settings: BTreeMap<String, Value>,
/// Per-network view settings (node-graph nav + previewing), keyed by the stable storage [`NetworkId`].
/// Per-peer like [`view_settings`](Self::view_settings); opaque `ui::nav::*` / `ui::previewing` blobs.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub network_view_settings: BTreeMap<NetworkId, BTreeMap<String, serde_json::Value>>,
#[serde(default)]
pub network_view_settings: BTreeMap<NetworkId, BTreeMap<String, Value>>,
/// Which hot ops are retired, so a late copy a peer re-sends after a reopen is dropped rather than retired a second
/// time. About one sequence per author; runs only for ops in flight when saved.
#[serde(default)]
pub settled: SettledHotOps,
/// The Lamport counter, so a reopen never mints a stamp already spent, even one no op in history or the hot log
/// carries any more.
#[serde(default)]
pub clock: u64,
}
+45 -70
View File
@@ -5,7 +5,7 @@
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{Codec, Error, GddV1, GddV1Layout, Layout, Manifest, io, manifest};
use document_graph_storage::{HotOp, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
use document_graph_storage::{HotOp, HotSequence, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
fn empty_container() -> AnyContainer {
AnyContainer::Memory(MemoryBackend::new())
@@ -44,7 +44,7 @@ fn create_in_round_trips_empty_document() {
futures::executor::block_on(async {
let container = empty_container();
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()).await {
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()) {
Ok(gdd) => gdd,
Err(error) => panic!("create_in failed: {error:?}"),
};
@@ -82,9 +82,7 @@ fn open_in_rejects_wrong_format_magic() {
#[test]
fn manifest_returns_what_create_in_wrote() {
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
assert_eq!(gdd.session().peer(), PeerId(13));
@@ -99,9 +97,7 @@ fn manifest_returns_what_create_in_wrote() {
#[test]
fn update_manifest_changes_visible_after_reopen() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
gdd.update_manifest(|m| m.editor_version = "ed-NEW".into())
.unwrap_or_else(|error| panic!("update_manifest failed: {error:?}"));
@@ -116,9 +112,7 @@ fn update_manifest_changes_visible_after_reopen() {
#[test]
fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// AddNetwork on the root network. Idempotent at apply, so two hot ops applied in sequence
// produces one network in the registry.
@@ -128,6 +122,7 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: HotSequence(1),
};
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
@@ -143,9 +138,7 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
#[test]
fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// Two hot ops: one with low timestamp (will retire), one with high (will stay).
let early = HotOp {
@@ -154,6 +147,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: HotSequence(1),
};
let late = HotOp {
op: RegistryDelta::AddNetwork {
@@ -161,6 +155,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 10, peer: PeerId(5) },
sequence: HotSequence(2),
};
gdd.apply_hot_op(early).unwrap();
gdd.apply_hot_op(late).unwrap();
@@ -189,9 +184,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
#[test]
fn last_broadcast_rev_persists_across_reopen() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// Retire one op so there is a real retired rev to mark as published.
let op = HotOp {
@@ -200,6 +193,7 @@ fn last_broadcast_rev_persists_across_reopen() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: HotSequence(1),
};
gdd.apply_hot_op(op).unwrap();
let retired = gdd.retire(TimeStamp { counter: 1, peer: PeerId(5) }).unwrap_or_else(|error| panic!("retire failed: {error:?}"));
@@ -220,9 +214,7 @@ fn export_folder_round_trips_through_open() {
use document_format::{ExportFormat, ExportOptions};
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("export");
@@ -231,7 +223,7 @@ fn export_folder_round_trips_through_open() {
.await
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
// Payloads keep the working-copy codecs: registry is MessagePack (`.bin`), manifest is JSON.
// Payloads keep the working-copy codecs: registry is postcard (`.bin`), manifest is JSON.
assert!(dest.join("registry.bin").exists());
assert!(dest.join("manifest.json").exists());
assert!(dest.join("session.json").exists());
@@ -250,9 +242,7 @@ fn export_zip_round_trips_via_deserialize() {
use document_format::{ExportFormat, ExportOptions};
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), 0xCD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), 0xCD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("doc.gdd.zip");
@@ -277,9 +267,7 @@ fn export_rejects_invalid_options() {
use document_format::{ExportFormat, ExportOptions};
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xEF, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("nope");
@@ -302,9 +290,7 @@ fn resource_round_trip_add_read_remove() {
use graphene_resource::{ResourceHash, ResourceId};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), 0xCAFE, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), 0xCAFE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let payload = b"deadbeef cafe babe";
let hash = ResourceHash::from(&payload[..]);
@@ -334,9 +320,7 @@ fn resource_survives_reopen() {
use graphene_resource::{ResourceHash, ResourceId};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), 0xC0DE, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), 0xC0DE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let payload = b"persistent bytes";
let hash = ResourceHash::from(&payload[..]);
@@ -365,9 +349,7 @@ fn resource_from_path_uses_fs_copy_on_folder_backend() {
// Need a folder-backed working copy to exercise the fs::copy path.
let working_dir = tempfile::tempdir().unwrap();
let working = AnyContainer::Folder(FolderBackend::create(working_dir.path()).unwrap());
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// Source file outside the working copy.
let payload = b"external resource bytes";
@@ -391,9 +373,7 @@ fn export_carries_resources() {
use graphene_resource::{ResourceHash, ResourceId};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), 0xBC, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), 0xBC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let payload = b"exported resource";
let hash = ResourceHash::from(&payload[..]);
@@ -416,14 +396,12 @@ fn export_carries_resources() {
#[test]
fn embed_all_resources_materializes_link_only_resource() {
use document_format::{ExportFormat, ExportOptions};
use document_graph_storage::NoMetadata;
use document_graph_storage::{NoMetadata, to_value};
use graph_craft::application_io::resource::ResourceStorage;
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), 0xF00D, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), 0xF00D, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// A resource whose only source is a URL, resolved to a hash. The bytes live solely in the
// byte store; the working copy never holds them.
@@ -470,8 +448,8 @@ fn embed_all_resources_materializes_link_only_resource() {
let entry = reopened.registry().resources.get(&id).expect("resource entry survived export");
assert_eq!(entry.hash, Some(hash));
let embedded = serde_json::to_value(DataSource::Embedded).unwrap();
let url = serde_json::to_value(DataSource::Url("https://example.com/r.bin".parse().unwrap())).unwrap();
let embedded = to_value(&DataSource::Embedded).unwrap();
let url = to_value(&DataSource::Url("https://example.com/r.bin".parse().unwrap())).unwrap();
let chain: Vec<_> = entry.sources.iter().map(|(_, value)| value.source.clone()).collect();
assert_eq!(chain, vec![embedded, url], "Embedded leads the chain, URL kept as fallback");
});
@@ -488,9 +466,7 @@ fn export_materializes_embedded_resource_from_byte_store() {
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), 0xBEEF, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), 0xBEEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// An Embedded resource whose bytes live only in the byte store, not the working copy.
let payload = b"embedded bytes in the cache";
@@ -531,9 +507,7 @@ fn export_round_trips_unretired_hot_ops() {
use graphene_resource::{DataSource, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xF15E, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xF15E, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let payload = b"hot resource bytes";
let hash = graphene_resource::ResourceHash::from(&payload[..]);
@@ -586,14 +560,12 @@ fn open_in_rejects_future_format_version() {
#[test]
fn create_in_records_default_codecs_in_manifest() {
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let codecs = gdd.manifest().codecs;
assert_eq!(codecs.registry, Codec::MessagePack);
assert_eq!(codecs.history, Codec::MessagePackFrames);
assert_eq!(codecs.hot_log, Codec::MessagePackFrames);
assert_eq!(codecs.registry, Codec::Postcard);
assert_eq!(codecs.history, Codec::PostcardFrames);
assert_eq!(codecs.hot_log, Codec::PostcardFrames);
assert_eq!(codecs.session, Codec::Json);
});
}
@@ -609,9 +581,7 @@ fn first_commit_registers_peer_and_survives_reopen() {
use graphene_resource::ResourceRegistry;
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let network = NodeNetwork {
exports: vec![NodeInput::node(core_types::uuid::NodeId(0), 0)],
@@ -630,11 +600,19 @@ fn first_commit_registers_peer_and_survives_reopen() {
gdd.commit_from_runtime(&network, &NoMetadata, &ResourceRegistry::new(), &HashMapResourceStorage::new())
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
assert_eq!(gdd.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "first commit registers the peer");
assert_eq!(
gdd.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
Some(UserId(21)),
"first commit registers the peer"
);
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
assert_eq!(reopened.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "registration survives reopen");
assert_eq!(
reopened.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
Some(UserId(21)),
"registration survives reopen"
);
});
}
@@ -645,9 +623,7 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
futures::executor::block_on(async {
use document_container::AsyncContainer;
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let hot_op = HotOp {
op: RegistryDelta::AddNetwork {
@@ -655,12 +631,13 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: HotSequence(1),
};
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
let (working, layout) = gdd.into_storage();
// Defaults: hot log is MessagePackFrames (.frames), manifest is always JSON.
assert!(working.exists(&io::path_for(layout.hot_log_basename(), Codec::MessagePackFrames)).await);
// Defaults: hot log is PostcardFrames (.frames), manifest is always JSON.
assert!(working.exists(&io::path_for(layout.hot_log_basename(), Codec::PostcardFrames)).await);
assert!(working.exists(&io::path_for(layout.manifest_basename(), Codec::Json)).await);
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
@@ -698,9 +675,7 @@ fn declarations_round_trip_through_byte_store() {
..Default::default()
};
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// Commit: declaration bytes flow into the byte store, not the Gdd container.
let byte_store = HashMapResourceStorage::new();
+108
View File
@@ -0,0 +1,108 @@
// Staging a whole document after a recorded batch, and what a reopen must carry over.
#![cfg(feature = "conversion")]
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::{NoMetadata, PeerId, Registry};
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
use graph_craft::{ProtoNodeIdentifier, concrete};
use graphene_resource::ResourceRegistry;
fn network_with_one_node() -> NodeNetwork {
let node = DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
call_argument: concrete!(()),
..Default::default()
};
NodeNetwork {
nodes: [(NodeId(1), node)].into_iter().collect(),
..Default::default()
}
}
/// A whole-document stage after a recorded batch stages nothing new: restating the batch would fail on the node it added.
#[test]
fn a_whole_document_stage_after_a_recorded_batch_stages_nothing_new() {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(21), 1, "ed".into(), "std".into()).unwrap();
let store = HashMapResourceStorage::new();
let resources = ResourceRegistry::new();
gdd.stage_runtime_snapshot(&NodeNetwork::default(), &NoMetadata, &resources, &store)
.expect("first whole-document stage");
let target = Registry::convert_from_runtime(&network_with_one_node(), &NoMetadata, &resources, PeerId(21)).unwrap();
let ops = document_graph_storage::delta::compute_deltas(gdd.registry(), &target.registry);
gdd.stage_constructed_ops(ops, &target.declaration_bytes, &store).expect("recorded batch");
let hot_before = gdd.session().hot_log().len();
gdd.stage_runtime_snapshot(&network_with_one_node(), &NoMetadata, &resources, &store)
.expect("the runtime already matches what was staged");
assert_eq!(gdd.session().hot_log().len(), hot_before, "nothing new to stage");
}
/// `registry.bin` is the retired snapshot the hot log replays onto, so an op still hot at save time must stay out of it.
#[test]
fn a_reopen_keeps_unretired_hot_ops_out_of_the_retired_snapshot() {
use document_graph_storage::{AttributeDelta, HotOp, HotSequence, RegistryDelta, TimeStamp, Value};
let set = |value: u32, counter: u64| HotOp {
op: RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta {
key: "k".into(),
value: Some(Value::from(serde_json::json!(value))),
},
},
timestamp: TimeStamp { counter, peer: PeerId(22) },
sequence: HotSequence(counter),
};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(22), 1, "ed".into(), "std".into()).unwrap();
gdd.apply_hot_op(set(1, 1)).unwrap();
gdd.apply_hot_op(set(2, 2)).unwrap();
gdd.retire(TimeStamp { counter: 1, peer: PeerId(22) }).unwrap();
let retired = gdd.session().retired_registry().clone();
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.unwrap();
assert!(reopened.session().retired_registry().value_equal(&retired), "the hot op leaked into the retired snapshot");
assert_eq!(reopened.session().hot_log().len(), 1);
});
}
/// A reopen continues this peer's clock and run of hot op sequences, with ops still hot and after they all retired,
/// since a reused sequence would let a peer's settled marks drop the new op.
#[test]
fn a_reopen_continues_the_hot_op_sequence() {
use document_graph_storage::{AttributeDelta, RegistryDelta, Value};
let set = |value: u32| RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta {
key: "k".into(),
value: Some(Value::from(serde_json::json!(value))),
},
};
// Stages one op and returns the sequence it got.
fn stage(gdd: &mut GddV1, op: RegistryDelta) -> u64 {
gdd.stage_constructed_ops(vec![op], &Default::default(), &HashMapResourceStorage::new()).unwrap();
gdd.session().hot_log().last().unwrap().sequence.0
}
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(23), 1, "ed".into(), "std".into()).unwrap();
stage(&mut gdd, set(1));
let up_to = gdd.session().hot_log().last().unwrap().timestamp;
gdd.retire(up_to).unwrap();
let last = stage(&mut gdd, set(2));
let (working, layout) = gdd.into_storage();
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
assert_eq!(stage(&mut reopened, set(3)), last + 1);
let up_to = reopened.session().hot_log().last().unwrap().timestamp;
reopened.retire(up_to).unwrap();
let last = reopened.session().last_hot_sequence().0;
let clock = reopened.session().clock_counter();
let (working, layout) = reopened.into_storage();
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
assert_eq!(reopened.session().clock_counter(), clock, "the clock carries over");
assert_eq!(stage(&mut reopened, set(4)), last + 1);
});
}
+7 -1
View File
@@ -5,9 +5,15 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
conversion = ["dep:graph-craft", "dep:core-types"]
default = ["conversion"]
@@ -22,7 +28,7 @@ serde = { workspace = true }
serde_json = { workspace = true }
blake3 = { workspace = true }
rustc-hash = { workspace = true }
rmp-serde = { workspace = true }
postcard = { workspace = true }
[dev-dependencies]
graph-craft = { workspace = true, features = ["loading"] }
+37 -16
View File
@@ -1,4 +1,4 @@
use crate::TimeStamp;
use crate::{TimeStamp, Value, ValueError, from_value, to_value};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
@@ -8,33 +8,54 @@ use std::collections::BTreeMap;
/// keys live on `Node.inputs_attributes[i]`; per-network keys live on `Network.attributes`.
pub mod attr;
/// A type-erased attribute value paired with the timestamp at which it was last set.
/// A type-erased attribute value paired with the timestamp at which it was last set. A deleted key
/// stays as a stamped tombstone, so an older write loses in either arrival order; readers see it as absent.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Value {
pub value: serde_json::Value,
pub struct AttributeValue {
pub value: Value,
pub timestamp: TimeStamp,
// No skipping: the registry is positional on disk.
#[serde(default)]
pub deleted: bool,
}
impl Value {
pub fn new(value: serde_json::Value, timestamp: TimeStamp) -> Self {
Self { value, timestamp }
impl AttributeValue {
pub fn new(value: Value, timestamp: TimeStamp) -> Self {
Self { value, timestamp, deleted: false }
}
/// The tombstone of a key deleted at `timestamp`.
pub fn deleted(timestamp: TimeStamp) -> Self {
Self {
value: Value::None,
timestamp,
deleted: true,
}
}
}
pub type Attributes = BTreeMap<String, Value>;
/// Attribute maps. Each entity carries an `attributes_timestamp`: when its map was last written whole, by an
/// addition or a whole-list input write. A key absent from the map is deleted as of that stamp, so an older
/// write is dropped and an older tombstone is redundant.
pub type Attributes = BTreeMap<String, AttributeValue>;
/// The live entries of an attribute map: every key that is not a tombstone.
pub fn live(attributes: &Attributes) -> impl Iterator<Item = (&String, &AttributeValue)> {
attributes.iter().filter(|(_, value)| !value.deleted)
}
/// Write helpers for `Attributes`.
pub trait AttributesWrite {
/// Inserts a JSON value under `key`.
fn set(&mut self, key: &str, value: serde_json::Value, timestamp: TimeStamp);
/// Inserts `value` under `key`.
fn set(&mut self, key: &str, value: Value, timestamp: TimeStamp);
/// Serializes `value` and inserts it under `key`.
fn set_serialized<T: serde::Serialize>(&mut self, key: &str, value: &T, timestamp: TimeStamp) -> Result<(), serde_json::Error> {
self.set(key, serde_json::to_value(value)?, timestamp);
fn set_serialized<T: serde::Serialize>(&mut self, key: &str, value: &T, timestamp: TimeStamp) -> Result<(), ValueError> {
self.set(key, to_value(value)?, timestamp);
Ok(())
}
/// Inserts only when `value != default`, so the read side falls back to the same default.
fn set_if_not_default<T: serde::Serialize + PartialEq>(&mut self, key: &str, value: &T, default: &T, timestamp: TimeStamp) -> Result<(), serde_json::Error> {
fn set_if_not_default<T: serde::Serialize + PartialEq>(&mut self, key: &str, value: &T, default: &T, timestamp: TimeStamp) -> Result<(), ValueError> {
if value != default {
self.set_serialized(key, value, timestamp)?;
}
@@ -43,8 +64,8 @@ pub trait AttributesWrite {
}
impl AttributesWrite for Attributes {
fn set(&mut self, key: &str, value: serde_json::Value, timestamp: TimeStamp) {
self.insert(key.to_string(), Value { value, timestamp });
fn set(&mut self, key: &str, value: Value, timestamp: TimeStamp) {
self.insert(key.to_string(), AttributeValue::new(value, timestamp));
}
}
@@ -66,6 +87,6 @@ pub trait AttributesRead {
impl AttributesRead for Attributes {
fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
self.get(key).and_then(|v| serde_json::from_value(v.value.clone()).ok())
self.get(key).filter(|v| !v.deleted).and_then(|v| from_value(&v.value).ok())
}
}
@@ -31,6 +31,7 @@ pub mod node {
pub mod session {
pub mod network {
pub const PREVIEWING: &str = "ui::previewing";
// TODO: Remove these graph ui nav-specific attributes
pub const NAV_PTZ: &str = "ui::nav::ptz";
pub const NAV_TRANSFORM: &str = "ui::nav::transform";
+78 -47
View File
@@ -1,13 +1,15 @@
use crate::{Attributes, AttributesWrite, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev};
use crate::{
AttributeValue, Attributes, AttributesWrite, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Prior, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId,
Value, attr, compute_rev,
};
use graphene_resource::ResourceHash;
use serde::{Deserialize, Serialize};
/// Content-addressed delta: `id` is `blake3_128(parents, author, timestamp, delta_type)`.
///
/// `reverse` is state-dependent undo bookkeeping (it captures pre-state at the moment the forward
/// op was applied), so it's serialized for storage but excluded from the identity hash — two peers
/// observing the same forward delta against different local states would otherwise compute
/// different Revs for the same logical op.
/// `reverse` is state-dependent undo bookkeeping (what the op overwrote, captured as it applied), so it's
/// serialized for storage but excluded from the identity hash: two peers applying the same forward delta to
/// different local states would otherwise compute different Revs for the same logical op.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Delta {
pub id: Rev,
@@ -16,16 +18,22 @@ pub struct Delta {
pub author: PeerId,
pub timestamp: TimeStamp,
pub kind: RegistryDelta,
pub reverse: RegistryDelta,
/// What every slot `kind` wrote held before it, stamps included, in write order. See [`Prior`].
pub reverse: Vec<Prior>,
/// Local, mutable annotations on this commit (interaction-end marker, future commit messages / labels).
/// Deliberately excluded from `compute_rev`: relabeling a commit must not change its content-addressed
/// identity, and two peers annotating the same op differently must still dedup to one `Rev`.
#[serde(default, skip_serializing_if = "Attributes::is_empty")]
#[serde(default)]
pub attributes: Attributes,
/// When the delta entered history, in Unix milliseconds by the clock of the peer that retired it; display only,
/// and outside the rev like `attributes`. Zero means unrecorded, saving the tag byte an `Option` costs per delta;
/// read it through [`retired_at`](Self::retired_at). Last, since the history codec is positional.
#[serde(default)]
pub(crate) retired_at_ms: u64,
}
impl Delta {
pub fn new(parent: Option<Rev>, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: RegistryDelta) -> Self {
pub fn new(parent: Option<Rev>, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: Vec<Prior>) -> Self {
let id = compute_rev(parent, author, timestamp, &kind);
Self {
id,
@@ -35,6 +43,7 @@ impl Delta {
kind,
reverse,
attributes: Attributes::default(),
retired_at_ms: 0,
}
}
@@ -52,9 +61,10 @@ impl Delta {
parent,
author,
timestamp,
reverse: kind.clone(),
reverse: Vec::new(),
kind,
attributes: Attributes::default(),
retired_at_ms: 0,
}
}
@@ -69,11 +79,16 @@ impl Delta {
/// Mark this delta as the last op of a user interaction, so the undo cursor treats it as a checkpoint.
pub fn mark_interaction_end(&mut self, timestamp: TimeStamp) {
self.attributes.set(attr::delta::INTERACTION_END, serde_json::Value::Bool(true), timestamp);
self.attributes.set(attr::delta::INTERACTION_END, Value::Bool(true), timestamp);
}
pub fn is_interaction_end(&self) -> bool {
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == serde_json::Value::Bool(true))
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == Value::Bool(true))
}
/// When the delta entered history in wall-clock milliseconds, if the peer that retired it recorded it.
pub fn retired_at(&self) -> Option<u64> {
(self.retired_at_ms != 0).then_some(self.retired_at_ms)
}
/// The content-addressed `Rev` this delta's identity fields hash to. Equals `id` for a delta built
@@ -98,8 +113,7 @@ pub enum RegistryDelta {
id: NodeId,
node: Node,
},
/// `snapshot` lets the reverse `AddNode` rebuild without reading the (already-removed) node from
/// the registry, mirroring `RemoveNetwork`.
/// `snapshot` is the node as removed, which folds in like any write so a removal of a node never seen still lands.
RemoveNode {
id: NodeId,
snapshot: Node,
@@ -119,6 +133,15 @@ pub enum RegistryDelta {
id: NodeId,
inputs: Vec<InputSlot>,
},
/// A node's implementation, for swapping what it computes without rebuilding the node.
///
/// Removing and re-adding the node would express the same change, but would also clear every
/// attribute it carries, so restating them would clobber whatever a concurrent peer wrote to the
/// node's name, lock or pin.
SetNodeImplementation {
id: NodeId,
implementation: Implementation,
},
ChangeNodeAttribute {
id: NodeId,
delta: AttributeDelta,
@@ -143,13 +166,12 @@ pub enum RegistryDelta {
id: NetworkId,
network: Network,
},
/// `snapshot` lets the reverse delta rebuild without re-walking history.
/// `snapshot` is the network as removed; see [`RemoveNode`](Self::RemoveNode).
RemoveNetwork {
id: NetworkId,
snapshot: Network,
},
/// Register a whole resource entry at once. Overwrites any existing entry for `id`; the reverse
/// of `RemoveResource`, the way `AddNetwork` pairs with `RemoveNetwork`.
/// Register a whole resource entry at once, the way `AddNetwork` pairs with `RemoveNetwork`.
AddResource {
id: ResourceId,
entry: ResourceEntry,
@@ -171,16 +193,15 @@ pub enum RegistryDelta {
AddSource {
id: ResourceId,
key: SourceKey,
source: serde_json::Value,
source: Value,
},
/// Remove one entry from a resource's source chain. LWW against the entry's timestamp.
RemoveSource {
id: ResourceId,
key: SourceKey,
},
/// Append-only registration of a device's `PeerId` against its owning `UserId`.
/// First write wins; conflicting re-registration errors. Duplicate identical registration
/// is a no-op. Not LWW — the mapping is forever.
/// Registers a device's `PeerId` to the `UserId` behind it. LWW per peer, so a device that changes person
/// registers again and the newest registration wins wherever it lands.
RegisterPeer {
peer: PeerId,
user: UserId,
@@ -195,42 +216,52 @@ pub enum RegistryDelta {
Merge {
extra_parents: Vec<Rev>,
},
/// The last op of its author's transaction. Changes nothing, and retirement drops it.
EndTransaction,
// Allow for future delta types without a model change
Other(serde_json::Value),
Other(Value),
}
/// `value: None` means remove. The timestamp comes from the wrapping `Delta`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AttributeDelta {
pub key: String,
pub value: Option<serde_json::Value>,
pub value: Option<Value>,
}
pub(crate) fn reverse_attribute_delta(delta: &AttributeDelta, attributes: &Attributes) -> AttributeDelta {
AttributeDelta {
key: delta.key.clone(),
value: attributes.get(&delta.key).map(|previous| previous.value.clone()),
}
}
pub(crate) fn apply_attribute_delta(delta: AttributeDelta, timestamp: TimeStamp, force: bool, attributes: &mut Attributes) {
/// Lands a single-key write. `floor` is the map's `attributes_timestamp`; see [`Attributes`]. A deletion
/// leaves a tombstone.
pub(crate) fn apply_attribute_delta(delta: AttributeDelta, timestamp: TimeStamp, attributes: &mut Attributes, floor: TimeStamp) {
let AttributeDelta { key, value } = delta;
match value {
Some(value) => match attributes.entry(key) {
std::collections::btree_map::Entry::Occupied(mut entry) => {
if force || timestamp > entry.get().timestamp {
entry.insert(Value { value, timestamp });
}
}
std::collections::btree_map::Entry::Vacant(entry) => {
entry.insert(Value { value, timestamp });
}
},
None => {
let should_remove = force || attributes.get(&key).is_none_or(|existing| timestamp > existing.timestamp);
if should_remove {
attributes.remove(&key);
}
}
let decided = attributes.get(&key).map_or(floor, |existing| existing.timestamp);
if timestamp <= decided {
return;
}
let entry = match value {
Some(value) => AttributeValue::new(value, timestamp),
None => AttributeValue::deleted(timestamp),
};
attributes.insert(key, entry);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_missing_retirement_time_costs_what_a_zero_costs_and_round_trips() {
let base = Delta::new(None, PeerId(1), TimeStamp { counter: 1, peer: PeerId(1) }, RegistryDelta::EndTransaction, Vec::new());
let mut stamped = base.clone();
stamped.retired_at_ms = 1_790_000_000_000;
let bare_base = postcard::to_allocvec(&base).expect("encode");
let bare_stamped = postcard::to_allocvec(&stamped).expect("encode");
// Only the integer's varint differs: one byte for zero, six for today's milliseconds, no tag byte in either.
assert_eq!(bare_stamped.len() - bare_base.len(), postcard::to_allocvec(&1_790_000_000_000u64).unwrap().len() - 1);
let decoded: Delta = postcard::from_bytes(&bare_stamped).expect("decode");
assert_eq!(decoded.retired_at(), Some(1_790_000_000_000));
let decoded: Delta = postcard::from_bytes(&bare_base).expect("decode");
assert_eq!(decoded.retired_at(), None);
}
}
+18 -18
View File
@@ -166,14 +166,14 @@ fn diff_resource_entry(id: ResourceId, from: &ResourceEntry, to: &ResourceEntry,
deltas.push(RegistryDelta::SetResourceHash { id, hash: to.hash });
}
for (key, _) in &from.sources {
for (key, _) in from.live_sources() {
if to.source(key).is_none() {
deltas.push(RegistryDelta::RemoveSource { id, key: *key });
}
}
// Compare source bodies only; the per-source timestamp is derived from the diff, not part of it.
for (key, to_source) in &to.sources {
for (key, to_source) in to.live_sources() {
if from.source(key).is_none_or(|from_source| from_source.source != to_source.source) {
deltas.push(RegistryDelta::AddSource {
id,
@@ -196,15 +196,15 @@ fn nodes_have_same_implementation(a: &Node, b: &Node) -> bool {
fn compute_attribute_deltas(from: &crate::Attributes, to: &crate::Attributes) -> Vec<AttributeDelta> {
let mut deltas = Vec::new();
for key in from.keys() {
if !to.contains_key(key) {
for (key, _) in crate::attributes::live(from) {
if to.get(key).is_none_or(|value| value.deleted) {
deltas.push(AttributeDelta { key: key.clone(), value: None });
}
}
// Compare by `value` only; the per-entry `timestamp` is derived from the diff, not part of it.
for (key, to_value) in to {
if from.get(key).is_none_or(|from_value| from_value.value != to_value.value) {
for (key, to_value) in crate::attributes::live(to) {
if from.get(key).is_none_or(|from_value| from_value.deleted || from_value.value != to_value.value) {
deltas.push(AttributeDelta {
key: key.clone(),
value: Some(to_value.value.clone()),
@@ -218,7 +218,7 @@ fn compute_attribute_deltas(from: &crate::Attributes, to: &crate::Attributes) ->
#[cfg(test)]
mod tests {
use super::*;
use crate::{Attributes, ExportSlot, Network, Node, NodeInput, TimeStamp};
use crate::{Attributes, ExportSlot, Network, Node, NodeInput, TimeStamp, Value};
#[test]
fn test_compute_deltas_empty() {
@@ -287,6 +287,7 @@ mod tests {
input: NodeInput::Import { index: 0 },
timestamp: TimeStamp::ORIGIN,
attributes: Attributes::new(),
attributes_timestamp: TimeStamp::ORIGIN,
});
let deltas = compute_deltas(&from, &to);
@@ -304,11 +305,7 @@ mod tests {
from.networks.insert(NetworkId(0), Network::default());
let mut to = from.clone();
to.networks
.get_mut(&NetworkId(0))
.unwrap()
.attributes
.set("ui::nav::width", serde_json::json!(640.0), TimeStamp::ORIGIN);
to.networks.get_mut(&NetworkId(0)).unwrap().attributes.set("ui::nav::width", Value::Float(640.), TimeStamp::ORIGIN);
let deltas = compute_deltas(&from, &to);
assert_eq!(deltas.len(), 1, "a changed per-network attribute must emit one delta");
@@ -341,9 +338,10 @@ mod tests {
let stamp = |counter: u64| TimeStamp { counter, peer: crate::PeerId(0) };
node.attributes.insert(
"test".to_string(),
crate::Value {
value: serde_json::json!("old"),
crate::AttributeValue {
value: Value::Str("old".into()),
timestamp: stamp(0),
deleted: false,
},
);
from.node_instances.insert(NodeId(42), node);
@@ -351,9 +349,10 @@ mod tests {
let mut to = from.clone();
to.node_instances.get_mut(&NodeId(42)).unwrap().attributes.insert(
"test".to_string(),
crate::Value {
value: serde_json::json!("new"),
crate::AttributeValue {
value: Value::Str("new".into()),
timestamp: stamp(1),
deleted: false,
},
);
@@ -376,9 +375,10 @@ mod tests {
let mut to = from.clone();
to.attributes.insert(
"doc::test_attribute".to_string(),
crate::Value {
value: serde_json::json!("value"),
crate::AttributeValue {
value: Value::Str("value".into()),
timestamp: stamp(1),
deleted: false,
},
);
+534 -306
View File
@@ -1,23 +1,29 @@
use std::collections::btree_map::Entry;
use std::collections::{HashMap, HashSet};
use std::hash::Hash;
use crate::{
CrdtError, Delta, ExportSlot, History, HotOp, LamportClock, MAX_EXPORT_SLOTS, NetworkId, NodeId, NodeInput, PeerId, Registry, RegistryDelta, ResourceEntry, Rev, SourceValue, TimeStamp,
apply_attribute_delta, reverse_attribute_delta,
Attributes, CrdtError, Delta, ExportSlot, History, HotOp, HotSequence, Implementation, InputSlot, LamportClock, MAX_EXPORT_SLOTS, MAX_INPUT_SLOTS, Network, NetworkId, Node, NodeId, NodeInput,
PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, Rev, SettledHotOps, SourceValue, TimeStamp, Tombstone, UserId, apply_attribute_delta,
};
#[derive(Clone, Debug)]
pub struct Document {
/// Working registry: retired state with the current hot ops applied on top. This is what live
/// reads and `registry()` observe, and what undo/redo force-apply against.
/// reads and `registry()` observe.
pub(crate) working_registry: Registry,
/// Live broadcast stream, applied to the `working_registry` on receive, GC'd at retirement.
/// Persisted for crash recovery so in-flight unretired work survives editor restarts.
pub(crate) hot_log: Vec<HotOp>,
/// The stamps of the hot log's ops, so a re-announced op is recognised without a scan.
pub(crate) hot_timestamps: HashSet<TimeStamp>,
/// Which hot ops are retired into history, so a late copy is dropped;
/// retired deltas keep no link back to their hot ops.
pub(crate) settled: SettledHotOps,
/// The registry as of the last retirement, with no un-retired hot ops applied. Retirement computes
/// each delta's `reverse` against this (so LWW reverses capture the true pre-op value, not the
/// hot-polluted working state) and advances it, stamping fields at the fresh `T_retire`. Kept equal
/// to `registry` *by value* whenever the hot log is empty (undo/redo resync it after moving the
/// cursor), but field timestamps can differ: retirement bumps the snapshot's to `T_retire` while the
/// working registry keeps the staging-time timestamps. Benign while the local monotonic clock makes
/// new edits win
/// hot-polluted working state) and advances it. It equals the working registry whenever the hot log is
/// empty.
pub(crate) retired_snapshot: Registry,
/// User's cursor in their local history chain. `None` on an empty document (no commits yet).
pub(crate) head: Option<Rev>,
@@ -28,97 +34,129 @@ pub struct Document {
pub(crate) redo_stack: Vec<Rev>,
pub(crate) clock: LamportClock,
pub(crate) peer: PeerId,
/// Latest retired commit on the local chain that has been broadcast to at least one peer.
/// Commits after this can be rewritten silently; commits at or before this are published
/// and require forward reverse-delta ops to undo. `None` means nothing broadcast yet.
/// The person behind this peer; what `RegisterPeer` records for it.
pub(crate) user: UserId,
/// Latest retired commit on the local chain that a peer holds. Commits after it can be undone silently; commits up
/// to it are published and stay. `None` means nothing published yet.
pub(crate) last_broadcast_rev: Option<Rev>,
/// Shared-monotonic counter feeding `next_node_id`. Bumped on every mint regardless of which
/// peer is calling; collision avoidance comes from hashing `(self.peer, counter)`, so two peers
/// reading the same counter still produce distinct IDs.
pub(crate) next_node_counter: u64,
/// Counts this peer's own hot ops, so each carries its position in a gap-free run. See [`HotOp::sequence`].
pub(crate) last_hot_sequence: HotSequence,
}
impl Document {
/// An empty document for `peer`, at the origin of its clock.
pub(crate) fn empty(peer: PeerId, user: UserId) -> Self {
Self {
working_registry: Registry::default(),
retired_snapshot: Registry::default(),
history: History::new(),
hot_log: Vec::new(),
hot_timestamps: HashSet::new(),
settled: SettledHotOps::default(),
head: None,
redo_stack: Vec::new(),
clock: LamportClock::new(peer),
peer,
user,
last_broadcast_rev: None,
next_node_counter: 0,
last_hot_sequence: HotSequence::NONE,
}
}
/// Mint a fresh `NodeId` scoped to this document's peer. The 64-bit ID is `blake3(peer, counter)`
/// truncated; the counter is shared across peers and persisted with the document.
pub fn next_node_id(&mut self) -> NodeId {
self.next_node_counter += 1;
let bytes = rmp_serde::to_vec(&(self.peer, self.next_node_counter)).expect("(PeerId, counter) must serialize");
let digest = blake3::hash(&bytes);
let mut hasher = blake3::Hasher::new();
postcard::to_io(&(self.peer, self.next_node_counter), &mut hasher).expect("(PeerId, counter) must serialize");
let digest = hasher.finalize();
let mut truncated = [0u8; 8];
truncated.copy_from_slice(&digest.as_bytes()[..8]);
NodeId(u64::from_le_bytes(truncated))
}
pub(crate) fn restore_node_from_history(&mut self, target: RegistryTarget, node_id: NodeId) -> Result<(), CrdtError> {
let delta = self
.find_in_ancestry(|d| matches!(d.reverse, RegistryDelta::AddNode { id, .. } if id == node_id))
.ok_or(CrdtError::NodeNotInHistory(node_id))?;
self.revert_delta(target, delta)
}
pub(crate) fn restore_network_from_history(&mut self, target: RegistryTarget, network_id: NetworkId) -> Result<(), CrdtError> {
// Find the Delta whose forward op removed this network. Its `reverse` is `AddNetwork`,
// which is what we want to re-apply.
let delta = self
.find_in_ancestry(|d| matches!(d.reverse, RegistryDelta::AddNetwork { id, .. } if id == network_id))
.ok_or(CrdtError::NetworkNotInHistory(network_id))?;
self.revert_delta(target, delta)
}
/// Search every delta reachable from `head` (following all parents, including a merge's
/// `extra_parents`) for the first matching `predicate`, breadth-first. Resurrection needs full
/// ancestry reachability, so a node added only on a merged-in branch is still found.
fn find_in_ancestry(&self, predicate: impl Fn(&Delta) -> bool) -> Option<Delta> {
let mut queue: std::collections::VecDeque<Rev> = self.head.into_iter().collect();
let mut seen: std::collections::HashSet<Rev> = self.head.into_iter().collect();
while let Some(rev) = queue.pop_front() {
let Some(delta) = self.history.get(rev) else { continue };
if predicate(delta) {
return Some(delta.clone());
}
for parent in delta.all_parents() {
if seen.insert(parent) {
queue.push_back(parent);
}
}
/// Put back what a delta overwrote in the retired snapshot (silent-zone undo), leaving it as folding history up
/// to the delta's parent would. The working registry follows: it is the same registry when nothing is hot.
pub(crate) fn revert_delta(&mut self, delta: &Delta) {
crate::prior::restore(&mut self.retired_snapshot, &delta.reverse);
if self.hot_log.is_empty() {
crate::prior::restore(&mut self.working_registry, &delta.reverse);
}
None
}
/// Apply a delta's `reverse` as the new forward op (silent-zone undo). Force-applied: structural
/// ops are idempotent, and LWW arms assign the reverse value unconditionally even though it carries
/// the same timestamp as the forward op it undoes.
pub(crate) fn revert_delta(&mut self, target: RegistryTarget, mut delta: Delta) -> Result<(), CrdtError> {
for parent in delta.all_parents() {
if !self.history.contains(parent) {
return Err(CrdtError::NotFoundInHistory(parent));
}
}
std::mem::swap(&mut delta.kind, &mut delta.reverse);
self.apply_op_with(target, delta.kind, delta.timestamp, ApplyMode::Force)
}
/// Apply a live broadcast op. Updates the registry via LWW and appends to the hot log.
/// Doesn't touch history or `head` — hot ops are transient.
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
self.apply_op(hot_op.op.clone(), hot_op.timestamp)?;
/// Apply a locally staged op: LWW into the registry, append to the hot log, leave history and `head`
/// alone. Skips the retirement check, so staging never silently drops local work; outside callers use
/// [`Session::apply_hot_op`](crate::Session::apply_hot_op).
pub(crate) fn apply_hot_op(&mut self, hot_op: HotOp, mode: ApplyMode) -> Result<(), CrdtError> {
self.apply_op_with(RegistryTarget::Working, hot_op.op.clone(), hot_op.timestamp, mode)?;
self.hot_timestamps.insert(hot_op.timestamp);
self.hot_log.push(hot_op);
Ok(())
}
/// Replay a hot op recovered from persisted state. Idempotent on structural ops so that
/// re-applying an op whose effect is already reflected in the registry is a no-op rather
/// than an error.
/// Replay a hot op recovered from persisted state or received from a peer. Replaying one already
/// reflected in the registry changes nothing.
pub fn replay_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
// Re-adding a settled op would leave a hot log entry no retirement will ever name.
if self.settled.covers(hot_op.id()) {
return Ok(());
}
// A re-announcement of a held op must not become a second copy.
if self.hot_timestamps.contains(&hot_op.timestamp) {
return Ok(());
}
// Our own ops raise the sequence counter too, should the persisted one lag behind the hot log.
if hot_op.timestamp.peer == self.peer {
self.last_hot_sequence = self.last_hot_sequence.max(hot_op.sequence);
}
self.apply_op_idempotent(hot_op.op.clone(), hot_op.timestamp)?;
self.hot_timestamps.insert(hot_op.timestamp);
self.hot_log.push(hot_op);
Ok(())
}
/// Apply a retired commit. Idempotent on structural ops (AddNode/AddNetwork on existing
/// targets, Remove on missing ones) since hot ops already produced the structural state.
/// The point is to bump field timestamps to T_retire via the LWW arms.
/// Take on a peer's marks as well as this peer's. Returns whether a hot op was dropped.
pub(crate) fn absorb_settled(&mut self, remote: &SettledHotOps) -> bool {
self.settled.absorb(remote);
self.drop_settled_hot_ops()
}
/// Bring the stamp index back in line after the hot log was filtered as a whole.
pub(crate) fn resync_hot_timestamps(&mut self) {
self.hot_timestamps = self.hot_log.iter().map(|hot_op| hot_op.timestamp).collect();
}
/// Re-derive the working registry as the retired snapshot plus every hot op, for a change that cannot
/// be applied in place. O(N + L), for rare paths only.
pub(crate) fn rebuild_working(&mut self) {
self.working_registry = self.retired_snapshot.clone();
for hot_op in std::mem::take(&mut self.hot_log) {
// Nothing is deferred, so this cannot fail on a referent; don't strand the op over anything else.
let _ = self.apply_op_idempotent(hot_op.op.clone(), hot_op.timestamp);
self.hot_log.push(hot_op);
}
}
/// Drop settled hot ops and re-derive the working registry without them; their effect comes back with their deltas.
fn drop_settled_hot_ops(&mut self) -> bool {
let before = self.hot_log.len();
let settled = &self.settled;
self.hot_log.retain(|hot_op| !settled.covers(hot_op.id()));
let dropped = self.hot_log.len() != before;
if dropped {
self.resync_hot_timestamps();
self.rebuild_working();
}
dropped
}
/// Apply a retired commit and record it in history.
pub fn apply_delta(&mut self, delta: Delta) -> Result<(), CrdtError> {
for parent in delta.all_parents() {
if !self.history.contains(parent) {
@@ -138,312 +176,503 @@ impl Document {
}
}
fn registry_ref(&self, target: RegistryTarget) -> &Registry {
pub(crate) fn registry_ref(&self, target: RegistryTarget) -> &Registry {
match target {
RegistryTarget::Working => &self.working_registry,
RegistryTarget::Snapshot => &self.retired_snapshot,
}
}
/// New local/remote op against the working registry: add ops error on duplicate targets and
/// `Change*` ops error on a missing target, while remove ops no-op when the target is already
/// absent; LWW arms keep the newer-timestamp value (strict `>`). The common entry point for edits.
/// A fresh local edit against the working registry; see [`ApplyMode::Live`].
#[cfg(test)]
pub(crate) fn apply_op(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Live)
}
/// Replay/retire against the working registry: structural ops skip duplicate/missing targets (the
/// state is already present from hot ops or a prior snapshot); LWW arms still gate on strict `>`.
/// An op from a peer or from persisted state, against the working registry.
pub(crate) fn apply_op_idempotent(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Idempotent)
}
/// Silent-zone undo/redo rewind against the working registry: structural ops are idempotent, and
/// LWW arms assign unconditionally. We own the single-writer chain here, so the precomputed reverse
/// (undo) or forward (redo) value is authoritative even though its timestamp ties what it replaces.
pub(crate) fn force_apply_op(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Force)
}
/// Applies one op. Every field of the registry is last-writer-wins on a timestamp, whether an entity
/// exists included, so the registry folds to the same values whatever order the ops land in:
///
/// - An addition writes every field of the entity at its stamp, and is evidence it exists from then.
/// - A removal is evidence the entity does not exist from its stamp. Its content stays as a tombstone,
/// and the removal's snapshot folds in like any other write.
/// - A write, or a reference from another entity's op, is evidence the entity exists at its stamp, so it
/// revives an older removal; an older write lands on the tombstone, for a later revival to see.
/// - A write to an entity never seen lands on a placeholder until its addition arrives; see [`write()`].
pub(crate) fn apply_op_with(&mut self, target: RegistryTarget, op: RegistryDelta, timestamp: TimeStamp, mode: ApplyMode) -> Result<(), CrdtError> {
// Advance the local clock past every observed op, including ones that subsequently no-op or
// error. Observation is about causality knowledge, not about whether the op took effect.
self.clock.observe(timestamp);
// Structural ops skip (rather than error) on duplicate/missing targets when not a fresh edit;
// LWW arms assign unconditionally only under `Force`.
let idempotent = mode != ApplyMode::Live;
let force = mode == ApplyMode::Force;
// Resurrect any concurrently-removed targets the op references before binding the registry
// (resurrection re-borrows `self` via history), so the mutation below holds one `registry` ref.
self.ensure_referenced_exist(target, &op)?;
let live = mode == ApplyMode::Live;
let registry = self.registry_mut(target);
match op {
RegistryDelta::AddNode { id, node } => {
if registry.node_instances.contains_key(&id) {
if idempotent {
// Hot ops already created this node; skip rather than error.
return Ok(());
}
if live && registry.node_instances.contains_key(&id) {
return Err(CrdtError::NodeAlreadyExists(id));
}
registry.node_instances.insert(id, node);
write_network(registry, node.network, timestamp, mode, |_| Ok(()))?;
add(&mut registry.node_instances, &mut registry.removed_nodes, id, node, timestamp);
}
RegistryDelta::RemoveNode { id, .. } => {
registry.node_instances.remove(&id);
RegistryDelta::RemoveNode { id, snapshot } => {
remove(&mut registry.node_instances, &mut registry.removed_nodes, id, snapshot, timestamp);
}
RegistryDelta::SetNodeInputs { id, inputs } => {
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
node.inputs = inputs;
RegistryDelta::SetNodeInputs { id, mut inputs } => {
inputs.iter_mut().for_each(|slot| stamp_slot(slot, timestamp));
let referenced: Vec<NodeId> = inputs
.iter()
.filter_map(|slot| match slot.input {
NodeInput::Node { id, .. } => Some(id),
_ => None,
})
.collect();
ensure_seen(registry, &referenced, mode)?;
write_node(registry, id, timestamp, mode, |node| {
merge_inputs(node, inputs, timestamp);
Ok(())
})?;
for referenced in referenced {
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
}
}
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
let input = node.inputs.get_mut(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
if force || timestamp > input.timestamp {
input.input = new_input;
input.timestamp = timestamp;
let referenced = match new_input {
NodeInput::Node { id, .. } => Some(id),
_ => None,
};
ensure_seen(registry, referenced.as_slice(), mode)?;
write_node(registry, id, timestamp, mode, |node| {
let Some(input) = slot_for_write(node, index as usize, timestamp, mode)? else { return Ok(()) };
if timestamp > input.timestamp {
input.input = new_input;
input.timestamp = timestamp;
}
Ok(())
})?;
if let Some(referenced) = referenced {
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
}
}
RegistryDelta::SetNodeImplementation { id, implementation } => {
ensure_seen(registry, &[id], mode)?;
if let Implementation::Network(network) = implementation {
write_network(registry, network, timestamp, mode, |_| Ok(()))?;
}
write_node(registry, id, timestamp, mode, |node| {
if timestamp > node.implementation_timestamp {
node.implementation = implementation;
node.implementation_timestamp = timestamp;
}
Ok(())
})?;
}
RegistryDelta::ChangeNodeAttribute { id, delta } => {
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
apply_attribute_delta(delta, timestamp, force, &mut node.attributes);
write_node(registry, id, timestamp, mode, |node| {
apply_attribute_delta(delta, timestamp, &mut node.attributes, node.attributes_timestamp);
Ok(())
})?;
}
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => {
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
let input = node.inputs.get_mut(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
apply_attribute_delta(delta, timestamp, force, &mut input.attributes);
write_node(registry, id, timestamp, mode, |node| {
let Some(input) = slot_for_write(node, index as usize, timestamp, mode)? else { return Ok(()) };
apply_attribute_delta(delta, timestamp, &mut input.attributes, input.attributes_timestamp);
Ok(())
})?;
}
RegistryDelta::SetNetworkExport { id, index, export } => {
let net = registry.networks.get_mut(&id).ok_or(CrdtError::NetworkDoesNotExist(id))?;
let slot_idx = index as usize;
if slot_idx >= net.exports.len() {
if slot_idx >= MAX_EXPORT_SLOTS {
return Err(CrdtError::ExportSlotOutOfBounds(index));
let referenced = match export {
Some(NodeInput::Node { id, .. }) => Some(id),
_ => None,
};
ensure_seen(registry, referenced.as_slice(), mode)?;
write_network(registry, id, timestamp, mode, |net| {
let slot_idx = index as usize;
if slot_idx >= net.exports.len() {
if slot_idx >= MAX_EXPORT_SLOTS {
return Err(CrdtError::ExportSlotOutOfBounds(index));
}
net.exports.resize(slot_idx + 1, ExportSlot::default());
}
net.exports.resize(
slot_idx + 1,
ExportSlot {
target: None,
timestamp: TimeStamp::ORIGIN,
},
);
}
let existing = &mut net.exports[slot_idx];
if force || timestamp > existing.timestamp {
existing.target = export;
existing.timestamp = timestamp;
let existing = &mut net.exports[slot_idx];
if timestamp > existing.timestamp {
existing.target = export;
existing.timestamp = timestamp;
}
Ok(())
})?;
if let Some(referenced) = referenced {
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
}
}
RegistryDelta::AddNetwork { id, network: contents } => {
if registry.networks.contains_key(&id) {
if idempotent {
return Ok(());
}
RegistryDelta::AddNetwork { id, network } => {
if live && registry.networks.contains_key(&id) {
return Err(CrdtError::NetworkAlreadyExists(id));
}
registry.networks.insert(id, contents);
add(&mut registry.networks, &mut registry.removed_networks, id, network, timestamp);
}
RegistryDelta::RemoveNetwork { id, .. } => {
registry.networks.remove(&id);
RegistryDelta::RemoveNetwork { id, snapshot } => {
remove(&mut registry.networks, &mut registry.removed_networks, id, snapshot, timestamp);
}
RegistryDelta::ChangeNetworkAttribute { id, delta } => {
let net = registry.networks.get_mut(&id).ok_or(CrdtError::NetworkDoesNotExist(id))?;
apply_attribute_delta(delta, timestamp, force, &mut net.attributes);
write_network(registry, id, timestamp, mode, |net| {
apply_attribute_delta(delta, timestamp, &mut net.attributes, net.attributes_timestamp);
Ok(())
})?;
}
RegistryDelta::SetResourceHash { id, hash } => {
let entry = registry.resources.entry(id).or_default();
if force || timestamp > entry.hash_timestamp {
entry.hash = hash;
entry.hash_timestamp = timestamp;
}
upsert_resource(registry, id, timestamp, |entry| {
if timestamp > entry.hash_timestamp {
entry.hash = hash;
entry.hash_timestamp = timestamp;
}
});
}
RegistryDelta::AddSource { id, key, source } => {
let entry = registry.resources.entry(id).or_default();
let value = SourceValue { source, timestamp };
if force { entry.force_set_source(key, value) } else { entry.set_source(key, value) }
upsert_resource(registry, id, timestamp, |entry| {
let value = SourceValue { source, timestamp, deleted: false };
entry.set_source(key, value);
});
}
RegistryDelta::RemoveSource { id, key } => {
if let Some(entry) = registry.resources.get_mut(&id) {
if force {
entry.force_remove_source(&key);
} else {
entry.remove_source(&key, timestamp);
}
}
// An upsert, so a removal for an entry never seen leaves a tombstone its addition loses to.
upsert_resource(registry, id, timestamp, |entry| {
entry.remove_source(&key, timestamp);
});
}
RegistryDelta::AddResource { id, entry } => {
registry.resources.insert(id, entry);
add(&mut registry.resources, &mut registry.removed_resources, id, entry, timestamp);
}
RegistryDelta::RemoveResource { id, .. } => {
registry.resources.remove(&id);
RegistryDelta::RemoveResource { id, snapshot } => {
remove(&mut registry.resources, &mut registry.removed_resources, id, snapshot, timestamp);
}
RegistryDelta::RegisterPeer { peer, user } => match registry.peer_users.get(&peer) {
Some(existing) if *existing != user => return Err(CrdtError::PeerRegistrationConflict(peer)),
Some(_) => {}
None => {
registry.peer_users.insert(peer, user);
RegistryDelta::RegisterPeer { peer, user } => {
// The newest registration of a device wins, whatever order they land in.
if registry.peer_users.get(&peer).is_none_or(|existing| timestamp > existing.at) {
registry.peer_users.insert(peer, PeerRegistration { user, at: timestamp });
}
},
}
RegistryDelta::ChangeDocumentAttribute { delta } => {
apply_attribute_delta(delta, timestamp, force, &mut registry.attributes);
apply_attribute_delta(delta, timestamp, &mut registry.attributes, TimeStamp::ORIGIN);
}
// Merge is a structural sync point only; it mutates no registry state.
RegistryDelta::Merge { .. } | RegistryDelta::Other(_) => {}
RegistryDelta::Merge { .. } | RegistryDelta::EndTransaction | RegistryDelta::Other(_) => {}
}
Ok(())
}
}
/// Resurrect (from history) any nodes/networks an op references that were concurrently removed, so
/// the op applies against a consistent registry. Cascading: a node's owning network is restored
/// before the node. No-op for ops that reference nothing absent.
fn ensure_referenced_exist(&mut self, target: RegistryTarget, op: &RegistryDelta) -> Result<(), CrdtError> {
match op {
RegistryDelta::AddNode { node, .. } => self.ensure_network_exists(target, node.network())?,
RegistryDelta::ChangeNodeInput { id, new_input, .. } => {
if let NodeInput::Node { id: referenced, .. } = new_input {
self.ensure_node_exists(target, *referenced)?;
}
self.ensure_node_exists(target, *id)?;
/// An entity whose existence and every field are last-writer-wins on a timestamp.
pub(crate) trait Presence: Sized {
/// The newest stamp of an addition or a write: the latest evidence the entity exists.
fn presence(&self) -> TimeStamp;
fn set_presence(&mut self, at: TimeStamp);
/// Stamps every field at `at`, the way an addition writes all of them.
fn stamp_all(&mut self, at: TimeStamp);
/// Folds `other` in, keeping whichever value of each field is newer.
fn merge(&mut self, other: Self);
/// Dead content for an entity nothing has added yet, for writes to land on until an addition comes.
/// Every field is at the origin, so the addition's values win.
fn placeholder() -> Self;
}
impl Presence for Node {
fn presence(&self) -> TimeStamp {
self.presence
}
fn set_presence(&mut self, at: TimeStamp) {
self.presence = at;
}
fn placeholder() -> Self {
Node::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(0)), 0)
}
fn stamp_all(&mut self, at: TimeStamp) {
self.presence = at;
self.added = at;
self.inputs_timestamp = at;
self.implementation_timestamp = at;
self.inputs.iter_mut().for_each(|slot| stamp_slot(slot, at));
stamp_attributes(&mut self.attributes, &mut self.attributes_timestamp, at);
}
fn merge(&mut self, other: Self) {
if other.added > self.added {
self.network = other.network;
self.added = other.added;
}
if other.implementation_timestamp > self.implementation_timestamp {
self.implementation = other.implementation;
self.implementation_timestamp = other.implementation_timestamp;
}
merge_inputs(self, other.inputs, other.inputs_timestamp);
merge_attributes(&mut self.attributes, &mut self.attributes_timestamp, other.attributes, other.attributes_timestamp);
self.presence = self.presence.max(other.presence);
}
}
impl Presence for Network {
fn presence(&self) -> TimeStamp {
self.presence
}
fn set_presence(&mut self, at: TimeStamp) {
self.presence = at;
}
fn placeholder() -> Self {
Network::default()
}
fn stamp_all(&mut self, at: TimeStamp) {
self.presence = at;
self.exports.iter_mut().for_each(|slot| slot.timestamp = at);
stamp_attributes(&mut self.attributes, &mut self.attributes_timestamp, at);
}
fn merge(&mut self, other: Self) {
let len = self.exports.len().max(other.exports.len());
self.exports.resize_with(len, ExportSlot::default);
for (slot, incoming) in self.exports.iter_mut().zip(other.exports) {
if incoming.timestamp > slot.timestamp {
*slot = incoming;
}
RegistryDelta::SetNodeInputs { id, inputs } => {
for slot in inputs {
if let NodeInput::Node { id: referenced, .. } = slot.input {
self.ensure_node_exists(target, referenced)?;
}
}
self.ensure_node_exists(target, *id)?;
}
merge_attributes(&mut self.attributes, &mut self.attributes_timestamp, other.attributes, other.attributes_timestamp);
self.presence = self.presence.max(other.presence);
}
}
impl Presence for ResourceEntry {
fn presence(&self) -> TimeStamp {
self.presence
}
fn set_presence(&mut self, at: TimeStamp) {
self.presence = at;
}
fn placeholder() -> Self {
ResourceEntry::default()
}
fn stamp_all(&mut self, at: TimeStamp) {
self.presence = at;
self.hash_timestamp = at;
self.stamp_sources(at);
}
fn merge(&mut self, other: Self) {
if other.hash_timestamp > self.hash_timestamp {
self.hash = other.hash;
self.hash_timestamp = other.hash_timestamp;
}
self.merge_sources(other.sources, other.sources_timestamp);
self.presence = self.presence.max(other.presence);
}
}
fn stamp_slot(slot: &mut InputSlot, at: TimeStamp) {
slot.timestamp = at;
stamp_attributes(&mut slot.attributes, &mut slot.attributes_timestamp, at);
}
/// Writes the map whole at `at`: the floor deletes every other key without a tombstone per key.
fn stamp_attributes(attributes: &mut Attributes, floor: &mut TimeStamp, at: TimeStamp) {
attributes.retain(|_, value| !value.deleted);
attributes.values_mut().for_each(|value| value.timestamp = at);
*floor = at;
}
/// Folds `other` in key by key. A key only one map holds is dead when the other map's floor is newer, since
/// that map was written whole after it; an entry stamped exactly at a floor was written by that whole-map
/// write and survives. Where both hold a key, the newer entry wins.
fn merge_attributes(attributes: &mut Attributes, floor: &mut TimeStamp, other: Attributes, other_floor: TimeStamp) {
attributes.retain(|_, value| value.timestamp >= other_floor);
for (key, value) in other {
match attributes.entry(key) {
Entry::Occupied(entry) if value.timestamp > entry.get().timestamp => *entry.into_mut() = value,
Entry::Vacant(entry) if value.timestamp >= *floor => {
entry.insert(value);
}
RegistryDelta::ChangeNodeAttribute { id, .. } | RegistryDelta::ChangeNodeInputAttribute { id, .. } => self.ensure_node_exists(target, *id)?,
RegistryDelta::SetNetworkExport {
id: network, export: export_target, ..
} => {
if let Some(NodeInput::Node { id: referenced, .. }) = export_target {
self.ensure_node_exists(target, *referenced)?;
}
self.ensure_network_exists(target, *network)?;
}
RegistryDelta::ChangeNetworkAttribute { id: network, .. } => self.ensure_network_exists(target, *network)?,
_ => {}
}
Ok(())
}
*floor = (*floor).max(other_floor);
}
fn ensure_node_exists(&mut self, target: RegistryTarget, node_id: NodeId) -> Result<(), CrdtError> {
if !self.registry_ref(target).node_instances.contains_key(&node_id) {
self.restore_node_from_history(target, node_id)?;
/// Folds an input list stamped `at` into the node's. The newer list decides the slot count, except that a
/// slot written after that shape still exists, with the gap up to it filled by unset slots stamped by the
/// shape. A slot both lists hold keeps its newer value, and its attributes fold key by key. A whole-list
/// write and a per-slot write thus land the same in either order.
fn merge_inputs(node: &mut Node, other: Vec<InputSlot>, at: TimeStamp) {
let (mut newer, shape, older) = if at > node.inputs_timestamp {
(other, at, std::mem::take(&mut node.inputs))
} else {
(std::mem::take(&mut node.inputs), node.inputs_timestamp, other)
};
for (index, incoming) in older.into_iter().enumerate() {
if index >= newer.len() {
if slot_newest(&incoming) <= shape {
continue;
}
newer.resize_with(index + 1, || InputSlot::unset(shape));
}
Ok(())
}
fn ensure_network_exists(&mut self, target: RegistryTarget, network_id: NetworkId) -> Result<(), CrdtError> {
if !self.registry_ref(target).networks.contains_key(&network_id) {
self.restore_network_from_history(target, network_id)?;
let slot = &mut newer[index];
if incoming.timestamp > slot.timestamp {
slot.input = incoming.input;
slot.timestamp = incoming.timestamp;
}
Ok(())
merge_attributes(&mut slot.attributes, &mut slot.attributes_timestamp, incoming.attributes, incoming.attributes_timestamp);
}
node.inputs = newer;
node.inputs_timestamp = shape;
}
/// Compute the inverse of `delta` against the registry named by `target`. Retirement passes
/// [`RegistryTarget::Snapshot`] so LWW reverses (export target, inputs, attributes, resource hash)
/// capture the true pre-op value rather than the hot-polluted working state.
pub(crate) fn compute_reverse_delta(&self, target: RegistryTarget, delta: &RegistryDelta) -> Result<RegistryDelta, CrdtError> {
let registry = self.registry_ref(target);
Ok(match delta {
RegistryDelta::AddNode { id, node } => RegistryDelta::RemoveNode { id: *id, snapshot: node.clone() },
RegistryDelta::RemoveNode { id, snapshot } => RegistryDelta::AddNode { id: *id, node: snapshot.clone() },
&RegistryDelta::SetNodeInputs { id, .. } => {
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
RegistryDelta::SetNodeInputs { id, inputs: node.inputs.clone() }
}
&RegistryDelta::ChangeNodeInput { id, index: input_idx, .. } => {
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
let slot = node.inputs().get(input_idx as usize).ok_or(CrdtError::InputIndexOutOfBounds(input_idx as usize))?;
RegistryDelta::ChangeNodeInput {
id,
index: input_idx,
new_input: slot.input.clone(),
}
}
&RegistryDelta::ChangeNodeAttribute { id, ref delta } => {
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
RegistryDelta::ChangeNodeAttribute {
id,
delta: reverse_attribute_delta(delta, node.attributes()),
}
}
&RegistryDelta::ChangeNodeInputAttribute { id, index, ref delta } => {
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
let input = node.inputs().get(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
RegistryDelta::ChangeNodeInputAttribute {
id,
index,
delta: reverse_attribute_delta(delta, &input.attributes),
}
}
&RegistryDelta::SetNetworkExport { id, index, .. } => {
// If the network is absent the forward op will resurrect it; the reverse is "set the export to None"
// since pre-forward there was no export to point at.
let export_target = registry.networks.get(&id).and_then(|net| net.exports.get(index as usize)).and_then(|s| s.target.clone());
RegistryDelta::SetNetworkExport { id, index, export: export_target }
}
RegistryDelta::AddNetwork { id, network } => RegistryDelta::RemoveNetwork { id: *id, snapshot: network.clone() },
&RegistryDelta::RemoveNetwork { id, ref snapshot } => RegistryDelta::AddNetwork { id, network: snapshot.clone() },
&RegistryDelta::ChangeNetworkAttribute { id, ref delta } => {
let current = registry.networks.get(&id).map(|net| &net.attributes).ok_or(CrdtError::NetworkDoesNotExist(id))?;
RegistryDelta::ChangeNetworkAttribute {
id,
delta: reverse_attribute_delta(delta, current),
}
}
RegistryDelta::ChangeDocumentAttribute { delta } => RegistryDelta::ChangeDocumentAttribute {
delta: reverse_attribute_delta(delta, &registry.attributes),
},
// Registrations are append-only and not user-undoable; reverse is the same op,
// which applies as a no-op on the already-registered PeerId.
&RegistryDelta::RegisterPeer { peer, user } => RegistryDelta::RegisterPeer { peer, user },
&RegistryDelta::SetResourceHash { id, .. } => RegistryDelta::SetResourceHash {
id,
hash: registry.resources.get(&id).and_then(|entry| entry.hash),
},
&RegistryDelta::AddSource { id, key, .. } => match registry.resources.get(&id).and_then(|entry| entry.source(&key)) {
// The slot already held a source: undo restores it.
Some(existing) => RegistryDelta::AddSource {
id,
key,
source: existing.source.clone(),
},
// The slot was empty: undo removes what this op added.
None => RegistryDelta::RemoveSource { id, key },
},
&RegistryDelta::RemoveSource { id, key } => match registry.resources.get(&id).and_then(|entry| entry.source(&key)) {
Some(existing) => RegistryDelta::AddSource {
id,
key,
source: existing.source.clone(),
},
// Nothing to restore; reverse is a no-op removal.
None => RegistryDelta::RemoveSource { id, key },
},
&RegistryDelta::AddResource { id, .. } => match registry.resources.get(&id) {
// Overwrote an existing entry: undo restores it.
Some(existing) => RegistryDelta::AddResource { id, entry: existing.clone() },
// Created a new entry: undo removes what this op added (snapshot is empty since there was nothing prior).
None => RegistryDelta::RemoveResource {
id,
snapshot: ResourceEntry::default(),
},
},
&RegistryDelta::RemoveResource { id, .. } => {
let snapshot = registry.resources.get(&id).cloned().unwrap_or_default();
RegistryDelta::AddResource { id, entry: snapshot }
}
RegistryDelta::Merge { extra_parents } => RegistryDelta::Merge { extra_parents: extra_parents.clone() },
&RegistryDelta::Other(_) => RegistryDelta::Other(serde_json::Value::Null),
})
/// The newest write the slot carries, its attributes included.
fn slot_newest(slot: &InputSlot) -> TimeStamp {
slot.attributes
.values()
.map(|value| value.timestamp)
.fold(slot.timestamp.max(slot.attributes_timestamp), TimeStamp::max)
}
/// The slot at `index` for a write at `at`. A slot past the end comes into being when the write is newer
/// than the list's shape, as in [`merge_inputs`], and is `None` when the shape is newer. For a fresh local
/// edit the index is out of bounds.
fn slot_for_write(node: &mut Node, index: usize, at: TimeStamp, mode: ApplyMode) -> Result<Option<&mut InputSlot>, CrdtError> {
if index >= node.inputs.len() {
if index >= MAX_INPUT_SLOTS || mode == ApplyMode::Live {
return Err(CrdtError::InputIndexOutOfBounds(index));
}
if at <= node.inputs_timestamp {
return Ok(None);
}
let shape = node.inputs_timestamp;
node.inputs.resize_with(index + 1, || InputSlot::unset(shape));
}
Ok(node.inputs.get_mut(index))
}
/// The entity's content wherever it sits: live, or held by its tombstone.
fn content_mut<'a, K: Hash + Eq + Copy, T>(live: &'a mut HashMap<K, T>, dead: &'a mut HashMap<K, Tombstone<T>>, id: K) -> Option<&'a mut T> {
live.get_mut(&id).or_else(|| dead.get_mut(&id).map(|mark| &mut mark.content))
}
/// Brings a removed entity back when its presence has grown past its removal. A placeholder stays dead
/// whatever its presence.
fn settle<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K) {
if dead.get(&id).is_some_and(|mark| !mark.placeholder && mark.content.presence() > mark.at) {
let mark = dead.remove(&id).expect("checked above");
live.insert(id, mark.content);
}
}
/// Folds `content` into whatever is held under `id`, or holds it as new. Content comes from an addition or
/// a removal's snapshot, so it proves the entity was added and a placeholder holding it stops being one.
fn fold<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, content: T) {
if let Some(mark) = dead.get_mut(&id).filter(|mark| mark.placeholder) {
// The placeholder holds only early writes: they land on the real content as if the addition came first.
let early = std::mem::replace(&mut mark.content, content);
mark.content.merge(early);
mark.placeholder = false;
} else if let Some(existing) = content_mut(live, dead, id) {
existing.merge(content);
} else {
live.insert(id, content);
}
settle(live, dead, id);
}
/// An addition at `at`: every field of `content` is written at `at`, and the entity exists from then
/// unless a newer removal holds it dead.
fn add<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, mut content: T, at: TimeStamp) {
content.stamp_all(at);
fold(live, dead, id, content);
}
/// A removal at `at`: the entity is dead from then unless a newer addition or write holds it live. The
/// snapshot folds in first, so a removal of an entity never seen still lands and its addition loses when
/// it arrives.
fn remove<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, snapshot: T, at: TimeStamp) {
fold(live, dead, id, snapshot);
if let Some(mark) = dead.get_mut(&id) {
mark.at = mark.at.max(at);
} else if live.get(&id).is_some_and(|content| at > content.presence()) {
let content = live.remove(&id).expect("checked above");
dead.insert(id, Tombstone { content, at, placeholder: false });
}
}
/// A write at `at` to the entity under `id`, applied by `write` to its content wherever it sits. The
/// write is evidence the entity exists at `at`, so it revives an older removal. A write to an entity
/// never seen lands on a placeholder tombstone that stays dead until an addition folds into it, so ops
/// land the same in any order and nothing is deferred. For a fresh local edit the entity is `missing()`.
fn write<K: Hash + Eq + Copy, T: Presence>(
live: &mut HashMap<K, T>,
dead: &mut HashMap<K, Tombstone<T>>,
id: K,
at: TimeStamp,
mode: ApplyMode,
missing: impl FnOnce() -> CrdtError,
write: impl FnOnce(&mut T) -> Result<(), CrdtError>,
) -> Result<(), CrdtError> {
let unseen = !live.contains_key(&id) && !dead.contains_key(&id);
if unseen {
if mode == ApplyMode::Live {
return Err(missing());
}
dead.insert(
id,
Tombstone {
content: T::placeholder(),
at: TimeStamp::ORIGIN,
placeholder: true,
},
);
}
let content = content_mut(live, dead, id).expect("held above");
if let Err(error) = write(content) {
// A rejected op changes nothing, so the placeholder made for it goes too.
if unseen {
dead.remove(&id);
}
return Err(error);
}
content.set_presence(content.presence().max(at));
settle(live, dead, id);
Ok(())
}
/// A fresh local edit cannot name a node never seen. Checked before an op's first write, so a refused op changes nothing.
fn ensure_seen(registry: &Registry, ids: &[NodeId], mode: ApplyMode) -> Result<(), CrdtError> {
let unseen = |id: &&NodeId| !registry.node_instances.contains_key(id) && !registry.removed_nodes.contains_key(id);
match ids.iter().find(unseen) {
Some(&id) if mode == ApplyMode::Live => Err(CrdtError::TargetNodeDoesNotExist(id)),
_ => Ok(()),
}
}
/// [`write()`] to a node; with a no-op `f`, records a reference to it.
fn write_node(registry: &mut Registry, id: NodeId, at: TimeStamp, mode: ApplyMode, f: impl FnOnce(&mut Node) -> Result<(), CrdtError>) -> Result<(), CrdtError> {
write(&mut registry.node_instances, &mut registry.removed_nodes, id, at, mode, || CrdtError::TargetNodeDoesNotExist(id), f)
}
fn write_network(registry: &mut Registry, id: NetworkId, at: TimeStamp, mode: ApplyMode, f: impl FnOnce(&mut Network) -> Result<(), CrdtError>) -> Result<(), CrdtError> {
write(&mut registry.networks, &mut registry.removed_networks, id, at, mode, || CrdtError::NetworkDoesNotExist(id), f)
}
/// Like [`write()`] for a resource, except that an entry never seen is created first, since single-field
/// resource ops are upserts. Every other field starts at the origin, so a later addition fills them in.
fn upsert_resource(registry: &mut Registry, id: ResourceId, at: TimeStamp, f: impl FnOnce(&mut ResourceEntry)) {
if !registry.resources.contains_key(&id) && !registry.removed_resources.contains_key(&id) {
registry.resources.insert(
id,
ResourceEntry {
presence: at,
..ResourceEntry::default()
},
);
}
let entry = content_mut(&mut registry.resources, &mut registry.removed_resources, id).expect("held above");
f(entry);
entry.set_presence(entry.presence().max(at));
settle(&mut registry.resources, &mut registry.removed_resources, id);
}
/// Which of a [`Document`]'s two registries an apply targets: the working copy (retired state plus
@@ -455,13 +684,12 @@ pub(crate) enum RegistryTarget {
Snapshot,
}
/// How [`Document::apply_op_with`] resolves structural collisions and LWW timestamp ties.
/// How [`Document::apply_op_with`] treats what it finds.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum ApplyMode {
/// Fresh local/remote edit: structural ops error on duplicate/missing targets; LWW uses strict `>`.
/// A fresh local edit: adding what exists, or writing to what was never seen, is an error, since a local
/// edit cannot mean either.
Live,
/// Replay/retire: structural ops skip duplicate/missing targets; LWW still uses strict `>`.
/// An op from a peer or from persisted state: every arm is a timestamp comparison.
Idempotent,
/// Silent-zone undo/redo rewind: structural ops are idempotent and LWW arms assign unconditionally.
Force,
}
+80 -66
View File
@@ -10,9 +10,12 @@ use serde::Serialize;
use crate::attr::*;
use crate::metadata_source::{NoMetadata, NodeMetadataSource};
use crate::{AttributesWrite, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ProtoNode, ROOT_NETWORK, Registry, ResourceHash, ResourceId, TimeStamp};
use crate::{
AttributesWrite, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ProtoNode, ROOT_NETWORK, Registry, ResourceHash, ResourceId, TimeStamp, Value,
ValueError, from_value, to_value,
};
fn map_serialization_error(key: &str) -> impl FnOnce(serde_json::Error) -> ConversionError + '_ {
fn map_serialization_error(key: &str) -> impl FnOnce(ValueError) -> ConversionError + '_ {
move |e| ConversionError::SerializationError(format!("{key}: {e:?}"))
}
@@ -40,7 +43,7 @@ impl NodePath {
}
fn to_global_id(&self, peer: PeerId) -> NodeId {
let bytes = rmp_serde::to_vec(&(peer, self)).expect("NodePath must serialize");
let bytes = postcard::to_stdvec(&(peer, self)).expect("NodePath must serialize");
let digest = blake3::hash(&bytes);
let mut truncated = [0u8; 8];
truncated.copy_from_slice(&digest.as_bytes()[..8]);
@@ -52,7 +55,7 @@ impl NodePath {
/// depending on traversal order. A domain tag keeps it from colliding with this node's own
/// `to_global_id`. The root network is `ROOT_NETWORK` and never goes through here.
fn owned_network_id(&self, peer: PeerId) -> NetworkId {
let bytes = rmp_serde::to_vec(&("network", peer, self)).expect("NodePath must serialize");
let bytes = postcard::to_stdvec(&("network", peer, self)).expect("NodePath must serialize");
let digest = blake3::hash(&bytes);
let mut truncated = [0u8; 8];
truncated.copy_from_slice(&digest.as_bytes()[..8]);
@@ -117,45 +120,29 @@ impl TryFrom<&NodeNetwork> for Registry {
pub type DeclarationBytes = HashMap<ResourceHash, Vec<u8>>;
/// A `from_runtime` conversion result: the reference-only [`Registry`] plus the proto-node
/// declaration *bytes* it extracted, keyed by content hash. `document-graph-storage` doesn't own a byte
/// store, so the caller (the `Gdd`) persists these into its content store; the registry only holds
/// the `ResourceId`/`ResourceHash` references.
/// declarations it extracted, as bytes keyed by content hash (for the caller's byte store) and as
/// decoded [`ProtoNode`]s keyed by id (for the caller's declaration cache).
pub struct RuntimeConversion {
pub registry: Registry,
pub declaration_bytes: DeclarationBytes,
pub declarations: crate::Declarations,
/// Each network's runtime `metadata_path` mapped to its stable storage `NetworkId`, for associating
/// per-network, per-peer view state (`session.json`) without re-deriving ids.
pub network_ids: HashMap<Vec<RuntimeNodeId>, NetworkId>,
}
impl RuntimeConversion {
/// Rebuild the [`Declarations`](crate::Declarations) map (`ResourceId` → [`ProtoNode`]) from the
/// extracted bytes, for callers that keep the bytes in hand instead of routing them through a
/// byte store (tests, the round-trip CLI). Editor/`Gdd` paths persist the bytes and resolve via
/// their byte store instead.
pub fn declarations(&self) -> Result<crate::Declarations, ConversionError> {
self.declaration_bytes
.iter()
.map(|(hash, bytes)| {
let proto = decode_declaration(bytes).map_err(|error| ConversionError::SerializationError(format!("declaration {hash}: {error}")))?;
Ok((ResourceId::from_hash(hash), proto))
})
.collect()
}
}
/// Encode a [`ProtoNode`] declaration to its content-addressed bytes: through a self-describing
/// `serde_json::Value` (so serde aliases keep working and the on-disk shape stays migratable), then
/// rmp-serialized (which encodes the intermediate `Value` compactly). Paired with [`decode_declaration`].
/// Encode a [`ProtoNode`] declaration to its content-addressed bytes: through the self-describing
/// [`Value`] (so serde aliases keep working and the on-disk shape stays migratable), then postcard.
/// Paired with [`decode_declaration`].
pub fn encode_declaration(proto: &ProtoNode) -> Result<Vec<u8>, String> {
let value = serde_json::to_value(proto).map_err(|error| error.to_string())?;
rmp_serde::to_vec(&value).map_err(|error| error.to_string())
let value = to_value(proto).map_err(|error| error.to_string())?;
postcard::to_stdvec(&value).map_err(|error| error.to_string())
}
/// Decode a [`ProtoNode`] declaration from the bytes [`encode_declaration`] produced.
pub fn decode_declaration(bytes: &[u8]) -> Result<ProtoNode, String> {
let value: serde_json::Value = rmp_serde::from_slice(bytes).map_err(|error| error.to_string())?;
serde_json::from_value(value).map_err(|error| error.to_string())
let value: Value = postcard::from_bytes(bytes).map_err(|error| error.to_string())?;
from_value(&value).map_err(|error| error.to_string())
}
impl Registry {
@@ -177,6 +164,7 @@ impl Registry {
let mut ctx = ConversionContext {
declaration_ids: HashMap::new(),
declaration_bytes: HashMap::new(),
declarations: HashMap::new(),
network_ids: HashMap::new(),
metadata,
peer,
@@ -195,6 +183,7 @@ impl Registry {
Ok(RuntimeConversion {
registry,
declaration_bytes: ctx.declaration_bytes,
declarations: ctx.declarations,
network_ids: ctx.network_ids,
})
}
@@ -203,7 +192,7 @@ impl Registry {
/// Snapshot the runtime [`ResourceRegistry`](graphene_resource::ResourceRegistry) into the storage
/// [`ResourceStore`](crate::ResourceStore). Each source's chain position becomes a fractional
/// [`Priority`](crate::Priority) (index-as-priority preserves order); the `DataSource` body is
/// stored type-erased as `serde_json::Value` so its on-disk shape can migrate freely. All
/// stored type-erased as [`Value`] so its on-disk shape can migrate freely. All
/// timestamps are `ORIGIN`, since this is a bootstrap snapshot, not an edit.
fn convert_resources(resources: &graphene_resource::ResourceRegistry, referenced: &std::collections::HashSet<ResourceId>, peer: PeerId, registry: &mut Registry) -> Result<(), ConversionError> {
for id in resources.ids() {
@@ -231,12 +220,14 @@ pub fn convert_resource_entry(resources: &graphene_resource::ResourceRegistry, i
priority: crate::Priority::new(position as f64).expect("enumerate index is finite"),
peer,
};
let body = serde_json::to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
entry.set_source(
let body = to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
// Built rather than written: the chain is put in place as converted, floor and all at the origin.
entry.force_set_source(
key,
crate::SourceValue {
source: body,
timestamp: TimeStamp::ORIGIN,
deleted: false,
},
);
}
@@ -289,6 +280,8 @@ struct ConversionContext<'m, M: NodeMetadataSource + ?Sized> {
declaration_ids: HashMap<String, ResourceId>,
/// Extracted declaration content keyed by hash, handed back for the caller's byte store.
declaration_bytes: DeclarationBytes,
/// The same declarations decoded, keyed by id, handed back for the caller's declaration cache.
declarations: crate::Declarations,
/// Maps each network's runtime `metadata_path` to its stable storage `NetworkId`, so the caller can
/// associate per-network, per-peer view state (in `session.json`) with networks without re-deriving ids.
network_ids: HashMap<Vec<RuntimeNodeId>, NetworkId>,
@@ -329,7 +322,7 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
runtime_node_id: *runtime_node_id,
};
let mut node = convert_node(doc_node, location, registry, ctx, true)?;
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(runtime_node_id.0), TimeStamp::ORIGIN);
node.attributes.set(node::ORIGINAL_NODE_ID, Value::Int(runtime_node_id.0.into()), TimeStamp::ORIGIN);
registry.node_instances.insert(global_id, node);
}
@@ -345,10 +338,18 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
.collect::<Result<Vec<_>, ConversionError>>()?;
let mut attributes = crate::Attributes::new();
write_ui_network_attributes(&mut attributes, ctx.metadata, metadata_path, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
write_ui_network_attributes(&mut attributes, node_network, metadata_path, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
write_scope_injections(&mut attributes, node_network, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
registry.networks.insert(network_id, Network { exports, attributes });
registry.networks.insert(
network_id,
Network {
presence: TimeStamp::ORIGIN,
exports,
attributes,
attributes_timestamp: TimeStamp::ORIGIN,
},
);
ctx.network_ids.insert(metadata_path.to_vec(), network_id);
Ok(())
@@ -426,6 +427,7 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
input: convert_input(input, parent_path, network_id, ctx.ids(metadata_path))?,
timestamp,
attributes: input_attrs,
attributes_timestamp: timestamp,
});
}
@@ -458,9 +460,14 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
write_ui_attributes(&mut attributes, ctx.metadata, metadata_path, runtime_node_id, timestamp)?;
Ok(Node {
presence: timestamp,
added: timestamp,
inputs_timestamp: timestamp,
implementation,
implementation_timestamp: timestamp,
inputs,
attributes,
attributes_timestamp: timestamp,
network: network_id,
})
}
@@ -477,11 +484,7 @@ pub fn encode_context_features(context_features: &ContextDependencies) -> Result
}
fn encode_if_not_default<T: Serialize + PartialEq>(key: &str, value: &T, default: &T) -> Result<crate::AttributeDelta, ConversionError> {
let value = if value == default {
None
} else {
Some(serde_json::to_value(value).map_err(map_serialization_error(key))?)
};
let value = if value == default { None } else { Some(to_value(value).map_err(map_serialization_error(key))?) };
Ok(crate::AttributeDelta { key: key.to_string(), value })
}
@@ -529,14 +532,14 @@ fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
(node::ui::PINNED, metadata.pinned(metadata_path, runtime_node_id)),
] {
if value {
attributes.set(key, serde_json::Value::Bool(true), timestamp);
attributes.set(key, Value::Bool(true), timestamp);
}
}
if let Some(name) = metadata.display_name(metadata_path, runtime_node_id)
&& !name.is_empty()
{
attributes.set(node::ui::DISPLAY_NAME, serde_json::Value::String(name.to_string()), timestamp);
attributes.set(node::ui::DISPLAY_NAME, Value::Str(name.to_string()), timestamp);
}
// One whole-vec attribute; per-slot LWW would be overkill for rename-on-output.
@@ -554,20 +557,25 @@ fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
/// does it: a runtime ID is not stable across a round trip.
fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes,
metadata: &M,
node_network: &NodeNetwork,
network_path: &[RuntimeNodeId],
parent_path: Option<&NodePath>,
network_id: NetworkId,
ids: NodeIds<'_, M>,
timestamp: TimeStamp,
) -> Result<(), ConversionError> {
// The same source the IDs resolve through, so a network's attributes and the nodes they name agree.
let Some(metadata) = ids.metadata else { return Ok(()) };
if let Some(reference) = metadata.reference(network_path) {
attributes.set(node::ui::REFERENCE, serde_json::Value::String(reference.to_string()), timestamp);
attributes.set(node::ui::REFERENCE, Value::Str(reference.to_string()), timestamp);
}
let to_storage_id = |runtime_id: RuntimeNodeId| ids.resolve(&child_path(parent_path, network_id, runtime_id), runtime_id);
let pinned_order = metadata.pinned_order(network_path);
// Only nodes the converted network still holds: the read side drops a stored ID it cannot find, so
// persisting one for a node deleted or reparented elsewhere would leave stored state disagreeing with
// what a peer converting the same input produces.
let pinned_order: Vec<_> = metadata.pinned_order(network_path).into_iter().filter(|pinned| node_network.nodes.contains_key(pinned)).collect();
if !pinned_order.is_empty() {
let stored: Vec<NodeId> = pinned_order.into_iter().map(to_storage_id).collect();
attributes
@@ -590,7 +598,7 @@ fn write_ui_input_attributes<M: NodeMetadataSource + ?Sized>(
) -> Result<(), ConversionError> {
let non_empty_string = |key: &'static str, value: Option<&str>, attributes: &mut crate::Attributes| {
if let Some(value) = value.filter(|s| !s.is_empty()) {
attributes.set(key, serde_json::Value::String(value.to_string()), timestamp);
attributes.set(key, Value::Str(value.to_string()), timestamp);
}
};
@@ -612,7 +620,7 @@ fn convert_input<M: NodeMetadataSource + ?Sized>(input: &GraphCraftNodeInput, pa
index: (*output_index).try_into().map_err(|_| ConversionError::IndexOverflow(*output_index))?,
},
GraphCraftNodeInput::Value { tagged_value, exposed } => {
let value = serde_json::to_value(&**tagged_value).map_err(|e| ConversionError::SerializationError(format!("{e:?}")))?;
let value = to_value(&**tagged_value).map_err(|e| ConversionError::SerializationError(format!("{e:?}")))?;
NodeInput::Value { value, exposed: *exposed }
}
GraphCraftNodeInput::Scope(s) => NodeInput::Scope(s.clone()),
@@ -626,7 +634,7 @@ fn convert_input<M: NodeMetadataSource + ?Sized>(input: &GraphCraftNodeInput, pa
}
/// The non-ui attributes a slot carries, derived from the input itself: the declared type of an
/// import, and a reflection node.s metadata. Public for staging paths that rebuild a node.s slots.
/// import, and a reflection node's metadata.
pub fn convert_input_attributes(input: &GraphCraftNodeInput) -> Result<crate::Attributes, ConversionError> {
let mut attributes = crate::Attributes::new();
let timestamp = TimeStamp::ORIGIN;
@@ -677,6 +685,7 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
register_declaration_resource(registry, id, hash, ctx.peer);
ctx.declaration_bytes.insert(hash, bytes);
ctx.declarations.insert(id, proto);
ctx.declaration_ids.insert(identifier_str, id);
Implementation::ProtoNode(id)
@@ -770,6 +779,7 @@ impl<'m> ScopedConversion<'m> {
ctx: ConversionContext {
declaration_ids: HashMap::new(),
declaration_bytes: HashMap::new(),
declarations: HashMap::new(),
network_ids: HashMap::new(),
metadata,
peer,
@@ -791,7 +801,7 @@ impl<'m> ScopedConversion<'m> {
};
let mut node = convert_node(doc_node, location, registry, &mut self.ctx, recurse)?;
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(local_id.0), TimeStamp::ORIGIN);
node.attributes.set(node::ORIGINAL_NODE_ID, Value::Int(local_id.0.into()), TimeStamp::ORIGIN);
registry.node_instances.insert(self.resolver.node_id(local_path, local_id), node);
Ok(())
}
@@ -814,24 +824,25 @@ impl<'m> ScopedConversion<'m> {
.collect::<Result<Vec<_>, ConversionError>>()?;
let mut attributes = crate::Attributes::new();
write_ui_network_attributes(
&mut attributes,
self.ctx.metadata,
local_path,
owner_path.as_ref(),
network_id,
self.ctx.ids(local_path),
TimeStamp::ORIGIN,
)?;
write_ui_network_attributes(&mut attributes, node_network, local_path, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
write_scope_injections(&mut attributes, node_network, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
registry.networks.insert(network_id, Network { exports, attributes });
registry.networks.insert(
network_id,
Network {
presence: TimeStamp::ORIGIN,
exports,
attributes,
attributes_timestamp: TimeStamp::ORIGIN,
},
);
Ok(())
}
/// The extracted proto-node declaration bytes, for the caller to persist into its byte store.
pub fn finish(self) -> DeclarationBytes {
self.ctx.declaration_bytes
/// The extracted proto-node declarations: the bytes for the caller's byte store, and the same
/// declarations decoded for its declaration cache.
pub fn finish(self) -> (DeclarationBytes, crate::Declarations) {
(self.ctx.declaration_bytes, self.ctx.declarations)
}
}
@@ -847,7 +858,10 @@ pub fn node_value_resource_refs(node: &Node) -> impl Iterator<Item = ResourceId>
/// The `TaggedValue::Resource` ID referenced by a stored value input, if any.
pub fn value_resource_ref(input: &NodeInput) -> Option<ResourceId> {
match input {
NodeInput::Value { value, .. } => value.get("Resource").and_then(|id| serde_json::from_value(id.clone()).ok()),
NodeInput::Value { value: Value::Object(fields), .. } => match fields.as_slice() {
[(key, id)] if key == "Resource" => from_value(id).ok(),
_ => None,
},
_ => None,
}
}
@@ -859,8 +873,8 @@ mod resource_ref_shape {
#[test]
fn resource_ref_shape_matches_serde() {
let id = ResourceId::from_hash(&ResourceHash::from(b"shape test".as_slice()));
let value = serde_json::to_value(TaggedValue::Resource(id)).expect("TaggedValue::Resource serializes");
let parsed: Option<ResourceId> = value.get("Resource").and_then(|inner| serde_json::from_value(inner.clone()).ok());
let value = to_value(&TaggedValue::Resource(id)).expect("TaggedValue::Resource serializes");
let parsed = value_resource_ref(&NodeInput::Value { value, exposed: false });
assert_eq!(parsed, Some(id), "The shape peek in node_value_resource_refs must match TaggedValue's serde form");
}
}
+43 -62
View File
@@ -3,21 +3,26 @@
//! [`History`] owns the deltas in topological order (every parent precedes its children) plus an
//! index from [`Rev`] to position for O(1) lookup. The order is a valid replay order, so it is what
//! gets serialized to the on-disk history file and what [`crate::Session::replay_from_history`]
//! consumes. Retired commits have a single writer in every regime (solo editing, or leader-ordered
//! collaboration where the leader serializes retired commits), so appending preserves the order by
//! construction. The only operation that introduces out-of-order deltas is [`merge`](History::merge),
//! which re-sorts the combined set into the canonical order to restore the invariant.
//! consumes. Appending a commit keeps the order; deltas arriving out of it are put back by
//! a canonical sort.
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use crate::{AttributesWrite, CrdtError, Delta, Rev, TimeStamp};
use crate::{AttributesWrite, CrdtError, Delta, RegistryDelta, ResourceHash, Rev, TimeStamp, Value};
/// Every mutator maintains the indexes, so the tips and named hashes are probes, not scans of a growing history.
#[derive(Clone, Debug, Default)]
pub struct History {
/// Deltas in topological order. Mutated only via [`push`](Self::push).
deltas: Vec<Delta>,
/// `Rev` to its position in `deltas`. Kept in sync with `deltas` by every mutator.
index: HashMap<Rev, usize>,
/// Every rev some delta names as a parent.
referenced: HashSet<Rev>,
/// Deltas no other delta names as a parent.
tips: HashSet<Rev>,
/// Content hashes the deltas name, from resource additions and removals.
resource_hashes: HashSet<ResourceHash>,
}
impl History {
@@ -27,8 +32,9 @@ impl History {
/// Build from deltas already in topological order (the on-disk load path), indexing them in place.
pub fn from_ordered(deltas: Vec<Delta>) -> Self {
let index = deltas.iter().enumerate().map(|(position, delta)| (delta.id, position)).collect();
Self { deltas, index }
let mut history = Self::default();
deltas.into_iter().for_each(|delta| history.push(delta));
history
}
pub fn get(&self, rev: Rev) -> Option<&Delta> {
@@ -39,6 +45,11 @@ impl History {
self.index.contains_key(&rev)
}
/// The content hashes named by any resource addition or removal in history.
pub fn resource_hashes(&self) -> &HashSet<ResourceHash> {
&self.resource_hashes
}
pub fn len(&self) -> usize {
self.deltas.len()
}
@@ -51,10 +62,22 @@ impl History {
/// (idempotent re-apply) overwrites the existing entry in place rather than appending, so the
/// order and index are unchanged.
pub fn push(&mut self, delta: Delta) {
match &delta.kind {
RegistryDelta::AddResource { entry, .. } => self.resource_hashes.extend(entry.hash),
RegistryDelta::RemoveResource { snapshot, .. } => self.resource_hashes.extend(snapshot.hash),
_ => {}
}
if let Some(&position) = self.index.get(&delta.id) {
self.deltas[position] = delta;
return;
}
for parent in delta.all_parents() {
self.referenced.insert(parent);
self.tips.remove(&parent);
}
if !self.referenced.contains(&delta.id) {
self.tips.insert(delta.id);
}
self.index.insert(delta.id, self.deltas.len());
self.deltas.push(delta);
}
@@ -64,66 +87,24 @@ impl History {
self.deltas.iter()
}
/// Absorb `incoming` (dedup by `Rev`) and canonically re-sort the whole combined history.
///
/// The sort is deterministic (topological, ties broken by `Rev`), so two peers that absorb the same
/// delta set produce byte-identical history, not merely two different valid orderings. This is the
/// history-convergence mechanism: arrival order is erased. Callers update the registry separately
/// (LWW apply is commutative, so the registry converges regardless of order).
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) {
for delta in incoming {
self.push(delta);
}
self.canonical_sort();
}
/// Re-order `deltas` into the canonical topological order and rebuild the index: parents precede
/// children, and among deltas whose parents are all emitted the lowest `Rev` goes first. O(V + E).
fn canonical_sort(&mut self) {
// Unsatisfied in-history parent count per delta, plus reverse edges to decrement as parents emit.
let mut pending_parents: HashMap<Rev, usize> = HashMap::with_capacity(self.deltas.len());
let mut children: HashMap<Rev, Vec<Rev>> = HashMap::new();
for delta in &self.deltas {
let in_history_parents = delta.all_parents().filter(|parent| self.index.contains_key(parent)).count();
pending_parents.insert(delta.id, in_history_parents);
for parent in delta.all_parents() {
if self.index.contains_key(&parent) {
children.entry(parent).or_default().push(delta.id);
}
}
}
// Ready set as a min-heap on `Rev` (via `Reverse`) so ties resolve deterministically.
let mut ready: std::collections::BinaryHeap<std::cmp::Reverse<Rev>> = pending_parents.iter().filter(|(_, count)| **count == 0).map(|(rev, _)| std::cmp::Reverse(*rev)).collect();
let mut order: Vec<Rev> = Vec::with_capacity(self.deltas.len());
while let Some(std::cmp::Reverse(rev)) = ready.pop() {
order.push(rev);
for child in children.get(&rev).into_iter().flatten() {
let count = pending_parents.get_mut(child).expect("child is in history");
*count -= 1;
if *count == 0 {
ready.push(std::cmp::Reverse(*child));
}
}
}
// `order` is a permutation of the existing revs, so reorder `deltas` to match and rebuild the index.
let mut by_rev: HashMap<Rev, Delta> = self.deltas.drain(..).map(|delta| (delta.id, delta)).collect();
self.index.clear();
for (position, rev) in order.iter().enumerate() {
if let Some(delta) = by_rev.remove(rev) {
self.index.insert(*rev, position);
self.deltas.push(delta);
/// `roots` and everything reachable from them through all parent links. Unknown roots are skipped.
pub(crate) fn ancestors(&self, roots: impl IntoIterator<Item = Rev>) -> HashSet<Rev> {
let mut seen = HashSet::new();
let mut stack: Vec<Rev> = roots.into_iter().filter(|rev| self.contains(*rev)).collect();
while let Some(rev) = stack.pop() {
if seen.insert(rev)
&& let Some(delta) = self.get(rev)
{
stack.extend(delta.all_parents());
}
}
seen
}
/// The current tips: revs that no other delta lists as a parent (the divergent heads). A linear
/// history has exactly one tip; concurrent branches have several. Sorted ascending for determinism.
pub fn tips(&self) -> Vec<Rev> {
let referenced: std::collections::HashSet<Rev> = self.deltas.iter().flat_map(|delta| delta.all_parents()).collect();
let mut tips: Vec<Rev> = self.deltas.iter().map(|delta| delta.id).filter(|rev| !referenced.contains(rev)).collect();
let mut tips: Vec<Rev> = self.tips.iter().copied().collect();
tips.sort_unstable();
tips
}
@@ -142,7 +123,7 @@ impl History {
/// Set a local annotation attribute (e.g. a commit message) on a retired delta in place. Excluded
/// from the delta's `Rev`, so identity and the index are unchanged. Returns whether the delta was found.
pub fn annotate(&mut self, rev: Rev, key: &str, value: serde_json::Value, timestamp: TimeStamp) -> bool {
pub fn annotate(&mut self, rev: Rev, key: &str, value: Value, timestamp: TimeStamp) -> bool {
match self.index.get(&rev) {
Some(&position) => {
self.deltas[position].attributes.set(key, value, timestamp);
+4 -2
View File
@@ -56,6 +56,8 @@ pub const ROOT_NETWORK: NetworkId = NetworkId(0);
/// Upper bound on a network's export slot count, guarding `SetExport` against a malicious or corrupted
/// slot index forcing an unbounded `exports` allocation.
pub(crate) const MAX_EXPORT_SLOTS: usize = 1 << 16;
/// A per-slot write can bring a slot past the end of the list into being, so it is capped the same way.
pub(crate) const MAX_INPUT_SLOTS: usize = 1 << 16;
/// Per-device identity. Stable per `(device, document)`. Used for CRDT tiebreaking and `NodeId`
/// scoping. Globally unique across all peers ever in a document.
@@ -119,9 +121,9 @@ pub(crate) fn compute_rev(parent: Option<Rev>, author: PeerId, timestamp: TimeSt
let mut parents: Vec<Rev> = parent.into_iter().chain(extra_parents.iter().copied()).collect();
parents.sort_unstable();
parents.dedup();
rmp_serde::to_vec(&("merge", parents)).expect("Merge identity fields must serialize")
postcard::to_stdvec(&("merge", parents)).expect("Merge identity fields must serialize")
}
_ => rmp_serde::to_vec(&(parent, author, timestamp, delta_type)).expect("Delta identity fields must serialize"),
_ => postcard::to_stdvec(&(parent, author, timestamp, delta_type)).expect("Delta identity fields must serialize"),
};
hasher.update(&bytes);
let digest = hasher.finalize();
+5
View File
@@ -7,9 +7,11 @@ pub mod document;
pub mod history;
pub mod ids;
pub mod model;
mod prior;
pub mod registry;
pub mod resources;
pub mod session;
pub mod value;
#[cfg(any(feature = "conversion", test))]
pub mod from_runtime;
@@ -24,9 +26,11 @@ pub use document::*;
pub use history::History;
pub use ids::*;
pub use model::*;
pub use prior::{NetworkField, NodeField, Prior};
pub use registry::*;
pub use resources::*;
pub use session::*;
pub use value::{Value, ValueError, from_value, to_value};
#[cfg(any(feature = "conversion", test))]
pub use from_runtime::{
@@ -40,6 +44,7 @@ pub use to_runtime::Declarations;
#[cfg(test)]
mod tests {
mod bookkeeping;
mod crdt;
mod round_trip;
}
+10 -6
View File
@@ -8,6 +8,8 @@ use std::collections::HashMap;
use core_types::uuid::NodeId as RuntimeNodeId;
use crate::Value;
/// One node's editor-side metadata, produced by `Registry::to_runtime_with_metadata`. One entry per
/// node, since every node carries an identity to restore even when it carries no `ui::*` attribute.
#[derive(Clone, Debug, PartialEq)]
@@ -38,10 +40,9 @@ pub struct NetworkMetadataEntry {
/// Stable storage id of this network. Lets the editor associate per-network, per-peer view state
/// (the node-graph nav, in `session.json`) with a network across reparenting.
pub network_id: crate::NetworkId,
/// Matches the runtime's `NodeNetworkPersistentMetadata::reference` — definition lineage tag.
/// Matches the runtime's `NodeNetworkPersistentMetadata::reference`: the definition lineage tag.
pub reference: Option<String>,
/// The display order of the network's pinned nodes. Shared for the same reason the pinned flag is:
/// a shared set with per-peer ordering could never reconcile.
/// The display order of the network's pinned nodes.
pub pinned_order: Vec<RuntimeNodeId>,
}
@@ -53,11 +54,11 @@ pub struct InputMetadataEntry {
pub input_description: Option<String>,
pub widget_override: Option<String>,
/// Reassembled from `ui::input_data::<sub_key>` attributes.
pub input_data: HashMap<String, serde_json::Value>,
pub input_data: HashMap<String, Value>,
}
/// Editor-side metadata source. Methods default to "no data" so implementors only override what
/// they carry. Returns are JSON-shaped where the underlying types live editor-side (PTZ, etc.).
/// they carry. Returns are type-erased as [`Value`] where the underlying types live editor-side (PTZ, etc.).
pub trait NodeMetadataSource {
fn position(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Option<Position> {
None
@@ -89,7 +90,7 @@ pub trait NodeMetadataSource {
None
}
/// Returns owned to stay object-safe. Each entry is stored as `ui::input_data::<key>` for per-key LWW.
fn input_data(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId, _input_index: usize) -> HashMap<String, serde_json::Value> {
fn input_data(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId, _input_index: usize) -> HashMap<String, Value> {
HashMap::new()
}
@@ -98,9 +99,12 @@ pub trait NodeMetadataSource {
fn storage_node_id(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Option<crate::NodeId> {
None
}
/// The definition the network was instantiated from, if it still names one.
fn reference(&self, _network_path: &[RuntimeNodeId]) -> Option<&str> {
None
}
/// The display order of the network's pinned nodes.
fn pinned_order(&self, _network_path: &[RuntimeNodeId]) -> Vec<RuntimeNodeId> {
Vec::new()
+78 -9
View File
@@ -1,12 +1,30 @@
use crate::{Attributes, NetworkId, NodeId, ResourceId, TimeStamp, attributes_value_equal};
use crate::{Attributes, NetworkId, NodeId, ResourceId, TimeStamp, Value, attributes_value_equal};
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Node {
/// The latest addition or write, so a concurrent removal resolves by last-writer-wins rather than
/// arrival order. See [`Registry::removed_nodes`](crate::Registry::removed_nodes).
#[serde(default)]
pub(crate) presence: TimeStamp,
/// When the node was last added, which decides its network between concurrent additions of one id.
#[serde(default)]
pub(crate) added: TimeStamp,
/// When the input list last changed shape, so whole-list and per-slot writes resolve the same in either
/// order: the list follows the newer write, and a slot both lists held keeps its newer value.
#[serde(default)]
pub(crate) inputs_timestamp: TimeStamp,
pub(crate) implementation: Implementation,
/// When the implementation was last written, so a swap resolves by last-writer-wins rather than by
/// the order ops happen to arrive in. Absent from documents written before swaps were expressible.
#[serde(default)]
pub(crate) implementation_timestamp: TimeStamp,
pub(crate) inputs: Vec<InputSlot>,
pub(crate) attributes: Attributes,
/// When `attributes` was last written whole; see [`Attributes`].
#[serde(default)]
pub(crate) attributes_timestamp: TimeStamp,
pub(crate) network: NetworkId,
}
@@ -43,14 +61,26 @@ impl Node {
attributes_value_equal(&self.attributes, &other.attributes)
}
/// A node in `network` whose `inputs` slots are unset, for a caller that fills them in with
/// `ChangeNodeInput`. The slot count is fixed at creation, since changing an input addresses a
/// slot by position.
pub fn new(network: NetworkId, implementation: Implementation, inputs: usize) -> Self {
Self {
presence: TimeStamp::ORIGIN,
added: TimeStamp::ORIGIN,
inputs_timestamp: TimeStamp::ORIGIN,
implementation,
implementation_timestamp: TimeStamp::ORIGIN,
inputs: vec![InputSlot::unset(TimeStamp::ORIGIN); inputs],
attributes: Attributes::new(),
attributes_timestamp: TimeStamp::ORIGIN,
network,
}
}
#[cfg(test)]
pub(crate) fn dummy() -> Self {
Self {
implementation: Implementation::ProtoNode(ResourceId::new()),
inputs: vec![],
attributes: Attributes::new(),
network: crate::ROOT_NETWORK,
}
Self::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::new()), 0)
}
}
@@ -61,6 +91,26 @@ pub struct InputSlot {
pub input: NodeInput,
pub timestamp: TimeStamp,
pub attributes: Attributes,
/// When `attributes` was last written whole; see [`Attributes`].
#[serde(default)]
pub attributes_timestamp: TimeStamp,
}
impl InputSlot {
/// A slot holding nothing, stamped `at`.
pub fn unset(at: TimeStamp) -> Self {
// `to_runtime` reads this back as a `TaggedValue`, whose unit `None` variant encodes as this string.
// Pinned by `unset_input_slot_deserializes_as_tagged_value_none`.
Self {
input: NodeInput::Value {
value: Value::Str("None".to_string()),
exposed: false,
},
timestamp: at,
attributes: Attributes::new(),
attributes_timestamp: at,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -70,7 +120,7 @@ pub enum NodeInput {
index: u32,
},
Value {
value: serde_json::Value,
value: Value,
exposed: bool,
},
Scope(Cow<'static, str>),
@@ -92,10 +142,16 @@ pub enum Implementation {
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Network {
/// The latest addition or write; see [`Node::presence`](crate::Node).
#[serde(default)]
pub(crate) presence: TimeStamp,
pub exports: Vec<ExportSlot>,
/// Per-network `ui::*` state (navigation, previewing). Separate from `Node.attributes` so
/// view-state edits LWW independently.
pub attributes: Attributes,
/// When `attributes` was last written whole; see [`Attributes`].
#[serde(default)]
pub attributes_timestamp: TimeStamp,
}
impl Network {
@@ -120,7 +176,7 @@ impl Network {
/// One positional export slot. `target == None` marks an empty/removed slot. Timestamp drives LWW
/// on concurrent `SetExport` ops.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ExportSlot {
pub target: Option<NodeInput>,
pub timestamp: TimeStamp,
@@ -154,6 +210,19 @@ mod tests {
}
}
/// `to_runtime` has to read back what `Node::new` writes into an unset slot, so its literal must stay
/// in step with how `TaggedValue::None` serializes.
#[test]
fn unset_input_slot_deserializes_as_tagged_value_none() {
let node = Node::new(crate::ROOT_NETWORK, Implementation::Network(crate::ROOT_NETWORK), 1);
let NodeInput::Value { value, .. } = &node.inputs()[0].input else {
panic!("a fresh slot holds a value input");
};
let tagged: graph_craft::document::value::TaggedValue = crate::from_value(value).expect("the unset slot value must deserialize");
assert_eq!(tagged, graph_craft::document::value::TaggedValue::None);
}
/// A `SetExport(None)` truncation leaves a trailing empty slot. Such a network is value-equal to
/// the same network without that slot, so the soak oracle doesn't false-report drift.
#[test]
+304
View File
@@ -0,0 +1,304 @@
use crate::{
AttributeValue, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, TimeStamp,
Tombstone,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::hash::Hash;
/// What a slot held before a delta wrote it, with its own stamps. Undo puts these back as they were, bypassing
/// LWW, so the registry is again exactly what folding history up to the delta's parent gives. Never sent or
/// applied as an op.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Prior {
/// The whole entity, live or tombstoned. `None, None` means it didn't exist, so undoing an addition leaves no
/// tombstone behind.
Node {
id: NodeId,
live: Option<Node>,
removed: Option<Tombstone<Node>>,
},
Network {
id: NetworkId,
live: Option<Network>,
removed: Option<Tombstone<Network>>,
},
Resource {
id: ResourceId,
live: Option<ResourceEntry>,
removed: Option<Tombstone<ResourceEntry>>,
},
/// One field of a live node, and the node's presence, which every write moves.
NodeField {
id: NodeId,
presence: TimeStamp,
field: NodeField,
},
/// One field of a live network, and its presence.
NetworkField {
id: NetworkId,
presence: TimeStamp,
field: NetworkField,
},
DocumentAttribute {
key: String,
previous: Option<AttributeValue>,
},
PeerUser {
peer: PeerId,
previous: Option<PeerRegistration>,
},
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NodeField {
/// Only the presence moved, by a reference from another entity's op.
Presence,
Attribute {
key: String,
previous: Option<AttributeValue>,
},
Input {
index: u32,
previous: InputSlot,
},
InputAttribute {
index: u32,
key: String,
previous: Option<AttributeValue>,
},
Inputs {
previous: Vec<InputSlot>,
inputs_timestamp: TimeStamp,
},
Implementation {
previous: Implementation,
implementation_timestamp: TimeStamp,
},
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NetworkField {
/// Only the presence moved, by a node added to or implemented by it.
Presence,
Attribute {
key: String,
previous: Option<AttributeValue>,
},
Exports {
previous: Vec<ExportSlot>,
},
}
/// What `op` is about to write in `registry`, in write order. Taken before the op applies.
pub(crate) fn capture(registry: &Registry, op: &RegistryDelta) -> Vec<Prior> {
let mut priors = Vec::new();
let node_input = |input: &NodeInput| match input {
NodeInput::Node { id, .. } => Some(*id),
_ => None,
};
match op {
RegistryDelta::AddNode { id, node } => {
priors.push(network_field(registry, node.network, |_| NetworkField::Presence));
priors.push(whole_node(registry, *id));
}
RegistryDelta::RemoveNode { id, .. } => priors.push(whole_node(registry, *id)),
RegistryDelta::SetNodeInputs { id, inputs } => {
priors.push(node_field(registry, *id, |node| NodeField::Inputs {
previous: node.inputs.clone(),
inputs_timestamp: node.inputs_timestamp,
}));
priors.extend(
inputs
.iter()
.filter_map(|slot| node_input(&slot.input))
.map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)),
);
}
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
priors.push(node_field(registry, *id, |node| {
input_field(node, *index, |slot| NodeField::Input {
index: *index,
previous: slot.clone(),
})
}));
priors.extend(node_input(new_input).map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)));
}
RegistryDelta::SetNodeImplementation { id, implementation } => {
if let Implementation::Network(network) = implementation {
priors.push(network_field(registry, *network, |_| NetworkField::Presence));
}
priors.push(node_field(registry, *id, |node| NodeField::Implementation {
previous: node.implementation.clone(),
implementation_timestamp: node.implementation_timestamp,
}));
}
RegistryDelta::ChangeNodeAttribute { id, delta } => priors.push(node_field(registry, *id, |node| NodeField::Attribute {
key: delta.key.clone(),
previous: node.attributes.get(&delta.key).cloned(),
})),
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => priors.push(node_field(registry, *id, |node| {
input_field(node, *index, |slot| NodeField::InputAttribute {
index: *index,
key: delta.key.clone(),
previous: slot.attributes.get(&delta.key).cloned(),
})
})),
RegistryDelta::SetNetworkExport { id, export, .. } => {
priors.push(network_field(registry, *id, |network| NetworkField::Exports { previous: network.exports.clone() }));
priors.extend(export.as_ref().and_then(node_input).map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)));
}
RegistryDelta::AddNetwork { id, .. } | RegistryDelta::RemoveNetwork { id, .. } => priors.push(whole_network(registry, *id)),
RegistryDelta::ChangeNetworkAttribute { id, delta } => {
priors.push(network_field(registry, *id, |network| NetworkField::Attribute {
key: delta.key.clone(),
previous: network.attributes.get(&delta.key).cloned(),
}));
}
RegistryDelta::AddResource { id, .. }
| RegistryDelta::RemoveResource { id, .. }
| RegistryDelta::SetResourceHash { id, .. }
| RegistryDelta::AddSource { id, .. }
| RegistryDelta::RemoveSource { id, .. } => priors.push(Prior::Resource {
id: *id,
live: registry.resources.get(id).cloned(),
removed: registry.removed_resources.get(id).cloned(),
}),
RegistryDelta::RegisterPeer { peer, .. } => priors.push(Prior::PeerUser {
peer: *peer,
previous: registry.peer_users.get(peer).copied(),
}),
RegistryDelta::ChangeDocumentAttribute { delta } => priors.push(Prior::DocumentAttribute {
key: delta.key.clone(),
previous: registry.attributes.get(&delta.key).cloned(),
}),
RegistryDelta::Merge { .. } | RegistryDelta::EndTransaction | RegistryDelta::Other(_) => {}
}
priors
}
/// Puts back what `priors` recorded, newest write first.
pub(crate) fn restore(registry: &mut Registry, priors: &[Prior]) {
for prior in priors.iter().rev() {
match prior {
Prior::Node { id, live, removed } => put_whole(&mut registry.node_instances, &mut registry.removed_nodes, *id, live.as_ref(), removed.as_ref()),
Prior::Network { id, live, removed } => put_whole(&mut registry.networks, &mut registry.removed_networks, *id, live.as_ref(), removed.as_ref()),
Prior::Resource { id, live, removed } => put_whole(&mut registry.resources, &mut registry.removed_resources, *id, live.as_ref(), removed.as_ref()),
Prior::NodeField { id, presence, field } => {
let Some(node) = registry.node_instances.get_mut(id) else {
debug_assert!(false, "a field prior is taken from a live node, which the later priors put back");
continue;
};
node.presence = *presence;
match field {
NodeField::Presence => {}
NodeField::Attribute { key, previous } => put_attribute(&mut node.attributes, key, previous.as_ref()),
NodeField::Input { index, previous } => {
if let Some(slot) = node.inputs.get_mut(*index as usize) {
*slot = previous.clone();
}
}
NodeField::InputAttribute { index, key, previous } => {
if let Some(slot) = node.inputs.get_mut(*index as usize) {
put_attribute(&mut slot.attributes, key, previous.as_ref());
}
}
NodeField::Inputs { previous, inputs_timestamp } => {
node.inputs = previous.clone();
node.inputs_timestamp = *inputs_timestamp;
}
NodeField::Implementation { previous, implementation_timestamp } => {
node.implementation = previous.clone();
node.implementation_timestamp = *implementation_timestamp;
}
}
}
Prior::NetworkField { id, presence, field } => {
let Some(network) = registry.networks.get_mut(id) else {
debug_assert!(false, "a field prior is taken from a live network, which the later priors put back");
continue;
};
network.presence = *presence;
match field {
NetworkField::Presence => {}
NetworkField::Attribute { key, previous } => put_attribute(&mut network.attributes, key, previous.as_ref()),
NetworkField::Exports { previous } => network.exports = previous.clone(),
}
}
Prior::DocumentAttribute { key, previous } => put_attribute(&mut registry.attributes, key, previous.as_ref()),
Prior::PeerUser { peer, previous } => match previous {
Some(registration) => _ = registry.peer_users.insert(*peer, *registration),
None => _ = registry.peer_users.remove(peer),
},
}
}
}
fn whole_node(registry: &Registry, id: NodeId) -> Prior {
Prior::Node {
id,
live: registry.node_instances.get(&id).cloned(),
removed: registry.removed_nodes.get(&id).cloned(),
}
}
fn whole_network(registry: &Registry, id: NetworkId) -> Prior {
Prior::Network {
id,
live: registry.networks.get(&id).cloned(),
removed: registry.removed_networks.get(&id).cloned(),
}
}
/// One field of a live node; anything else, a write that lands on a tombstone or a placeholder, records the
/// whole entity.
fn node_field(registry: &Registry, id: NodeId, field: impl FnOnce(&Node) -> NodeField) -> Prior {
match registry.node_instances.get(&id) {
Some(node) => Prior::NodeField {
id,
presence: node.presence,
field: field(node),
},
None => whole_node(registry, id),
}
}
fn network_field(registry: &Registry, id: NetworkId, field: impl FnOnce(&Network) -> NetworkField) -> Prior {
match registry.networks.get(&id) {
Some(network) => Prior::NetworkField {
id,
presence: network.presence,
field: field(network),
},
None => whole_network(registry, id),
}
}
/// A write to one slot, or to the whole list when the slot doesn't exist yet, since writing past the end grows it.
fn input_field(node: &Node, index: u32, field: impl FnOnce(&InputSlot) -> NodeField) -> NodeField {
match node.inputs.get(index as usize) {
Some(slot) => field(slot),
None => NodeField::Inputs {
previous: node.inputs.clone(),
inputs_timestamp: node.inputs_timestamp,
},
}
}
fn put_whole<K: Hash + Eq + Copy, T: Clone>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, was_live: Option<&T>, was_removed: Option<&Tombstone<T>>) {
match was_live {
Some(content) => _ = live.insert(id, content.clone()),
None => _ = live.remove(&id),
}
match was_removed {
Some(mark) => _ = dead.insert(id, mark.clone()),
None => _ = dead.remove(&id),
}
}
fn put_attribute(attributes: &mut crate::Attributes, key: &str, previous: Option<&AttributeValue>) {
match previous {
Some(value) => _ = attributes.insert(key.to_string(), value.clone()),
None => _ = attributes.remove(key),
}
}
+56 -8
View File
@@ -1,7 +1,13 @@
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceEntry, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// The live document: what exists and what it holds.
///
/// Every field is last-writer-wins on a timestamp, including whether an entity exists, so the registry
/// depends on the set of ops applied and not their order. A removed entity keeps a tombstone stamped with
/// the removal: an op stamped earlier is dropped in either arrival order, and one stamped later revives the
/// entity from it. The live maps hold only what exists.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Registry {
pub node_instances: HashMap<NodeId, Node>,
@@ -9,13 +15,55 @@ pub struct Registry {
/// Content-addressable resources (images, fonts, eventually proto-node declarations) referenced
/// by `ResourceId`. See [`ResourceStore`].
pub resources: ResourceStore,
/// Append-only mapping from per-device `PeerId` to per-human `UserId`.
/// Registered by each device's first contribution via `RegistryDelta::RegisterPeer`.
pub peer_users: HashMap<PeerId, UserId>,
/// Which person each device is, registered via `RegistryDelta::RegisterPeer` by a device's first
/// contribution and whenever its user changes. Lets undo and history authorship scope by person across
/// the peer ids one person accumulates.
pub peer_users: HashMap<PeerId, PeerRegistration>,
pub attributes: Attributes,
/// Tombstones of removed nodes, so an op on one is ordered against its removal whichever arrives first.
#[serde(default)]
pub removed_nodes: HashMap<NodeId, Tombstone<Node>>,
/// Tombstones of removed networks; see [`removed_nodes`](Self::removed_nodes).
#[serde(default)]
pub removed_networks: HashMap<NetworkId, Tombstone<Network>>,
/// Tombstones of removed resources; see [`removed_nodes`](Self::removed_nodes).
#[serde(default)]
pub removed_resources: HashMap<ResourceId, Tombstone<ResourceEntry>>,
}
/// A device's registration to a person, and when it was made.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerRegistration {
pub user: UserId,
pub at: TimeStamp,
}
/// A removed entity: its content, for reviving it, and when it was removed, for ordering later-arriving
/// ops against the removal.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Tombstone<T> {
pub content: T,
pub at: TimeStamp,
/// Nothing has added the entity yet, so it stays dead until an addition folds in; the content only holds
/// writes that arrived ahead of it. See [`Registry::removed_nodes`].
#[serde(default)]
pub placeholder: bool,
}
impl Registry {
/// The node under `id`, live or as it was when removed. For a reference to a node the runtime cannot
/// hold, which still needs the id the node had there.
#[cfg(any(feature = "conversion", test))]
pub(crate) fn node_or_removed(&self, id: NodeId) -> Option<&Node> {
self.node_instances.get(&id).or_else(|| self.removed_nodes.get(&id).map(|mark| &mark.content))
}
/// The network under `id`, live or as it was when removed.
#[cfg(any(feature = "conversion", test))]
pub(crate) fn network_or_removed(&self, id: NetworkId) -> Option<&Network> {
self.networks.get(&id).or_else(|| self.removed_networks.get(&id).map(|mark| &mark.content))
}
/// True if both registries agree on every value-bearing field, ignoring per-slot and
/// per-attribute timestamps. Mirrors `compute_deltas`'s value-only semantics, so unchanged
/// state at a stamped slot doesn't count as drift. `peer_users` is excluded: it isn't diffed by
@@ -85,10 +133,10 @@ impl Registry {
}
pub(crate) fn attributes_value_equal(a: &Attributes, b: &Attributes) -> bool {
if a.len() != b.len() {
if crate::attributes::live(a).count() != crate::attributes::live(b).count() {
return false;
}
a.iter().all(|(key, value)| b.get(key).is_some_and(|other| value.value == other.value))
crate::attributes::live(a).all(|(key, value)| b.get(key).is_some_and(|other| !other.deleted && value.value == other.value))
}
/// Value-level resource comparison: same resolved hashes and same source chains (keyed by
@@ -100,8 +148,8 @@ pub(crate) fn resources_value_equal(a: &ResourceStore, b: &ResourceStore) -> boo
a.iter().all(|(id, entry)| {
b.get(id).is_some_and(|other| {
entry.hash == other.hash
&& entry.sources.len() == other.sources.len()
&& entry.sources.iter().all(|(key, value)| other.source(key).is_some_and(|other_value| value.source == other_value.source))
&& entry.live_sources().count() == other.live_sources().count()
&& entry.live_sources().all(|(key, value)| other.source(key).is_some_and(|other_value| value.source == other_value.source))
})
})
}
+135 -68
View File
@@ -1,4 +1,4 @@
use crate::{PeerId, TimeStamp};
use crate::{PeerId, TimeStamp, Value, from_value, to_value};
use graphene_resource::{ResourceHash, ResourceId};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
@@ -11,13 +11,28 @@ pub struct SourceKey {
pub peer: PeerId,
}
/// One entry in a resource's source chain. The `source` body is type-erased (`serde_json::Value`)
/// One entry in a resource's source chain. The `source` body is type-erased (`Value`)
/// so the on-disk `DataSource` shape can evolve through migrations without the storage layer
/// committing to a Rust enum; `timestamp` drives LWW on re-setting this same entry.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceValue {
pub source: serde_json::Value,
pub source: Value,
pub timestamp: TimeStamp,
/// A removed source stays as a stamped tombstone, so an older addition loses in either arrival order;
/// readers see it as absent.
#[serde(default)]
pub deleted: bool,
}
impl SourceValue {
/// The tombstone of a source removed at `timestamp`.
pub fn deleted(timestamp: TimeStamp) -> Self {
Self {
source: Value::None,
timestamp,
deleted: true,
}
}
}
/// A single content-addressable resource: an ordered, conflict-mergeable chain of fallback sources
@@ -26,8 +41,13 @@ pub struct SourceValue {
/// resource agree by construction, since the hash is content-derived).
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct ResourceEntry {
/// The latest addition or write; see [`Node::presence`](crate::Node).
pub(crate) presence: TimeStamp,
/// Fallback chain kept sorted by `SourceKey`, so iteration yields highest-priority first.
pub sources: Vec<(SourceKey, SourceValue)>,
/// When `sources` was last written whole, by an addition of the entry. A key the chain does not hold is
/// deleted as of then, as with [`Attributes`](crate::Attributes).
pub sources_timestamp: TimeStamp,
pub hash: Option<ResourceHash>,
pub hash_timestamp: TimeStamp,
}
@@ -39,12 +59,22 @@ impl<'de> Deserialize<'de> for ResourceEntry {
// collapse any duplicate keys, keeping the higher-timestamp value (LWW).
#[derive(Deserialize)]
struct Raw {
#[serde(default)]
presence: TimeStamp,
sources: Vec<(SourceKey, SourceValue)>,
#[serde(default)]
sources_timestamp: TimeStamp,
hash: Option<ResourceHash>,
hash_timestamp: TimeStamp,
}
let Raw { mut sources, hash, hash_timestamp } = Raw::deserialize(deserializer)?;
let Raw {
presence,
mut sources,
sources_timestamp,
hash,
hash_timestamp,
} = Raw::deserialize(deserializer)?;
sources.sort_by_key(|(a, _)| *a);
sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| {
// `dedup_by` keeps the first of each run; sorting is stable, so resolve duplicates by LWW.
@@ -57,7 +87,13 @@ impl<'de> Deserialize<'de> for ResourceEntry {
true
});
Ok(Self { sources, hash, hash_timestamp })
Ok(Self {
presence,
sources,
sources_timestamp,
hash,
hash_timestamp,
})
}
}
@@ -66,82 +102,107 @@ impl ResourceEntry {
/// source entry and the resolved hash carry `timestamp` so later LWW writes order against it.
/// The bytes themselves are persisted separately by the caller's byte store.
pub fn embedded(hash: ResourceHash, peer: PeerId, timestamp: TimeStamp) -> Self {
let embedded = serde_json::to_value(graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
let embedded = to_value(&graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
let priority = Priority::new(0.).expect("0. is finite");
let sources = vec![(SourceKey { priority, peer }, SourceValue { source: embedded, timestamp })];
let sources = vec![(
SourceKey { priority, peer },
SourceValue {
source: embedded,
timestamp,
deleted: false,
},
)];
Self {
presence: timestamp,
sources,
sources_timestamp: timestamp,
hash: Some(hash),
hash_timestamp: timestamp,
}
}
/// The source body and timestamp stored under `key`, if any.
/// The live source stored under `key`, if any; a tombstone is absent.
pub fn source(&self, key: &SourceKey) -> Option<&SourceValue> {
self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)).ok().map(|index| &self.sources[index].1)
self.find(key).ok().map(|index| &self.sources[index].1).filter(|value| !value.deleted)
}
/// Insert or LWW-overwrite the entry at `key`. A re-set at an existing key wins only if `value`'s
/// timestamp is strictly newer; a fresh key is inserted in sorted position.
pub fn set_source(&mut self, key: SourceKey, value: SourceValue) {
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
Ok(index) => {
if value.timestamp > self.sources[index].1.timestamp {
self.sources[index].1 = value;
}
}
Err(index) => self.sources.insert(index, (key, value)),
}
/// The live sources in precedence order, tombstones skipped.
pub(crate) fn live_sources(&self) -> impl Iterator<Item = (&SourceKey, &SourceValue)> {
self.sources.iter().filter(|(_, value)| !value.deleted).map(|(key, value)| (key, value))
}
/// Like [`set_source`](Self::set_source) but assigns unconditionally (silent-zone rewind), where the
/// precomputed reverse/forward value is authoritative even if its timestamp ties what it replaces.
pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) {
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
fn find(&self, key: &SourceKey) -> Result<usize, usize> {
self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key))
}
/// The stamp that decides a write to `key`: its entry's, tombstone included, or the chain's floor.
fn decided(&self, key: &SourceKey) -> TimeStamp {
self.find(key).map_or(self.sources_timestamp, |index| self.sources[index].1.timestamp)
}
fn put(&mut self, key: SourceKey, value: SourceValue) {
match self.find(&key) {
Ok(index) => self.sources[index].1 = value,
Err(index) => self.sources.insert(index, (key, value)),
}
}
/// Remove the entry at `key` if its timestamp is strictly older than `timestamp` (LWW). Returns
/// whether anything was removed.
pub fn remove_source(&mut self, key: &SourceKey, timestamp: TimeStamp) -> bool {
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)) {
Ok(index) if timestamp > self.sources[index].1.timestamp => {
self.sources.remove(index);
true
/// Writes the chain whole at `at`: the floor deletes every other key without a tombstone per key.
pub(crate) fn stamp_sources(&mut self, at: TimeStamp) {
self.sources.retain(|(_, value)| !value.deleted);
self.sources.iter_mut().for_each(|(_, value)| value.timestamp = at);
self.sources_timestamp = at;
}
/// Folds another chain in key by key, the way attribute maps merge: a key only one chain holds is
/// dead when the other chain's floor is newer than it, and the newer entry wins where both hold a key.
pub(crate) fn merge_sources(&mut self, other: Vec<(SourceKey, SourceValue)>, other_floor: TimeStamp) {
self.sources.retain(|(_, value)| value.timestamp >= other_floor);
for (key, value) in other {
match self.find(&key) {
Ok(index) if value.timestamp > self.sources[index].1.timestamp => self.sources[index].1 = value,
Err(index) if value.timestamp >= self.sources_timestamp => self.sources.insert(index, (key, value)),
_ => {}
}
_ => false,
}
self.sources_timestamp = self.sources_timestamp.max(other_floor);
}
/// Insert or LWW-overwrite the entry at `key`. A re-set at an existing key wins only if `value`'s
/// timestamp is strictly newer; a fresh key is inserted in sorted position.
pub fn set_source(&mut self, key: SourceKey, value: SourceValue) {
if value.timestamp > self.decided(&key) {
self.put(key, value);
}
}
/// Like [`remove_source`](Self::remove_source) but removes unconditionally (silent-zone rewind).
pub fn force_remove_source(&mut self, key: &SourceKey) -> bool {
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)) {
Ok(index) => {
self.sources.remove(index);
true
}
_ => false,
/// Like [`set_source`](Self::set_source) but assigns unconditionally, for building an entry.
pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) {
self.put(key, value);
}
/// Remove the source at `key` if what decides it is strictly older than `timestamp` (LWW), leaving a
/// tombstone. Returns whether the removal landed.
pub fn remove_source(&mut self, key: &SourceKey, timestamp: TimeStamp) -> bool {
if timestamp <= self.decided(key) {
return false;
}
self.put(*key, SourceValue::deleted(timestamp));
true
}
/// True if the chain already carries a `DataSource::Embedded` source. Decodes each source body into
/// `DataSource` so a shape change in the serialized form can't slip an embedded source past detection.
pub fn has_embedded_source(&self) -> bool {
self.sources.iter().any(|(_, value)| {
matches!(
serde_json::from_value::<graphene_resource::DataSource>(value.source.clone()),
Ok(graphene_resource::DataSource::Embedded)
)
})
self.live_sources()
.any(|(_, value)| matches!(from_value::<graphene_resource::DataSource>(&value.source), Ok(graphene_resource::DataSource::Embedded)))
}
/// A `SourceKey` ordered strictly ahead of every current source, so an inserted entry becomes the
/// highest-precedence fallback.
pub fn highest_precedence_key(&self, peer: PeerId) -> SourceKey {
let min_priority = self.sources.first().map(|(key, _)| key.priority.value()).unwrap_or(0.);
let min_priority = self.live_sources().next().map(|(key, _)| key.priority.value()).unwrap_or(0.);
SourceKey {
priority: Priority::new(min_priority - 1.).expect("finite priority minus one is finite"),
peer,
@@ -225,15 +286,15 @@ mod tests {
}
/// Deserialization routes through `Priority::new`, so a non-finite value on disk is rejected rather
/// than silently producing an unsound map key. MessagePack (the storage format) can carry a
/// than silently producing an unsound map key. Postcard (the storage format) can carry a
/// non-finite `f64`, unlike JSON, so this guards the real round-trip path.
#[test]
fn priority_deserialize_validates_finiteness() {
let finite = rmp_serde::to_vec(&3.5_f64).unwrap();
assert!(rmp_serde::from_slice::<Priority>(&finite).is_ok());
let finite = postcard::to_stdvec(&3.5_f64).unwrap();
assert!(postcard::from_bytes::<Priority>(&finite).is_ok());
let non_finite = rmp_serde::to_vec(&f64::INFINITY).unwrap();
assert!(rmp_serde::from_slice::<Priority>(&non_finite).is_err(), "a non-finite priority on disk must be rejected");
let non_finite = postcard::to_stdvec(&f64::INFINITY).unwrap();
assert!(postcard::from_bytes::<Priority>(&non_finite).is_err(), "a non-finite priority on disk must be rejected");
}
/// `ResourceEntry`'s accessors rely on `sources` being sorted by `SourceKey`. Deserializing an
@@ -248,20 +309,23 @@ mod tests {
peer: PeerId(1),
},
SourceValue {
source: serde_json::json!(priority),
source: Value::Float(priority),
timestamp: TimeStamp::ORIGIN,
deleted: false,
},
)
};
// Serialize a deliberately unsorted chain through the raw shape, then deserialize as `ResourceEntry`.
let unsorted = serde_json::json!({
"sources": [source(2.), source(0.), source(1.)],
"hash": null,
"hash_timestamp": TimeStamp::ORIGIN,
});
// Build a deliberately unsorted chain as a literal (bypassing the sorted-insert API), then round-trip it through `Value`.
let unsorted = ResourceEntry {
presence: TimeStamp::ORIGIN,
sources_timestamp: TimeStamp::ORIGIN,
sources: vec![source(2.), source(0.), source(1.)],
hash: None,
hash_timestamp: TimeStamp::ORIGIN,
};
let entry: ResourceEntry = serde_json::from_value(unsorted).expect("deserialize");
let entry: ResourceEntry = from_value(&to_value(&unsorted).expect("serialize")).expect("deserialize");
let priorities: Vec<f64> = entry.sources.iter().map(|(key, _)| key.priority.value()).collect();
assert_eq!(priorities, vec![0., 1., 2.], "sources must be sorted by SourceKey after deserialization");
}
@@ -278,20 +342,23 @@ mod tests {
(
key,
SourceValue {
source: serde_json::json!(body),
source: Value::Str(body.into()),
timestamp: TimeStamp { counter, peer: PeerId(1) },
deleted: false,
},
)
};
let with_duplicates = serde_json::json!({
"sources": [entry(5, "newer"), entry(1, "older")],
"hash": null,
"hash_timestamp": TimeStamp::ORIGIN,
});
let with_duplicates = ResourceEntry {
presence: TimeStamp::ORIGIN,
sources_timestamp: TimeStamp::ORIGIN,
sources: vec![entry(5, "newer"), entry(1, "older")],
hash: None,
hash_timestamp: TimeStamp::ORIGIN,
};
let resource: ResourceEntry = serde_json::from_value(with_duplicates).expect("deserialize");
let resource: ResourceEntry = from_value(&to_value(&with_duplicates).expect("serialize")).expect("deserialize");
assert_eq!(resource.sources.len(), 1, "duplicate keys must collapse to one entry");
assert_eq!(resource.sources[0].1.source, serde_json::json!("newer"), "the higher-timestamp value must win");
assert_eq!(resource.sources[0].1.source, Value::Str("newer".into()), "the higher-timestamp value must win");
}
}
+337 -151
View File
@@ -2,7 +2,9 @@
use crate::NodeMetadataSource;
#[cfg(any(feature = "conversion", test))]
use crate::from_runtime;
use crate::{ApplyMode, Delta, Document, History, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId};
use crate::{
ApplyMode, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId, Value, to_value,
};
use graphene_resource::{ResourceHash, ResourceId};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
@@ -27,22 +29,17 @@ impl Session {
Self::with_peer(PeerId(core_types::uuid::generate_uuid()))
}
/// Construct a session bound to a specific `PeerId`. Used by tests; production code wants
/// `Session::new`.
/// A session for `peer` standing for itself as a person. For tests and tools without a stored identity;
/// a working copy wants [`with_identity`](Self::with_identity).
pub fn with_peer(peer: PeerId) -> Self {
Self::with_identity(peer, UserId(peer.0))
}
/// A session for device `peer` used by person `user`. The user is what the peer's registration records,
/// and what undo and history authorship scope by.
pub fn with_identity(peer: PeerId, user: UserId) -> Self {
Self {
document: Document {
working_registry: Registry::default(),
retired_snapshot: Registry::default(),
history: History::new(),
hot_log: Vec::new(),
head: None,
redo_stack: Vec::new(),
clock: LamportClock::new(peer),
peer,
last_broadcast_rev: None,
next_node_counter: 0,
},
document: Document::empty(peer, user),
remote_tips: HashMap::new(),
}
}
@@ -51,6 +48,22 @@ impl Session {
self.document.peer
}
pub fn user(&self) -> UserId {
self.document.user
}
/// The person a peer is registered to, if its registration has landed here.
pub fn user_of(&self, peer: PeerId) -> Option<UserId> {
let registered = || self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user);
(peer == self.document.peer).then_some(self.document.user).or_else(registered)
}
/// Whether `peer` is this person: this device, or another registered to the same user. Undo in a
/// session scopes by this, so a fresh copy of a document still undoes what its user did from another.
pub fn is_mine(&self, peer: PeerId) -> bool {
self.user_of(peer) == Some(self.document.user)
}
pub fn registry(&self) -> &Registry {
&self.document.working_registry
}
@@ -64,8 +77,7 @@ impl Session {
/// Diff the current registry against a fresh conversion of `network`, then commit each emitted
/// op as its own `Delta` on the local chain. One `clock.tick()` per op (strictly causal within
/// a commit). Returns the new `Rev`s in commit order (empty if nothing changed) plus the
/// proto-node declaration bytes the conversion extracted, keyed by content hash, for the caller
/// to persist into its byte store (`document-graph-storage` itself is byte-unaware).
/// conversion, whose extracted declarations the caller persists and caches.
///
/// Stages the diff as hot ops rather than retired deltas: each op is applied to the registry and
/// pushed onto the hot log. The caller persists the returned hot frames and then calls `retire`
@@ -76,11 +88,11 @@ impl Session {
network: &graph_craft::document::NodeNetwork,
metadata: &M,
resources: &graphene_resource::ResourceRegistry,
) -> Result<(Vec<HotOp>, from_runtime::DeclarationBytes), CommitError> {
) -> Result<(Vec<HotOp>, from_runtime::RuntimeConversion), CommitError> {
let conversion = Registry::convert_from_runtime(network, metadata, resources, self.document.peer)?;
let ops = crate::delta::compute_deltas(&self.document.working_registry, &conversion.registry);
let hot_ops = self.stage_ops(ops)?;
Ok((hot_ops, conversion.declaration_bytes))
Ok((hot_ops, conversion))
}
/// Resolve each runtime `network_path` to its stable [`NetworkId`] for this document's peer, so the
@@ -105,7 +117,7 @@ impl Session {
/// Used on a throwaway session clone at export time so the exported registry and history agree;
/// callers must guarantee the bytes are available in the export's resource store.
pub fn embed_resource_sources(&mut self, ids: impl IntoIterator<Item = ResourceId>) -> Result<Vec<Rev>, CrdtError> {
let embedded = serde_json::to_value(graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
let embedded = to_value(&graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
let mut ops = Vec::new();
for id in ids {
@@ -141,25 +153,45 @@ impl Session {
///
/// The peer's first contribution is preceded by a `RegisterPeer` op, so the device's
/// `PeerId → UserId` mapping is established (and, under causal delivery, observed by other peers)
/// before any of its edits. A no-op batch doesn't register — registration rides a real edit.
fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
/// before any of its edits. A no-op batch doesn't register, since registration rides a real edit.
pub(crate) fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
// A batch is staged whole or not at all: a refused op takes back the ones before it, which reached nothing yet.
let mut pending: Vec<RegistryDelta> = ops.into_iter().collect();
if pending.is_empty() {
return Ok(Vec::new());
}
if !self.document.working_registry.peer_users.contains_key(&self.document.peer) {
let user = UserId(self.document.peer.0);
pending.insert(0, RegistryDelta::RegisterPeer { peer: self.document.peer, user });
let (peer, user) = (self.document.peer, self.document.user);
if self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user) != Some(user) {
pending.insert(0, RegistryDelta::RegisterPeer { peer, user });
}
// Reusing a sequence would let retirement marks drop the new op, so a batch that would run past the end is refused whole.
if self.document.last_hot_sequence.0.checked_add(pending.len() as u64).is_none() {
return Err(CrdtError::SequencesExhausted);
}
let sequence_before = self.document.last_hot_sequence;
let mut staged = Vec::with_capacity(pending.len());
for op in pending {
let sequence = HotSequence(self.document.last_hot_sequence.0 + 1);
let hot_op = HotOp {
op,
timestamp: self.document.clock.tick(),
sequence,
};
self.document.apply_hot_op(hot_op.clone())?;
if let Err(error) = self.document.apply_hot_op(hot_op.clone(), ApplyMode::Live) {
// The run continues where it was, so no sequence goes unused.
self.document.last_hot_sequence = sequence_before;
if !staged.is_empty() {
let taken: HashSet<HotOpId> = staged.iter().map(HotOp::id).collect();
self.document.hot_log.retain(|hot_op| !taken.contains(&hot_op.id()));
self.document.resync_hot_timestamps();
self.document.rebuild_working();
}
return Err(error);
}
self.document.last_hot_sequence = sequence;
staged.push(hot_op);
}
Ok(staged)
@@ -167,19 +199,26 @@ impl Session {
/// Wrap each op as a `Delta`, apply it, and chain it onto the local history. One tick per op.
///
/// Operates on the *retired snapshot*: reverses are computed against and forward ops applied to it,
/// so each `reverse` captures the true pre-op value rather than the hot-polluted working state. The
/// Operates on the *retired snapshot*: each `reverse` is captured from it and the forward op applied to it, so
/// the reverse holds the true pre-op state rather than the hot-polluted working state. The
/// working registry already reflects these ops (they were staged as hot ops before retirement, or
/// equal the snapshot when there are none), so it is left untouched.
///
/// `idempotent`: pass `true` when the snapshot already reflects the op (retirement of an already-
/// applied hot op) so duplicate structural inserts no-op rather than error.
fn commit_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>, idempotent: bool) -> Result<Vec<Rev>, CrdtError> {
self.commit_ops_authored_at(ops.into_iter().map(|op| (op, None)), idempotent)
}
/// [`commit_ops`](Self::commit_ops) for ops authored elsewhere, paired with the timestamp they were
/// authored at (`None` to mint one). The delta's timestamp is what the registry resolves LWW on, so
/// retirement passes the op's own.
fn commit_ops_authored_at(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Option<TimeStamp>)>, idempotent: bool) -> Result<Vec<Rev>, CrdtError> {
let target = RegistryTarget::Snapshot;
let ops = ops.into_iter();
let mut produced = Vec::with_capacity(ops.size_hint().0);
for op in ops {
for (op, authored_at) in ops {
// A new edit abandons any undone-forward branch: those revs stay in the DAG but are no
// longer reachable via redo. (Mirrors the legacy editor clearing its redo history on
// commit.) Done on the first real op so a no-op commit doesn't silently disable redo.
@@ -187,10 +226,10 @@ impl Session {
self.document.redo_stack.clear();
}
let reverse = self.document.compute_reverse_delta(target, &op)?;
let timestamp = self.document.clock.tick();
let reverse = crate::prior::capture(self.document.registry_ref(target), &op);
let timestamp = authored_at.unwrap_or_else(|| self.document.clock.tick());
let parent = self.document.head;
let author = self.document.peer;
let author = timestamp.peer;
let delta = Delta::new(parent, author, timestamp, op, reverse);
let rev = delta.id;
@@ -214,7 +253,7 @@ impl Session {
/// Wrap an already-materialized snapshot. Trusts `registry` to match `history`; advances the
/// clock past every observed timestamp but does not re-apply ops. `history` is taken in on-disk
/// (topological) order.
pub fn load(peer: PeerId, registry: Registry, history: Vec<Delta>, head: Option<Rev>, redo_stack: Vec<Rev>, next_node_counter: u64) -> Self {
pub fn load(peer: PeerId, user: UserId, registry: Registry, history: Vec<Delta>, head: Option<Rev>, redo_stack: Vec<Rev>, next_node_counter: u64) -> Self {
let mut clock = LamportClock::new(peer);
for delta in &history {
clock.observe(delta.timestamp);
@@ -227,13 +266,11 @@ impl Session {
retired_snapshot: registry.clone(),
working_registry: registry,
history: History::from_ordered(history),
hot_log: Vec::new(),
head,
redo_stack,
clock,
peer,
last_broadcast_rev: None,
next_node_counter,
..Document::empty(peer, user)
},
remote_tips: HashMap::new(),
}
@@ -241,8 +278,8 @@ impl Session {
/// Rebuild the registry from scratch by applying every delta in causal order.
/// `deltas` must be in causal order (every parent before its children).
pub fn replay_from_history(peer: PeerId, deltas: impl IntoIterator<Item = Delta>, next_node_counter: u64) -> Result<Self, CrdtError> {
let mut session = Self::with_peer(peer);
pub fn replay_from_history(peer: PeerId, user: UserId, deltas: impl IntoIterator<Item = Delta>, next_node_counter: u64) -> Result<Self, CrdtError> {
let mut session = Self::with_identity(peer, user);
session.document.next_node_counter = next_node_counter;
for delta in deltas {
@@ -257,9 +294,21 @@ impl Session {
Ok(session)
}
/// Apply a hot op without going through the broadcast stream.
/// Apply a hot op from another peer. Idempotent, and a no-op for one history already covers: a late
/// delivery must not put a retired op back in the hot log.
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
self.document.apply_hot_op(hot_op)
self.document.replay_hot_op(hot_op)
}
/// Which hot ops are done with, for a peer catching up and for persisting. See [`SettledHotOps`].
pub fn settled_marks(&self) -> &SettledHotOps {
&self.document.settled
}
/// Take on a peer's marks, or this peer's persisted ones: whatever they cover that the hot log still holds is
/// dropped, and the working registry re-derived without it.
pub fn absorb_settled_marks(&mut self, remote: &SettledHotOps) {
self.document.absorb_settled(remote);
}
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
@@ -268,57 +317,52 @@ impl Session {
self.document.replay_hot_op(hot_op)
}
/// Integrate `incoming` retired deltas from another branch and emit a [`RegistryDelta::Merge`]
/// joining the resulting tips, returning the new merge `Rev` (or `None` if `incoming` adds nothing).
/// Applies each incoming op to the registry, then hands the set to [`History::merge`]. Incoming
/// deltas must arrive in causal order.
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) -> Result<Option<Rev>, CrdtError> {
let mut absorbed: Vec<Delta> = Vec::new();
for delta in incoming {
if self.document.history.contains(delta.id) {
continue;
}
self.document.apply_op_idempotent(delta.kind.clone(), delta.timestamp)?;
absorbed.push(delta);
/// The retired snapshot as history alone produces it, independent of arrival order and the hot log.
/// Folded over `head`'s ancestry only: an undone delta stays in the DAG for redo to find, and folding
/// all of history would restore work the user undid.
pub fn snapshot_from_history(&self) -> Result<Registry, CrdtError> {
// Every op lands the same whatever order it arrives in, so applying each once is the fold.
let reachable = self.document.history.ancestors(self.document.head);
let mut scratch = Document::empty(self.document.peer, self.document.user);
for delta in self.document.history.iter().filter(|delta| reachable.contains(&delta.id)) {
scratch.apply_op_with(RegistryTarget::Working, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
}
if absorbed.is_empty() {
return Ok(None);
}
self.document.history.merge(absorbed);
let tips = self.document.history.tips();
let timestamp = self.document.clock.tick();
let merge = Delta::merge(tips, self.document.peer, timestamp);
let merge_rev = merge.id;
// The merge's parents are the current tips, so it sorts last: `push` preserves the canonical
// order without re-sorting the whole history.
self.document.history.push(merge);
self.document.head = Some(merge_rev);
// Merge runs with an empty hot log; keep the retired snapshot in step with the working registry.
self.document.retired_snapshot = self.document.working_registry.clone();
Ok(Some(merge_rev))
Ok(scratch.working_registry)
}
/// Promote hot ops with timestamp `≤ up_to` into retired deltas, re-applied with fresh
/// retirement timestamps so LWW arms bump field timestamps to `T_retire`.
pub fn history_len(&self) -> usize {
self.document.history.len()
}
/// The hot ops stamped at or before `up_to`, which [`retire`](Self::retire) drains. Sent with the deltas,
/// since a lagging op can arrive below the cutoff afterwards.
pub fn hot_ops_up_to(&self, up_to: TimeStamp) -> Vec<HotOpId> {
self.document.hot_log.iter().filter(|hot_op| hot_op.timestamp <= up_to).map(HotOp::id).collect()
}
/// Promote the given hot ops into retired deltas, in hot-log order, each keeping the timestamp it was
/// authored at. Markers commit nothing. Ops not in the log are ignored.
///
/// Today: one retired delta per hot op. Coarsening is a future step.
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, CrdtError> {
let mut drained = Vec::new();
let mut remaining = Vec::with_capacity(self.document.hot_log.len());
for hot_op in self.document.hot_log.drain(..) {
if hot_op.timestamp <= up_to {
drained.push(hot_op);
} else {
remaining.push(hot_op);
}
}
self.document.hot_log = remaining;
/// One retired delta per hot op.
pub fn retire_hot_ops(&mut self, ids: &[HotOpId]) -> Result<Vec<Rev>, CrdtError> {
let wanted: HashSet<HotOpId> = ids.iter().copied().collect();
let (drained, kept): (Vec<HotOp>, Vec<HotOp>) = self.document.hot_log.drain(..).partition(|hot_op| wanted.contains(&hot_op.id()));
self.document.hot_log = kept;
self.document.resync_hot_timestamps();
self.document.settled.extend(drained.iter().map(HotOp::id));
self.commit_ops(drained.into_iter().map(|hot_op| hot_op.op), true)
let ops = drained
.into_iter()
.filter(|hot_op| !matches!(hot_op.op, RegistryDelta::EndTransaction))
.map(|hot_op| (hot_op.op, Some(hot_op.timestamp)));
self.commit_ops_authored_at(ops, true)
}
/// Promote every hot op stamped at or before `up_to`, whatever its author.
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, CrdtError> {
let ids = self.hot_ops_up_to(up_to);
self.retire_hot_ops(&ids)
}
/// Mark a retired delta as the end of a user interaction, so the undo cursor treats it as a checkpoint.
/// Called once per interaction by the editor-facing commit path (not by resource/internal commits).
pub fn mark_interaction_end(&mut self, rev: Rev) {
@@ -329,38 +373,36 @@ impl Session {
/// Low-level: set a local annotation attribute (e.g. a commit message) on a retired delta in place.
/// Excluded from the delta's content-addressed `Rev`, so identity is unchanged. Returns whether the
/// delta was found. The `Gdd` layer re-persists the affected history frame after calling this.
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: serde_json::Value) -> bool {
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: Value) -> bool {
let timestamp = self.document.clock.tick();
self.document.history.annotate(rev, key, value, timestamp)
}
/// Whether there is a retired commit at `head` that can be undone in the silent zone (a commit
/// after `last_broadcast_rev`). `head == 0` is the empty history; published commits aren't
/// silently undoable (that needs a forward reverse-delta op, deferred until transport lands).
///
/// The earliest interaction (the document's loaded/created base) is *not* undoable: undoing it would
/// rewind into the pre-base state, which legacy never offers (opening a document gives an empty undo
/// history). We detect "head is on the earliest interaction" by walking `head`'s interaction back along
/// first-parents and checking whether it bottoms out at the root with no earlier interaction boundary to
/// land on. If so, there is nothing before this interaction to undo to, so undo is disabled.
/// Whether the interaction at `head` can be undone in the silent zone: it is this user's own, holds no merge, and
/// nothing in it was published, since rewinding a step peers hold would diverge from them. The document's first
/// interaction is not undoable, as opening a document starts with an empty undo history.
pub fn can_undo(&self) -> bool {
let Some(head) = self.document.head else { return false };
if self.document.last_broadcast_rev == Some(head) {
return false;
}
self.interaction_start_parent(head).is_some()
self.document.head.is_some_and(|head| self.interaction_start_parent(head, true).is_some())
}
/// Walk the interaction containing `rev` back along first-parents to its first delta, returning the
/// rev the cursor would rest on after undoing this interaction, or `None` if that is the root (the
/// earliest interaction, which is not undoable). Mirrors the boundary condition in [`undo`](Self::undo):
/// stop when the parent is an `interaction_end` boundary or the root.
fn interaction_start_parent(&self, rev: Rev) -> Option<Rev> {
let mut current = rev;
/// The rev the cursor rests on once the interaction ending at `end` is undone: the parent where the previous
/// interaction ended, a merge, or another user's delta begins. `None` when `end` is a merge, the interaction starts
/// at the root, or, for a `silent` undo, it is not this user's or holds a published delta.
fn interaction_start_parent(&self, end: Rev, silent: bool) -> Option<Rev> {
let history = &self.document.history;
let mut current = history.get(end)?;
let user = self.user_of(current.author);
if matches!(current.kind, RegistryDelta::Merge { .. }) || (silent && user != Some(self.document.user)) {
return None;
}
let boundary = |delta: &Delta| delta.is_interaction_end() || matches!(delta.kind, RegistryDelta::Merge { .. }) || self.user_of(delta.author) != user;
loop {
let parent = self.document.history.get(current)?.parent?;
if self.document.history.get(parent).is_some_and(|d| d.is_interaction_end()) {
return Some(parent);
if silent && self.document.last_broadcast_rev == Some(current.id) {
return None;
}
let parent = history.get(current.parent?)?;
if boundary(parent) {
return Some(parent.id);
}
current = parent;
}
@@ -370,37 +412,22 @@ impl Session {
!self.document.redo_stack.is_empty()
}
/// Silent-zone undo of one *interaction*: revert deltas walking `head` back along first-parents until
/// it reaches the previous interaction boundary (a delta marked `interaction_end`) or the empty root. One
/// interaction spans several deltas (one `commit_from_runtime` batch), so undo reverts the whole run,
/// not a single delta — matching the legacy per-interaction undo granularity. The undone interaction's
/// `head` rev is pushed onto the redo stack. Reflog semantics: the DAG is never rewritten.
/// Silent-zone undo of one interaction: put back what its deltas overwrote, newest first, until `head` rests where it
/// began (see [`can_undo`](Self::can_undo)). Its `head` rev goes on the redo stack; the DAG is not rewritten.
pub fn undo(&mut self) -> Result<Rev, CrdtError> {
if !self.can_undo() {
return Err(CrdtError::NothingToUndo);
}
let checkpoint = self.document.head.ok_or(CrdtError::NothingToUndo)?;
let base = self.interaction_start_parent(checkpoint, true).ok_or(CrdtError::NothingToUndo)?;
// Revert this interaction's last delta, then keep going back until `head` rests on the previous
// interaction's boundary (its `interaction_end` delta) or the root.
loop {
let rev = self.document.head.ok_or(CrdtError::NothingToUndo)?;
while let Some(rev) = self.document.head.filter(|&rev| rev != base) {
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
let parent = delta.parent;
self.document.revert_delta(RegistryTarget::Working, delta)?;
self.document.head = parent;
match parent {
None => break,
Some(parent) if self.document.history.get(parent).is_some_and(|d| d.is_interaction_end()) => break,
Some(_) => {}
}
self.document.revert_delta(&delta);
self.document.head = delta.parent;
}
// Undo runs with an empty hot log, so keep the retired snapshot in lockstep with the rewound
// working registry (the next interaction's reverses are computed against it).
self.document.retired_snapshot = self.document.working_registry.clone();
// With ops hot, working is the rewound snapshot plus them.
if !self.document.hot_log.is_empty() {
self.document.rebuild_working();
}
self.document.redo_stack.push(checkpoint);
Ok(checkpoint)
}
@@ -420,23 +447,28 @@ impl Session {
forward.push(delta);
}
// Force-apply so each forward value wins the LWW tie against the reverse that undo force-applied
// at the same timestamp. Symmetric with `revert_delta`.
// Undo left the snapshot exactly at the fold up to `head`, so applying the deltas as retirement did folds
// them in again, a newer write merged in before them still winning over theirs.
let hot = !self.document.hot_log.is_empty();
for delta in forward.into_iter().rev() {
self.document.force_apply_op(delta.kind.clone(), delta.timestamp)?;
self.document.apply_op_with(RegistryTarget::Snapshot, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
if !hot {
self.document.apply_op_with(RegistryTarget::Working, delta.kind, delta.timestamp, ApplyMode::Idempotent)?;
}
}
if hot {
self.document.rebuild_working();
}
self.document.head = Some(checkpoint);
// Redo runs with an empty hot log; keep the retired snapshot in lockstep with the working registry.
self.document.retired_snapshot = self.document.working_registry.clone();
Ok(checkpoint)
}
/// Build a synthetic linear history whose replay reproduces `registry`. Each op gets a
/// freshly-ticked clock timestamp and chains to the previous op's `Rev`.
pub fn bootstrap_from_registry(peer: PeerId, registry: Registry) -> Result<Self, CrdtError> {
pub fn bootstrap_from_registry(peer: PeerId, user: UserId, registry: Registry) -> Result<Self, CrdtError> {
let ops = crate::delta::compute_deltas(&Registry::default(), &registry);
let mut session = Self::with_peer(peer);
let mut session = Self::with_identity(peer, user);
session.commit_ops(ops, false)?;
// No hot ops on this path, so the working registry must mirror the freshly-built snapshot.
session.document.working_registry = session.document.retired_snapshot.clone();
@@ -467,16 +499,42 @@ impl Session {
/// bytes. Walks current resources plus each delta's `AddResource`/`RemoveResource` snapshot.
pub fn all_referenced_resource_hashes(&self) -> HashSet<ResourceHash> {
let mut hashes: HashSet<ResourceHash> = self.document.working_registry.resources.values().filter_map(|entry| entry.hash).collect();
hashes.extend(self.document.history.resource_hashes());
hashes
}
/// Every proto-node declaration resource referenced by the current registry or anywhere in history,
/// with its content hash, or `None` where the hash never resolved.
pub fn all_declaration_resources(&self) -> HashMap<ResourceId, Option<ResourceHash>> {
let registry = &self.document.working_registry;
let mut hashes: HashMap<ResourceId, ResourceHash> = registry.resources.iter().filter_map(|(id, entry)| Some((*id, entry.hash?))).collect();
for delta in self.document.history.iter() {
match &delta.kind {
RegistryDelta::AddResource { entry, .. } => hashes.extend(entry.hash),
RegistryDelta::RemoveResource { snapshot, .. } => hashes.extend(snapshot.hash),
RegistryDelta::AddResource { id, entry } => hashes.extend(entry.hash.map(|hash| (*id, hash))),
RegistryDelta::RemoveResource { id, snapshot } => hashes.extend(snapshot.hash.map(|hash| (*id, hash))),
RegistryDelta::SetResourceHash { id, hash: Some(hash) } => {
hashes.insert(*id, *hash);
}
_ => {}
}
}
hashes
let current_nodes = registry.node_instances.values();
let historic_nodes = self.document.history.iter().filter_map(|delta| match &delta.kind {
RegistryDelta::AddNode { node, .. } => Some(node),
RegistryDelta::RemoveNode { snapshot, .. } => Some(snapshot),
_ => None,
});
current_nodes
.chain(historic_nodes)
.filter_map(|node| match node.implementation() {
Implementation::ProtoNode(id) => Some(*id),
Implementation::Network(_) => None,
})
.map(|id| (id, hashes.get(&id).copied()))
.collect()
}
pub fn hot_log(&self) -> &[HotOp] {
@@ -507,7 +565,7 @@ impl Session {
}
/// Test-only: commit a single op as a retired delta on the local chain, returning the result so a
/// test can observe a resurrection failure (e.g. `NotFoundInHistory`).
/// test can observe a failure (e.g. `NotFoundInHistory`).
#[cfg(test)]
pub(crate) fn commit_op_for_test(&mut self, op: RegistryDelta) -> Result<(), CrdtError> {
self.commit_ops(std::iter::once(op), false).map(|_| ())
@@ -520,6 +578,29 @@ impl Session {
pub fn next_node_counter(&self) -> u64 {
self.document.next_node_counter
}
/// The sequence of the last hot op this peer authored, which is how many it has. Carried across a reload, so no
/// sequence is spent twice.
pub fn last_hot_sequence(&self) -> HotSequence {
self.document.last_hot_sequence
}
/// The Lamport counter, persisted so a reopen never mints a stamp it already spent, even one no op in history or
/// the hot log carries any more.
pub fn clock_counter(&self) -> u64 {
self.document.clock.counter
}
/// Continue the Lamport clock after a load. Raises only, like observing an op.
pub fn restore_clock(&mut self, counter: u64) {
self.document.clock.counter = self.document.clock.counter.max(counter);
}
/// Restore the authored-op count after a load, keeping a fresh op off a spent sequence. Raises only:
/// replaying a persisted hot log afterwards cannot lower it.
pub fn restore_hot_sequence(&mut self, sequence: HotSequence) {
self.document.last_hot_sequence = self.document.last_hot_sequence.max(sequence);
}
}
/// Errors from `Session::commit_from_runtime`.
@@ -545,10 +626,122 @@ impl Default for Session {
pub struct HotOp {
pub op: RegistryDelta,
pub timestamp: TimeStamp,
/// Position in its author's run. See [`HotSequence`].
pub sequence: HotSequence,
}
impl HotOp {
/// Identifies the op in the settled marks, which track a contiguous prefix per author.
pub fn id(&self) -> HotOpId {
HotOpId {
peer: self.timestamp.peer,
sequence: self.sequence,
}
}
}
/// Position in one author's run of hot ops, counting from 1 with no gaps. Kept apart from the Lamport
/// counter, which skips on observing a higher remote timestamp and so cannot bound a contiguous prefix.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct HotSequence(pub u64);
impl HotSequence {
/// Before this author has written anything, covering no op.
pub const NONE: Self = Self(0);
/// The position after this one, for adjacency. Saturates: a run ending at the last position has no successor.
pub fn next(self) -> Self {
Self(self.0.saturating_add(1))
}
}
/// One hot op's author and position in its run. Retirement names promoted ops by these, which tells a
/// receiver which prefix history covers.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct HotOpId {
pub peer: PeerId,
pub sequence: HotSequence,
}
/// Which hot ops are retired into history: `settled_up_to` is each author's gap-free prefix, and `settled_beyond`
/// the settled ops past it. Gaps exist only while ops are in flight, so an author collapses to its prefix. Replicated and persisted, so a
/// late copy of a settled op is dropped wherever it lands.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SettledHotOps {
pub settled_up_to: HashMap<PeerId, HotSequence>,
/// Settled ops past their author's prefix, as inclusive runs, one per gap in flight.
pub settled_beyond: HashMap<PeerId, Vec<(HotSequence, HotSequence)>>,
}
/// Sort and coalesce runs, joining any that touch or abut.
fn coalesce(runs: &mut Vec<(HotSequence, HotSequence)>) {
runs.sort_unstable();
runs.dedup_by(|(start, end), (_, last_end)| {
let joins = *start <= last_end.next();
if joins {
*last_end = (*last_end).max(*end);
}
joins
});
}
impl SettledHotOps {
/// Whether history already holds this hot op.
pub fn covers(&self, id: HotOpId) -> bool {
self.settled_up_to.get(&id.peer).is_some_and(|&through| id.sequence <= through)
|| self
.settled_beyond
.get(&id.peer)
.is_some_and(|runs| runs.iter().any(|&(start, end)| (start..=end).contains(&id.sequence)))
}
/// Take on `remote`'s coverage as well as this one's.
pub(crate) fn absorb(&mut self, remote: &Self) {
for (&peer, &remote_through) in &remote.settled_up_to {
let through = self.settled_up_to.entry(peer).or_default();
*through = (*through).max(remote_through);
}
for (&peer, runs) in &remote.settled_beyond {
self.settled_beyond.entry(peer).or_default().extend(runs.iter().copied());
}
self.compact();
}
/// Record newly settled ops.
pub fn extend(&mut self, retired: impl IntoIterator<Item = HotOpId>) {
for id in retired {
self.settled_beyond.entry(id.peer).or_default().push((id.sequence, id.sequence));
}
self.compact();
}
/// Fold runs that continue their author's prefix into `settled_up_to`, leaving only those past a gap.
fn compact(&mut self) {
for (&peer, runs) in &mut self.settled_beyond {
coalesce(runs);
let mut through = self.settled_up_to.get(&peer).copied().unwrap_or(HotSequence::NONE);
let joined = runs.iter().take_while(|&&(start, end)| {
let joins = start <= through.next();
if joins {
through = through.max(end);
}
joins
});
let joined = joined.count();
runs.drain(..joined);
if through != HotSequence::NONE {
self.settled_up_to.insert(peer, through);
}
}
self.settled_beyond.retain(|_, runs| !runs.is_empty());
}
}
#[derive(Debug, thiserror::Error)]
pub enum CrdtError {
#[error("This peer has authored every hot op sequence there is")]
SequencesExhausted,
#[error("Target node {0} does not exist")]
TargetNodeDoesNotExist(NodeId),
#[error("Network {0} does not exist")]
@@ -559,10 +752,6 @@ pub enum CrdtError {
ExportSlotOutOfBounds(u32),
#[error("Delta {0} not found in history")]
NotFoundInHistory(Rev),
#[error("No history entry resurrects node {0}")]
NodeNotInHistory(NodeId),
#[error("No history entry resurrects network {0}")]
NetworkNotInHistory(NetworkId),
#[error("Nothing to undo")]
NothingToUndo,
#[error("Nothing to redo")]
@@ -571,9 +760,6 @@ pub enum CrdtError {
NodeAlreadyExists(NodeId),
#[error("Network {0} already exists")]
NetworkAlreadyExists(NetworkId),
/// PeerId is already registered to a different UserId.
#[error("Peer {0:?} is already registered to a different user")]
PeerRegistrationConflict(PeerId),
#[error("Delta stored under {stored} hashes to {expected}")]
RevMismatch { stored: Rev, expected: Rev },
}
@@ -0,0 +1,165 @@
use crate::{AttributeDelta, CrdtError, HotOpId, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, RegistryDelta, Session, UserId, Value};
pub(super) fn set_attribute(key: &str, value: u32) -> RegistryDelta {
RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta {
key: key.to_string(),
value: Some(Value::from(serde_json::json!(value))),
},
}
}
pub(super) fn add_network(id: u64) -> RegistryDelta {
RegistryDelta::AddNetwork {
id: NetworkId(id),
network: Network::default(),
}
}
/// Retirement takes the ops under the cutoff in any log order: every op commutes, so the snapshot folds to
/// the working registry's values with a later-stamped op left hot.
#[test]
fn retirement_takes_the_ops_under_the_cutoff_in_any_applied_order() {
let mut host = Session::with_peer(PeerId(1));
// A guest's late-stamped op sits ahead of an earlier-stamped one: the log is in arrival order, stamps
// are the authors' clocks.
let hot = |op, counter, peer| crate::HotOp {
op,
timestamp: crate::TimeStamp { counter, peer: PeerId(peer) },
sequence: crate::HotSequence(1),
};
let (late, own) = (hot(add_network(9), 50, 2), hot(set_attribute("x", 1), 20, 3));
host.apply_hot_op(late.clone()).expect("the late-stamped op lands first");
host.apply_hot_op(own.clone()).expect("the earlier-stamped op lands second");
assert_eq!(host.hot_ops_up_to(own.timestamp).len(), 1, "only the op under the cutoff retires");
host.retire(own.timestamp).expect("retire");
assert_eq!(host.hot_log().len(), 1, "the later-stamped op stays hot");
assert!(!host.retired_registry().networks.contains_key(&NetworkId(9)));
assert!(host.registry().networks.contains_key(&NetworkId(9)));
assert!(host.retired_registry().attributes.get("x").is_some_and(|value| !value.deleted));
host.retire(late.timestamp).expect("retire the rest");
assert!(host.hot_log().is_empty());
assert!(host.registry().value_equal(host.retired_registry()));
}
/// A device's registration to a person is a write like any other: a later one replaces it, and a peer that
/// receives the two in the other order ends up with the same mapping.
#[test]
fn a_peers_registration_is_the_newest_by_stamp_whatever_order_it_lands() {
// Registration rides the staging path, so the steps go through the hot log and retire.
fn stage_and_retire(session: &mut Session, op: RegistryDelta) {
let hot = session.stage_ops([op]).expect("stage");
let ids: Vec<crate::HotOpId> = hot.iter().map(crate::HotOp::id).collect();
session.retire_hot_ops(&ids).expect("retire");
}
let mut device = Session::with_identity(PeerId(1), UserId(10));
stage_and_retire(&mut device, set_attribute("first", 1));
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(10));
// The person at the device changes: the next batch registers again, and the newer registration wins.
device.document.user = UserId(20);
stage_and_retire(&mut device, set_attribute("second", 2));
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(20));
let registrations = device.history().filter(|delta| matches!(delta.kind, RegistryDelta::RegisterPeer { .. })).count();
assert_eq!(registrations, 2, "one registration per person the device stood for");
let mut other = Session::with_peer(PeerId(2));
for delta in device.cloned_deltas().into_iter().rev() {
other.document.apply_op_idempotent(delta.kind, delta.timestamp).unwrap();
}
assert_eq!(other.user_of(PeerId(1)), Some(UserId(20)), "the newest registration wins in any order");
assert_eq!(other.user_of(PeerId(3)), None, "a peer never registered has no user");
}
#[test]
fn a_batch_past_the_last_sequence_is_refused_whole() {
let mut session = Session::with_peer(PeerId(1));
session.restore_hot_sequence(crate::HotSequence(u64::MAX - 1));
assert!(matches!(session.stage_ops([set_attribute("k", 1)]), Err(crate::CrdtError::SequencesExhausted)));
assert!(session.hot_log().is_empty());
}
/// The settled marks carry over a reopen, so a late copy of a retired op is dropped rather than retired again.
#[test]
fn a_reopened_session_drops_a_late_copy_of_a_retired_op() {
let op = crate::HotOp {
op: set_attribute("k", 1),
timestamp: crate::TimeStamp { counter: 3, peer: PeerId(2) },
sequence: crate::HotSequence(1),
};
let mut host = Session::with_peer(PeerId(1));
host.apply_hot_op(op.clone()).unwrap();
host.retire(op.timestamp).unwrap();
let mut reopened = Session::load(PeerId(1), UserId(1), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
reopened.absorb_settled_marks(host.settled_marks());
reopened.apply_hot_op(op.clone()).unwrap();
assert!(reopened.hot_log().is_empty());
assert!(reopened.retire(op.timestamp).unwrap().is_empty());
assert_eq!(reopened.history_len(), host.history_len());
}
/// A local op naming a node never seen is refused before it writes anything, its target included, so the working
/// registry stays the snapshot plus the hot log.
#[test]
fn a_refused_local_op_leaves_the_working_registry_unchanged() {
let mut s = Session::with_peer(PeerId(1));
let node = Node::new(NetworkId(1), Implementation::Network(NetworkId(1)), 1);
s.stage_ops([
RegistryDelta::AddNetwork {
id: NetworkId(1),
network: Network::default(),
},
RegistryDelta::AddNode { id: NodeId(1), node },
])
.unwrap();
let before = s.registry().clone();
let refused = s.stage_ops([RegistryDelta::ChangeNodeInput {
id: NodeId(1),
index: 0,
new_input: NodeInput::Node { id: NodeId(404), index: 0 },
}]);
assert!(matches!(refused, Err(CrdtError::TargetNodeDoesNotExist(_))));
assert_eq!(s.registry(), &before, "the refused op's write to node 1 stayed in the working registry");
}
/// A batch refused partway stages nothing: the caller only gets the error, so ops left staged would never be persisted
/// or sent.
#[test]
fn a_refused_batch_stages_nothing() {
let mut s = Session::with_peer(PeerId(1));
s.stage_ops([RegistryDelta::AddNetwork {
id: NetworkId(1),
network: Network::default(),
}])
.unwrap();
let hot_before = s.hot_log().len();
let refused = s.stage_ops([
set_attribute("lands", 1),
RegistryDelta::ChangeNodeInput {
id: NodeId(404),
index: 0,
new_input: NodeInput::Value {
value: Value::from(serde_json::json!(1)),
exposed: false,
},
},
]);
assert!(refused.is_err());
assert_eq!(s.hot_log().len(), hot_before, "a refused batch stages nothing");
}
#[test]
fn settled_marks_round_trip_through_json() {
let mut marks = crate::SettledHotOps::default();
let id = |peer: u64, sequence: u64| HotOpId {
peer: PeerId(peer),
sequence: crate::HotSequence(sequence),
};
marks.extend([id(1, 1), id(1, 2), id(1, 5), id(u64::MAX, 3)]);
let json = serde_json::to_string(&marks).unwrap();
assert_eq!(serde_json::from_str::<crate::SettledHotOps>(&json).unwrap(), marks);
}
File diff suppressed because it is too large. Load diff
+22 -15
View File
@@ -7,7 +7,7 @@ use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput,
use graph_craft::graphene_compiler::Compiler;
use graph_craft::{ProtoNodeIdentifier, Type, concrete};
use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry};
use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry, from_value};
/// Helper function to verify a NodeNetwork can be compiled successfully.
/// Note: This only works for complete networks with all inputs resolved.
@@ -20,12 +20,10 @@ fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
/// Convert a runtime network to a storage `Registry`, returning the declarations alongside it.
/// Proto-node declaration content is no longer stored in the registry (it lives in a byte store);
/// these tests have no byte store, so they keep the extracted bytes in hand and rebuild a
/// `Declarations` map for the back-conversion.
/// these tests have no byte store, so they keep the extracted `Declarations` in hand for the back-conversion.
fn to_registry(network: &NodeNetwork) -> (Registry, crate::Declarations) {
let conversion = Registry::convert_from_runtime(network, &crate::NoMetadata, &Default::default(), PeerId(0)).expect("Failed to convert NodeNetwork to Registry");
let declarations = conversion.declarations().expect("rebuild declarations");
(conversion.registry, declarations)
(conversion.registry, conversion.declarations)
}
/// A one-node network whose single node references `id` via a `TaggedValue::Resource` input, so
@@ -477,7 +475,7 @@ fn test_ui_metadata_round_trip() {
);
let conversion = Registry::convert_from_runtime(&network, &metadata, &Default::default(), PeerId(0)).expect("Failed to convert to Registry with metadata");
let declarations = conversion.declarations().expect("rebuild declarations");
let declarations = conversion.declarations;
let registry = conversion.registry;
let (converted, entries) = registry.to_runtime_with_metadata(&declarations).expect("Failed to convert Registry back with metadata");
@@ -532,7 +530,7 @@ fn resources_round_trip_through_from_runtime() {
assert_eq!(entry.sources.len(), 2, "both sources carried through");
// The chain iterates in priority order; decode bodies back to DataSource to compare.
let decoded: Vec<DataSource> = entry.sources.iter().map(|(_, v)| serde_json::from_value(v.source.clone()).expect("source body decodes")).collect();
let decoded: Vec<DataSource> = entry.sources.iter().map(|(_, v)| from_value(&v.source).expect("source body decodes")).collect();
assert_eq!(decoded, vec![DataSource::Embedded, DataSource::Url("https://example.com/img.png".parse().unwrap())]);
// All source keys carry the document peer.
@@ -611,10 +609,9 @@ fn unreferenced_runtime_resource_is_not_snapshotted() {
assert!(!registry.resources.contains_key(&orphan), "the unreferenced (orphan) resource must not be snapshotted");
}
/// A node-input `TaggedValue::F64` must survive the storage round-trip bit-exact. Inputs are stored as a
/// self-describing `serde_json::Value` (encoded with the registry's MessagePack codec), so this guards
/// against any precision loss in the f64 -> serde_json::Number -> f64 path for a value with a full
/// 17-significant-digit mantissa.
/// A node-input `TaggedValue::Number` must survive the storage round-trip bit-exact. Inputs are stored
/// type-erased as a `Value`, so this guards against any precision loss in the f64
/// -> Value -> f64 path for a value with a full 17-significant-digit mantissa.
#[test]
fn node_input_f64_round_trips_bit_exact() {
use graph_craft::document::value::TaggedValue;
@@ -625,7 +622,7 @@ fn node_input_f64_round_trips_bit_exact() {
nodes: [(
NodeId(0),
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::F64(precise), false)],
inputs: vec![NodeInput::value(TaggedValue::Number(precise), false)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
..Default::default()
},
@@ -642,8 +639,8 @@ fn node_input_f64_round_trips_bit_exact() {
let NodeInput::Value { tagged_value, .. } = input else {
panic!("expected a value input, got {input:?}")
};
let TaggedValue::F64(actual) = &**tagged_value else {
panic!("expected F64, got {:?}", tagged_value)
let TaggedValue::Number(actual) = &**tagged_value else {
panic!("expected Number, got {:?}", tagged_value)
};
assert_eq!(actual.to_bits(), precise.to_bits(), "f64 node input drifted: {actual} != {precise}");
@@ -661,7 +658,7 @@ fn duplicate_runtime_node_id_is_rejected() {
// Force both root-network nodes onto the same runtime ID.
for node in registry.node_instances.values_mut() {
node.attributes.set(crate::attr::node::ORIGINAL_NODE_ID, serde_json::json!(7), TimeStamp::ORIGIN);
node.attributes.set(crate::attr::node::ORIGINAL_NODE_ID, crate::Value::Int(7), TimeStamp::ORIGIN);
}
let error = registry.to_runtime_with_metadata(&declarations).expect_err("duplicate runtime ID must error");
@@ -760,18 +757,28 @@ fn cyclic_network_reference_is_rejected() {
registry.node_instances.insert(
crate::NodeId(0),
Node {
presence: Default::default(),
added: Default::default(),
inputs_timestamp: Default::default(),
implementation: Implementation::Network(child_network_id),
implementation_timestamp: Default::default(),
inputs: Vec::new(),
attributes: crate::Attributes::default(),
attributes_timestamp: Default::default(),
network: crate::ROOT_NETWORK,
},
);
registry.node_instances.insert(
crate::NodeId(1),
Node {
presence: Default::default(),
added: Default::default(),
inputs_timestamp: Default::default(),
implementation: Implementation::Network(crate::ROOT_NETWORK),
implementation_timestamp: Default::default(),
inputs: Vec::new(),
attributes: crate::Attributes::default(),
attributes_timestamp: Default::default(),
network: child_network_id,
},
);
+39 -32
View File
@@ -10,7 +10,7 @@ use rustc_hash::{FxHashMap, FxHashSet};
use crate::attr::*;
use crate::metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry};
use crate::{AttributesRead, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId};
use crate::{AttributesRead, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId, Value, from_value};
#[derive(Debug, thiserror::Error)]
pub enum ConversionError {
@@ -38,7 +38,8 @@ pub enum ConversionError {
pub type Declarations = std::collections::HashMap<ResourceId, ProtoNode>;
impl Registry {
/// Returns the network plus per-node metadata entries (one per node carrying any `ui::*` attribute).
/// Returns the network plus one metadata entry per node, since every node carries an identity to
/// restore even when it has no `ui::*` attribute.
pub fn to_runtime_with_metadata(&self, declarations: &Declarations) -> Result<(NodeNetwork, Vec<NodeMetadataEntry>), ConversionError> {
let (network, node_entries, _) = self.to_runtime_with_full_metadata(declarations)?;
Ok((network, node_entries))
@@ -50,19 +51,7 @@ impl Registry {
let mut node_metadata = Some(Vec::new());
let mut network_metadata = Some(Vec::new());
// Group nodes by their owning network in one pass, so each `convert_network` call (one per
// network, including nested ones) takes its node list by lookup instead of rescanning the whole
// flat `node_instances` map, which would be quadratic on graphs with many networks.
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
for (&global_id, node) in &self.node_instances {
nodes_by_network.entry(node.network).or_default().push((global_id, node));
}
let context = ConversionContext {
registry: self,
declarations,
nodes_by_network,
};
let context = ConversionContext::new(self, declarations);
// Reject cycles up front so the recursive conversion below can assume the network reference
// graph is acyclic and never blow the stack on a self-referential `Implementation::Network`.
@@ -74,15 +63,15 @@ impl Registry {
/// Rebuild the runtime [`ResourceRegistry`](graphene_resource::ResourceRegistry) from the stored
/// `resources`. Each entry's source chain is restored in priority order (the chain is kept
/// sorted by key) with bodies decoded from their type-erased `serde_json::Value` form back to
/// sorted by key) with bodies decoded from their type-erased `Value` form back to
/// `DataSource`; the resolved hash, if any, is restored last. Inverse of `convert_resources` in
/// `from_runtime`.
pub fn to_resource_registry(&self) -> Result<graphene_resource::ResourceRegistry, ConversionError> {
let mut registry = graphene_resource::ResourceRegistry::new();
for (id, entry) in &self.resources {
for (_, source) in &entry.sources {
let decoded: graphene_resource::DataSource = serde_json::from_value(source.source.clone()).map_err(|error| ConversionError::DeserializationError(error.to_string()))?;
for (_, source) in entry.live_sources() {
let decoded: graphene_resource::DataSource = from_value(&source.source).map_err(|error| ConversionError::DeserializationError(error.to_string()))?;
registry.push_source_back(id, decoded);
}
if let Some(hash) = entry.hash {
@@ -103,6 +92,26 @@ struct ConversionContext<'a> {
nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &'a Node)>>,
}
impl<'a> ConversionContext<'a> {
fn new(registry: &'a Registry, declarations: &'a Declarations) -> Self {
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
for (&global_id, node) in &registry.node_instances {
nodes_by_network.entry(node.network).or_default().push((global_id, node));
}
Self {
registry,
declarations,
nodes_by_network,
}
}
}
/// The id the node had in the runtime it was converted from, kept as an attribute so a conversion back
/// lands it under the id the editor's metadata is keyed by.
fn runtime_node_id(global_id: NodeId, node: &Node) -> RuntimeNodeId {
RuntimeNodeId(node.attributes.get_typed(node::ORIGINAL_NODE_ID).unwrap_or(global_id.0))
}
/// Converts a single network. Recurses through `Implementation::Network` owning nodes.
///
/// **ID remapping:** Registry uses globally hashed IDs; runtime networks need local IDs. We pull
@@ -165,7 +174,7 @@ fn convert_network(
node_collector: &mut Option<Vec<NodeMetadataEntry>>,
network_collector: &mut Option<Vec<NetworkMetadataEntry>>,
) -> Result<NodeNetwork, ConversionError> {
let network = context.registry.networks.get(&network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
let network = context.registry.network_or_removed(network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
if let Some(collector) = network_collector.as_mut() {
collector.push(extract_network_metadata(context.registry, &network.attributes, metadata_path, network_id));
@@ -173,8 +182,8 @@ fn convert_network(
let mut nodes: FxHashMap<RuntimeNodeId, DocumentNode> = FxHashMap::default();
for &(global_id, node) in context.nodes_by_network.get(&network_id).map(Vec::as_slice).unwrap_or_default() {
let local_id = node.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(global_id.0);
let runtime_id = RuntimeNodeId(local_id);
let runtime_id = runtime_node_id(global_id, node);
let local_id = runtime_id.0;
if let Some(collector) = node_collector.as_mut() {
collector.push(extract_ui_metadata(node, global_id, metadata_path, runtime_id));
@@ -231,8 +240,7 @@ fn read_scope_injections(registry: &Registry, network_id: NetworkId, attributes:
});
};
let local_id = referenced.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(storage_id.0);
Ok((key, (RuntimeNodeId(local_id), ty)))
Ok((key, (runtime_node_id(storage_id, referenced), ty)))
})
.collect()
}
@@ -266,12 +274,11 @@ fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[R
/// Node references stored here are storage IDs, resolved back to runtime-local IDs the way
/// `read_scope_injections` does. A reference to a node that is no longer in this network is dropped
/// rather than failing the conversion: the preview target or a pinned node can have been deleted.
/// rather than failing the conversion: a pinned node can have been deleted.
fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes, network_path: &[RuntimeNodeId], network_id: NetworkId) -> NetworkMetadataEntry {
let to_runtime_id = |storage_id: NodeId| {
let node = registry.node_instances.get(&storage_id).filter(|node| node.network == network_id)?;
let local_id = node.attributes.get(node::ORIGINAL_NODE_ID).and_then(|value| value.value.as_u64()).unwrap_or(storage_id.0);
Some(RuntimeNodeId(local_id))
Some(runtime_node_id(storage_id, node))
};
let pinned_order = attributes
@@ -291,8 +298,7 @@ fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes,
/// Reassembles `input_data` by scanning every attribute under `ui::input_data::` and stripping the prefix.
fn extract_input_metadata(attributes: &crate::Attributes) -> InputMetadataEntry {
let input_data: HashMap<String, serde_json::Value> = attributes
.iter()
let input_data: HashMap<String, Value> = crate::attributes::live(attributes)
.filter_map(|(key, value)| key.strip_prefix(node::input::ui::DATA_PREFIX).map(|sub_key| (sub_key.to_owned(), value.value.clone())))
.collect();
@@ -334,7 +340,9 @@ fn convert_node(
fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput, input_attributes: &crate::Attributes) -> Result<GraphCraftNodeInput, ConversionError> {
Ok(match input {
NodeInput::Node { id: node_id, index: output_index } => {
let referenced = registry.node_instances.get(node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
// A node removed concurrently keeps its id, as the editor holds a dangling input; only a node
// never seen has no id to map to.
let referenced = registry.node_or_removed(*node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
// Runtime references are local to one network. A cross-network reference would remap to a
// local ID that doesn't exist in the current runtime network, so reject it.
@@ -345,14 +353,13 @@ fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput,
});
}
let local_id = referenced.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(node_id.0);
GraphCraftNodeInput::Node {
node_id: RuntimeNodeId(local_id),
node_id: runtime_node_id(*node_id, referenced),
output_index: *output_index as usize,
}
}
NodeInput::Value { value, exposed } => {
let tagged_value: TaggedValue = serde_json::from_value(value.clone()).map_err(|e| ConversionError::DeserializationError(format!("TaggedValue: {e:?}")))?;
let tagged_value: TaggedValue = from_value(value).map_err(|e| ConversionError::DeserializationError(format!("TaggedValue: {e:?}")))?;
GraphCraftNodeInput::Value {
tagged_value: MemoHash::new(tagged_value),
exposed: *exposed,
+265
View File
@@ -0,0 +1,265 @@
use serde::de::{self, DeserializeOwned, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
pub fn to_value<T: Serialize + ?Sized>(value: &T) -> Result<Value, ValueError> {
serde_json::to_value(value).map(Value::from).map_err(ValueError)
}
pub fn from_value<T: DeserializeOwned>(value: &Value) -> Result<T, ValueError> {
serde_json::from_value(value.clone().into()).map_err(ValueError)
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "Self")]
pub enum Value {
None,
Bool(bool),
Int(i128),
Float(f64),
Str(String),
Array(Vec<Value>),
Object(Vec<(String, Value)>),
}
// Using `Serializer::is_human_readable` to determine whether to serialize tagged.
// We assume that any human-readable format is self describing and does not need tags.
impl Serialize for Value {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
if !serializer.is_human_readable() {
return Value::serialize(self, serializer);
}
match self {
Value::None => serializer.serialize_unit(),
Value::Bool(boolean) => serializer.serialize_bool(*boolean),
Value::Int(int) => serializer.serialize_i128(*int),
Value::Float(float) => serializer.serialize_f64(*float),
Value::Str(string) => serializer.serialize_str(string),
Value::Array(array) => serializer.collect_seq(array),
Value::Object(object) => serializer.collect_map(object.iter().map(|(key, value)| (key, value))),
}
}
}
// Using `Deserialize::is_human_readable` to determine whether to deserialize tagged.
// We assume that any human-readable format is self describing and does not need tags.
impl<'de> Deserialize<'de> for Value {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
if !deserializer.is_human_readable() {
return Value::deserialize(deserializer);
}
struct Untagged;
impl<'de> Visitor<'de> for Untagged {
type Value = Value;
fn visit_unit<E>(self) -> Result<Value, E> {
Ok(Value::None)
}
fn visit_none<E>(self) -> Result<Value, E> {
Ok(Value::None)
}
fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Value, D::Error> {
Deserialize::deserialize(deserializer)
}
fn visit_bool<E>(self, value: bool) -> Result<Value, E> {
Ok(Value::Bool(value))
}
fn visit_i64<E>(self, value: i64) -> Result<Value, E> {
Ok(Value::Int(value.into()))
}
fn visit_u64<E>(self, value: u64) -> Result<Value, E> {
Ok(Value::Int(value.into()))
}
fn visit_i128<E>(self, value: i128) -> Result<Value, E> {
Ok(Value::Int(value))
}
fn visit_u128<E: de::Error>(self, value: u128) -> Result<Value, E> {
i128::try_from(value).map(Value::Int).map_err(E::custom)
}
fn visit_f64<E>(self, value: f64) -> Result<Value, E> {
Ok(Value::Float(value))
}
fn visit_str<E>(self, value: &str) -> Result<Value, E> {
Ok(Value::Str(value.to_owned()))
}
fn visit_string<E>(self, value: String) -> Result<Value, E> {
Ok(Value::Str(value))
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Value, A::Error> {
let mut array = Vec::with_capacity(seq.size_hint().unwrap_or(0));
while let Some(value) = seq.next_element()? {
array.push(value);
}
Ok(Value::Array(array))
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Value, A::Error> {
let mut object: Vec<(String, Value)> = Vec::with_capacity(map.size_hint().unwrap_or(0));
while let Some(entry) = map.next_entry()? {
object.push(entry);
}
object.sort_by(|a, b| a.0.cmp(&b.0));
object.dedup_by(|b, a| {
let dedup = b.0 == a.0;
if dedup {
std::mem::swap(&mut a.1, &mut b.1);
}
dedup
});
Ok(Value::Object(object))
}
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a valid Value")
}
}
deserializer.deserialize_any(Untagged)
}
}
impl From<serde_json::Value> for Value {
fn from(value: serde_json::Value) -> Self {
use serde_json::Value as Json;
match value {
Json::Null => Value::None,
Json::Bool(boolean) => Value::Bool(boolean),
Json::Number(number) => {
if let Some(int) = number.as_i64() {
Value::Int(int.into())
} else if let Some(int) = number.as_u64() {
Value::Int(int.into())
} else {
Value::Float(number.as_f64().unwrap_or(f64::NAN))
}
}
Json::String(string) => Value::Str(string),
Json::Array(array) => Value::Array(array.into_iter().map(Into::into).collect()),
Json::Object(object) => Value::Object(object.into_iter().map(|(key, value)| (key, value.into())).collect()),
}
}
}
impl From<Value> for serde_json::Value {
fn from(value: Value) -> Self {
use serde_json::Value as Json;
match value {
Value::None => Json::Null,
Value::Bool(boolean) => Json::Bool(boolean),
Value::Int(int) => match (i64::try_from(int), u64::try_from(int)) {
(Ok(int), _) => int.into(),
(_, Ok(int)) => int.into(),
(Err(_), Err(_)) => (int as f64).into(),
},
Value::Float(float) => float.into(),
Value::Str(string) => Json::String(string),
Value::Array(array) => Json::Array(array.into_iter().map(Into::into).collect()),
Value::Object(object) => Json::Object(object.into_iter().map(|(key, value)| (key, value.into())).collect()),
}
}
}
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub struct ValueError(serde_json::Error);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips_through_postcard() {
let value = serde_json::json!({
"null": null,
"bools": [true, false],
"ints": [0, -1, i64::MIN, u64::MAX],
"floats": [1.5, -0.25, 1e300],
"str": "text",
"empty": { "array": [], "object": {} },
"nested": { "b": [{ "c": 1 }], "a": "z" },
});
let bytes = postcard::to_stdvec(&Value::from(value.clone())).unwrap();
let decoded: Value = postcard::from_bytes(&bytes).unwrap();
assert_eq!(serde_json::Value::from(decoded), value);
}
#[test]
fn round_trips_through_json_untagged() {
let json = serde_json::json!({ "a": [1, -2, 2.5, "s", null, true], "b": {}, "c": [] });
let value = Value::from(json.clone());
let text = serde_json::to_string(&value).unwrap();
assert_eq!(text, serde_json::to_string(&json).unwrap());
assert_eq!(serde_json::to_value(&value).unwrap(), json);
assert_eq!(serde_json::from_str::<Value>(&text).unwrap(), value);
}
#[test]
fn json_object_keys_sort_and_last_duplicate_wins() {
let value: Value = serde_json::from_str(r#"{"b": 1, "a": 2, "b": 3}"#).unwrap();
assert_eq!(value, Value::Object(vec![("a".into(), Value::Int(2)), ("b".into(), Value::Int(3))]));
}
#[derive(Debug, PartialEq, Serialize, Deserialize)]
enum Sample {
Unit,
Newtype(u8),
Tuple(i64, String),
Struct { flag: bool, nested: Option<Box<Sample>> },
}
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Record {
samples: Vec<Sample>,
by_id: std::collections::BTreeMap<u32, f64>,
bytes: Vec<u8>,
letter: char,
unit: (),
big: u64,
}
fn record() -> Record {
Record {
samples: vec![
Sample::Unit,
Sample::Newtype(7),
Sample::Tuple(-3, "t".into()),
Sample::Struct {
flag: true,
nested: Some(Box::new(Sample::Unit)),
},
Sample::Struct { flag: false, nested: None },
],
by_id: [(2, 0.5), (10, -1.)].into(),
bytes: vec![0, 255],
letter: 'x',
unit: (),
big: u64::MAX,
}
}
#[test]
fn from_value_round_trips_serde_types() {
assert_eq!(from_value::<Record>(&to_value(&record()).unwrap()).unwrap(), record());
}
#[test]
fn number_variants_map_to_serde_json_numbers() {
let json = |value: Value| serde_json::Value::from(value);
assert_eq!(json(Value::Int(u64::MAX.into())), serde_json::json!(u64::MAX));
assert_eq!(json(Value::Int(-1)), serde_json::json!(-1));
assert_eq!(json(Value::Int(i128::MAX)), serde_json::json!(i128::MAX as f64));
assert_eq!(json(Value::Float(2.)), serde_json::json!(2.));
assert_eq!(Value::from(serde_json::json!(2.)), Value::Float(2.));
assert_eq!(Value::from(serde_json::json!(2)), Value::Int(2));
}
#[test]
fn postcard_tags_follow_declaration_order() {
let encode = |value: Value| postcard::to_stdvec(&value).unwrap();
assert_eq!(encode(Value::None), [0]);
assert_eq!(encode(Value::Bool(true)), [1, 1]);
assert_eq!(encode(Value::Int(-1)), [2, 1]);
assert_eq!(encode(Value::Float(0.)), [3, 0, 0, 0, 0, 0, 0, 0, 0]);
assert_eq!(encode(Value::Str("ab".into())), [4, 2, b'a', b'b']);
assert_eq!(encode(Value::Array(vec![Value::None])), [5, 1, 0]);
assert_eq!(encode(Value::Object(vec![("k".into(), Value::None)])), [6, 1, 1, b'k', 0]);
}
}
+6
View File
@@ -4,9 +4,15 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
default = ["gpu"]
wasm = ["graphene-std/wasm", "interpreted-executor/wasm", "dep:wasm-bindgen"]
+2 -2
View File
@@ -14,14 +14,14 @@ impl Editor {
environment: Environment,
uuid_random_seed: u64,
resource_storage: Arc<dyn ResourceStorage>,
working_copy_root: Option<std::path::PathBuf>,
document_store: Arc<dyn document_container::store::DocumentStore>,
mut application_io: PlatformApplicationIo,
wake: Wake,
) -> Self {
ENVIRONMENT.set(environment).expect("Editor shoud only be initialized once");
graphene_std::uuid::set_uuid_seed(uuid_random_seed);
let mut dispatcher = Dispatcher::new(resource_storage, working_copy_root);
let mut dispatcher = Dispatcher::new(resource_storage, document_store);
dispatcher.message_handlers.future_message_handler.set_wake(wake);
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
crate::node_graph_executor::replace_application_io(application_io);
+4
View File
@@ -193,5 +193,9 @@ pub const UI_SCALE_DEFAULT: f64 = 1.;
pub const UI_SCALE_MIN: f64 = 0.5;
pub const UI_SCALE_MAX: f64 = 3.;
// DIALOGS
pub const MAX_UNSAVED_DOCUMENTS_IN_DIALOG: usize = 5;
pub const MAX_DOCUMENT_NAME_LENGTH_IN_DIALOG: usize = 60;
// ACTIONS
pub const BLEND_COUNT_PER_LAYER: usize = 10;
+6 -3
View File
@@ -89,16 +89,19 @@ const DEBUG_MESSAGE_BLOCK_LIST: &[MessageDiscriminant] = &[
const DEBUG_MESSAGE_ENDING_BLOCK_LIST: &[&str] = &["PointerMove", "PointerOutsideViewport", "Overlays", "Draw", "CurrentTime", "Time"];
impl Dispatcher {
pub fn new(resource_storage: Arc<dyn ResourceStorage>, working_copy_root: Option<std::path::PathBuf>) -> Self {
pub fn new(resource_storage: Arc<dyn ResourceStorage>, document_store: Arc<dyn document_container::store::DocumentStore>) -> Self {
let mut s = Self::default();
s.message_handlers.resource_storage_message_handler = ResourceStorageMessageHandler::new(resource_storage);
s.message_handlers.portfolio_message_handler.set_working_copy_root(working_copy_root);
s.message_handlers.portfolio_message_handler.set_document_store(document_store);
s
}
#[cfg(test)]
pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self {
let mut s = Self::new(Arc::new(graph_craft::application_io::resource::HashMapResourceStorage::new()), None);
let mut s = Self::new(
Arc::new(graph_craft::application_io::resource::HashMapResourceStorage::new()),
Arc::new(document_container::store::MemoryStore::default()),
);
s.message_handlers.portfolio_message_handler = PortfolioMessageHandler::with_executor(executor);
s
}
+2
View File
@@ -19,3 +19,5 @@ pub mod node_graph_executor;
pub mod test_utils;
pub mod utility_traits;
pub mod utility_types;
pub use document_container::store as document_store;
@@ -1,6 +1,10 @@
use crate::consts::{MAX_DOCUMENT_NAME_LENGTH_IN_DIALOG, MAX_UNSAVED_DOCUMENTS_IN_DIALOG};
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
use std::borrow::Cow;
use std::fmt::Write;
/// A dialog for confirming the closing of all documents viewable via `File -> Close All` in the menu bar.
pub struct CloseAllDocumentsDialog {
pub unsaved_document_names: Vec<String>,
@@ -30,7 +34,26 @@ impl DialogLayoutHolder for CloseAllDocumentsDialog {
impl LayoutHolder for CloseAllDocumentsDialog {
fn layout(&self) -> Layout {
let unsaved_list = "• ".to_string() + &self.unsaved_document_names.join("\n• ");
let mut unsaved_list = "• ".to_string()
+ &self
.unsaved_document_names
.iter()
.take(MAX_UNSAVED_DOCUMENTS_IN_DIALOG)
.map(|name| {
if name.chars().count() > MAX_DOCUMENT_NAME_LENGTH_IN_DIALOG {
Cow::Owned(name.chars().take(MAX_DOCUMENT_NAME_LENGTH_IN_DIALOG).chain(std::iter::once('…')).collect())
} else {
Cow::Borrowed(name.as_str())
}
})
.collect::<Vec<_>>()
.join("\n• ");
let remaining = self.unsaved_document_names.len().saturating_sub(MAX_UNSAVED_DOCUMENTS_IN_DIALOG);
if remaining > 0 {
let s = if remaining == 1 { "" } else { "s" };
let _ = write!(unsaved_list, "\n... and {remaining} more document{s}");
}
Layout(vec![
LayoutGroup::row(vec![TextLabel::new("Save documents before closing them?").bold(true).multiline(true).widget_instance()]),
@@ -118,22 +118,9 @@ pub enum FrontendMessage {
filename: String,
},
TriggerPersistenceReadState,
TriggerPersistenceReadDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
},
TriggerPersistenceWriteState {
state: PersistedState,
},
TriggerPersistenceDeleteDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
},
TriggerPersistenceWriteDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
document: String,
},
TriggerOpenLaunchDocuments,
TriggerLoadPreferences,
TriggerSavePreferences {
@@ -1,7 +1,5 @@
use std::path::PathBuf;
use graph_craft::application_io::resource::ResourceHash;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::utility_types::WorkspacePanelLayout;
use crate::messages::prelude::*;
@@ -12,9 +10,6 @@ pub struct DocumentInfo {
pub id: DocumentId,
pub name: String,
#[serde(default)]
#[cfg_attr(feature = "wasm", tsify(type = "unknown"))]
pub resources: Option<Box<[ResourceHash]>>,
#[serde(default)]
pub path: Option<PathBuf>,
pub is_saved: bool,
}
@@ -1,4 +1,5 @@
pub mod layout_widget;
pub mod tooltip_markdown;
pub mod widgets;
pub mod widget_prelude {
@@ -0,0 +1,78 @@
//! Tooltips render a subset of Markdown: `code` spans, fenced code blocks, `**bold**`, and `*italic*`, where a backslash makes a
//! following backslash, asterisk, or backtick literal. Text from outside the editor goes through these so it shows exactly as written.
/// Escapes text so its backslashes, asterisks, and backticks show as themselves rather than as formatting.
pub fn escape_markdown(text: &str) -> String {
let mut escaped = String::with_capacity(text.len());
for character in text.chars() {
if matches!(character, '\\' | '*' | '`') {
escaped.push('\\');
}
escaped.push(character);
}
escaped
}
/// Wraps text in a code span that nothing inside can close, as in CommonMark: the fence outruns every run of backticks within,
/// and a space pads the text where it would touch the fence or lose its own edge spaces to the span's trimming.
pub fn markdown_code_span(text: &str) -> String {
if text.is_empty() {
return String::new();
}
let longest_run = text.split(|character| character != '`').map(str::len).max().unwrap_or_default();
let fence = "`".repeat(longest_run + 1);
let touches_fence = text.starts_with('`') || text.ends_with('`');
let loses_edge_spaces = text.starts_with(' ') && text.ends_with(' ') && text.contains(|character| character != ' ');
let padding = if touches_fence || loses_edge_spaces { " " } else { "" };
format!("{fence}{padding}{text}{padding}{fence}")
}
/// Wraps text in a fenced code block that nothing inside can close, as in CommonMark: the fence outruns every run of backticks within.
/// The fences are lines of their own, so the block goes at the start of a line.
pub fn markdown_code_block(text: &str) -> String {
if text.is_empty() {
return String::new();
}
let longest_run = text.split(|character| character != '`').map(str::len).max().unwrap_or_default();
let fence = "`".repeat(longest_run.max(2) + 1);
format!("{fence}\n{text}\n{fence}")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escaped_text_holds_no_formatting() {
assert_eq!(escape_markdown("a*b*c"), "a\\*b\\*c");
assert_eq!(escape_markdown("`code`"), "\\`code\\`");
assert_eq!(escape_markdown("ends with \\"), "ends with \\\\");
assert_eq!(escape_markdown("<b>&amp;</b>"), "<b>&amp;</b>", "HTML is the tooltip's to escape");
}
#[test]
fn code_spans_contain_anything() {
assert_eq!(markdown_code_span("x"), "`x`");
assert_eq!(markdown_code_span("a`b"), "``a`b``");
assert_eq!(markdown_code_span("a``b`"), "``` a``b` ```");
assert_eq!(markdown_code_span("`"), "`` ` ``");
assert_eq!(markdown_code_span(" x "), "` x `");
assert_eq!(markdown_code_span(" "), "` `");
assert_eq!(markdown_code_span("a\\"), "`a\\`", "a backslash is literal inside a span");
assert_eq!(markdown_code_span("**<i>**"), "`**<i>**`");
assert_eq!(markdown_code_span(""), "");
}
#[test]
fn code_blocks_contain_anything() {
assert_eq!(markdown_code_block("x\n^"), "```\nx\n^\n```");
assert_eq!(markdown_code_block("```\n**<i>**"), "````\n```\n**<i>**\n````");
assert_eq!(markdown_code_block("`"), "```\n`\n```");
assert_eq!(markdown_code_block(""), "");
}
}
@@ -215,10 +215,6 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
List<Gradient>,
List<String>,
List<f64>,
List<f32>,
List<u32>,
List<u64>,
List<i32>,
List<i64>,
List<bool>,
List<DVec2>,
@@ -275,10 +271,6 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
Item<Gradient>,
Item<String>,
Item<f64>,
Item<f32>,
Item<u32>,
Item<u64>,
Item<i32>,
Item<i64>,
Item<bool>,
Item<DVec2>,
@@ -577,7 +569,7 @@ impl TableItemLayout for Coverage {
impl TableItemLayout for TransferCurve {
fn type_name() -> &'static str {
"Transfer Curve"
"TransferCurve"
}
fn identifier(&self) -> String {
let points = self.points().len();
@@ -842,37 +834,12 @@ impl TableItemLayout for Gradient {
}
}
macro_rules! impl_table_item_layout_for_number {
($($ty:ty => $type_name:literal),* $(,)?) => {
$(
impl TableItemLayout for $ty {
fn type_name() -> &'static str {
$type_name
}
fn identifier(&self) -> String {
format!("{self}")
}
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
}
}
)*
}
}
impl_table_item_layout_for_number!(
u32 => "Number (u32)",
i32 => "Number (i32)",
u64 => "Number (u64)",
i64 => "Number (i64)",
);
impl TableItemLayout for f32 {
impl TableItemLayout for i64 {
fn type_name() -> &'static str {
"Number (f32)"
"Integer"
}
fn identifier(&self) -> String {
// Only infinity widens to f64 without gaining digits, so finite values keep the f32 spelling
if self.is_infinite() { format_f64(*self as f64) } else { format!("{self}") }
format!("{self}")
}
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
@@ -968,26 +935,6 @@ fn string_preview(value: &str) -> String {
first_line.chars().take(MAX_CHARACTERS - 1).chain(['…']).collect()
}
impl TableItemLayout for Option<f64> {
fn type_name() -> &'static str {
"Option<f64>"
}
fn identifier(&self) -> String {
"Option<f64>".to_string()
}
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
let text = match self {
Some(value) => format!("Some({})", format_f64(round_away_float_noise(*value))),
None => "None".to_string(),
};
vec![TextLabel::new(text).selectable(true).narrow(true).widget_instance()]
}
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
vec![LayoutGroup::row(self.value_widgets(PathStep::Element(0), _data))]
}
}
impl TableItemLayout for DVec2 {
fn type_name() -> &'static str {
"Vec2"
@@ -1272,13 +1219,8 @@ macro_rules! known_item_types {
DVec2,
Affine2,
Vec2,
Option<f64>,
f64,
f32,
u8,
u32,
u64,
i32,
i64,
bool,
String,
@@ -1,12 +1,12 @@
use std::collections::VecDeque;
use std::collections::{BTreeMap, HashSet};
use document_graph_storage::Registry;
use document_graph_storage::{Declarations, Registry, Value};
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry, ResourceStorage};
use super::utility_types::network_interface::NodeNetworkInterface;
use super::utility_types::network_interface::editor_delta::{EditorDelta, construct_batch};
use super::utility_types::network_interface::storage_metadata::{StorageMetadataView, collect_network_view_settings};
use super::utility_types::network_interface::storage_metadata::{StorageMetadataView, build_interface_from_storage, collect_network_view_settings};
/// Per-document undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor that is
/// becoming the authoritative history. Owns the dual-stack bookkeeping push/pop/clear and the cursor's stage/retire/move/verify
@@ -25,6 +25,25 @@ pub struct DocumentHistory {
/// future built by `load_document` resolves.
#[derivative(Debug = "ignore")]
storage: Option<document_format::GddV1>,
/// Decoded proto-node declarations for every registry state the cursor can reach, filled at mount
/// and extended on each staging, so a cursor rebuild never touches the byte store.
#[derivative(Debug = "ignore")]
declarations: Declarations,
/// Whether the next commit must convert the whole document rather than stage what the store recorded.
///
/// True when the working copy holds no baseline for a batch to apply to, and whenever the runtime has
/// moved without recording it (an upgrade on open), since the recorded batch would then describe only
/// part of the distance between the two.
needs_whole_document_stage: bool,
}
/// Why [`DocumentHistory::move_cursor`] produced no interface.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CursorMoveError {
/// Nothing to move to, unmounted, or the move itself failed. The cursor did not move.
NotMoved,
/// The cursor moved but the rebuild from it failed. It stays moved unless the caller reverts it.
RebuildFailed,
}
impl DocumentHistory {
@@ -80,9 +99,23 @@ impl DocumentHistory {
self.storage.as_mut()
}
/// Attach (or clear) the `Gdd` working copy once the mount future resolves.
pub fn set_storage(&mut self, storage: Option<document_format::GddV1>) {
self.storage = storage;
/// Attach the `Gdd` working copy once the mount future resolves, with the declarations it references.
pub fn set_storage(&mut self, storage: document_format::GddV1, declarations: Declarations) {
self.needs_whole_document_stage |= storage.registry().node_instances.is_empty();
self.storage = Some(storage);
self.declarations = declarations;
}
/// Marks the working copy as needing a whole-document stage on its next commit, for a change to the
/// runtime that went unrecorded and so cannot be described by the recorded batch.
pub fn require_whole_document_stage(&mut self) {
self.needs_whole_document_stage = true;
}
/// Detach the `Gdd` working copy, dropping its declaration cache with it.
pub fn clear_storage(&mut self) {
self.storage = None;
self.declarations.clear();
}
/// Retire the pending staged hot ops into durable Gdd history as one undo unit. Called at each undo-step
@@ -95,45 +128,45 @@ impl DocumentHistory {
}
}
/// Stage the runtime snapshot into the `Gdd` working copy at each `CommitTransaction`. No-op while
/// unmounted. Proto-node declaration bytes go into `byte_store` (the app-global resource cache). The
/// staged hot ops are retired by [`retire_storage_interaction`](Self::retire_storage_interaction) at
/// undo-step boundaries. `validate` (the `validate_storage_round_trip` preference) gates the per-commit
/// round-trip check, off by default for its perf cost.
pub fn stage_snapshot(
&mut self,
deltas: &[EditorDelta],
interface: &NodeNetworkInterface,
registry: &ResourceRegistry,
view_settings: BTreeMap<String, serde_json::Value>,
legacy_document: &str,
byte_store: &dyn ResourceStorage,
) {
/// Stage a `CommitTransaction` into the `Gdd` working copy: the first commit writes the whole document,
/// every later one stages the `deltas` the store recorded. No-op while unmounted. Proto-node declaration
/// bytes go into `byte_store` (the app-global resource cache). The staged hot ops are retired by
/// [`retire_storage_interaction`](Self::retire_storage_interaction) at undo-step boundaries.
pub fn stage_snapshot(&mut self, deltas: &[EditorDelta], interface: &NodeNetworkInterface, registry: &ResourceRegistry, view_settings: BTreeMap<String, Value>, byte_store: &dyn ResourceStorage) {
let needs_whole_document_stage = self.needs_whole_document_stage;
let Some(storage) = self.storage.as_mut() else { return };
// A working copy that does not hold the document yet has no baseline for a batch of changes to
// apply to, so the first commit writes the whole document and every later one stages only what
// the store recorded. Reading that from the working copy rather than from the caller means a path
// that mounts storage and then commits does not have to know which of the two it is.
let staged = match storage.registry().node_instances.is_empty() {
let staged = match needs_whole_document_stage {
true => Self::stage_whole_document(storage, interface, registry, byte_store),
// An autosave with nothing edited since the last commit still persists the view state below.
false if deltas.is_empty() => Ok(()),
false => Self::stage_recorded(storage, deltas, interface, registry, byte_store),
false if deltas.is_empty() => Ok(Declarations::new()),
// The batch is drained by the time it reaches here, so a failed staging would leave the working copy
// permanently behind. Converting the whole document restages the same edit from whatever the working
// copy holds, including a batch that failed partway through.
false => Self::stage_recorded(storage, deltas, interface, registry, byte_store).or_else(|error| {
log::error!("Staging recorded deltas failed, falling back to a whole document snapshot: {error}");
Self::stage_whole_document(storage, interface, registry, byte_store)
}),
};
if let Err(error) = staged {
log::error!("Storage snapshot staging failed: {error}");
return;
match staged {
Ok(declarations) => {
self.declarations.extend(declarations);
self.needs_whole_document_stage = false;
}
Err(error) => {
log::error!("Storage snapshot staging failed: {error}");
return;
}
}
self.persist_view_state(interface, view_settings, legacy_document);
self.persist_view_state(interface, view_settings);
}
/// Converts the whole document and stages the difference from what the working copy holds.
///
/// Stages without retiring: a tool drag fires several `CommitTransaction`s but is one legacy undo
/// step, so the ops accumulate in the hot log and coalesce at the next undo-step boundary.
fn stage_whole_document(storage: &mut document_format::GddV1, interface: &NodeNetworkInterface, registry: &ResourceRegistry, byte_store: &dyn ResourceStorage) -> Result<(), String> {
fn stage_whole_document(storage: &mut document_format::GddV1, interface: &NodeNetworkInterface, registry: &ResourceRegistry, byte_store: &dyn ResourceStorage) -> Result<Declarations, String> {
let metadata_view = StorageMetadataView::new(interface);
storage
.stage_runtime_snapshot(interface.document_network(), &metadata_view, registry, byte_store)
@@ -152,20 +185,19 @@ impl DocumentHistory {
interface: &NodeNetworkInterface,
registry: &ResourceRegistry,
byte_store: &dyn ResourceStorage,
) -> Result<(), String> {
) -> Result<Declarations, String> {
let peer = storage.session().peer();
let metadata_view = StorageMetadataView::new(interface);
let constructed = construct_batch(deltas, storage.registry(), registry, &metadata_view, peer).map_err(|error| error.to_string())?;
storage
.stage_constructed_ops(constructed.ops, &constructed.declaration_bytes, byte_store)
.map_err(|error| error.to_string())
.stage_constructed_ops(constructed.ops, &constructed.declarations.bytes, byte_store)
.map_err(|error| error.to_string())?;
Ok(constructed.declarations.decoded)
}
/// The parts of a commit that are not the graph: the per-peer view settings, and the legacy bytes the
/// dual-write soak validates the new format against. Both staging paths persist them; they differ
/// only in how the graph ops are derived.
fn persist_view_state(&mut self, interface: &NodeNetworkInterface, view_settings: BTreeMap<String, serde_json::Value>, legacy_document: &str) {
/// The parts of a commit that are not the graph: the per-peer and per-network view settings.
fn persist_view_state(&mut self, interface: &NodeNetworkInterface, view_settings: BTreeMap<String, Value>) {
let Some(storage) = self.storage.as_mut() else { return };
let network_view_settings = storage
@@ -182,38 +214,51 @@ impl DocumentHistory {
{
log::error!("Persisting per-network view settings failed: {error}");
}
if let Err(error) = storage.store_legacy_document(legacy_document.as_bytes()) {
log::error!("Embedding legacy document into working copy failed: {error}");
}
}
/// Move the `Gdd` undo/redo cursor along the retired interaction chain, flushing any open interaction
/// first. Returns a clone of the post-move `Gdd` (`Arc`-shared) so a `'static` rebuild future can read
/// the rewound state while the live document keeps its cursor. `None` when there is nothing to move to,
/// unmounted, or the move failed.
pub fn move_cursor(&mut self, undo: bool) -> Option<document_format::GddV1> {
/// first, and rebuild the interface from the rewound registry using the declaration cache.
pub fn move_cursor(&mut self, undo: bool) -> Result<NodeNetworkInterface, CursorMoveError> {
self.retire_storage_interaction();
let storage = self.storage.as_mut()?;
let storage = self.storage.as_mut().ok_or(CursorMoveError::NotMoved)?;
let moved = if undo {
if !storage.can_undo() {
return None;
return Err(CursorMoveError::NotMoved);
}
storage.undo().map(|_| ())
} else {
if !storage.can_redo() {
return None;
return Err(CursorMoveError::NotMoved);
}
storage.redo().map(|_| ())
};
if let Err(error) = moved {
log::error!("Storage undo/redo cursor move failed: {error}");
return None;
return Err(CursorMoveError::NotMoved);
}
Some(storage.clone())
storage
.registry()
.to_runtime_with_full_metadata(&self.declarations)
.map_err(|error| error.to_string())
.and_then(|(network, node_entries, network_entries)| build_interface_from_storage(network, node_entries, network_entries).map_err(|error| error.to_string()))
.map_err(|error| {
log::error!("Storage undo/redo rebuild failed: {error}");
CursorMoveError::RebuildFailed
})
}
/// Step the cursor back the other way, undoing a [`move_cursor`](Self::move_cursor) in the `undo`
/// direction whose rebuild failed.
pub fn revert_cursor(&mut self, undo: bool) {
let Some(storage) = self.storage.as_mut() else { return };
let reverted = if undo { storage.redo() } else { storage.undo() };
if let Err(error) = reverted {
log::error!("Storage undo/redo cursor revert failed: {error}");
}
}
// Soak round-trip verification (runtime-gated by `validate_storage_round_trip`)
@@ -240,13 +285,7 @@ impl DocumentHistory {
}
};
let target = &conversion.registry;
let declarations = match conversion.declarations() {
Ok(declarations) => declarations,
Err(error) => {
log::error!("storage round-trip: declaration rebuild failed: {error}");
return;
}
};
let declarations = &conversion.declarations;
let stored = storage.registry();
if !stored.value_equal(target) {
@@ -260,7 +299,7 @@ impl DocumentHistory {
panic!("storage round-trip: timestamp order inconsistent between stored and target");
}
let (round_tripped, _entries) = match stored.to_runtime_with_metadata(&declarations) {
let (round_tripped, _entries) = match stored.to_runtime_with_metadata(declarations) {
Ok(result) => result,
Err(error) => {
log::error!("storage round-trip: to_runtime failed: {error}");
@@ -1,10 +1,10 @@
use super::DocumentHistory;
use super::document_diff::diff_networks;
use super::node_graph::document_node_definitions;
use super::utility_types::error::EditorError;
use super::utility_types::misc::{GroupFolderType, SNAP_FUNCTIONS_FOR_BOUNDING_BOXES, SNAP_FUNCTIONS_FOR_PATHS, SnappingOptions, SnappingState};
use super::utility_types::network_interface::{self, NodeNetworkInterface, TransactionStatus};
use super::utility_types::nodes::{CollapsedLayers, LayerStructureEntry, SelectedNodes};
use super::{CursorMoveError, DocumentHistory};
use crate::application::{GRAPHITE_GIT_COMMIT_HASH, generate_uuid};
use crate::consts::{
ASYMPTOTIC_EFFECT, BLEND_COUNT_PER_LAYER, COLOR_OVERLAY_GRAY, DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, GDD_FILE_EXTENSION, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH, SCALE_EFFECT, SCROLLBAR_SPACING,
@@ -32,6 +32,8 @@ use crate::messages::tool::tool_messages::select_tool::SelectToolPointerKeys;
use crate::messages::tool::tool_messages::tool_prelude::Key;
use crate::messages::tool::utility_types::ToolType;
use crate::node_graph_executor::NodeGraphExecutor;
use document_container::AnyContainer;
use document_graph_storage::Declarations;
use glam::{DAffine2, DVec2};
use graph_craft::application_io::resource::ResourceId;
use graph_craft::application_io::wgpu_available;
@@ -148,6 +150,10 @@ pub struct DocumentMessageHandler {
/// Undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor.
#[serde(skip)]
history: DocumentHistory,
/// The document's container in the document store. `None` for a document created this session until its store entry opens.
#[serde(skip)]
#[derivative(Debug = "ignore")]
pub(crate) container: Option<AnyContainer>,
/// Hash of the document snapshot that was most recently saved to disk by the user.
#[serde(skip)]
saved_hash: Option<u64>,
@@ -199,6 +205,7 @@ impl Default for DocumentMessageHandler {
breadcrumb_network_path: Vec::new(),
selection_network_path: Vec::new(),
history: DocumentHistory::default(),
container: None,
saved_hash: None,
auto_saved_hash: None,
layer_range_selection_reference: None,
@@ -406,8 +413,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![] });
self.layer_range_selection_reference = None;
}
DocumentMessage::DocumentHistoryBackward => self.undo_with_history(document_id, viewport, resource_storage, responses),
DocumentMessage::DocumentHistoryForward => self.redo_with_history(document_id, viewport, resource_storage, responses),
DocumentMessage::DocumentHistoryBackward => self.undo_with_history(document_id, viewport, preferences.validate_storage_round_trip, responses),
DocumentMessage::DocumentHistoryForward => self.redo_with_history(document_id, viewport, preferences.validate_storage_round_trip, responses),
DocumentMessage::DocumentStructureChanged => {
if layers_panel_open {
self.network_interface.load_structure();
@@ -563,6 +570,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
responses.add(DocumentMessage::AbortTransaction);
self.node_graph_handler.drag_start = None;
self.node_graph_handler.select_if_not_dragged = None;
self.node_graph_handler.duplicated_in_drag = false;
}
// Abort box selection
else if self.node_graph_handler.box_selection_start.is_some() {
@@ -1808,7 +1816,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
impl DocumentMessageHandler {
/// Build a document handler from a `.gdd` working copy.
pub fn from_storage(interface: NodeNetworkInterface, storage: document_format::GddV1, name: String, path: Option<std::path::PathBuf>) -> Self {
pub fn from_storage(interface: NodeNetworkInterface, storage: document_format::GddV1, declarations: Declarations, name: String, path: Option<std::path::PathBuf>) -> Self {
let mut document = Self {
network_interface: interface,
name,
@@ -1821,7 +1829,7 @@ impl DocumentMessageHandler {
Ok(resource_registry) => document.resources.registry = resource_registry,
Err(error) => log::error!("Opening .gdd: failed to rebuild resource registry: {error}"),
}
document.history.set_storage(Some(storage));
document.history.set_storage(storage, declarations);
document
}
@@ -1833,6 +1841,12 @@ impl DocumentMessageHandler {
self.network_interface.validate_output_names(node_id, node, &path);
}
// Restoring the parallel-array invariant is how the document arrives, not an edit to it, so what the
// fix-ups recorded must not ride along in the first real commit. They still have to reach storage,
// so the next commit converts the whole document rather than staging the batch that follows them.
self.network_interface.discard_deltas();
self.history.require_whole_document_stage();
self.network_interface.load_structure();
}
@@ -2016,9 +2030,14 @@ impl DocumentMessageHandler {
self.history.storage_mut()
}
/// Attach (or clear) the `Gdd` working copy once the mount future resolves.
pub fn set_storage(&mut self, storage: Option<document_format::GddV1>) {
self.history.set_storage(storage);
/// Attach the `Gdd` working copy once the mount future resolves, with the declarations it references.
pub fn set_storage(&mut self, storage: document_format::GddV1, declarations: Declarations) {
self.history.set_storage(storage, declarations);
}
/// Detach the `Gdd` working copy.
pub fn clear_storage(&mut self) {
self.history.clear_storage();
}
/// Retire the pending staged hot ops into durable Gdd history as one undo unit.
@@ -2026,6 +2045,12 @@ impl DocumentMessageHandler {
self.history.retire_storage_interaction();
}
/// Marks the working copy as needing a whole-document stage on its next commit, for a change to the
/// runtime that went unrecorded.
pub(crate) fn require_whole_document_stage(&mut self) {
self.history.require_whole_document_stage();
}
/// Stages what the store recorded since the last commit into the `Gdd` working copy.
///
/// The batch boundary: everything the interface recorded since the last one is this commit's batch.
@@ -2037,20 +2062,19 @@ impl DocumentMessageHandler {
return;
}
let (view_settings, legacy_document) = self.storage_side_channels();
self.history
.stage_snapshot(&deltas, &self.network_interface, &self.resources.registry, view_settings, legacy_document.as_str(), byte_store);
let view_settings = self.storage_view_settings();
self.history.stage_snapshot(&deltas, &self.network_interface, &self.resources.registry, view_settings, byte_store);
if validate {
self.history.verify_round_trip(&self.network_interface, &self.resources.registry);
}
}
/// The per-peer view settings and legacy bytes that ride along with either kind of staging.
fn storage_side_channels(&self) -> (std::collections::BTreeMap<String, serde_json::Value>, String) {
/// The per-peer view settings that ride along with either kind of staging.
fn storage_view_settings(&self) -> std::collections::BTreeMap<String, document_graph_storage::Value> {
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::DocumentSettings;
let view_settings = DocumentSettings {
DocumentSettings {
document_ptz: &self.document_ptz,
render_mode: &self.render_mode,
overlays_visibility: &self.overlays_visibility_settings,
@@ -2058,17 +2082,15 @@ impl DocumentMessageHandler {
snapping_state: &self.snapping_state,
collapsed: &self.collapsed,
}
.to_view_map();
(view_settings, self.serialize_document())
.to_view_map()
}
/// Restore `view_settings` map into the document.
pub fn apply_stored_document_settings(&mut self, view_settings: &std::collections::BTreeMap<String, serde_json::Value>) {
pub fn apply_stored_document_settings(&mut self, view_settings: &std::collections::BTreeMap<String, document_graph_storage::Value>) {
use document_graph_storage::attr::session::doc;
fn decode<T: serde::de::DeserializeOwned>(view_settings: &std::collections::BTreeMap<String, serde_json::Value>, key: &str) -> Option<T> {
view_settings.get(key).and_then(|value| serde_json::from_value(value.clone()).ok())
fn decode<T: serde::de::DeserializeOwned>(view_settings: &std::collections::BTreeMap<String, document_graph_storage::Value>, key: &str) -> Option<T> {
view_settings.get(key).and_then(|value| document_graph_storage::from_value(value).ok())
}
if let Some(value) = decode(view_settings, doc::PTZ) {
@@ -2091,24 +2113,27 @@ impl DocumentMessageHandler {
}
}
/// Move the `Gdd` undo/redo cursor and spawn the async future that rebuilds the
/// interface from the cursor and swaps it in. `had_oracle` records whether the legacy snapshot already
/// applied, so the completion can compare; it travels with the spawned message. Returns whether the
/// cursor moved, so callers know a rebuild is pending.
fn drive_storage_undo_redo(&mut self, document_id: DocumentId, resource_storage: &ResourceStorageMessageHandler, had_oracle: bool, undo: bool, responses: &mut VecDeque<Message>) -> bool {
let Some(gdd) = self.history.move_cursor(undo) else { return false };
responses.add(crate::messages::portfolio::document_storage_io::rebuild_gdd_cursor(
gdd,
resource_storage.resources_mut(),
document_id,
had_oracle,
));
true
/// Move the `Gdd` undo/redo cursor, swap in the interface rebuilt from it, and autosave so the legacy
/// document matches the cursor. `had_oracle` records whether the legacy snapshot already applied, so the
/// rebuild can be compared against it.
fn drive_storage_undo_redo(&mut self, document_id: DocumentId, had_oracle: bool, undo: bool, validate: bool, responses: &mut VecDeque<Message>) {
match self.history.move_cursor(undo) {
Ok(rebuilt) => {
self.apply_gdd_cursor_rebuild(rebuilt, had_oracle, validate, responses);
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
}
Err(CursorMoveError::NotMoved) => {}
// Without the legacy snapshot the interface stayed put, so the cursor has to follow it back.
Err(CursorMoveError::RebuildFailed) => {
if !had_oracle {
self.history.revert_cursor(undo);
}
}
}
}
/// Swap in the interface rebuilt from the `Gdd` cursor. Always overwrites the interface.
pub(crate) fn apply_gdd_cursor_rebuild(&mut self, mut rebuilt: NodeNetworkInterface, had_oracle: bool, validate: bool, responses: &mut VecDeque<Message>) {
fn apply_gdd_cursor_rebuild(&mut self, mut rebuilt: NodeNetworkInterface, had_oracle: bool, validate: bool, responses: &mut VecDeque<Message>) {
rebuilt.copy_all_transient_view_state(&self.network_interface);
std::mem::swap(&mut rebuilt.resolved_types, &mut self.network_interface.resolved_types);
rebuilt.load_structure();
@@ -2419,7 +2444,7 @@ impl DocumentMessageHandler {
paths
}
pub fn undo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, resource_storage: &ResourceStorageMessageHandler, responses: &mut VecDeque<Message>) {
pub fn undo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
let legacy_applied = if let Some(previous_network) = self.undo(viewport, responses) {
self.history.push_redo(previous_network);
true
@@ -2427,7 +2452,7 @@ impl DocumentMessageHandler {
false
};
self.drive_storage_undo_redo(document_id, resource_storage, legacy_applied, true, responses);
self.drive_storage_undo_redo(document_id, legacy_applied, true, validate, responses);
}
/// Installs a history snapshot as the active network interface, carrying over the current view state and structure load, and returns the replaced interface.
@@ -2461,7 +2486,7 @@ impl DocumentMessageHandler {
Some(previous_network)
}
pub fn redo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, resource_storage: &ResourceStorageMessageHandler, responses: &mut VecDeque<Message>) {
pub fn redo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
let legacy_applied = if let Some(previous_network) = self.redo(viewport, responses) {
self.history.push_undo(previous_network);
true
@@ -2469,7 +2494,7 @@ impl DocumentMessageHandler {
false
};
self.drive_storage_undo_redo(document_id, resource_storage, legacy_applied, false, responses);
self.drive_storage_undo_redo(document_id, legacy_applied, false, validate, responses);
}
pub fn redo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
@@ -2804,9 +2829,9 @@ impl DocumentMessageHandler {
self.network_interface.move_node_to_chain_start(&solidify_id, layer, &[], false);
if has_fill && has_stroke {
let (existing_index, new_index) = (0_f64, 1_f64);
let (existing_index, new_index) = (0_i64, 1_i64);
let existing_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(existing_index), false))]);
let existing_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Integer(existing_index), false))]);
let existing_index_id = NodeId::new();
self.network_interface.insert_node(existing_index_id, existing_index_template, &[]);
self.network_interface.move_node_to_chain_start(&existing_index_id, layer, &[], false);
@@ -2828,7 +2853,7 @@ impl DocumentMessageHandler {
self.network_interface.set_display_name(&new_layer_id, original_name, &[]);
}
let new_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(new_index), false))]);
let new_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Integer(new_index), false))]);
let new_index_id = NodeId::new();
self.network_interface.insert_node(new_index_id, new_index_template, &[]);
self.network_interface.move_node_to_chain_start(&new_index_id, new_layer, &[], false);
@@ -287,7 +287,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
// Insert the main chain node (Blend or Morph) depending on whether a blend count is provided, referencing
// its control path input by the Blend template's named position or the Morph proto node's parameter symbol
let (path_input_connector, layer_alias, path_alias) = if let Some(count) = blend_count {
let blend_node_id = modify_inputs.insert_blend_data(layer, count as f64);
let blend_node_id = modify_inputs.insert_blend_data(layer, count as i64);
(InputConnector::node_at_index(blend_node_id, BLEND_PATH_INPUT_INDEX), "Blend", "Blend Path")
} else {
let morph_node_id = modify_inputs.insert_morph_data(layer);
@@ -881,9 +881,9 @@ fn insert_brush_strokes_chain(network_interface: &mut NodeNetworkInterface, laye
let strokes_node = strokes_node_type.node_template_input_override([
Some(NodeInput::value(TaggedValue::Strokes(Vec::new()), false)),
Some(NodeInput::value(TaggedValue::Color(color), false)),
Some(NodeInput::value(TaggedValue::F64(diameter), false)),
Some(NodeInput::value(TaggedValue::F64(hardness), false)),
Some(NodeInput::value(TaggedValue::F64(flow), false)),
Some(NodeInput::value(TaggedValue::Number(diameter), false)),
Some(NodeInput::value(TaggedValue::Number(hardness), false)),
Some(NodeInput::value(TaggedValue::Number(flow), false)),
]);
network_interface.insert_node(strokes_node_id, strokes_node, &[]);
network_interface.set_input(&InputConnector::node_at_index(layer.to_node(), 1), NodeInput::node(strokes_node_id, 0), &[]);
@@ -19,7 +19,7 @@ pub fn update_transform(network_interface: &mut NodeNetworkInterface, node_id: &
);
network_interface.set_input(
&InputConnector::node(*node_id, graphene_std::transform_nodes::transform::RotationInput),
NodeInput::value(TaggedValue::F64(rotation), false),
NodeInput::value(TaggedValue::Number(rotation), false),
&[],
);
network_interface.set_input(
@@ -70,7 +70,7 @@ pub fn get_current_transform(inputs: &[NodeInput]) -> DAffine2 {
} else {
DVec2::ZERO
};
let rotation = if let Some(&TaggedValue::F64(rotation)) = inputs[2].as_value() { rotation } else { 0. };
let rotation = if let Some(&TaggedValue::Number(rotation)) = inputs[2].as_value() { rotation } else { 0. };
let scale = if let Some(&TaggedValue::DVec2(scale)) = inputs[3].as_value() { scale } else { DVec2::ONE };
let skew = if let Some(&TaggedValue::DVec2(skew)) = inputs[4].as_value() { skew } else { DVec2::ZERO };
@@ -94,10 +94,10 @@ impl<'a> ModifyInputsContext<'a> {
self.network_interface.move_node_to_chain_start(&boolean_id, layer, &[], self.import);
}
pub fn insert_blend_data(&mut self, layer: LayerNodeIdentifier, count: f64) -> NodeId {
pub fn insert_blend_data(&mut self, layer: LayerNodeIdentifier, count: i64) -> NodeId {
let blend = resolve_network_node_type("Blend")
.expect("Blend node does not exist")
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::F64(count), false))]);
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::Integer(count), false))]);
let blend_id = NodeId::new();
self.network_interface.insert_node(blend_id, blend, &[]);
@@ -109,7 +109,7 @@ impl<'a> ModifyInputsContext<'a> {
pub fn insert_morph_data(&mut self, layer: LayerNodeIdentifier) -> NodeId {
let morph = resolve_proto_node_type(graphene_std::vector::morph::IDENTIFIER)
.expect("Morph node does not exist")
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::F64(0.5), false))]);
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::Number(0.5), false))]);
let morph_id = NodeId::new();
self.network_interface.insert_node(morph_id, morph, &[]);
@@ -131,7 +131,7 @@ impl<'a> ModifyInputsContext<'a> {
// Add Auto-Tangents node (between Origins to Polyline and Path), with spread=1 and preserve_existing=false
let auto_tangents = resolve_proto_node_type(graphene_std::vector::auto_tangents::IDENTIFIER)
.expect("Auto-Tangents node does not exist")
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(1.), false)), Some(NodeInput::value(TaggedValue::Bool(false), false))]);
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Number(1.), false)), Some(NodeInput::value(TaggedValue::Bool(false), false))]);
let auto_tangents_id = NodeId::new();
self.network_interface.insert_node(auto_tangents_id, auto_tangents, &[]);
self.network_interface.move_node_to_chain_start(&auto_tangents_id, layer, &[], self.import);
@@ -157,13 +157,13 @@ impl<'a> ModifyInputsContext<'a> {
self.network_interface.insert_node(shape_id, shape, &[]);
self.network_interface.move_node_to_chain_start(&shape_id, layer, &[], self.import);
if include_transform {
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
.expect("Transform node does not exist")
if include_fill {
let fill = resolve_proto_node_type(graphene_std::vector_nodes::fill::IDENTIFIER)
.expect("Fill node does not exist")
.default_node_template();
let transform_id = NodeId::new();
self.network_interface.insert_node(transform_id, transform, &[]);
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[], self.import);
let fill_id = NodeId::new();
self.network_interface.insert_node(fill_id, fill, &[]);
self.network_interface.move_node_to_chain_start(&fill_id, layer, &[], self.import);
}
if include_stroke {
@@ -175,13 +175,14 @@ impl<'a> ModifyInputsContext<'a> {
self.network_interface.move_node_to_chain_start(&stroke_id, layer, &[], self.import);
}
if include_fill {
let fill = resolve_proto_node_type(graphene_std::vector_nodes::fill::IDENTIFIER)
.expect("Fill node does not exist")
// Ensure the transform node occurs after the stroke node.
if include_transform {
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
.expect("Transform node does not exist")
.default_node_template();
let fill_id = NodeId::new();
self.network_interface.insert_node(fill_id, fill, &[]);
self.network_interface.move_node_to_chain_start(&fill_id, layer, &[], self.import);
let transform_id = NodeId::new();
self.network_interface.insert_node(transform_id, transform, &[]);
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[], self.import);
}
}
@@ -193,14 +194,14 @@ impl<'a> ModifyInputsContext<'a> {
Some(NodeInput::value(TaggedValue::None, false)),
Some(NodeInput::value(TaggedValue::String(text), false)),
Some(NodeInput::value(TaggedValue::Resource(font_resource_id), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.font_size), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.line_height_ratio), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.letter_spacing), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.letter_tilt), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.font_size), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.line_height_ratio), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.letter_spacing), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.letter_tilt), false)),
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_width.is_some()), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.max_width.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.max_width.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_height.is_some()), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.max_height.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.max_height.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::TextAlign(typesetting.align), false)),
]);
let text_to_vector = resolve_proto_node_type(graphene_std::text::text_to_vector::IDENTIFIER)
@@ -526,7 +527,7 @@ impl<'a> ModifyInputsContext<'a> {
);
self.set_input_with_refresh(
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::OpacityInput),
NodeInput::value(TaggedValue::F64(opacity * 100.), false),
NodeInput::value(TaggedValue::Number(opacity * 100.), false),
false,
);
}
@@ -555,7 +556,7 @@ impl<'a> ModifyInputsContext<'a> {
);
self.set_input_with_refresh(
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::FillInput),
NodeInput::value(TaggedValue::F64(fill * 100.), false),
NodeInput::value(TaggedValue::Number(fill * 100.), false),
false,
);
}
@@ -666,7 +667,7 @@ impl<'a> ModifyInputsContext<'a> {
}
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_positions::PositionsInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(positions), false), false);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Numbers(positions), false), false);
}
/// The 'Gradient Midpoints' counterpart of [`Self::gradient_positions_set`], likewise update-only.
@@ -690,7 +691,7 @@ impl<'a> ModifyInputsContext<'a> {
}
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_midpoints::MidpointsInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(midpoints), false), false);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Numbers(midpoints), false), false);
}
/// Update the transform to map the unit gradient ((0,0), (1, 0)) to the geometry's local space.
@@ -865,7 +866,7 @@ impl<'a> ModifyInputsContext<'a> {
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintInput);
self.set_input_with_refresh(input_connector, NodeInput::value(color.map_or_else(TaggedValue::no_paint, TaggedValue::Color), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::WeightInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.weight), false), true);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.weight), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::AlignInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeAlign(stroke.align), false), false);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::CapInput);
@@ -873,11 +874,11 @@ impl<'a> ModifyInputsContext<'a> {
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::JoinInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeJoin(stroke.join), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::MiterLimitInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.join_miter_limit), false), false);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.join_miter_limit), false), false);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashPatternInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::DashPattern(stroke.dash_lengths), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.dash_offset), false), true);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.dash_offset), false), true);
}
/// Update the transform value of the upstream Transform node based a change to its existing value and the given parent transform.
@@ -3,7 +3,7 @@ mod document_history;
mod document_message;
mod document_message_handler;
#[cfg(test)]
mod storage_tests;
pub(crate) mod storage_tests;
pub mod data_panel;
pub mod graph_operation;
@@ -15,7 +15,7 @@ pub mod resource;
pub mod utility_types;
pub(crate) use document_diff::diff_networks;
pub(crate) use document_history::DocumentHistory;
pub(crate) use document_history::{CursorMoveError, DocumentHistory};
#[doc(inline)]
pub use document_message::{DocumentMessage, DocumentMessageDiscriminant};
#[doc(inline)]
@@ -422,7 +422,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
let half_viewport = viewport.center_in_viewport_space().into_dvec2();
let start_offset = viewport_to_document.transform_vector2(self.mouse_position - half_viewport);
let end_offset = viewport_to_document.transform_vector2(ipp.mouse.position - half_viewport);
let angle = start_offset.angle_to(end_offset);
let angle = start_offset.try_angle_to(end_offset).unwrap_or(0.);
tilt_raw_not_snapped + angle
};
@@ -40,17 +40,30 @@ pub struct NodePropertiesContext<'a> {
impl NodePropertiesContext<'_> {
pub fn call_widget_override(&mut self, node_id: &NodeId, index: usize) -> Option<Vec<LayoutGroup>> {
let input_properties_row = self.network_interface.persistent_input_metadata(node_id, index, self.selection_network_path)?;
if let Some(widget_override) = &input_properties_row.widget_override {
let Some(widget_override_lambda) = INPUT_OVERRIDES.get(widget_override) else {
log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override");
// The stored override wins, falling back to the definition's own so documents saved before it gained one still
// pick it up. Only `Custom` is recovered, since the other kinds also need input data stored at insertion time.
let widget_override = input_properties_row.widget_override.clone().or_else(|| {
let implementation = self.network_interface.implementation(node_id, self.selection_network_path)?;
let DocumentNodeImplementation::ProtoNode(proto_node_identifier) = implementation else {
return None;
};
widget_override_lambda(*node_id, index, self)
.map_err(|error| log::error!("Error in widget override lambda: {error}"))
.ok()
} else {
None
}
let metadata = registry::NODE_METADATA.lock().unwrap();
let field = metadata.get(proto_node_identifier)?.fields.get(index)?;
match field.widget_override {
registry::RegistryWidgetOverride::Custom(name) => Some(name.to_string()),
_ => None,
}
})?;
let Some(widget_override_lambda) = INPUT_OVERRIDES.get(&widget_override) else {
log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override");
return None;
};
widget_override_lambda(*node_id, index, self)
.map_err(|error| log::error!("Error in widget override lambda: {error}"))
.ok()
}
}
@@ -348,14 +361,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// 2: Max (clamp subpath count to at least 1 for empty path case)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::F64(1.), false)],
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 2)),
..Default::default()
},
// 3: Floor (integer count per subpath)
// 3: As Number (the integer count enters the network's decimal math)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
inputs: vec![NodeInput::import(item!(f64), 1)],
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER),
inputs: vec![NodeInput::import(item!(i64), 1)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 13)),
..Default::default()
},
@@ -369,14 +382,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// 5: Subtract (count - 1, open subpath denominator)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::subtract::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::F64(1.), false)],
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 14)),
..Default::default()
},
// 6: Read Index (current repetition index)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(context::read_index::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::U32(0), false)],
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::Integer(0), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 7)),
..Default::default()
},
@@ -425,7 +438,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// 13: Multiply (fraction × 0.9999999999 to avoid overflowing to the next subpath)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::F64(0.9999999999), false)],
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::Number(0.9999999999), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 7)),
..Default::default()
},
@@ -459,14 +472,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// 17: Max (clamp count to at least 1)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::F64(1.), false)],
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 13)),
..Default::default()
},
// 18: Max (clamp open-path denominator to at least 1 to avoid division by zero when count = 1)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::F64(1.), false)],
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 14)),
..Default::default()
},
@@ -479,7 +492,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
}),
inputs: vec![
NodeInput::type_default(list!(Vector), true),
NodeInput::value(TaggedValue::F64(10.), false),
NodeInput::value(TaggedValue::Integer(10), false),
NodeInput::value(TaggedValue::Bool(Default::default()), false),
NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false),
NodeInput::type_default(item!(Vector), false),
@@ -801,7 +814,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
inputs: vec![
NodeInput::import(item!(String), 0),
NodeInput::import(item!(String), 1),
NodeInput::import(item!(f64), 2),
NodeInput::import(item!(i64), 2),
NodeInput::import(item!(bool), 3),
NodeInput::import(item!(bool), 4),
],
@@ -811,14 +824,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
// Node 1: item_at_index at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them)
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::item_at_index::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 0)),
..Default::default()
},
// Node 2: remove_at_index at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::remove_at_index::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 2)),
..Default::default()
@@ -833,7 +846,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
inputs: vec![
NodeInput::value(TaggedValue::String(String::new()), true),
NodeInput::value(TaggedValue::String(String::new()), false),
NodeInput::value(TaggedValue::F64(0.), false),
NodeInput::value(TaggedValue::Integer(0), false),
NodeInput::value(TaggedValue::Bool(false), false),
NodeInput::value(TaggedValue::Bool(false), false),
],
@@ -927,7 +940,6 @@ fn static_node_properties() -> NodeProperties {
map.insert("offset_path_properties".to_string(), Box::new(node_properties::offset_path_properties));
map.insert("selective_color_properties".to_string(), Box::new(node_properties::selective_color_properties));
map.insert("exposure_properties".to_string(), Box::new(node_properties::exposure_properties));
map.insert("math_properties".to_string(), Box::new(node_properties::math_properties));
map.insert("format_number_properties".to_string(), Box::new(node_properties::format_number_properties));
map.insert("string_capitalization_properties".to_string(), Box::new(node_properties::string_capitalization_properties));
map.insert("rectangle_properties".to_string(), Box::new(node_properties::rectangle_properties));
@@ -1098,6 +1110,11 @@ fn static_input_properties() -> InputProperties {
))])
}),
);
map.insert(
// A type-witness input, whose stored value's type selects the node's row: the dropdown lists the types the rows accept there
"type_choice".to_string(),
Box::new(|node_id, index, context| Ok(vec![node_properties::type_choice_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context))])),
);
map.insert(
"vec2".to_string(),
Box::new(|node_id, index, context| {
@@ -1351,7 +1368,7 @@ fn static_input_properties() -> InputProperties {
let Some(input) = document_node.inputs.get(index) else {
return Err("Input not found in transform rotation input override".to_string());
};
if let Some(&TaggedValue::F64(val)) = input.as_non_exposed_value() {
if let Some(&TaggedValue::Number(val)) = input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(val))
@@ -1360,7 +1377,7 @@ fn static_input_properties() -> InputProperties {
.range_min(Some(-180.))
.range_max(Some(180.))
.on_update(node_properties::update_value_at_index(
|number_input: &NumberInput| TaggedValue::F64(number_input.value.unwrap()),
|number_input: &NumberInput| TaggedValue::Number(number_input.value.unwrap()),
node_id,
index,
))
@@ -1448,6 +1465,22 @@ fn static_input_properties() -> InputProperties {
"text_area".to_string(),
Box::new(|node_id, index, context| Ok(vec![LayoutGroup::row(node_properties::text_area_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context)))])),
);
map.insert(
// A math expression, flagged with a warning icon while it fails to parse
"math_expression".to_string(),
Box::new(|node_id, index, context| {
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
Ok(vec![LayoutGroup::row(node_properties::math_expression_widget(info, false))])
}),
);
map.insert(
// Like `math_expression`, where a lone reducer token like `+` or `min` applied across the node's items is also valid
"math_expression_or_reducer".to_string(),
Box::new(|node_id, index, context| {
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
Ok(vec![LayoutGroup::row(node_properties::math_expression_widget(info, true))])
}),
);
map.insert(
"text_font".to_string(),
Box::new(|node_id, index, context| {
@@ -60,6 +60,7 @@ pub enum NodeGraphMessage {
DisconnectInput {
input_connector: InputConnector,
},
DisconnectRootNode,
EnterNestedNetwork,
DuplicateSelectedNodes,
ExposeInput {
@@ -57,6 +57,8 @@ pub struct NodeGraphMessageHandler {
widgets: [LayoutGroup; 2],
/// Used to add a transaction for the first node move when dragging.
begin_dragging: bool,
/// Track if nodes were duplicated during the current drag via Alt-drag.
pub duplicated_in_drag: bool,
/// Used to prevent entering a nested network if the node is dragged after double clicking
node_has_moved_in_drag: bool,
/// If dragging the selected nodes, this stores the starting position both in viewport and node graph coordinates,
@@ -406,20 +408,12 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
NodeGraphMessage::DisconnectInput { input_connector } => {
network_interface.disconnect_input(&input_connector, selection_network_path);
}
NodeGraphMessage::DisconnectRootNode => {
network_interface.start_previewing_without_restore(selection_network_path);
}
NodeGraphMessage::DuplicateSelectedNodes => {
let all_selected_nodes = network_interface.upstream_chain_nodes(selection_network_path);
let copy_ids = all_selected_nodes.iter().enumerate().map(|(new, id)| (*id, NodeId(new as u64))).collect::<HashMap<NodeId, NodeId>>();
// Copy the selected nodes
let nodes = network_interface.copy_nodes(&copy_ids, selection_network_path).collect::<Vec<_>>();
let new_ids = nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect::<HashMap<_, _>>();
responses.add(DocumentMessage::AddTransaction);
responses.add(NodeGraphMessage::AddNodes { nodes, new_ids: new_ids.clone() });
responses.add(NodeGraphMessage::SelectedNodesSet {
nodes: new_ids.values().cloned().collect(),
});
Self::duplicate_selected_nodes(network_interface, selection_network_path, responses);
}
NodeGraphMessage::EnterNestedNetwork => {
// Do not enter the nested network if the node was dragged
@@ -796,6 +790,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
if self.drag_start.is_some() {
self.drag_start = None;
self.select_if_not_dragged = None;
self.duplicated_in_drag = false;
responses.add(DocumentMessage::AbortTransaction);
responses.add(NodeGraphMessage::SelectedNodesSet {
nodes: self.selection_before_pointer_down.clone(),
@@ -1041,6 +1036,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
.collect::<Vec<_>>();
self.begin_dragging = true;
self.node_has_moved_in_drag = false;
self.duplicated_in_drag = false;
self.update_node_graph_hints(responses);
}
@@ -1096,8 +1092,18 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
self.wire_in_progress_to_connector = Some(point);
// Disconnect if the wire was previously connected to an input
if let Some(disconnecting) = &self.disconnecting {
// Previewing leaves the export alone, so dragging its wire off is an ordinary disconnect
responses.add(NodeGraphMessage::DisconnectInput { input_connector: *disconnecting });
let mut disconnect_root_node = false;
if let Previewing::Yes { root_node_to_restore } = network_interface.previewing(selection_network_path)
&& root_node_to_restore.is_some()
&& *disconnecting == InputConnector::Export(0)
{
disconnect_root_node = true;
}
if disconnect_root_node {
responses.add(NodeGraphMessage::DisconnectRootNode);
} else {
responses.add(NodeGraphMessage::DisconnectInput { input_connector: *disconnecting });
}
// Update the frontend that the node is disconnected
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SendGraph);
@@ -1158,13 +1164,17 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
if self.begin_dragging {
self.begin_dragging = false;
if ipp.keyboard.get(Key::Alt as usize) {
responses.add(NodeGraphMessage::DuplicateSelectedNodes);
// Duplicate nodes inline within the existing PointerDown transaction.
// This means a completed Alt-drag is one undo step, and aborting (right-click / Escape)
// rolls back both the duplication and the move with a single plain AbortTransaction.
Self::duplicate_selected_nodes(network_interface, selection_network_path, responses);
// Duplicating sets a 2x2 offset, so shift the nodes back to the original position
responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount {
graph_delta: IVec2::new(-2, -2),
rubber_band: false,
});
self.preview_on_mouse_up = None;
self.duplicated_in_drag = true;
}
}
@@ -1470,6 +1480,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
self.drag_start = None;
self.begin_dragging = false;
self.duplicated_in_drag = false;
self.box_selection_start = None;
self.wire_in_progress_from_connector = None;
@@ -1516,15 +1527,17 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
// Collect the distance to move the shaken nodes after the undo
let graph_delta = IVec2::new(((point.x - drag_start.start_x) / 24.).round() as i32, ((point.y - drag_start.start_y) / 24.).round() as i32);
// Keep the incremental rounding baseline in sync with the total shift reapplied below
drag_start.round_x = graph_delta.x;
drag_start.round_y = graph_delta.y;
if !self.duplicated_in_drag {
// Keep the incremental rounding baseline in sync with the total shift reapplied below
drag_start.round_x = graph_delta.x;
drag_start.round_y = graph_delta.y;
// Undo to the state of the graph before shaking
responses.add(DocumentMessage::AbortTransaction);
// Undo to the state of the graph before shaking (skip for Alt-drag to avoid removing the duplicates)
responses.add(DocumentMessage::AbortTransaction);
// Add a history step to abort to the state before shaking if right clicked
responses.add(DocumentMessage::StartTransaction);
// Add a history step to abort to the state before shaking if right clicked
responses.add(DocumentMessage::StartTransaction);
}
let Some(selected_nodes) = network_interface.selected_nodes_in_nested_network(selection_network_path) else {
log::error!("Could not get selected nodes in ShakeNode");
@@ -1609,7 +1622,9 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
}
}
responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { graph_delta, rubber_band: false });
if !self.duplicated_in_drag {
responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { graph_delta, rubber_band: false });
}
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SendGraph);
}
@@ -2247,6 +2262,20 @@ impl NodeGraphMessageHandler {
common
}
fn duplicate_selected_nodes(network_interface: &NodeNetworkInterface, selection_network_path: &[NodeId], responses: &mut VecDeque<Message>) {
let all_selected_nodes = network_interface.upstream_chain_nodes(selection_network_path);
let copy_ids = all_selected_nodes.iter().enumerate().map(|(new, id)| (*id, NodeId(new as u64))).collect::<HashMap<NodeId, NodeId>>();
let nodes = network_interface.copy_nodes(&copy_ids, selection_network_path).collect::<Vec<_>>();
let new_ids = nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect::<HashMap<_, _>>();
responses.add(NodeGraphMessage::AddNodes { nodes, new_ids: new_ids.clone() });
responses.add(NodeGraphMessage::SelectedNodesSet {
nodes: new_ids.values().cloned().collect(),
});
}
/// Send the cached layout to the frontend for the control bar at the top of the node panel
fn send_node_bar_layout(&self, responses: &mut VecDeque<Message>) {
responses.add(LayoutMessage::SendLayout {
@@ -2678,8 +2707,8 @@ impl NodeGraphMessageHandler {
wire_path_update: None,
}));
if let Some(wire_to_preview) = network_interface.wire_to_preview(graph_wire_style, breadcrumb_network_path) {
added_wires.push(wire_to_preview);
if let Some(wire_to_root) = network_interface.wire_to_root(graph_wire_style, breadcrumb_network_path) {
added_wires.push(wire_to_root);
} else {
added_wires.push(WirePathUpdate {
id: NodeId(u64::MAX),
@@ -2730,8 +2759,11 @@ impl NodeGraphMessageHandler {
log::error!("Could not get position for node: {node_id}");
continue;
};
// Asked of the preview itself rather than inferred from the export, which previewing no longer rewires
let previewed = matches!(network_interface.previewing(breadcrumb_network_path), Previewing::Yes { previewed } if previewed.node_id == node_id);
let is_export = network_interface
.input_from_connector(&InputConnector::Export(0), breadcrumb_network_path)
.is_some_and(|export| export.as_node().is_some_and(|export_node_id| node_id == export_node_id));
let is_root_node = network_interface.root_node(breadcrumb_network_path).is_some_and(|root_node| root_node.node_id == node_id);
let previewed = is_export && !is_root_node;
let locked = network_interface.is_locked(&node_id, breadcrumb_network_path);
@@ -2913,6 +2945,7 @@ impl Default for NodeGraphMessageHandler {
widgets: [LayoutGroup::row(Vec::new()), LayoutGroup::row(Vec::new())],
drag_start: None,
begin_dragging: false,
duplicated_in_drag: false,
node_has_moved_in_drag: false,
shift_without_push: false,
box_selection_start: None,
@@ -2944,6 +2977,7 @@ impl PartialEq for NodeGraphMessageHandler {
&& self.widgets == other.widgets
&& self.drag_start == other.drag_start
&& self.begin_dragging == other.begin_dragging
&& self.duplicated_in_drag == other.duplicated_in_drag
&& self.node_has_moved_in_drag == other.node_has_moved_in_drag
&& self.box_selection_start == other.box_selection_start
&& self.initial_disconnecting == other.initial_disconnecting
@@ -2,6 +2,7 @@
use super::document_node_definitions::{NODE_OVERRIDES, NodePropertiesContext};
use super::utility_types::FrontendGraphDataType;
use crate::messages::layout::utility_types::tooltip_markdown::{escape_markdown, markdown_code_block, markdown_code_span};
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
@@ -24,7 +25,7 @@ use graphene_std::raster::{
AdjustmentChannel, BlendMode, CellularDistanceFunction, CellularReturnType, Color, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RedGreenBlueAlpha,
RelativeAbsolute, SelectiveColorChoice, TonalRange,
};
use graphene_std::raster_types::Image;
use graphene_std::raster_types::{CPU, GPU, Image, Raster};
use graphene_std::text::{Font, TextAlign};
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve;
@@ -38,7 +39,9 @@ use graphene_std::vector::style::{
build_transform_with_y_preservation,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
use graphene_std::{Artboard, Graphic, Vector};
use graphene_std::{NodeParameter, ParameterRef};
use math_parser::parser::MessagePart;
use std::path::PathBuf;
pub(crate) fn string_properties(text: &str) -> Vec<LayoutGroup> {
@@ -170,14 +173,19 @@ pub fn start_widgets(parameter_widgets_info: &ParameterWidgetsInfo) -> Vec<Widge
widgets
}
/// The numeric bounds and widget mode of a number parameter, sourced from the node's field metadata.
/// The presentation of a parameter's widget, sourced from the node's field metadata: numeric bounds, widget modes, and unit of measure.
#[derive(Clone, Copy, Default)]
pub(crate) struct NumberOptions {
pub(crate) struct ParameterOptions {
pub soft_min: Option<f64>,
pub soft_max: Option<f64>,
pub hard_min: Option<f64>,
pub hard_max: Option<f64>,
pub slider: bool,
pub multiline: bool,
pub progression: bool,
pub unit: Option<&'static str>,
pub display_decimal_places: Option<u32>,
pub step: Option<f64>,
}
/// The values a range slider's two ends map to linearly and the one its double-click restores, if known.
@@ -206,29 +214,25 @@ fn definition_default_number(parameter_widgets_info: &ParameterWidgetsInfo) -> O
let input = resolve_document_node_type(&identifier)?.node_template.inputs.get(parameter_widgets_info.index)?;
match input.as_value()? {
TaggedValue::F64(value) => Some(*value),
TaggedValue::F32(value) => Some(*value as f64),
TaggedValue::Number(value) => Some(*value),
_ => None,
}
}
pub(crate) fn property_from_type(
node_id: NodeId,
index: usize,
ty: &Type,
number_options: NumberOptions,
unit: Option<&str>,
display_decimal_places: Option<u32>,
step: Option<f64>,
context: &mut NodePropertiesContext,
) -> Result<Vec<LayoutGroup>, Vec<LayoutGroup>> {
let NumberOptions {
pub(crate) fn property_from_type(node_id: NodeId, index: usize, ty: &Type, options: ParameterOptions, context: &mut NodePropertiesContext) -> Result<Vec<LayoutGroup>, Vec<LayoutGroup>> {
let ParameterOptions {
soft_min,
soft_max,
hard_min,
hard_max,
slider,
} = number_options;
multiline,
progression,
unit,
display_decimal_places,
step,
} = options;
let mut number_input = NumberInput::default();
if slider {
number_input = number_input.mode_range();
@@ -243,10 +247,8 @@ pub(crate) fn property_from_type(
number_input = number_input.step(step);
}
// Applies the parameter's typing clamp and slider extent to the widget, given the type's own default bounds.
// Per end: the clamp is the hard bound (or unbounded if only a soft bound is given, since soft is a suggested
// extent rather than a limit), and the slider extent is the soft bound, each falling back to the hard bound
// and then to the type default when unspecified. An end with any explicit bound ignores the type default.
// The hard bound sets the typing clamp, and the soft bound (or the hard one) the slider extent, each falling
// back to the passed-in default. A soft bound alone leaves that end unclamped, since soft is only a suggestion.
let bounded = |number_input: NumberInput, type_min: f64, type_max: f64| {
let clamp_min = hard_min.unwrap_or(if soft_min.is_some() { f64::NEG_INFINITY } else { type_min });
let clamp_max = hard_max.unwrap_or(if soft_max.is_some() { f64::INFINITY } else { type_max });
@@ -260,12 +262,11 @@ pub(crate) fn property_from_type(
.range_max(Some(extent_max).filter(|bound| bound.is_finite()))
};
// A range-mode number clamped at both ends by its own hard bounds, or by a type whose extent is a true limit, becomes a range
// slider beside its number input, unless a soft bound lets typing pass the slider. An Angle's type default is no such limit.
// A range-mode number hard-clamped at both ends becomes a range slider beside its number input, unless a soft bound lets typing pass it
let no_soft_bounds = soft_min.is_none() && soft_max.is_none();
let hard_both_ends = hard_min.is_some() && hard_max.is_some();
let number_or_slider = |default_info: ParameterWidgetsInfo, number_input: NumberInput, type_limits: bool| -> LayoutGroup {
let fixed_extent = number_input.mode == NumberInputMode::Range && no_soft_bounds && (hard_both_ends || type_limits);
let number_or_slider = |default_info: ParameterWidgetsInfo, number_input: NumberInput| -> LayoutGroup {
let fixed_extent = number_input.mode == NumberInputMode::Range && no_soft_bounds && hard_both_ends;
match (number_input.min, number_input.max) {
(Some(min), Some(max)) if fixed_extent && min.is_finite() && max.is_finite() && min < max => {
let default = definition_default_number(&default_info);
@@ -298,112 +299,98 @@ pub(crate) fn property_from_type(
let mut extra_widgets = vec![];
let widgets = match ty {
Type::Concrete(concrete_type) => {
match concrete_type.alias.as_ref().map(|x| x.as_ref()) {
// Aliased types (ambiguous values)
Some("Percentage") | Some("PercentageF32") => number_or_slider(default_info, bounded(number_input.percentage(), 0., 100.), true),
Some("SignedPercentage") | Some("SignedPercentageF32") => number_or_slider(default_info, bounded(number_input.percentage(), -100., 100.), true),
Some("Angle") | Some("AngleF32") => number_or_slider(default_info, bounded(number_input.mode_range(), -180., 180.).unit(unit.unwrap_or("°")), false),
Some("Multiplier") => number_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY).unit(unit.unwrap_or("x"))).into(),
Some("PixelLength") => number_widget(default_info, bounded(number_input, 0., f64::INFINITY).unit(unit.unwrap_or(" px"))).into(),
Some("Length") => number_widget(default_info, bounded(number_input, 0., f64::INFINITY)).into(),
Some("Fraction") => number_or_slider(default_info, bounded(number_input.mode_range(), 0., 1.), true),
Some("Progression") => progression_widget(default_info, bounded(number_input, 0., f64::INFINITY)).into(),
Some("SignedInteger") => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
Some("SeedValue") => number_widget(default_info, bounded(number_input.int(), 0., f64::INFINITY)).into(),
Some("PixelSize") => vec2_widget(default_info, "X", "Y", unit.unwrap_or(" px"), None, false),
Some("TextArea") => text_area_widget(default_info).into(),
use std::any::TypeId;
// For all other types, use TypeId-based matching
_ => {
use std::any::TypeId;
// The compiler peels a rank-0 `Item` cell to its element before this arm runs, so widgets dispatch on the bare element `T`
fn id_is<T: 'static>(id: TypeId) -> bool {
id == TypeId::of::<T>()
}
// The compiler peels a rank-0 `Item` cell to its element before this arm runs, so widgets dispatch on the bare element `T`
fn id_is<T: 'static>(id: TypeId) -> bool {
id == TypeId::of::<T>()
}
match concrete_type.id {
// ===============
// PRIMITIVE TYPES
// ===============
Some(x) if id_is::<f64>(x) || id_is::<f32>(x) => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY), false),
Some(x) if id_is::<u32>(x) => number_widget(default_info, bounded(number_input.int(), 0., f64::from(u32::MAX))).into(),
Some(x) if id_is::<u64>(x) => number_widget(default_info, bounded(number_input.int(), 0., f64::INFINITY)).into(),
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
Some(x) if id_is::<String>(x) => text_widget(default_info).into(),
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", "", None, false),
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
// ============
// STRUCT TYPES
// ============
Some(x) if id_is::<Font>(x) => font_widget(default_info),
Some(x) if id_is::<TransferCurve>(x) => transfer_curve_widget(default_info),
Some(x) if id_is::<Footprint>(x) => footprint_widget(default_info, &mut extra_widgets),
Some(x) if id_is::<Box<VectorModification>>(x) => vector_modification_widget(default_info).into(),
Some(x) if id_is::<Image<Color>>(x) => image_data_widget(default_info).into(),
Some(x) if id_is::<Resource>(x) => resource_widget(default_info, Vec::new()).into(),
// ===============================
// MANUALLY IMPLEMENTED ENUM TYPES
// ===============================
Some(x) if id_is::<ReferencePoint>(x) => reference_point_widget(default_info, false).into(),
Some(x) if id_is::<BlendMode>(x) => blend_mode_widget(default_info),
// =========================
// AUTO-GENERATED ENUM TYPES
// =========================
Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientInterpolation>(x) => enum_choice::<GradientInterpolation>().for_socket(default_info).property_row(),
Some(x) if id_is::<RealTimeMode>(x) => enum_choice::<RealTimeMode>().for_socket(default_info).property_row(),
Some(x) if id_is::<RedGreenBlue>(x) => enum_choice::<RedGreenBlue>().for_socket(default_info).property_row(),
Some(x) if id_is::<RedGreenBlueAlpha>(x) => enum_choice::<RedGreenBlueAlpha>().for_socket(default_info).property_row(),
Some(x) if id_is::<XY>(x) => enum_choice::<XY>().for_socket(default_info).property_row(),
Some(x) if id_is::<StringCapitalization>(x) => enum_choice::<StringCapitalization>().for_socket(default_info).property_row(),
Some(x) if id_is::<TextDenomination>(x) => enum_choice::<TextDenomination>().for_socket(default_info).property_row(),
Some(x) if id_is::<NoiseType>(x) => enum_choice::<NoiseType>().for_socket(default_info).property_row(),
Some(x) if id_is::<FractalType>(x) => enum_choice::<FractalType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<CellularDistanceFunction>(x) => enum_choice::<CellularDistanceFunction>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<CellularReturnType>(x) => enum_choice::<CellularReturnType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<DomainWarpType>(x) => enum_choice::<DomainWarpType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<RelativeAbsolute>(x) => enum_choice::<RelativeAbsolute>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<TonalRange>(x) => enum_choice::<TonalRange>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<AdjustmentChannel>(x) => enum_choice::<AdjustmentChannel>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<HueSaturationRange>(x) => enum_choice::<HueSaturationRange>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<GridType>(x) => enum_choice::<GridType>().for_socket(default_info).property_row(),
Some(x) if id_is::<StrokeCap>(x) => enum_choice::<StrokeCap>().for_socket(default_info).property_row(),
Some(x) if id_is::<StrokeJoin>(x) => enum_choice::<StrokeJoin>().for_socket(default_info).property_row(),
Some(x) if id_is::<StrokeAlign>(x) => enum_choice::<StrokeAlign>().for_socket(default_info).property_row(),
Some(x) if id_is::<ArcType>(x) => enum_choice::<ArcType>().for_socket(default_info).property_row(),
Some(x) if id_is::<RowsOrColumns>(x) => enum_choice::<RowsOrColumns>().for_socket(default_info).property_row(),
Some(x) if id_is::<TextAlign>(x) => enum_choice::<TextAlign>().for_socket(default_info).property_row(),
Some(x) if id_is::<MergeByDistanceAlgorithm>(x) => enum_choice::<MergeByDistanceAlgorithm>().for_socket(default_info).property_row(),
Some(x) if id_is::<ExtrudeJoiningAlgorithm>(x) => enum_choice::<ExtrudeJoiningAlgorithm>().for_socket(default_info).property_row(),
Some(x) if id_is::<PointSpacingType>(x) => enum_choice::<PointSpacingType>().for_socket(default_info).property_row(),
Some(x) if id_is::<BooleanOperation>(x) => enum_choice::<BooleanOperation>().for_socket(default_info).property_row(),
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).property_row(),
Some(x) if id_is::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().for_socket(default_info).property_row(),
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).property_row(),
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).property_row(),
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).property_row(),
// =====
// OTHER
// =====
_ => return Err(unsupported_widgets(default_info, concrete_type.to_string())),
}
}
match concrete_type.id {
// ===============
// PRIMITIVE TYPES
// ===============
Some(x) if id_is::<f64>(x) => match progression {
true => progression_widget(default_info, bounded(number_input, 0., f64::INFINITY)).into(),
false => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)),
},
Some(x) if id_is::<i64>(x) => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
Some(x) if id_is::<String>(x) => match multiline {
true => text_area_widget(default_info).into(),
false => text_widget(default_info).into(),
},
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false),
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
// ============
// STRUCT TYPES
// ============
Some(x) if id_is::<Font>(x) => font_widget(default_info),
Some(x) if id_is::<TransferCurve>(x) => transfer_curve_widget(default_info),
Some(x) if id_is::<Footprint>(x) => footprint_widget(default_info, &mut extra_widgets),
Some(x) if id_is::<Box<VectorModification>>(x) => vector_modification_widget(default_info).into(),
Some(x) if id_is::<Image<Color>>(x) => image_data_widget(default_info).into(),
Some(x) if id_is::<Resource>(x) => resource_widget(default_info, Vec::new()).into(),
// ===============================
// MANUALLY IMPLEMENTED ENUM TYPES
// ===============================
Some(x) if id_is::<ReferencePoint>(x) => reference_point_widget(default_info, false).into(),
Some(x) if id_is::<BlendMode>(x) => blend_mode_widget(default_info),
// =========================
// AUTO-GENERATED ENUM TYPES
// =========================
Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientInterpolation>(x) => enum_choice::<GradientInterpolation>().for_socket(default_info).property_row(),
Some(x) if id_is::<RealTimeMode>(x) => enum_choice::<RealTimeMode>().for_socket(default_info).property_row(),
Some(x) if id_is::<RedGreenBlue>(x) => enum_choice::<RedGreenBlue>().for_socket(default_info).property_row(),
Some(x) if id_is::<RedGreenBlueAlpha>(x) => enum_choice::<RedGreenBlueAlpha>().for_socket(default_info).property_row(),
Some(x) if id_is::<XY>(x) => enum_choice::<XY>().for_socket(default_info).property_row(),
Some(x) if id_is::<StringCapitalization>(x) => enum_choice::<StringCapitalization>().for_socket(default_info).property_row(),
Some(x) if id_is::<TextDenomination>(x) => enum_choice::<TextDenomination>().for_socket(default_info).property_row(),
Some(x) if id_is::<NoiseType>(x) => enum_choice::<NoiseType>().for_socket(default_info).property_row(),
Some(x) if id_is::<FractalType>(x) => enum_choice::<FractalType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<CellularDistanceFunction>(x) => enum_choice::<CellularDistanceFunction>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<CellularReturnType>(x) => enum_choice::<CellularReturnType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<DomainWarpType>(x) => enum_choice::<DomainWarpType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<RelativeAbsolute>(x) => enum_choice::<RelativeAbsolute>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<TonalRange>(x) => enum_choice::<TonalRange>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<AdjustmentChannel>(x) => enum_choice::<AdjustmentChannel>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<HueSaturationRange>(x) => enum_choice::<HueSaturationRange>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<GridType>(x) => enum_choice::<GridType>().for_socket(default_info).property_row(),
Some(x) if id_is::<StrokeCap>(x) => enum_choice::<StrokeCap>().for_socket(default_info).property_row(),
Some(x) if id_is::<StrokeJoin>(x) => enum_choice::<StrokeJoin>().for_socket(default_info).property_row(),
Some(x) if id_is::<StrokeAlign>(x) => enum_choice::<StrokeAlign>().for_socket(default_info).property_row(),
Some(x) if id_is::<ArcType>(x) => enum_choice::<ArcType>().for_socket(default_info).property_row(),
Some(x) if id_is::<RowsOrColumns>(x) => enum_choice::<RowsOrColumns>().for_socket(default_info).property_row(),
Some(x) if id_is::<TextAlign>(x) => enum_choice::<TextAlign>().for_socket(default_info).property_row(),
Some(x) if id_is::<MergeByDistanceAlgorithm>(x) => enum_choice::<MergeByDistanceAlgorithm>().for_socket(default_info).property_row(),
Some(x) if id_is::<ExtrudeJoiningAlgorithm>(x) => enum_choice::<ExtrudeJoiningAlgorithm>().for_socket(default_info).property_row(),
Some(x) if id_is::<PointSpacingType>(x) => enum_choice::<PointSpacingType>().for_socket(default_info).property_row(),
Some(x) if id_is::<BooleanOperation>(x) => enum_choice::<BooleanOperation>().for_socket(default_info).property_row(),
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).property_row(),
Some(x) if id_is::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().for_socket(default_info).property_row(),
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).property_row(),
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).property_row(),
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).property_row(),
// =====
// OTHER
// =====
_ => return Err(unsupported_widgets(default_info, concrete_type.to_string())),
}
}
Type::Item(element) => return property_from_type(node_id, index, element, number_options, unit, display_decimal_places, step, context),
Type::Item(element) => return property_from_type(node_id, index, element, options, context),
Type::List(element) => match element.as_ref() {
Type::Concrete(element_type) if element_type.name == std::any::type_name::<f64>() => array_of_number_widget(default_info, TextInput::default()).into(),
_ => return Err(unsupported_widgets(default_info, ty.to_string())),
},
Type::Generic(_) => vec![TextLabel::new("Generic Type (Not Supported)").widget_instance()].into(),
Type::Fn(_, out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
Type::Future(out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
Type::Fn(_, out) => return property_from_type(node_id, index, out, options, context),
Type::Future(out) => return property_from_type(node_id, index, out, options, context),
};
extra_widgets.push(widgets);
@@ -430,6 +417,60 @@ pub fn text_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<WidgetIn
widgets
}
/// A math expression's text field, with a warning icon in the assist area giving the error in its tooltip while the expression fails to parse.
pub fn math_expression_widget(mut parameter_widgets_info: ParameterWidgetsInfo, accepts_reducers: bool) -> Vec<WidgetInstance> {
let Some(TaggedValue::String(expression)) = parameter_widgets_info.input().and_then(|input| input.as_non_exposed_value()) else {
return text_widget(parameter_widgets_info);
};
let Some(error) = math_expression_error(expression, accepts_reducers) else {
return text_widget(parameter_widgets_info);
};
// The 12px icon is padded to a checkbox's 16px so the field still lines up with the rows around it
parameter_widgets_info.blank_assist = false;
let mut widgets = start_widgets(&parameter_widgets_info);
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
IconLabel::new("Warning").tooltip_label("Invalid Math Expression").tooltip_description(error).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextInput::new(expression.clone())
.on_update(parameter_widgets_info.update_value(|x: &TextInput| TaggedValue::String(x.value.clone())))
.on_commit(commit_value)
.widget_instance(),
]);
widgets
}
/// Why a math expression fails to parse, as tooltip Markdown, or `None` when it parses. Where the node applies a lone operator or
/// function name like `+` or `min` across its items, that counts as valid too. An error at a place in the expression repeats the
/// expression with carets under that place, as a compiler does.
fn math_expression_error(expression: &str, accepts_reducers: bool) -> Option<String> {
// A blank expression is unfinished rather than wrong, so it goes unflagged like any empty field
if expression.trim().is_empty() || (accepts_reducers && math_parser::reducer::classify_reducer(expression, math_parser::context::NothingMap).is_some()) {
return None;
}
let error = math_parser::ast::Node::try_parse_from_str(expression).err()?;
// The quoted code may be the expression's own text, so it goes in a span nothing inside can close, and the prose is escaped
let messages = error.messages().iter().map(|message| {
let parts = message.parts().iter().map(|part| match part {
MessagePart::Text(text) => escape_markdown(text),
MessagePart::Code(code) => markdown_code_span(code),
});
let prose = parts.collect::<String>();
// The carets and their label line up under the expression's characters, with one caret where the span is empty, like at the end of the input
let Some(span) = message.span() else { return prose };
let indent = " ".repeat(expression.get(..span.start).map_or(0, |text| text.chars().count()));
let carets = "^".repeat(expression.get(span.start..span.end).map_or(0, |text| text.chars().count()).max(1));
format!("{prose}\n{}", markdown_code_block(&format!("{expression}\n{indent}{carets}\n{indent}error here")))
});
Some(messages.collect::<Vec<_>>().join("\n"))
}
pub fn text_area_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<WidgetInstance> {
let mut widgets = start_widgets(&parameter_widgets_info);
@@ -807,7 +848,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.widget_instance(),
]);
}
Some(&TaggedValue::F64(value)) => {
Some(&TaggedValue::Number(value)) => {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(value))
@@ -846,14 +887,14 @@ pub fn array_of_number_widget(parameter_widgets_info: ParameterWidgetsInfo, text
.filter(|x| !x.is_empty())
.map(graphene_std::core_types::misc::parse_f64)
.collect::<Option<Vec<_>>>()
.map(TaggedValue::F64Array)
.map(TaggedValue::Numbers)
};
let Some(input) = parameter_widgets_info.input() else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
return vec![];
};
if let Some(TaggedValue::F64Array(values)) = &input.as_non_exposed_value() {
if let Some(TaggedValue::Numbers(values)) = &input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
text_input
@@ -1008,7 +1049,7 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
log::warn!("A widget failed to be built because its node's input index is invalid.");
return vec![];
};
if let Some(&TaggedValue::F64(x)) = input.as_non_exposed_value() {
if let Some(&TaggedValue::Number(x)) = input.as_non_exposed_value() {
let whole_part = x.trunc();
let fractional_part = x.fract();
@@ -1021,7 +1062,7 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
.min(0.)
.max(0.99999)
.value(Some(fractional_part))
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::F64(whole_part + input.value.unwrap())))
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::Number(whole_part + input.value.unwrap())))
.on_commit(commit_value)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
@@ -1033,7 +1074,7 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
.min(0.)
.is_integer(true)
.value(Some(whole_part))
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::F64(input.value.unwrap() + fractional_part)))
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::Number(input.value.unwrap() + fractional_part)))
.on_commit(commit_value)
.widget_instance(),
])
@@ -1120,35 +1161,19 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
return vec![];
};
match input.as_non_exposed_value() {
Some(&TaggedValue::F64(x)) => widgets.extend_from_slice(&[
Some(&TaggedValue::Number(x)) => widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(x))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::F64(x.value.unwrap())))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::Number(x.value.unwrap())))
.on_commit(commit_value)
.widget_instance(),
]),
Some(&TaggedValue::F32(x)) => widgets.extend_from_slice(&[
Some(&TaggedValue::Integer(x)) => widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(x as f64))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::F32(x.value.unwrap() as f32)))
.on_commit(commit_value)
.widget_instance(),
]),
Some(&TaggedValue::U32(x)) => widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(x as f64))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::U32((x.value.unwrap()) as u32)))
.on_commit(commit_value)
.widget_instance(),
]),
Some(&TaggedValue::U64(x)) => widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(x as f64))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::U64((x.value.unwrap()) as u64)))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::Integer(x.value.unwrap().round() as i64)))
.on_commit(commit_value)
.widget_instance(),
]),
@@ -1157,7 +1182,7 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
number_props
// We use an arbitrary `y` instead of an arbitrary `x` here because the "Grid" node's "Spacing" value's height should be used from rectangular mode when transferred to "Y Spacing" in isometric mode
.value(Some(dvec2.y))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::F64(x.value.unwrap())))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::Number(x.value.unwrap())))
.on_commit(commit_value)
.widget_instance(),
]),
@@ -1201,6 +1226,96 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
LayoutGroup::row(widgets).with_tooltip_description("Formula used for blending.")
}
/// A dropdown choosing among the types this input takes across the node's registered rows. The input is a type witness:
/// its stored value's type, not the value itself, selects the row, which is how a node offers a choice of output type.
pub fn type_choice_widget(parameter_widgets_info: ParameterWidgetsInfo) -> LayoutGroup {
let mut widgets = start_widgets(&parameter_widgets_info);
let Some(current) = parameter_widgets_info.input().and_then(|input| input.as_non_exposed_value()) else {
return LayoutGroup::row(widgets);
};
// Every element type the node's rows accept at this input
let mut offered: Vec<Type> = Vec::new();
let implementation = parameter_widgets_info
.network_interface
.implementation(&parameter_widgets_info.node_id, parameter_widgets_info.selection_network_path);
if let Some(DocumentNodeImplementation::ProtoNode(identifier)) = implementation
&& let Some(rows) = interpreted_executor::node_registry::NODE_REGISTRY.get(identifier)
{
for row in rows.keys() {
let Some(ty) = row.inputs.get(parameter_widgets_info.index) else { continue };
let element = wire_element(ty);
if !offered.contains(&element) {
offered.push(element);
}
}
}
let sections = type_choice_sections(&offered);
let entry_sections = sections
.iter()
.map(|section| {
section
.iter()
.map(|ty| {
let chosen = TaggedValue::from_type_or_none(ty);
MenuListEntry::new(ty.to_string())
.label(ty.to_string())
.on_update(parameter_widgets_info.update_value(move |_| chosen.clone()))
.on_commit(commit_value)
})
.collect()
})
.collect();
// The dropdown counts its selection across every section, since separators divide the entries without renumbering them
let current_element = wire_element(&current.ty());
let selected = sections.iter().flatten().position(|ty| *ty == current_element).map(|position| position as u32);
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
DropdownInput::new(entry_sections).selected_index(selected).widget_instance(),
]);
LayoutGroup::row(widgets)
}
/// The element a wire type carries, peeling the `Item` or `List` rank a registry row or stored value wraps it in.
fn wire_element(ty: &Type) -> Type {
match ty.nested_type() {
Type::Item(element) | Type::List(element) => (**element).clone(),
other => other.clone(),
}
}
/// The canonical order and grouping of the graph's types, which a type choice renders as dropdown sections divided by separators.
/// Enums stay unlisted on purpose, joining any other unnamed type in a trailing alphabetical section.
fn type_choice_sections(offered: &[Type]) -> Vec<Vec<Type>> {
let vocabulary = [
vec![concrete!(bool), concrete!(i64), concrete!(f64)],
vec![concrete!(DVec2)],
vec![concrete!(DAffine2)],
vec![concrete!(Artboard)],
vec![
concrete!(Graphic),
concrete!(Vector),
concrete!(Raster<CPU>),
concrete!(Raster<GPU>),
concrete!(Color),
concrete!(Gradient),
concrete!(String),
],
];
let mut sections: Vec<Vec<Type>> = vocabulary.iter().map(|section| section.iter().filter(|ty| offered.contains(ty)).cloned().collect()).collect();
let mut unlisted: Vec<Type> = offered.iter().filter(|ty| !vocabulary.iter().any(|section| section.contains(ty))).cloned().collect();
unlisted.sort_by_key(|ty| ty.to_string());
sections.push(unlisted);
sections.retain(|section| !section.is_empty());
sections
}
pub fn color_widget(parameter_widgets_info: ParameterWidgetsInfo, color_button: ColorInput) -> LayoutGroup {
let mut widgets = start_widgets(&parameter_widgets_info);
@@ -1719,7 +1834,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodePropertiesCont
let exposed = input.is_some_and(|input| input.is_exposed());
let value = input
.and_then(|input| input.as_value())
.and_then(|tagged| if let TaggedValue::F32(value) = tagged { Some(*value as f64) } else { None })
.and_then(|tagged| if let TaggedValue::Number(value) = tagged { Some(*value) } else { None })
.unwrap_or(0.);
(exposed, value)
})
@@ -1842,7 +1957,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodePropertiesCont
NodeGraphMessage::SetInputValue {
node_id,
input_index,
value: TaggedValue::F32(scale.value(scale_position) as f32).into(),
value: TaggedValue::Number(scale.value(scale_position)).into(),
}
.into()
}
@@ -1878,11 +1993,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodePropertiesCont
.value(Some(current))
.min_width(60)
.max_width(60)
.on_update(update_value_at_index(
move |widget: &NumberInput| TaggedValue::F32(widget.value.unwrap_or(0.) as f32),
node_id,
input_index,
))
.on_update(update_value_at_index(move |widget: &NumberInput| TaggedValue::Number(widget.value.unwrap_or(0.)), node_id, input_index))
.on_commit(commit_value)
.widget_instance(),
);
@@ -1906,8 +2017,8 @@ pub(crate) fn hue_saturation_properties(node_id: NodeId, context: &mut NodePrope
Some(TaggedValue::HueSaturationRange(range)) => *range,
_ => HueSaturationRange::Master,
};
let f32_value = |parameter: &ParameterRef| match document_node.inputs.get(parameter.input_index).and_then(|input| input.as_value()) {
Some(TaggedValue::F32(value)) => *value,
let slider_value = |parameter: &ParameterRef| match document_node.inputs.get(parameter.input_index).and_then(|input| input.as_value()) {
Some(TaggedValue::Number(value)) => *value as f32,
_ => 0.,
};
@@ -1975,9 +2086,9 @@ pub(crate) fn hue_saturation_properties(node_id: NodeId, context: &mut NodePrope
Gradient::from((0..=stops).map(stop).collect::<Vec<_>>())
};
let saturation_track = if colorize_value {
toward_hue(f32_value(&hue) / 360.)
toward_hue(slider_value(&hue) / 360.)
} else if let Some([_, range_start, range_end, _]) = &range_values {
let (start, end) = (f32_value(range_start), f32_value(range_end));
let (start, end) = (slider_value(range_start), slider_value(range_end));
let center = start + (end - start).rem_euclid(360.) / 2.;
toward_hue(center / 360.)
} else {
@@ -2121,8 +2232,7 @@ fn slider_row(
};
// An exposed input shows only its label and source
let (current, tagged_value): (f64, fn(f64) -> TaggedValue) = match input.as_non_exposed_value() {
Some(&TaggedValue::F64(value)) => (value, TaggedValue::F64),
Some(&TaggedValue::F32(value)) => (value as f64, |value| TaggedValue::F32(value as f32)),
Some(&TaggedValue::Number(value)) => (value, TaggedValue::Number),
_ => return widgets,
};
let ParameterWidgetsInfo { node_id, index, .. } = parameter_widgets_info;
@@ -2184,7 +2294,7 @@ fn gradient_slider_row(
.ok()
.and_then(|document_node| document_node.inputs.get(input_index))
.and_then(|input| input.as_non_exposed_value())
.and_then(|tagged| if let TaggedValue::F32(value) = tagged { Some(*value as f64) } else { None });
.and_then(|tagged| if let TaggedValue::Number(value) = tagged { Some(*value) } else { None });
// Only add the slider and number widgets when the input is not exposed
if let Some(current) = current {
@@ -2193,7 +2303,7 @@ fn gradient_slider_row(
max: value_max,
default: Some(default_value),
};
let value_at = move |position| TaggedValue::F32(slider.value(position) as f32);
let value_at = move |position| TaggedValue::Number(slider.value(position));
row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
row.push(
@@ -2216,11 +2326,7 @@ fn gradient_slider_row(
.min_width(60)
.max_width(60)
.display_decimal_places(0)
.on_update(update_value_at_index(
move |widget: &NumberInput| TaggedValue::F32(widget.value.unwrap_or(0.) as f32),
node_id,
input_index,
))
.on_update(update_value_at_index(move |widget: &NumberInput| TaggedValue::Number(widget.value.unwrap_or(0.)), node_id, input_index))
.on_commit(commit_value)
.widget_instance(),
);
@@ -2642,7 +2748,7 @@ pub(crate) fn format_number_properties(node_id: NodeId, context: &mut NodeProper
let (no_decimals, decimal_sep_value, use_thousands, thousands_sep_value) = match get_document_node(node_id, context) {
Ok(document_node) => {
let decimal_places = match document_node.input(DecimalPlacesInput).and_then(|input| input.as_value()) {
Some(&TaggedValue::U32(x)) => x,
Some(&TaggedValue::Integer(x)) => x,
_ => 2,
};
let decimal_sep = match document_node.input(DecimalSeparatorInput).and_then(|input| input.as_non_exposed_value()) {
@@ -2966,10 +3072,7 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
return Vec::new();
};
let mut number_options = NumberOptions::default();
let mut display_decimal_places = None;
let mut step = None;
let mut unit_suffix = None;
let mut options = ParameterOptions::default();
let input_type = match implementation {
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => 'early_return: {
// Clone to end the `network_interface` borrow held via `implementation`, freeing the mutable borrow `input_type` needs below
@@ -2982,16 +3085,18 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
.get(&proto_node_identifier)
.and_then(|metadata| metadata.fields.get(input_index))
{
number_options = NumberOptions {
options = ParameterOptions {
soft_min: field.number_soft_min,
soft_max: field.number_soft_max,
hard_min: field.number_hard_min,
hard_max: field.number_hard_max,
slider: field.number_mode_range,
multiline: field.multiline,
progression: field.progression,
unit: field.unit,
display_decimal_places: field.number_display_decimal_places,
step: field.number_step,
};
display_decimal_places = field.number_display_decimal_places;
unit_suffix = field.unit;
step = field.number_step;
default_type = field.default_type.clone();
}
@@ -3019,7 +3124,7 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
.unwrap_or(concrete!(())),
};
property_from_type(node_id, input_index, &input_type, number_options, unit_suffix, display_decimal_places, step, context).unwrap_or_else(|value| value)
property_from_type(node_id, input_index, &input_type, options, context).unwrap_or_else(|value| value)
});
layout.extend(row);
@@ -3404,63 +3509,6 @@ pub fn offset_path_properties(node_id: NodeId, context: &mut NodePropertiesConte
vec![LayoutGroup::row(distance), join, LayoutGroup::row(miter_limit)]
}
pub fn math_properties(node_id: NodeId, context: &mut NodePropertiesContext) -> Vec<LayoutGroup> {
use graphene_std::math_nodes::math::*;
let expression = (|| {
let mut widgets = start_widgets(&ParameterWidgetsInfo::new(node_id, ExpressionInput, true, context));
let document_node = match get_document_node(node_id, context) {
Ok(document_node) => document_node,
Err(err) => {
log::error!("Could not get document node in offset_path_properties: {err}");
return Vec::new();
}
};
let Some(input) = document_node.input(ExpressionInput) else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
return vec![];
};
if let Some(TaggedValue::String(x)) = &input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextInput::new(x.clone())
.centered(true)
.on_update(update_value(
|x: &TextInput| {
TaggedValue::String({
let mut expression = x.value.trim().to_string();
if ["+", "-", "*", "/", "^"].iter().any(|&infix| infix == expression) {
expression = format!("A {expression} B");
} else if expression == "^" {
expression = String::from("A^B");
} else if expression == "%" || expression == "mod" {
expression = String::from("mod(a, b)");
}
expression
})
},
node_id,
ExpressionInput,
))
.on_commit(commit_value)
.widget_instance(),
])
}
widgets
})();
let operand_b = number_widget(ParameterWidgetsInfo::new(node_id, OperandBInput, true, context), NumberInput::default());
let operand_a_hint = vec![TextLabel::new("(Operand A is the primary input)").widget_instance()];
vec![
LayoutGroup::row(expression).with_tooltip_description(r#"A math expression that may incorporate "A" and/or "B", such as "sqrt(A + B) - B^2"."#),
LayoutGroup::row(operand_b).with_tooltip_description(r#"The value of "B" when calculating the expression."#),
LayoutGroup::row(operand_a_hint).with_tooltip_description(r#""A" is fed by the value from the previous node in the primary data flow, or it is 0 if disconnected."#),
]
}
pub struct ParameterWidgetsInfo<'a> {
document_id: DocumentId,
network_interface: &'a NodeNetworkInterface,
@@ -3699,3 +3747,53 @@ pub mod choice {
pub struct ForValue<W>(PhantomData<W>);
}
#[cfg(test)]
mod tests {
use super::*;
use graph_craft::{item, list};
#[test]
fn wire_element_reads_every_spelling_down_to_the_element() {
// A stored value's ranked type, a registry row's fn type, and a mapped row's list all carry the same element
let row = Type::Fn(Box::new(concrete!(())), Box::new(Type::Future(Box::new(item!(f64)))));
let mapped_row = Type::Fn(Box::new(concrete!(())), Box::new(Type::Future(Box::new(list!(f64)))));
for ty in [TaggedValue::Number(0.).ty(), item!(f64), list!(f64), row, mapped_row] {
assert_eq!(wire_element(&ty), concrete!(f64), "{ty:?} should read down to its element");
}
// The element of a stored value and of the row that accepts it agree, which is what selects the dropdown entry
assert_eq!(wire_element(&TaggedValue::Integer(0).ty()), wire_element(&item!(i64)));
assert_ne!(wire_element(&TaggedValue::Integer(0).ty()), wire_element(&item!(f64)));
}
#[test]
fn math_expressions_are_flagged_only_when_they_fail_to_parse() {
for (expression, accepts_reducers) in [("x * 2", false), ("", false), (" ", true), ("min", false), ("+", true), ("min", true)] {
assert_eq!(math_expression_error(expression, accepts_reducers), None, "`{expression}`");
}
assert!(math_expression_error("2 +", false).is_some());
assert!(math_expression_error("+", false).is_some(), "a lone reducer is an error where the node applies none");
assert_eq!(math_expression_error("sin(I)", true).as_deref(), Some("A matrix stands where a value is needed"));
}
#[test]
fn math_expression_errors_quote_the_expression_safely() {
// The expression's own text sits in code it can't close, while the message's own code keeps its formatting, and the expression
// repeats in a block below with labeled carets under the error's span
assert_eq!(math_expression_error("`abc", false).as_deref(), Some("`` `abc `` is not recognized\n```\n`abc\n^^^^\nerror here\n```"));
assert_eq!(
math_expression_error("7 % 3", false).as_deref(),
Some("`%` is reserved for percentages, so the remainder is written `mod(a, b)`\n```\n7 % 3\n ^\n error here\n```")
);
assert!(math_expression_error("(1", false).unwrap().ends_with("\n(1\n ^\n error here\n```"));
assert!(math_expression_error("πx @ 2", false).unwrap().ends_with("\nπx @ 2\n ^\n error here\n```"));
assert!(!math_expression_error("sin(I)", false).unwrap().contains('^'), "a sort error has no place to point at");
// A quoted token like `*` is a code span, so it can't pair with another into italics
let error = math_expression_error("2 * * 3", false).unwrap();
let prose = error.lines().next().unwrap();
assert!(prose.starts_with("Found `*`, expected ") && !prose.split('`').step_by(2).any(|text| text.contains('*')), "{error}");
}
}
@@ -33,7 +33,7 @@ impl FrontendGraphDataType {
"Color" => Self::Color,
"Gradient" => Self::Gradient,
"String" => Self::Typography,
"f64" | "f32" | "u32" | "u64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
raster if raster.starts_with("Raster") => Self::Raster,
_ => Self::General,
}
@@ -0,0 +1,215 @@
//! Document store lifecycle: discovery, session restore, legacy/storage reconciliation, mode changes, and removal.
use crate::messages::frontend::utility_types::PersistedState;
use crate::messages::portfolio::document_storage_io::document_key;
use crate::messages::prelude::*;
use crate::test_utils::EditorTestUtils;
use document_container::{AnyContainer, AsyncContainer};
fn dispatch(editor: &mut EditorTestUtils, message: impl Into<Message>) -> Vec<FrontendMessage> {
editor.editor.handle_message(message)
}
fn portfolio(editor: &EditorTestUtils) -> &PortfolioMessageHandler {
&editor.editor.dispatcher.message_handlers.portfolio_message_handler
}
fn restart(editor: &mut EditorTestUtils, state: PersistedState) {
dispatch(editor, PortfolioMessage::DestroyAllDocuments);
dispatch(editor, PersistentStateMessage::LoadState { state });
}
fn new_document(editor: &mut EditorTestUtils, name: &str) -> DocumentId {
dispatch(editor, PortfolioMessage::NewDocumentWithName { name: name.into() });
portfolio(editor).active_document_id.unwrap()
}
async fn container(editor: &EditorTestUtils, document_id: DocumentId) -> AnyContainer {
portfolio(editor).document_store().open(document_key(document_id)).await.unwrap()
}
async fn stored_ids(editor: &EditorTestUtils) -> Vec<DocumentId> {
portfolio(editor).document_store().list().await.unwrap().into_iter().map(|key| DocumentId(key.0)).collect()
}
#[tokio::test]
async fn stored_documents_are_discovered_without_session_state() {
let mut editor = EditorTestUtils::create();
let one = new_document(&mut editor, "One");
let two = new_document(&mut editor, "Two");
restart(&mut editor, PersistedState::default());
let state = portfolio(&editor).persisted_state_snapshot();
let mut ids: Vec<_> = state.documents.iter().map(|info| info.id).collect();
ids.sort();
let mut expected = vec![one, two];
expected.sort();
assert_eq!(ids, expected);
assert_ne!(
state.documents[0].name, state.documents[1].name,
"names are not stored in the legacy file, so discovered documents get distinct generated ones"
);
assert_eq!(portfolio(&editor).documents.len(), 2);
assert!(portfolio(&editor).active_document().is_some());
}
#[tokio::test]
async fn session_state_restores_order_names_and_selection() {
let mut editor = EditorTestUtils::create();
new_document(&mut editor, "First");
let selected = new_document(&mut editor, "Second");
let state = portfolio(&editor).persisted_state_snapshot();
let expected: Vec<_> = state.documents.iter().map(|info| (info.id, info.name.clone())).collect();
restart(&mut editor, state);
let restored = portfolio(&editor).persisted_state_snapshot();
assert_eq!(restored.documents.iter().map(|info| (info.id, info.name.clone())).collect::<Vec<_>>(), expected);
assert_eq!(portfolio(&editor).active_document_id, Some(selected));
}
#[tokio::test]
async fn session_entries_without_stored_content_are_dropped() {
let mut editor = EditorTestUtils::create();
let kept = new_document(&mut editor, "Kept");
let mut state = portfolio(&editor).persisted_state_snapshot();
let mut ghost = state.documents[0].clone();
ghost.id = DocumentId(0xdead);
state.documents.push(ghost);
restart(&mut editor, state);
let ids: Vec<_> = portfolio(&editor).persisted_state_snapshot().documents.iter().map(|info| info.id).collect();
assert_eq!(ids, vec![kept]);
}
#[tokio::test]
async fn legacy_only_container_gets_storage() {
let mut editor = EditorTestUtils::create();
let id = DocumentId(0xabc);
let container = container(&editor, id).await;
container.write("legacy.graphite", DocumentMessageHandler::default().serialize_document().as_bytes()).await.unwrap();
restart(&mut editor, PersistedState::default());
assert!(portfolio(&editor).documents.contains_key(&id));
assert!(editor.active_document().storage().is_some());
assert!(container.exists("manifest.json").await);
assert!(container.exists("legacy.graphite").await);
}
#[tokio::test]
async fn legacy_mode_reads_legacy_only_and_leaves_storage_files_alone() {
let mut editor = EditorTestUtils::create();
dispatch(&mut editor, PreferencesMessage::SaveAsGdd { enabled: false });
let id = new_document(&mut editor, "Legacy");
let container = container(&editor, id).await;
assert!(!container.exists("manifest.json").await);
container.write("manifest.json", b"broken").await.unwrap();
restart(&mut editor, PersistedState::default());
assert!(portfolio(&editor).documents.contains_key(&id));
assert!(editor.active_document().storage().is_none());
assert_eq!(container.read("manifest.json").await.unwrap().as_slice(), b"broken");
}
#[tokio::test]
async fn storage_only_container_recovers_and_writes_legacy() {
let mut editor = EditorTestUtils::create();
let id = new_document(&mut editor, "Storage");
let container = container(&editor, id).await;
container.remove("legacy.graphite").await.unwrap();
restart(&mut editor, PersistedState::default());
assert!(portfolio(&editor).documents.contains_key(&id));
assert!(editor.active_document().storage().is_some());
assert!(container.exists("legacy.graphite").await);
}
#[tokio::test]
async fn legacy_wins_over_stale_storage_and_history_is_kept() {
let mut editor = EditorTestUtils::create();
let id = new_document(&mut editor, "Changed");
let container = container(&editor, id).await;
let before = editor.active_document().serialize_document();
let network_before = editor.active_document().document_network().clone();
editor.draw_rect(0., 0., 100., 100.).await;
dispatch(&mut editor, PortfolioMessage::AutoSaveDocument { document_id: id });
container.write("legacy.graphite", before.as_bytes()).await.unwrap();
restart(&mut editor, PersistedState::default());
assert_eq!(editor.active_document().document_network(), &network_before);
let storage = editor.active_document().storage().expect("storage attached");
assert!(storage.can_undo(), "the stale stored state stays reachable as history");
}
#[tokio::test]
async fn unchanged_content_keeps_cursor_and_redo_across_restart() {
let mut editor = EditorTestUtils::create();
let id = new_document(&mut editor, "Undo");
let network_before = editor.active_document().document_network().clone();
editor.draw_rect(0., 0., 100., 100.).await;
dispatch(&mut editor, PortfolioMessage::AutoSaveDocument { document_id: id });
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(editor.active_document().document_network(), &network_before);
assert!(editor.active_document().storage().unwrap().can_redo());
assert!(editor.active_document().is_auto_saved(), "the rebuild completion autosaves the cursor's network");
restart(&mut editor, PersistedState::default());
assert_eq!(editor.active_document().document_network(), &network_before);
let storage = editor.active_document().storage().expect("storage attached");
assert!(storage.can_redo(), "reopening identical content must not stage a new interaction");
assert!(!storage.can_undo());
}
#[tokio::test]
async fn closing_removes_the_stored_document() {
let mut editor = EditorTestUtils::create();
let id = new_document(&mut editor, "Closed");
assert_eq!(stored_ids(&editor).await, vec![id]);
dispatch(&mut editor, PortfolioMessage::CloseDocument { document_id: id });
assert!(stored_ids(&editor).await.is_empty());
restart(&mut editor, PersistedState::default());
assert!(portfolio(&editor).persisted_state_snapshot().documents.is_empty());
}
#[tokio::test]
async fn storage_preference_attaches_and_drops_sessions() {
let mut editor = EditorTestUtils::create();
dispatch(&mut editor, PreferencesMessage::SaveAsGdd { enabled: false });
let id = new_document(&mut editor, "Toggle");
let container = container(&editor, id).await;
assert!(editor.active_document().storage().is_none());
assert!(container.exists("legacy.graphite").await);
dispatch(&mut editor, PreferencesMessage::SaveAsGdd { enabled: true });
assert!(editor.active_document().storage().is_some());
assert!(container.exists("manifest.json").await);
dispatch(&mut editor, PreferencesMessage::SaveAsGdd { enabled: false });
assert!(editor.active_document().storage().is_none());
}
#[tokio::test]
async fn unreadable_document_is_reported_and_kept_until_discarded() {
let mut editor = EditorTestUtils::create();
let id = DocumentId(7);
container(&editor, id).await.write("legacy.graphite", b"not a document").await.unwrap();
restart(&mut editor, PersistedState::default());
assert!(!portfolio(&editor).documents.contains_key(&id));
assert!(portfolio(&editor).persisted_state_snapshot().documents.is_empty());
assert_eq!(stored_ids(&editor).await, vec![id]);
dispatch(&mut editor, FailedDocumentsMessage::DiscardFailedToLoadDocuments);
assert!(stored_ids(&editor).await.is_empty());
}
@@ -6,7 +6,7 @@
use std::collections::{BTreeSet, HashMap};
use document_graph_storage::{NodeMetadataSource, PeerId, Registry};
use document_graph_storage::{NodeMetadataSource, PeerId, Registry, to_value};
use super::test_support::{load_demo, node_paths};
use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler;
@@ -28,7 +28,7 @@ fn editor_metadata_round_trip_against_demo() {
let network = interface.document_network().clone();
let conversion = Registry::convert_from_runtime(&network, &source, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations().expect("rebuild declarations");
let declarations = conversion.declarations;
let registry = conversion.registry;
let (_converted_network, entries) = registry.to_runtime_with_metadata(&declarations).expect("to_runtime_with_metadata failed");
@@ -137,7 +137,7 @@ fn editor_interface_rebuild_round_trip() {
let network = original.document_network().clone();
let conversion = Registry::convert_from_runtime(&network, &original_view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations().expect("rebuild declarations");
let declarations = conversion.declarations;
let registry = conversion.registry;
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime_with_full_metadata failed");
@@ -256,7 +256,7 @@ fn rebuilt_interface_keeps_storage_identities() {
let network = document.network_interface.document_network().clone();
let conversion = Registry::convert_from_runtime(&network, &view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations().expect("rebuild declarations");
let declarations = conversion.declarations;
let registry = conversion.registry;
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime_with_full_metadata failed");
@@ -272,10 +272,7 @@ fn rebuilt_interface_keeps_storage_identities() {
assert_eq!(reconverted_ids, stored_ids, "re-converting the rebuilt interface under a different peer changed the node identities");
}
/// Opening an old document runs its upgrades through the ordinary mutators, so the store records them.
/// Those recordings are the document arriving rather than edits to it, so the migration has to leave
/// the buffer empty instead of handing the first commit a pile of changes to the document's own
/// starting state.
/// Migrating an opened document must leave the recorded-delta buffer empty.
#[test]
fn migrating_a_document_records_no_changes() {
let mut document = load_demo("painted-dreams.graphite");
@@ -308,7 +305,7 @@ fn pinned_order_round_trips_through_the_registry() {
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
let conversion = Registry::convert_from_runtime(&network, &view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations().expect("rebuild declarations");
let declarations = conversion.declarations;
let (rebuilt_network, node_entries, network_entries) = conversion.registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime failed");
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage failed");
@@ -345,26 +342,14 @@ fn document_settings_round_trip() {
let mut restored = DocumentMessageHandler::default();
restored.apply_stored_document_settings(&view_settings);
assert_eq!(serde_json::to_value(restored.render_mode).unwrap(), serde_json::to_value(document.render_mode).unwrap(), "render_mode");
assert_eq!(to_value(&restored.render_mode).unwrap(), to_value(&document.render_mode).unwrap(), "render_mode");
assert_eq!(to_value(&restored.rulers_visible).unwrap(), to_value(&document.rulers_visible).unwrap(), "rulers_visible");
assert_eq!(to_value(&restored.document_ptz).unwrap(), to_value(&document.document_ptz).unwrap(), "document_ptz");
assert_eq!(
serde_json::to_value(restored.rulers_visible).unwrap(),
serde_json::to_value(document.rulers_visible).unwrap(),
"rulers_visible"
);
assert_eq!(
serde_json::to_value(restored.document_ptz).unwrap(),
serde_json::to_value(document.document_ptz).unwrap(),
"document_ptz"
);
assert_eq!(
serde_json::to_value(restored.overlays_visibility_settings).unwrap(),
serde_json::to_value(document.overlays_visibility_settings).unwrap(),
to_value(&restored.overlays_visibility_settings).unwrap(),
to_value(&document.overlays_visibility_settings).unwrap(),
"overlays"
);
assert_eq!(
serde_json::to_value(restored.snapping_state).unwrap(),
serde_json::to_value(document.snapping_state).unwrap(),
"snapping_state"
);
assert_eq!(serde_json::to_value(restored.collapsed).unwrap(), serde_json::to_value(document.collapsed).unwrap(), "collapsed");
assert_eq!(to_value(&restored.snapping_state).unwrap(), to_value(&document.snapping_state).unwrap(), "snapping_state");
assert_eq!(to_value(&restored.collapsed).unwrap(), to_value(&document.collapsed).unwrap(), "collapsed");
}
@@ -4,6 +4,7 @@
//!
//! Shared fixtures live in [`test_support`].
mod lifecycle_tests;
mod metadata_tests;
mod round_trip_tests;
mod test_support;
pub(crate) mod test_support;
@@ -1,13 +1,13 @@
//! End-to-end storage round-trip tests: drive real edits through the editor, push the document
//! through a fresh in-memory `Gdd` (stage → retire → persist), reopen from the same container, and
//! assert the reopened document matches. Exercises the full persistence pipeline (conversion,
//! MessagePack codecs, hot-op retirement, file layout, replay-on-open) that the debug-only
//! postcard codecs, hot-op retirement, file layout, replay-on-open) that the debug-only
//! `verify_storage_round_trip` only checks in-process without an actual save/reopen.
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::{NodeMetadataSource, PeerId};
use document_graph_storage::{NodeMetadataSource, PeerId, to_value};
use graph_craft::application_io::resource::HashMapResourceStorage;
use super::test_support::{RoundTrip, node_paths, round_trip_through_gdd};
@@ -158,9 +158,7 @@ async fn edit_after_open_commits_cleanly() {
// reopened registry: the editor's .gdd-open path.
let byte_store = HashMapResourceStorage::new();
let source = editor.active_document();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
let source_network = source.network_interface.document_network().clone();
let source_view = StorageMetadataView::new(&source.network_interface);
gdd.commit_from_runtime(&source_network, &source_view, &source.resources.registry, &byte_store)
@@ -176,7 +174,7 @@ async fn edit_after_open_commits_cleanly() {
{
let document = editor.active_document_mut();
document.network_interface = rebuilt;
document.set_storage(Some(reopened));
document.set_storage(reopened, declarations);
document.finalize_storage_load();
}
@@ -210,9 +208,7 @@ async fn edit_after_open_commits_cleanly() {
#[tokio::test]
async fn gdd_undo_redo_walks_interactions() {
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
// Commit the active document's current runtime state as one interaction.
async fn commit_interaction(gdd: &mut GddV1, document: &DocumentMessageHandler, byte_store: &HashMapResourceStorage) {
@@ -263,9 +259,7 @@ async fn gdd_undo_redo_walks_interactions() {
#[tokio::test]
async fn reopen_after_undo_restores_consistent_registry() {
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
async fn commit_interaction(gdd: &mut GddV1, document: &DocumentMessageHandler, byte_store: &HashMapResourceStorage) {
let network = document.network_interface.document_network().clone();
@@ -334,7 +328,7 @@ async fn live_undo_shadows_storage_cursor() {
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
let byte_store = mount_in_memory_storage(&mut editor).await;
let byte_store = mount_in_memory_storage(&mut editor);
// Capture the loaded state as the base interaction, then make a real edit (fires CommitTransaction).
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let before_edit = editor.active_document().network_interface.document_network().clone();
@@ -373,9 +367,9 @@ async fn round_trip_document_settings() {
// The `ui::doc::*` view settings survived the persist/reopen cycle (in session.json, not the registry).
let settings = &round_trip.view_settings;
assert_eq!(settings.get(doc::RENDER_MODE), Some(&serde_json::to_value(RenderMode::Outline).unwrap()), "render_mode");
assert_eq!(settings.get(doc::RULERS_VISIBLE), Some(&serde_json::to_value(false).unwrap()), "rulers_visible");
assert_eq!(settings.get(doc::SNAPPING), Some(&serde_json::to_value(&document.snapping_state).unwrap()), "snapping_state");
assert_eq!(settings.get(doc::RENDER_MODE), Some(&to_value(&RenderMode::Outline).unwrap()), "render_mode");
assert_eq!(settings.get(doc::RULERS_VISIBLE), Some(&to_value(&false).unwrap()), "rulers_visible");
assert_eq!(settings.get(doc::SNAPPING), Some(&to_value(&document.snapping_state).unwrap()), "snapping_state");
}
/// The exported `.gdd` archive must carry `session.json` so view settings (notably the document PTZ)
@@ -387,15 +381,13 @@ async fn gdd_archive_round_trips_view_settings() {
use document_graph_storage::attr::session::doc;
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
// Stage a distinctive PTZ into the working copy's `view_settings`, as `commit_storage_snapshot` does.
let mut ptz = crate::messages::portfolio::document::utility_types::misc::PTZ::default();
ptz.pan = glam::DVec2::new(-960., -540.);
ptz.set_zoom(0.459);
let view_settings = std::collections::BTreeMap::from([(doc::PTZ.to_string(), serde_json::to_value(ptz).unwrap())]);
let view_settings = std::collections::BTreeMap::from([(doc::PTZ.to_string(), to_value(&ptz).unwrap())]);
gdd.set_view_settings(view_settings).expect("set_view_settings");
// Export to an in-memory archive, then reopen it from bytes into a fresh container.
@@ -410,7 +402,7 @@ async fn gdd_archive_round_trips_view_settings() {
assert_eq!(
reopened.view_settings().get(doc::PTZ),
Some(&serde_json::to_value(ptz).unwrap()),
Some(&to_value(&ptz).unwrap()),
"the document PTZ must survive a .gdd archive export/open (session.json travels in the archive)"
);
}
@@ -437,9 +429,7 @@ async fn per_network_navigation_round_trips_via_session_not_registry() {
let expected_pan = editor.active_document().network_interface.node_graph_ptz(&[]).unwrap().pan;
// Commit the document into a fresh `Gdd`, collecting the per-network view state the editor persists.
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
let document = editor.active_document();
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
@@ -472,14 +462,14 @@ async fn per_network_navigation_round_trips_via_session_not_registry() {
}
/// Mirror the real "new document, draw a rect, press undo" flow: mount storage and capture the
/// new-document base as the mount-time snapshot (as `DocumentStorageMounted` does), then draw a rect
/// new-document base as the attach-time snapshot (as `StorageAttached` does), then draw a rect
/// (one `CommitTransaction` interaction) and undo. The shadow must reproduce the legacy-restored interface.
#[tokio::test]
async fn live_undo_new_document_draw_rect() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let byte_store = mount_in_memory_storage(&mut editor).await;
let byte_store = mount_in_memory_storage(&mut editor);
// Mount-time snapshot: capture the new-document graph as the base interaction.
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
@@ -569,7 +559,7 @@ async fn undo_image_paste_resources_subset_of_runtime() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let byte_store = mount_in_memory_storage(&mut editor).await;
let byte_store = mount_in_memory_storage(&mut editor);
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.handle_message(paste_named_image()).await;
@@ -601,7 +591,7 @@ async fn undo_twice_steps_cursor_two_interactions() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let byte_store = mount_in_memory_storage(&mut editor).await;
let byte_store = mount_in_memory_storage(&mut editor);
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let base = editor.active_document().network_interface.document_network().clone();
@@ -674,11 +664,9 @@ fn assert_cursor_matches_runtime(document: &DocumentMessageHandler, at: &str) {
/// Mount a fresh in-memory `Gdd` onto the active document so `commit_storage_snapshot` (the real
/// autosave path) runs against it. Returns the byte store the document's resources resolve through.
async fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> HashMapResourceStorage {
let gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0x5EED, "test".into(), "test".into())
.await
.expect("create_in");
editor.active_document_mut().set_storage(Some(gdd));
fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> HashMapResourceStorage {
let gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0x5EED, "test".into(), "test".into()).expect("create_in");
editor.active_document_mut().set_storage(gdd, Default::default());
HashMapResourceStorage::new()
}
@@ -701,7 +689,7 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
})
.await;
let byte_store = mount_in_memory_storage(&mut editor).await;
let byte_store = mount_in_memory_storage(&mut editor);
// First autosave: captures the loaded document. `verify_storage_round_trip` panics on drift.
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
@@ -769,7 +757,7 @@ async fn none_fill_survives_document_reopen() {
// Reopen through the editor's real open path, which runs the document migrations
let serialized = editor.active_document().serialize_document();
editor
.handle_message(PortfolioMessage::OpenDocumentFile {
.handle_message(PortfolioMessage::OpenLegacyDocumentFile {
document_name: None,
document_path: None,
document_serialized_content: serialized,
@@ -792,7 +780,7 @@ async fn legacy_four_input_fill_migrates_to_the_split_transform_shape() {
let mut editor = EditorTestUtils::create();
editor
.handle_message(PortfolioMessage::OpenDocumentFile {
.handle_message(PortfolioMessage::OpenLegacyDocumentFile {
document_name: None,
document_path: None,
document_serialized_content: LEGACY_DOCUMENT.to_string(),
@@ -850,7 +838,7 @@ async fn eight_input_fill_migrates_the_spread_input_into_the_ramp() {
let mut editor = EditorTestUtils::create();
editor
.handle_message(PortfolioMessage::OpenDocumentFile {
.handle_message(PortfolioMessage::OpenLegacyDocumentFile {
document_name: None,
document_path: None,
document_serialized_content: EIGHT_INPUT_DOCUMENT.to_string(),
@@ -46,7 +46,7 @@ pub fn node_paths(interface: &NodeNetworkInterface) -> Vec<(Vec<NodeId>, NodeId)
pub struct RoundTrip {
pub rebuilt: NodeNetworkInterface,
pub registry: document_graph_storage::Registry,
pub view_settings: std::collections::BTreeMap<String, serde_json::Value>,
pub view_settings: std::collections::BTreeMap<String, document_graph_storage::Value>,
}
/// Push `document`'s current runtime state through a fresh in-memory `Gdd` and reopen it. The commit goes
@@ -56,9 +56,7 @@ pub struct RoundTrip {
pub async fn round_trip_through_gdd(document: &DocumentMessageHandler) -> RoundTrip {
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
@@ -1,11 +1,6 @@
use super::*;
use graph_craft::runtime_delta::RuntimeDelta;
// Replay: putting a delta back into the interface, the inverse of the store recording one.
//
// Mechanism only. A mutator decides policy, validates, and lays nodes out, then records what it
// settled on; replaying reproduces that outcome rather than deciding it again. A peer running
// different layout rules must still end up with the state the delta describes.
impl NodeNetworkInterface {
/// Mirrors a delta into the interface without recording it.
///
@@ -23,8 +18,7 @@ impl NodeNetworkInterface {
fn mirror(&mut self, delta: &EditorDelta) {
match delta {
// The metadata arrives separately, so a node lands with default metadata that the paired
// snapshot then fills in. Replacing an entry and adding one are the same write here; they
// differ only in what the storage side has to remove first.
// snapshot then fills in
EditorDelta::Graph(RuntimeDelta::AddNode { network_path, node_id, node }) | EditorDelta::Graph(RuntimeDelta::ReplaceNode { network_path, node_id, node }) => {
let template = NodeTemplate::from_parts((**node).clone(), DocumentNodePersistentMetadata::default());
self.insert_node_entry(NodeLocator::new(*node_id, network_path), template);
@@ -30,11 +30,10 @@ impl NodeNetworkInterface {
self.unload_stack_dependents(network_path);
let Some(history) = self.selection_history_mut(network_path) else {
log::error!("Could not get nested network_metadata in selected_nodes");
log::error!("Could not get nested network_metadata in selected_nodes_mut");
return None;
};
// Initialize default value if selection_undo_history is empty
if history.undo.is_empty() {
history.undo.push_back(SelectedNodes::default());
}
@@ -81,7 +80,7 @@ impl NodeNetworkInterface {
pub(crate) fn try_load_stack_dependents(&self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in stack_dependents");
log::error!("Could not get nested network_metadata in try_load_stack_dependents");
return;
};
@@ -101,7 +100,7 @@ impl NodeNetworkInterface {
return None;
};
let Some(stack_dependents) = transient.stack_dependents.get_loaded_mut() else {
log::error!("could not load stack_dependents");
log::error!("Could not load stack dependents in try_get_stack_dependents");
return None;
};
Some(stack_dependents)
@@ -148,7 +147,7 @@ impl NodeNetworkInterface {
.get(&OutputConnector::primary_output(current_node))
.map(|layer_outward_wires| layer_outward_wires.first().copied())
}) else {
log::error!("Cannot load outward wires in load_stack_dependents");
log::error!("Cannot load outward wires in load_stack_dependents_for_nodes");
return;
};
let Some(first_downstream_input) = first_downstream_input else {
@@ -188,7 +187,7 @@ impl NodeNetworkInterface {
new_owned_nodes.insert(*layer_sole_dependent);
}
let Some(layer_node) = self.node_metadata(&upstream_layer, network_path) else {
log::error!("Could not get layer node in load_stack_dependents");
log::error!("Could not get layer node in load_stack_dependents_for_nodes");
continue;
};
layer_node.transient_metadata.owned_nodes.store(new_owned_nodes);
@@ -232,7 +231,7 @@ impl NodeNetworkInterface {
}
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get current network in load_stack_dependents");
log::error!("Could not get current network in load_stack_dependents_for_nodes");
return;
};
@@ -277,11 +276,11 @@ impl NodeNetworkInterface {
self.load_import_export_ports(network_path);
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in export_ports");
log::error!("Could not get nested network_metadata in import_export_ports");
return None;
};
let Some(ports) = transient.import_export_ports.get_loaded_mut() else {
log::error!("could not load import ports");
log::error!("Could not load import export ports in import_export_ports");
return None;
};
Some(ports)
@@ -297,7 +296,7 @@ impl NodeNetworkInterface {
pub fn load_import_export_ports(&self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in export_ports");
log::error!("Could not get nested network_metadata in load_import_export_ports");
return;
};
network_metadata.transient_metadata.import_export_ports.ensure_loaded(|| self.compute_import_export_ports(network_path));
@@ -305,7 +304,7 @@ impl NodeNetworkInterface {
pub(crate) fn unload_import_export_ports(&mut self, network_path: &[NodeId]) {
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in unload_export_ports");
log::error!("Could not get nested network_metadata in unload_import_export_ports");
return;
};
transient.import_export_ports.unload();
@@ -313,13 +312,13 @@ impl NodeNetworkInterface {
// Always unload all wires connected to them as well
let number_of_imports = self.number_of_imports(network_path);
let Some(outward_wires) = self.outward_wires(network_path) else {
log::error!("Could not get outward wires in remove_import");
log::error!("Could not get outward wires in unload_import_export_ports");
return;
};
let mut input_connectors = Vec::new();
for import_index in 0..number_of_imports {
let Some(outward_wires_for_import) = outward_wires.get(&OutputConnector::Import(import_index)).cloned() else {
log::error!("Could not get outward wires for import in remove_import");
log::error!("Could not get outward wires for import in unload_import_export_ports");
return;
};
input_connectors.extend(outward_wires_for_import);
@@ -343,7 +342,7 @@ impl NodeNetworkInterface {
return None;
};
let Some(click_targets) = transient.modify_import_export.get_loaded_mut() else {
log::error!("could not load modify import export ports");
log::error!("Could not load modify import export in modify_import_export");
return None;
};
Some(click_targets)
@@ -351,7 +350,7 @@ impl NodeNetworkInterface {
pub fn load_modify_import_export(&self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in modify_import_export");
log::error!("Could not get nested network_metadata in load_modify_import_export");
return;
};
network_metadata
@@ -362,7 +361,7 @@ impl NodeNetworkInterface {
pub(crate) fn unload_modify_import_export(&mut self, network_path: &[NodeId]) {
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in unload_export_ports");
log::error!("Could not get nested network_metadata in unload_modify_import_export");
return;
};
transient.modify_import_export.unload();
@@ -388,7 +387,7 @@ impl NodeNetworkInterface {
.all_nodes_bounding_box
.with_loaded_or(|| self.compute_all_nodes_bounding_box(network_path), |bounds| *bounds);
if bounding_box.is_none() {
log::error!("could not load all nodes bounding box");
log::error!("Could not load all nodes bounding box in all_nodes_bounding_box");
}
bounding_box
}
@@ -424,7 +423,7 @@ impl NodeNetworkInterface {
return None;
};
let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else {
log::error!("could not load outward wires");
log::error!("Could not load outward wires in outward_wires");
return None;
};
@@ -441,14 +440,14 @@ impl NodeNetworkInterface {
fn load_outward_wires(&self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in outward_wires");
log::error!("Could not get nested network_metadata in load_outward_wires");
return;
};
network_metadata.transient_metadata.outward_wires.ensure_loaded(|| self.compute_outward_wires(network_path));
}
/// Every input fed by each node output and each import of the network.
fn compute_outward_wires(&self, network_path: &[NodeId]) -> Option<HashMap<OutputConnector, Vec<InputConnector>>> {
pub(super) fn compute_outward_wires(&self, network_path: &[NodeId]) -> Option<HashMap<OutputConnector, Vec<InputConnector>>> {
let mut outward_wires = HashMap::new();
let Some(network) = self.nested_network(network_path) else {
log::error!("Could not get nested network in compute_outward_wires");
@@ -469,7 +468,7 @@ impl NodeNetworkInterface {
// A missing entry means a wire references a node output or import that does not exist, so log it and register the connector anyway rather than crashing
let push_outward_wire = |outward_wires: &mut HashMap<OutputConnector, Vec<InputConnector>>, output_connector: OutputConnector, input_connector: InputConnector| {
let outward_wires_entry = outward_wires.entry(output_connector).or_insert_with(|| {
log::error!("Output connector {output_connector:?} should be initialized in load_outward_wires");
log::error!("Output connector {output_connector:?} should be initialized in compute_outward_wires");
Vec::new()
});
outward_wires_entry.push(input_connector);
@@ -510,23 +509,72 @@ impl NodeNetworkInterface {
/// avoiding a full rebuild. If the cache is not loaded, this is a no-op (it will be fully
/// rebuilt on the next read via `outward_wires()`).
pub(crate) fn update_outward_wires(&mut self, network_path: &[NodeId], input_connector: &InputConnector, old_input: &NodeInput, new_input: &NodeInput) {
let Some(transient) = self.network_transient_mut(network_path) else {
return;
};
let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else {
return;
let drained = {
let Some(transient) = self.network_transient_mut(network_path) else { return };
let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else { return };
unhook_outward_wire(outward_wires, input_connector, old_input);
hook_outward_wire(outward_wires, input_connector, new_input);
drained_outward_wire(outward_wires, old_input)
};
// Remove the input_connector from the old output's downstream list
if let Some(old_output) = OutputConnector::from_input(old_input)
&& let Some(connections) = outward_wires.get_mut(&old_output)
{
connections.retain(|c| c != input_connector);
if let Some(output) = drained {
self.delist_vacated_output(network_path, output);
}
}
/// The same update for a node whose whole input list was swapped.
pub(crate) fn update_outward_wires_for_inputs(&mut self, network_path: &[NodeId], node_id: &NodeId, old_inputs: &[NodeInput], new_inputs: &[NodeInput]) {
let drained = {
let Some(transient) = self.network_transient_mut(network_path) else { return };
let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else { return };
for (input_index, old_input) in old_inputs.iter().enumerate() {
unhook_outward_wire(outward_wires, &InputConnector::node_at_index(*node_id, input_index), old_input);
}
for (input_index, new_input) in new_inputs.iter().enumerate() {
hook_outward_wire(outward_wires, &InputConnector::node_at_index(*node_id, input_index), new_input);
}
old_inputs.iter().filter_map(|old_input| drained_outward_wire(outward_wires, old_input)).collect::<Vec<_>>()
};
for output in drained {
self.delist_vacated_output(network_path, output);
}
}
/// Drops an emptied entry for an output the network no longer has, which a fresh computation keys only while a wire still reaches it.
fn delist_vacated_output(&mut self, network_path: &[NodeId], output: OutputConnector) {
let still_exists = match output {
OutputConnector::Node { node_id, output_index } => output_index < self.number_of_outputs(&node_id, network_path),
OutputConnector::Import(import_index) => import_index < self.number_of_imports(network_path),
};
if still_exists {
return;
}
// Add the input_connector to the new output's downstream list
if let Some(new_output) = OutputConnector::from_input(new_input) {
outward_wires.entry(new_output).or_default().push(*input_connector);
let Some(transient) = self.network_transient_mut(network_path) else { return };
let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else { return };
outward_wires.remove(&output);
}
/// Lists or delists a node's outputs after their count changed, since every output is keyed even with no consumers.
pub(crate) fn update_outward_wires_for_outputs(&mut self, network_path: &[NodeId], node_id: &NodeId, old_output_count: usize, new_output_count: usize) {
let Some(transient) = self.network_transient_mut(network_path) else { return };
let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else { return };
// A consumer still wired to a vanished output keeps the entry, as a fresh computation lists it too
for output_index in new_output_count..old_output_count {
let output = OutputConnector::node(*node_id, output_index);
if outward_wires.get(&output).is_some_and(Vec::is_empty) {
outward_wires.remove(&output);
}
}
for output_index in old_output_count..new_output_count {
outward_wires.entry(OutputConnector::node(*node_id, output_index)).or_default();
}
}
@@ -546,7 +594,7 @@ impl NodeNetworkInterface {
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |layer_width| *layer_width)
}
/// Unloads layer width if the node is a layer
/// Unloads layer width if the node is a layer.
pub fn try_unload_layer_width(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
let is_layer = self.is_layer(node_id, network_path);
@@ -554,7 +602,6 @@ impl NodeNetworkInterface {
return;
};
// If the node is a layer, then the width and click targets need to be recalculated
if is_layer {
transient.layer_width.unload();
}
@@ -599,14 +646,8 @@ impl NodeNetworkInterface {
}
fn load_wire(&self, input: &InputConnector, graph_wire_style: GraphWireStyle, network_path: &[NodeId]) {
let dashed = match self.previewing(network_path) {
Previewing::Yes { .. } => match input {
InputConnector::Node { .. } => false,
InputConnector::Export(export_index) => *export_index == 0,
},
Previewing::No => false,
};
let Some(wire) = self.wire_path_from_input(input, graph_wire_style, dashed, network_path) else {
// The export keeps its own solid wire while previewing, since previewing does not rewire it
let Some(wire) = self.wire_path_from_input(input, graph_wire_style, false, network_path) else {
log::error!("Could not load wire path from input");
return;
};
@@ -663,7 +704,7 @@ impl NodeNetworkInterface {
fn unload_wires_for_node(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
let number_of_outputs = self.number_of_outputs(node_id, network_path);
let Some(outward_wires) = self.outward_wires(network_path) else {
log::error!("Could not get outward wires in reorder_export");
log::error!("Could not get outward wires in unload_wires_for_node");
return;
};
let mut input_connectors = Vec::new();
@@ -688,27 +729,26 @@ impl NodeNetworkInterface {
network_metadata.transient_metadata.wires.borrow_mut().remove(input);
}
/// The dashed wire from the previewed node to the export, drawn alongside the solid wire the export
/// is really connected to.
///
/// Previewing does not rewire the export, so both are shown: the solid wire says what the document
/// renders, and this one says what this peer is looking at instead.
pub fn wire_to_preview(&self, graph_wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<WirePathUpdate> {
/// When previewing, there may be a second path to the root node.
pub fn wire_to_root(&self, graph_wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<WirePathUpdate> {
let input = InputConnector::Export(0);
let current_export = self.upstream_output_connector(&input, network_path)?;
let Previewing::Yes { previewed } = self.previewing(network_path) else { return None };
let root_node = match self.previewing(network_path) {
Previewing::Yes { root_node_to_restore } => root_node_to_restore,
Previewing::No => None,
}?;
// The export already reaches it, so a second wire would land on top of the solid one
if self.upstream_output_connector(&input, network_path).and_then(|export| export.node_id()) == Some(previewed.node_id) {
if Some(root_node.node_id) == current_export.node_id() {
return None;
}
let Some(input_position) = self.get_input_center(&input, network_path) else {
log::error!("Could not get input position for wire end in preview: {input:?}");
log::error!("Could not get input position for wire end in root node: {input:?}");
return None;
};
let upstream_output = OutputConnector::node(previewed.node_id, previewed.output_index);
let upstream_output = OutputConnector::node(root_node.node_id, root_node.output_index);
let Some(output_position) = self.get_output_center(&upstream_output, network_path) else {
log::error!("Could not get output position for wire start in preview: {upstream_output:?}");
log::error!("Could not get output position for wire start in root node: {upstream_output:?}");
return None;
};
let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0);
@@ -726,7 +766,7 @@ impl NodeNetworkInterface {
path_string,
data_type,
thick,
dashed: false,
dashed: true,
is_list,
center_path_string,
});
@@ -749,7 +789,7 @@ impl NodeNetworkInterface {
return Some((BezPath::new(), BezPath::new(), false));
};
let Some(output_position) = self.get_output_center(&upstream_output, network_path) else {
log::error!("Could not get output port for wire start: {:?}", upstream_output);
log::error!("Could not get output port for wire start: {upstream_output:?}");
return None;
};
let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0);
@@ -786,7 +826,7 @@ impl NodeNetworkInterface {
let transient = self.node_transient_mut(node_id, network_path)?;
let Some(click_targets) = transient.click_targets.get_loaded_mut() else {
log::error!("Could not load node type metadata when getting click targets");
log::error!("Could not load click targets in node_click_targets");
return None;
};
Some(click_targets)
@@ -794,7 +834,7 @@ impl NodeNetworkInterface {
pub(crate) fn load_node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) {
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
log::error!("Could not get nested node_metadata in node_click_targets");
log::error!("Could not get nested node_metadata in load_node_click_targets");
return;
};
node_metadata.transient_metadata.click_targets.ensure_loaded(|| self.compute_node_click_targets(node_id, network_path));
@@ -821,16 +861,18 @@ impl NodeNetworkInterface {
let node_metadata = self.node_metadata(node_id, network_path)?;
let result = node_metadata.transient_metadata.click_targets.with_loaded(read);
if result.is_none() {
log::error!("Could not load node type metadata when getting click targets");
log::error!("Could not load click targets in with_node_click_targets_if_loaded");
}
result
}
pub fn node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
self.load_node_click_targets(node_id, network_path);
self.try_get_node_bounding_box(node_id, network_path)
self.with_node_click_targets(node_id, network_path, |click_targets| click_targets.node_click_target.bounding_box())
.flatten()
}
/// The bounding box only if the click targets are already loaded, for a caller that is walking many
/// nodes and cannot afford to load each one it looks at.
pub fn try_get_node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
self.with_node_click_targets_if_loaded(node_id, network_path, |click_targets| click_targets.node_click_target.bounding_box())
.flatten()
@@ -848,7 +890,7 @@ impl NodeNetworkInterface {
pub fn unload_node_click_targets(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
let Some(transient) = self.node_transient_mut(node_id, network_path) else {
log::error!("Could not get nested node_metadata in unload_node_click_target");
log::error!("Could not get nested node_metadata in unload_node_click_targets");
return;
};
transient.click_targets.unload();
@@ -875,3 +917,24 @@ impl NodeNetworkInterface {
}
}
}
/// Drops `input_connector` from the consumers of the output that `input` was wired to.
fn unhook_outward_wire(outward_wires: &mut HashMap<OutputConnector, Vec<InputConnector>>, input_connector: &InputConnector, input: &NodeInput) {
if let Some(output) = OutputConnector::from_input(input)
&& let Some(connections) = outward_wires.get_mut(&output)
{
connections.retain(|connection| connection != input_connector);
}
}
/// Adds `input_connector` to the consumers of the output that `input` is wired to.
fn hook_outward_wire(outward_wires: &mut HashMap<OutputConnector, Vec<InputConnector>>, input_connector: &InputConnector, input: &NodeInput) {
if let Some(output) = OutputConnector::from_input(input) {
outward_wires.entry(output).or_default().push(*input_connector);
}
}
/// The output `input` was wired to, once it has lost its last consumer.
fn drained_outward_wire(outward_wires: &HashMap<OutputConnector, Vec<InputConnector>>, input: &NodeInput) -> Option<OutputConnector> {
OutputConnector::from_input(input).filter(|output| outward_wires.get(output).is_some_and(Vec::is_empty))
}
@@ -1,4 +1,4 @@
use super::{InputConnector, OutputConnector, Previewing, RootNode, TransactionStatus};
use super::{InputConnector, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, OutputConnector, Previewing, RootNode, TransactionStatus};
use crate::messages::portfolio::document::node_graph::utility_types::Direction;
use crate::test_utils::test_prelude::*;
use graph_craft::document::NodeInput;
@@ -127,7 +127,7 @@ async fn cyclic_connection_is_rejected_without_side_effects() {
}
/// The check answers for the network with the proposed input substituted, so it has to see a loop that
/// closes through intermediate nodes rather than only one that connects two neighbours.
/// closes through intermediate nodes rather than only one that connects two neighbors.
#[tokio::test]
async fn a_cycle_closing_through_a_chain_is_rejected() {
let mut editor = EditorTestUtils::create();
@@ -172,6 +172,31 @@ async fn connecting_an_export_is_never_cyclic() {
assert_invariants(&editor, "after connecting the export");
}
#[tokio::test]
async fn toggling_preview_on_a_disconnected_export() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name(rectangle_definition()).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.disconnect_input(&InputConnector::Export(0), &[]);
// Previewing a node while the export is disconnected is a preview with nothing to restore
network_interface.toggle_preview(node, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::Yes { root_node_to_restore: None });
let export = network_interface.input_from_connector(&InputConnector::Export(0), &[]);
assert_eq!(export.and_then(|input| input.as_node()), Some(node), "The previewed node should be wired to the export");
// Ending the preview restores the disconnected export
network_interface.toggle_preview(node, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::No);
let export = network_interface.input_from_connector(&InputConnector::Export(0), &[]);
assert!(export.is_some_and(|input| input.as_node().is_none()), "Ending the preview should disconnect the export again");
assert_invariants(&editor, "after toggling preview twice");
}
#[tokio::test]
async fn artboard_identity_is_independent_of_scene_connectivity() {
let mut editor = EditorTestUtils::create();
@@ -381,10 +406,8 @@ async fn signature_edits_keep_parallel_metadata_in_sync() {
assert_invariants(&editor, "after removing the added export");
}
/// Previewing renders a different node without rewiring anything: the export keeps whatever it is
/// connected to, so ending a preview has nothing to restore and cannot disconnect anything.
#[tokio::test]
async fn previewing_leaves_the_export_alone() {
async fn toggle_preview_transitions_with_a_connected_export() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
@@ -396,125 +419,212 @@ async fn previewing_leaves_the_export_alone() {
let export_node = |network_interface: &super::NodeNetworkInterface| network_interface.input_from_connector(&InputConnector::Export(0), &[]).and_then(|input| input.as_node());
assert_eq!(export_node(network_interface), Some(artboard));
// Previewing a node names it without touching the export
// Previewing a node remembers the artboard as the connection to restore
network_interface.toggle_preview(node, &[]);
assert_eq!(export_node(network_interface), Some(node));
assert_eq!(
network_interface.previewing(&[]),
Previewing::Yes {
previewed: RootNode { node_id: node, output_index: 0 }
root_node_to_restore: Some(RootNode { node_id: artboard, output_index: 0 })
}
);
assert_eq!(export_node(network_interface), Some(artboard), "Previewing must not rewire the export");
// Previewing a different node moves the preview, still without touching the export
network_interface.toggle_preview(artboard, &[]);
assert_eq!(
network_interface.previewing(&[]),
Previewing::Yes {
previewed: RootNode { node_id: artboard, output_index: 0 }
}
);
// Toggling the previewed node again restores the artboard connection
network_interface.toggle_preview(node, &[]);
assert_eq!(export_node(network_interface), Some(artboard));
// Toggling the previewed node again ends the preview, leaving the export as it always was
network_interface.toggle_preview(artboard, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::No);
// Toggling the restore node while previewing promotes it to the export with nothing left to restore
network_interface.toggle_preview(node, &[]);
network_interface.toggle_preview(artboard, &[]);
assert_eq!(export_node(network_interface), Some(artboard));
assert_eq!(network_interface.previewing(&[]), Previewing::Yes { root_node_to_restore: None });
// Toggling it once more ends the preview by disconnecting the export entirely
network_interface.toggle_preview(artboard, &[]);
assert_eq!(export_node(network_interface), None);
assert_eq!(network_interface.previewing(&[]), Previewing::No);
assert_invariants(&editor, "after cycling through the preview states");
}
/// The graph handed to the compiler renders the previewed node, which is the whole point of a preview
/// that does not rewire the document.
#[tokio::test]
async fn the_evaluated_network_renders_the_previewed_node() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let artboard = NodeId::new();
editor.handle_message(new_artboard_message(artboard)).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 20).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.toggle_preview(node, &[]);
let evaluated = network_interface.network_to_evaluate();
assert_eq!(
evaluated.exports.first().and_then(|export| export.as_node()),
Some(node),
"The network being evaluated should export the previewed node"
);
assert_eq!(
network_interface.document_network().exports.first().and_then(|export| export.as_node()),
Some(artboard),
"The document itself should be unchanged"
);
fn assert_interface_invariants(network_interface: &NodeNetworkInterface, context: &str) {
let violations = network_interface.validate_invariants();
assert!(violations.is_empty(), "Invariant violations {context}:\n{}", violations.join("\n"));
}
/// The previewed node is marked for the frontend so it can be highlighted. Derived from the preview
/// itself: it used to be inferred from the export, which previewing no longer rewires, so inferring it
/// would silently mark nothing.
#[tokio::test]
async fn the_previewed_node_is_flagged_for_the_frontend() {
use crate::messages::portfolio::document::node_graph::NodeGraphMessageHandler;
fn value_input() -> NodeInput {
NodeInput::value(TaggedValue::None, false)
}
let mut editor = EditorTestUtils::create();
editor.new_document().await;
/// A source feeding a node that feeds a consumer, with the outward wire cache loaded so every later mutation has to keep it current.
fn wired_interface() -> (NodeNetworkInterface, NodeId, NodeId, NodeId) {
let (source, node, consumer) = (NodeId(1), NodeId(2), NodeId(3));
let mut network_interface = NodeNetworkInterface::default();
network_interface.insert_node(
source,
NodeTemplate {
inputs: vec![value_input()],
..Default::default()
},
&[],
);
network_interface.insert_node(
node,
NodeTemplate {
inputs: vec![value_input(), value_input()],
..Default::default()
},
&[],
);
network_interface.insert_node(
consumer,
NodeTemplate {
inputs: vec![value_input()],
..Default::default()
},
&[],
);
network_interface.set_input(&InputConnector::node_at_index(node, 0), NodeInput::node(source, 0), &[]);
network_interface.set_input(&InputConnector::node_at_index(consumer, 0), NodeInput::node(node, 0), &[]);
let artboard = NodeId::new();
editor.handle_message(new_artboard_message(artboard)).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 20).await;
assert!(network_interface.outward_wires(&[]).is_some());
assert_interface_invariants(&network_interface, "after wiring the fixture");
(network_interface, source, node, consumer)
}
let handler = NodeGraphMessageHandler::default();
let network_interface = &mut editor.active_document_mut().network_interface;
#[test]
fn replacing_inputs_keeps_the_loaded_wire_cache_exact() {
let (mut network_interface, source, node, _) = wired_interface();
let flagged = |handler: &NodeGraphMessageHandler, network_interface: &mut super::NodeNetworkInterface| {
handler
.collect_nodes(network_interface, &[])
.into_iter()
.filter(|node| node.previewed)
.map(|node| node.id)
.collect::<Vec<_>>()
let mut template = NodeTemplate {
inputs: vec![value_input(); 3],
..Default::default()
};
template.normalize_input_metadata();
network_interface.replace_inputs(&node, &[], &mut template);
assert_interface_invariants(&network_interface, "after replacing the inputs of a wired node");
// The wire returns at a new index, as a migration restores the inputs it keeps
network_interface.set_input(&InputConnector::node_at_index(node, 2), NodeInput::node(source, 0), &[]);
assert_interface_invariants(&network_interface, "after rewiring the source into the replaced node");
}
#[test]
fn replacing_an_implementation_keeps_its_outputs_listed_in_the_wire_cache() {
let (mut network_interface, _, node, _) = wired_interface();
let second_output = OutputConnector::node(node, 1);
// An implementation swap leaves the output names to the open path, so restore them as it does before validating
let swap_implementation = |network_interface: &mut NodeNetworkInterface, template: &mut NodeTemplate, context: &str| {
network_interface.replace_implementation(&node, &[], template);
let document_node = network_interface.document_node(&node, &[]).cloned().unwrap();
network_interface.validate_output_names(&node, &document_node, &[]);
assert_interface_invariants(network_interface, context);
};
assert!(flagged(&handler, network_interface).is_empty(), "Nothing is previewed to begin with");
let two_exports = NodeNetworkTemplate {
exports: vec![value_input(), value_input()],
..Default::default()
};
let mut template = NodeTemplate {
implementation: NodeTemplateImplementation::Network(two_exports),
..Default::default()
};
swap_implementation(&mut network_interface, &mut template, "after giving a node a second output");
assert!(
network_interface.outward_wires(&[]).is_some_and(|wires| wires.contains_key(&second_output)),
"a gained output should be listed"
);
network_interface.toggle_preview(node, &[]);
assert_eq!(flagged(&handler, network_interface), vec![node], "The previewed node should be the one flagged");
network_interface.toggle_preview(node, &[]);
assert!(flagged(&handler, network_interface).is_empty(), "Ending the preview should unflag it");
swap_implementation(&mut network_interface, &mut NodeTemplate::default(), "after taking the second output away");
assert!(
network_interface.outward_wires(&[]).is_some_and(|wires| !wires.contains_key(&second_output)),
"a lost output should be delisted"
);
}
/// Resolving a batch of positions shares one downstream walk, so it has to agree with resolving each
/// node on its own. A stack is the case that matters: every layer walks through the ones below it, so
/// a shared memo is what keeps the batch from being quadratic.
#[tokio::test]
async fn batched_positions_agree_with_resolving_each_node() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(new_artboard_message(NodeId::new())).await;
// A vanished output keeps its entry while a consumer is still wired to it, so the entry has to go when that consumer leaves
#[test]
fn rewiring_off_a_vanished_output_delists_it_from_the_wire_cache() {
let (mut network_interface, source, node, consumer) = wired_interface();
let second_output = OutputConnector::node(node, 1);
for offset in 0..4 {
editor.draw_rect(0., offset as f64 * 20., 100., offset as f64 * 20. + 10.).await;
}
let restore_output_names = |network_interface: &mut NodeNetworkInterface| {
let document_node = network_interface.document_node(&node, &[]).cloned().unwrap();
network_interface.validate_output_names(&node, &document_node, &[]);
};
let network_interface = &editor.active_document().network_interface;
let node_ids = network_interface.document_network().nodes.keys().copied().collect::<Vec<_>>();
assert!(node_ids.len() > 4, "the fixture should build a stack, found {} nodes", node_ids.len());
// Give the node a second output and move the consumer onto it
let two_exports = NodeNetworkTemplate {
exports: vec![value_input(), value_input()],
..Default::default()
};
let mut template = NodeTemplate {
implementation: NodeTemplateImplementation::Network(two_exports),
..Default::default()
};
network_interface.replace_implementation(&node, &[], &mut template);
restore_output_names(&mut network_interface);
network_interface.set_input(&InputConnector::node_at_index(consumer, 0), NodeInput::node(node, 1), &[]);
assert_interface_invariants(&network_interface, "after wiring a consumer to the second output");
let batched = network_interface.positions(node_ids.iter().copied(), &[]);
let individually = node_ids
.iter()
.filter_map(|node_id| network_interface.position(node_id, &[]).map(|position| (*node_id, position)))
.collect::<Vec<_>>();
// Taking that output away leaves the consumer dangling, which a fresh computation still lists
network_interface.replace_implementation(&node, &[], &mut NodeTemplate::default());
restore_output_names(&mut network_interface);
assert!(
network_interface.outward_wires(&[]).is_some_and(|wires| wires.contains_key(&second_output)),
"a vanished output should keep its entry while something is still wired to it"
);
assert_eq!(batched.len(), individually.len(), "The batch should resolve exactly the nodes that resolve on their own");
for (node_id, position) in individually {
assert_eq!(
batched.iter().find(|(batched_id, _)| *batched_id == node_id).map(|(_, position)| *position),
Some(position),
"Batched position disagrees for node {node_id}"
);
}
network_interface.set_input(&InputConnector::node_at_index(consumer, 0), NodeInput::node(source, 0), &[]);
assert!(
network_interface.outward_wires(&[]).is_some_and(|wires| !wires.contains_key(&second_output)),
"the entry should go once the last consumer leaves a vanished output"
);
assert_interface_invariants(&network_interface, "after rewiring off a vanished output");
}
#[test]
fn inserting_and_deleting_nodes_keeps_the_loaded_wire_cache_exact() {
let (mut network_interface, _, node, _) = wired_interface();
network_interface.insert_node(NodeId(4), NodeTemplate::default(), &[]);
assert_interface_invariants(&network_interface, "after inserting a node while the cache is loaded");
network_interface.delete_nodes(vec![node], false, &[]);
assert_interface_invariants(&network_interface, "after deleting a wired node");
}
#[test]
fn adding_an_import_ahead_of_a_wired_input_keeps_the_loaded_wire_cache_exact() {
let (source, node) = (NodeId(1), NodeId(2));
let mut network_interface = NodeNetworkInterface::default();
network_interface.insert_node(
source,
NodeTemplate {
inputs: vec![value_input()],
..Default::default()
},
&[],
);
let network = NodeNetworkTemplate {
exports: vec![value_input()],
..Default::default()
};
let template = NodeTemplate {
implementation: NodeTemplateImplementation::Network(network),
inputs: vec![value_input()],
output_names: vec![String::new()],
..Default::default()
};
network_interface.insert_node(node, template, &[]);
network_interface.set_input(&InputConnector::node_at_index(node, 0), NodeInput::node(source, 0), &[]);
assert!(network_interface.outward_wires(&[]).is_some());
// Inserting ahead of the wired input moves that wire to index 1
network_interface.add_import(TaggedValue::None, true, 0, "", "", &[node]);
assert_interface_invariants(&network_interface, "after adding an import ahead of a wired input");
let consumers = network_interface.outward_wires(&[]).and_then(|wires| wires.get(&OutputConnector::node(source, 0)).cloned());
assert_eq!(consumers.as_deref(), Some([InputConnector::node_at_index(node, 1)].as_slice()));
}
@@ -4,7 +4,7 @@ use super::{InputMetadata, InputPersistentMetadata};
use document_graph_storage::attr::network as network_attr;
use document_graph_storage::attr::node as node_attr;
use document_graph_storage::from_runtime::{ConversionError, DeclarationBytes};
use document_graph_storage::{AttributeDelta, Attributes, Implementation, NodeMetadataSource, PathResolver, Position, Registry, RegistryDelta, ScopedConversion, TimeStamp};
use document_graph_storage::{AttributeDelta, Attributes, Implementation, NodeMetadataSource, PathResolver, Position, Registry, RegistryDelta, ScopedConversion, TimeStamp, Value};
use document_graph_storage::{convert_input_attributes, convert_resource_entry, encode_input_ui_attributes, encode_node_ui_attributes, node_value_resource_refs, value_resource_ref};
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry};
use graph_craft::document::NodeId;
@@ -82,7 +82,15 @@ pub enum NetworkMetadataChange {
pub struct ConstructedOps {
pub ops: Vec<RegistryDelta>,
pub declaration_bytes: DeclarationBytes,
pub declarations: BatchDeclarations,
}
/// The proto-node declarations a batch extracted: the bytes for the caller's byte store, and the same
/// declarations decoded for its declaration cache, which a cursor rebuild reads instead of the bytes.
#[derive(Default)]
pub struct BatchDeclarations {
pub bytes: DeclarationBytes,
pub decoded: document_graph_storage::Declarations,
}
/// Constructs the storage ops for one gesture's deltas, in delta order. Removal closures and
@@ -100,57 +108,67 @@ pub fn construct_batch(
peer: document_graph_storage::PeerId,
) -> Result<ConstructedOps, ConversionError> {
let identities = IdentitiesOnly(metadata);
let resolver = PathResolver::new(Some(&identities), peer);
let context = ConversionContext {
resources,
identities: &identities,
resolver: PathResolver::new(Some(&identities), peer),
peer,
};
let mut batch = BatchRegistry::new(working);
let mut ops = Vec::new();
let mut declaration_bytes = DeclarationBytes::new();
let mut declarations = BatchDeclarations::default();
let mut batch_removed_nodes = Vec::new();
// In delta order, so each delta reads what the ones before it did. Removals accumulate as they are
// met rather than being gathered up front, since a removal can name a node an earlier delta added.
// In delta order, so each delta reads what the ones before it did
for delta in deltas {
delta.construct(resources, peer, &identities, &resolver, &mut batch, &mut batch_removed_nodes, &mut ops, &mut declaration_bytes)?;
delta.construct(&context, &mut batch, &mut batch_removed_nodes, &mut ops, &mut declarations)?;
}
batch_removed_nodes.sort();
batch_removed_nodes.dedup();
batch_removed_nodes.sort_by_key(|(id, _)| *id);
batch_removed_nodes.dedup_by_key(|(id, _)| *id);
construct_resource_removals(&batch_removed_nodes, &batch, &mut ops);
Ok(ConstructedOps { ops, declaration_bytes })
Ok(ConstructedOps { ops, declarations })
}
/// What every delta in a batch converts against, fixed for the whole batch.
struct ConversionContext<'a> {
resources: &'a ResourceRegistry,
identities: &'a dyn NodeMetadataSource,
resolver: PathResolver<'a>,
peer: document_graph_storage::PeerId,
}
impl EditorDelta {
#[allow(clippy::too_many_arguments)]
fn construct(
&self,
resources: &ResourceRegistry,
peer: document_graph_storage::PeerId,
identities: &dyn NodeMetadataSource,
resolver: &PathResolver,
context: &ConversionContext,
batch: &mut BatchRegistry,
batch_removed_nodes: &mut Vec<document_graph_storage::NodeId>,
batch_removed_nodes: &mut Vec<(document_graph_storage::NodeId, document_graph_storage::Node)>,
ops: &mut Vec<RegistryDelta>,
declaration_bytes: &mut DeclarationBytes,
declarations: &mut BatchDeclarations,
) -> Result<(), ConversionError> {
match self {
EditorDelta::Graph(RuntimeDelta::AddNode { network_path, node_id, node }) => {
construct_structural_additions(network_path, *node_id, node, batch, resources, identities, peer, ops, declaration_bytes)?;
construct_structural_additions(network_path, *node_id, node, batch, context, ops, declarations)?;
}
EditorDelta::Graph(RuntimeDelta::ReplaceNode { network_path, node_id, node }) => {
construct_removals(resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
construct_structural_additions(network_path, *node_id, node, batch, resources, identities, peer, ops, declaration_bytes)?;
// Only what the previous implementation owned goes; the node stays so the addition below
// updates it in place and its `ui::*` attributes survive the swap.
construct_removals_below(context.resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
construct_structural_additions(network_path, *node_id, node, batch, context, ops, declarations)?;
}
EditorDelta::Graph(RuntimeDelta::RemoveNode { network_path, node_id }) => {
construct_removals(resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
construct_removals(context.resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
}
EditorDelta::Graph(RuntimeDelta::SetVisibility { network_path, node_id, visible }) => {
ops.push(RegistryDelta::ChangeNodeAttribute {
id: resolver.node_id(network_path, *node_id),
id: context.resolver.node_id(network_path, *node_id),
delta: AttributeDelta {
key: node_attr::VISIBLE.to_string(),
value: (!visible).then_some(serde_json::Value::Bool(false)),
value: (!visible).then_some(Value::Bool(false)),
},
});
}
@@ -161,24 +179,32 @@ impl EditorDelta {
input_index,
input,
}) => {
let new_input = context.resolver.convert_input_at(input, network_path)?;
construct_referenced_resource(Some(context.resolver.node_id(network_path, *node_id)), &new_input, context, batch, ops)?;
ops.push(RegistryDelta::ChangeNodeInput {
id: resolver.node_id(network_path, *node_id),
id: context.resolver.node_id(network_path, *node_id),
index: (*input_index).try_into().map_err(|_| ConversionError::IndexOverflow(*input_index))?,
new_input: resolver.convert_input_at(input, network_path)?,
new_input,
});
}
EditorDelta::Graph(RuntimeDelta::SetExport { network_path, export_index, input }) => {
let export = input.as_ref().map(|input| context.resolver.convert_input_at(input, network_path)).transpose()?;
if let Some(export) = export.as_ref() {
construct_referenced_resource(None, export, context, batch, ops)?;
}
ops.push(RegistryDelta::SetNetworkExport {
id: resolver.network_id(network_path),
id: context.resolver.network_id(network_path),
index: (*export_index).try_into().map_err(|_| ConversionError::IndexOverflow(*export_index))?,
export: input.as_ref().map(|input| resolver.convert_input_at(input, network_path)).transpose()?,
export,
});
}
EditorDelta::Graph(RuntimeDelta::SetCallArgument { network_path, node_id, call_argument }) => {
ops.push(RegistryDelta::ChangeNodeAttribute {
id: resolver.node_id(network_path, *node_id),
id: context.resolver.node_id(network_path, *node_id),
delta: document_graph_storage::from_runtime::encode_call_argument(call_argument)?,
});
}
@@ -189,38 +215,41 @@ impl EditorDelta {
context_features,
}) => {
ops.push(RegistryDelta::ChangeNodeAttribute {
id: resolver.node_id(network_path, *node_id),
id: context.resolver.node_id(network_path, *node_id),
delta: document_graph_storage::from_runtime::encode_context_features(context_features)?,
});
}
EditorDelta::NodeMetadataSnapshot { network_path, node_id, metadata } => {
construct_metadata_snapshot(network_path, *node_id, metadata, batch, resolver, ops)?;
construct_metadata_snapshot(network_path, *node_id, metadata, batch, &context.resolver, ops)?;
}
EditorDelta::Graph(RuntimeDelta::SetInputs { network_path, node_id, inputs }) => {
// Only the slots are written, so the node's attributes and everything nested under it are
// left as they are: an edit made earlier in this batch is not reverted by the rebuild.
// The slots' `ui::*` attributes arrive with the paired input metadata delta.
// The slots' `ui::*` attributes arrive with the paired input metadata delta
let inputs = inputs
.iter()
.map(|input| {
Ok(document_graph_storage::InputSlot {
input: resolver.convert_input_at(input, network_path)?,
input: context.resolver.convert_input_at(input, network_path)?,
timestamp: TimeStamp::ORIGIN,
attributes: convert_input_attributes(input)?,
attributes_timestamp: TimeStamp::ORIGIN,
})
})
.collect::<Result<Vec<_>, ConversionError>>()?;
for slot in &inputs {
construct_referenced_resource(Some(context.resolver.node_id(network_path, *node_id)), &slot.input, context, batch, ops)?;
}
ops.push(RegistryDelta::SetNodeInputs {
id: resolver.node_id(network_path, *node_id),
id: context.resolver.node_id(network_path, *node_id),
inputs,
});
}
EditorDelta::NodeMetadata { network_path, node_id, change } => {
ops.extend(node_metadata_ops(resolver.node_id(network_path, *node_id), change)?);
ops.extend(node_metadata_ops(context.resolver.node_id(network_path, *node_id), change)?);
}
EditorDelta::NodeInputMetadata {
@@ -228,12 +257,10 @@ impl EditorDelta {
node_id,
input_metadata,
} => {
let global_id = resolver.node_id(network_path, *node_id);
let global_id = context.resolver.node_id(network_path, *node_id);
let source = InputMetadataSource(input_metadata);
let working_node = batch.node(global_id);
// An insert shifts every later slot, so the array is asserted whole: a `ui::` key the slot
// no longer carries is cleared rather than left behind at its old index.
for input_index in 0..input_metadata.len() {
let mut encoded = Attributes::new();
encode_input_ui_attributes(&mut encoded, &source, network_path, *node_id, input_index, TimeStamp::ORIGIN)?;
@@ -253,10 +280,10 @@ impl EditorDelta {
let delta = match change {
NetworkMetadataChange::Reference(reference) => AttributeDelta {
key: node_attr::ui::REFERENCE.to_string(),
value: reference.clone().map(serde_json::Value::String),
value: reference.clone().map(Value::Str),
},
NetworkMetadataChange::PinnedOrder(order) => {
let stored: Vec<_> = order.iter().map(|node_id| resolver.node_id(network_path, *node_id)).collect();
let stored: Vec<_> = order.iter().map(|node_id| context.resolver.node_id(network_path, *node_id)).collect();
AttributeDelta {
key: network_attr::PINNED_ORDER.to_string(),
value: (!stored.is_empty()).then(|| serialize_attribute(network_attr::PINNED_ORDER, &stored)).transpose()?,
@@ -265,7 +292,7 @@ impl EditorDelta {
};
ops.push(RegistryDelta::ChangeNetworkAttribute {
id: resolver.network_id(network_path),
id: context.resolver.network_id(network_path),
delta,
});
}
@@ -275,8 +302,8 @@ impl EditorDelta {
}
}
fn serialize_attribute<T: serde::Serialize>(key: &str, value: &T) -> Result<serde_json::Value, ConversionError> {
serde_json::to_value(value).map_err(|error| ConversionError::SerializationError(format!("{key}: {error:?}")))
fn serialize_attribute<T: serde::Serialize>(key: &str, value: &T) -> Result<Value, ConversionError> {
document_graph_storage::to_value(value).map_err(|error| ConversionError::SerializationError(format!("{key}: {error:?}")))
}
/// The attribute writes one metadata field makes, as the whole-document encoder would write them.
@@ -284,11 +311,11 @@ fn serialize_attribute<T: serde::Serialize>(key: &str, value: &T) -> Result<serd
/// A field set back to its unset value clears the attribute, since absence is how that encoder spells
/// unset. Clearing rather than writing a sentinel keeps the two paths producing the same registry.
fn node_metadata_ops(global_id: document_graph_storage::NodeId, change: &NodeMetadataChange) -> Result<Vec<RegistryDelta>, ConversionError> {
let node_attribute = |key: &str, value: Option<serde_json::Value>| RegistryDelta::ChangeNodeAttribute {
let node_attribute = |key: &str, value: Option<Value>| RegistryDelta::ChangeNodeAttribute {
id: global_id,
delta: AttributeDelta { key: key.to_string(), value },
};
let input_attribute = |key: &str, index: usize, value: Option<serde_json::Value>| {
let input_attribute = |key: &str, index: usize, value: Option<Value>| {
Ok::<_, ConversionError>(RegistryDelta::ChangeNodeInputAttribute {
id: global_id,
index: index.try_into().map_err(|_| ConversionError::IndexOverflow(index))?,
@@ -296,10 +323,9 @@ fn node_metadata_ops(global_id: document_graph_storage::NodeId, change: &NodeMet
})
};
// Absence is how the encoder spells an unset flag, and the empty string is the runtime's own
// sentinel for an unset name.
let flag = |value: bool| value.then_some(serde_json::Value::Bool(true));
let non_empty = |value: &str| (!value.is_empty()).then(|| serde_json::Value::String(value.to_string()));
// The empty string is the runtime's own sentinel for an unset name
let flag = |value: bool| value.then_some(Value::Bool(true));
let non_empty = |value: &str| (!value.is_empty()).then(|| Value::Str(value.to_string()));
Ok(match change {
NodeMetadataChange::NodeType(node_type) => {
let position = position_from_runtime(node_type);
@@ -325,36 +351,67 @@ fn node_metadata_ops(global_id: document_graph_storage::NodeId, change: &NodeMet
/// Converts through the same encoders as a whole-document conversion, with identities only as the
/// source: ui attributes arrive via the gesture's paired `NodeMetadata` delta.
#[allow(clippy::too_many_arguments)]
fn construct_structural_additions(
network_path: &[NodeId],
node_id: NodeId,
node: &graph_craft::document::DocumentNode,
batch: &mut BatchRegistry,
resources: &ResourceRegistry,
identities: &dyn NodeMetadataSource,
peer: document_graph_storage::PeerId,
context: &ConversionContext,
ops: &mut Vec<RegistryDelta>,
declaration_bytes: &mut DeclarationBytes,
declarations: &mut BatchDeclarations,
) -> Result<(), ConversionError> {
let mut scoped = ScopedConversion::new(identities, peer);
let mut scoped = ScopedConversion::new(context.identities, context.peer);
let mut scratch = Registry::default();
scoped.convert_node_at(&mut scratch, network_path, node_id, node, true)?;
declaration_bytes.extend(scoped.finish());
let (bytes, decoded) = scoped.finish();
declarations.bytes.extend(bytes);
declarations.decoded.extend(decoded);
let mut networks: Vec<_> = scratch.networks.iter().collect();
networks.sort_by_key(|(id, _)| **id);
let mut networks: Vec<_> = scratch.networks.iter().map(|(id, network)| (*id, network.clone())).collect();
networks.sort_by_key(|(id, _)| *id);
for (id, network) in networks {
ops.push(RegistryDelta::AddNetwork { id: *id, network: network.clone() });
ops.push(RegistryDelta::AddNetwork { id, network: network.clone() });
batch.record_network(id, network);
}
// Recorded as well as emitted, so a later delta in this batch that reads one of these nodes back
// finds it rather than looking only at the registry the batch started from.
// Recorded as well as emitted, so a later delta in this batch can read these nodes back
let mut nodes: Vec<_> = scratch.node_instances.iter().collect();
nodes.sort_by_key(|(id, _)| **id);
let added: Vec<_> = nodes.into_iter().map(|(id, node)| (*id, node.clone())).collect();
for (id, node) in added {
ops.push(RegistryDelta::AddNode { id, node: node.clone() });
// A node the registry already holds is updated rather than rebuilt: rebuilding would clear the
// `ui::*` attributes it carries, and restating those would clobber whatever a concurrent peer
// wrote to its name, lock or pin.
match batch.node(id) {
Some(held) => {
// The swap did not write the slots' `ui::*` attributes; a whole-slot assignment would drop the
// names and descriptions held for the slots that survive it.
let inputs = node
.inputs()
.iter()
.enumerate()
.map(|(index, slot)| {
let mut slot = slot.clone();
if let Some(previous) = held.inputs().get(index) {
slot.attributes.extend(
previous
.attributes
.iter()
.filter(|(key, value)| key.starts_with("ui::") && !value.deleted)
.map(|(key, value)| (key.clone(), value.clone())),
);
}
slot
})
.collect();
ops.push(RegistryDelta::SetNodeImplementation {
id,
implementation: node.implementation().clone(),
});
ops.push(RegistryDelta::SetNodeInputs { id, inputs });
}
None => ops.push(RegistryDelta::AddNode { id, node: node.clone() }),
}
batch.record_addition(id, node);
}
@@ -376,7 +433,7 @@ fn construct_structural_additions(
for id in tagged {
if batch.resource(id).is_none()
&& !scratch.resources.contains_key(&id)
&& let Some(entry) = convert_resource_entry(resources, id, peer)?
&& let Some(entry) = convert_resource_entry(context.resources, id, context.peer)?
{
batch.record_resource(id, entry.clone());
ops.push(RegistryDelta::AddResource { id, entry });
@@ -386,6 +443,31 @@ fn construct_structural_additions(
Ok(())
}
/// Stages the resource a value input references, so setting an input to an asset persists the entry
/// alongside the reference rather than leaving the registry pointing at something it does not hold.
fn construct_referenced_resource(
owner: Option<document_graph_storage::NodeId>,
input: &document_graph_storage::NodeInput,
context: &ConversionContext,
batch: &mut BatchRegistry,
ops: &mut Vec<RegistryDelta>,
) -> Result<(), ConversionError> {
let Some(id) = value_resource_ref(input) else { return Ok(()) };
if let Some(owner) = owner {
batch.record_input_resource(owner, id);
}
if batch.resource(id).is_some() {
return Ok(());
}
let Some(entry) = convert_resource_entry(context.resources, id, context.peer)? else {
return Ok(());
};
batch.record_resource(id, entry.clone());
ops.push(RegistryDelta::AddResource { id, entry });
Ok(())
}
fn construct_metadata_snapshot(
network_path: &[NodeId],
node_id: NodeId,
@@ -429,11 +511,12 @@ fn construct_metadata_snapshot(
nested_path.push(id);
let network_id = resolver.network_id(&nested_path);
let target = network_metadata.persistent_metadata.reference.clone().map(serde_json::Value::String);
let target = network_metadata.persistent_metadata.reference.clone().map(Value::Str);
// Read through the batch rather than the pre-batch registry: a `ReplaceNode` earlier in this
// batch rebuilds the network without a reference, so comparing against the old state would
// suppress the write and leave the rebuilt network missing it.
let current = batch
.working
.networks
.get(&network_id)
.network(network_id)
.and_then(|network| network.attributes.get(node_attr::ui::REFERENCE))
.map(|value| value.value.clone());
if current != target {
@@ -446,6 +529,22 @@ fn construct_metadata_snapshot(
});
}
// Restated alongside the reference, since a rebuild clears the network's attributes and the
// order would otherwise be lost for every nested network the snapshot covers.
let pinned_order: Vec<_> = network_metadata
.persistent_metadata
.pinned_node_order
.iter()
.map(|pinned| resolver.node_id(&nested_path, *pinned))
.collect();
ops.push(RegistryDelta::ChangeNetworkAttribute {
id: network_id,
delta: AttributeDelta {
key: network_attr::PINNED_ORDER.to_string(),
value: (!pinned_order.is_empty()).then(|| serialize_attribute(network_attr::PINNED_ORDER, &pinned_order)).transpose()?,
},
});
for (child_id, child) in &network_metadata.persistent_metadata.node_metadata {
pending.push((nested_path.clone(), *child_id, &child.persistent_metadata));
}
@@ -486,37 +585,69 @@ fn ui_attribute_writes(current: Option<&Attributes>, encoded: &Attributes) -> Ve
/// Emits the removal of a node and everything nested under it, recording what was removed so the
/// batch's resource liveness accounts for all of it at the end.
fn construct_removals(node_id: document_graph_storage::NodeId, batch: &BatchRegistry, batch_removed_nodes: &mut Vec<document_graph_storage::NodeId>, ops: &mut Vec<RegistryDelta>) {
fn construct_removals(
node_id: document_graph_storage::NodeId,
batch: &mut BatchRegistry,
batch_removed_nodes: &mut Vec<(document_graph_storage::NodeId, document_graph_storage::Node)>,
ops: &mut Vec<RegistryDelta>,
) {
construct_removals_with(node_id, true, batch, batch_removed_nodes, ops)
}
/// Removes everything the node's implementation owns while leaving the node itself, for a swap that
/// keeps the node in place.
fn construct_removals_below(
node_id: document_graph_storage::NodeId,
batch: &mut BatchRegistry,
batch_removed_nodes: &mut Vec<(document_graph_storage::NodeId, document_graph_storage::Node)>,
ops: &mut Vec<RegistryDelta>,
) {
construct_removals_with(node_id, false, batch, batch_removed_nodes, ops)
}
fn construct_removals_with(
node_id: document_graph_storage::NodeId,
include_node: bool,
batch: &mut BatchRegistry,
batch_removed_nodes: &mut Vec<(document_graph_storage::NodeId, document_graph_storage::Node)>,
ops: &mut Vec<RegistryDelta>,
) {
let (mut removed_nodes, mut removed_networks) = removal_closure(node_id, batch);
removed_nodes.sort();
removed_networks.sort();
for id in &removed_nodes {
let Some(snapshot) = batch.node(*id) else { continue };
if !include_node && *id == node_id {
continue;
}
let Some(snapshot) = batch.node(*id).cloned() else { continue };
ops.push(RegistryDelta::RemoveNode { id: *id, snapshot: snapshot.clone() });
// Kept by value: a replacement later in this batch re-adds the same ID with different content, so
// looking the node up again at the end would read what replaced it rather than what was removed.
batch_removed_nodes.push((*id, snapshot));
batch.record_removal(*id);
}
for id in &removed_networks {
let Some(snapshot) = batch.working.networks.get(id) else { continue };
let Some(snapshot) = batch.network(*id) else { continue };
ops.push(RegistryDelta::RemoveNetwork { id: *id, snapshot: snapshot.clone() });
}
batch_removed_nodes.extend(removed_nodes);
}
/// Emits removals for resources referenced only by the batch's removed nodes, checked after every
/// removal is known.
fn construct_resource_removals(batch_removed_nodes: &[document_graph_storage::NodeId], batch: &BatchRegistry, ops: &mut Vec<RegistryDelta>) {
let removed_node_set: HashSet<_> = batch_removed_nodes.iter().copied().collect();
fn construct_resource_removals(batch_removed_nodes: &[(document_graph_storage::NodeId, document_graph_storage::Node)], batch: &BatchRegistry, ops: &mut Vec<RegistryDelta>) {
// A node this batch wrote an input on and then removed orphans whatever that write referenced, which
// the stored node does not mention.
let mut candidates: Vec<ResourceId> = batch_removed_nodes
.iter()
.filter_map(|id| batch.node(*id))
.flat_map(|node| {
.flat_map(|(id, _)| batch.input_resources.get(id).into_iter().flatten().copied())
.chain(batch_removed_nodes.iter().map(|(_, node)| node).flat_map(|node| {
let declaration = match node.implementation() {
Implementation::ProtoNode(declaration) => Some(*declaration),
Implementation::Network(_) => None,
};
declaration.into_iter().chain(node_value_resource_refs(node))
})
}))
.collect();
candidates.sort();
candidates.dedup();
@@ -526,16 +657,18 @@ fn construct_resource_removals(batch_removed_nodes: &[document_graph_storage::No
// Gathered in one pass so each candidate is a lookup rather than another scan of the whole registry
let mut still_referenced: HashSet<ResourceId> = HashSet::new();
for (id, node) in batch.working.node_instances.iter().chain(&batch.added) {
if removed_node_set.contains(id) {
continue;
}
for (id, node) in batch.live_nodes() {
if let Implementation::ProtoNode(declaration) = node.implementation() {
still_referenced.insert(*declaration);
}
still_referenced.extend(node_value_resource_refs(node));
// What this batch wrote onto a node that survives it is a live reference, even though the stored
// node still carries the input it had before.
still_referenced.extend(batch.input_resources.get(&id).into_iter().flatten().copied());
}
for network in batch.working.networks.values() {
// The batch's own networks count too: one added earlier in it can export a resource the removal would
// otherwise see as orphaned.
for network in batch.working.networks.values().chain(batch.added_networks.values()) {
still_referenced.extend(network.exports.iter().filter_map(|slot| slot.target.as_ref().and_then(value_resource_ref)));
}
@@ -552,20 +685,24 @@ fn construct_resource_removals(batch_removed_nodes: &[document_graph_storage::No
}
/// The registry a delta is constructed against: what the batch started from, plus the nodes deltas
/// earlier in the same batch have added.
///
/// A delta that reads a node back cannot read only the starting registry. A node added and removed
/// within one batch is not in it, and a later delta that rebuilds a node would rebuild the version
/// that predates the batch. Additions are tracked rather than the whole registry copied, so the cost
/// is the size of the batch rather than of the document.
/// earlier in the same batch have added, since a delta can read back or remove a node an earlier one
/// added.
///
/// Nodes are also indexed by network, so a removal closure walks only the subtree it removes instead
/// of rescanning every node for each nested network it meets.
struct BatchRegistry<'a> {
working: &'a Registry,
added: HashMap<document_graph_storage::NodeId, document_graph_storage::Node>,
added_networks: HashMap<document_graph_storage::NetworkId, document_graph_storage::Network>,
added_resources: HashMap<ResourceId, document_graph_storage::ResourceEntry>,
by_network: HashMap<document_graph_storage::NetworkId, Vec<document_graph_storage::NodeId>>,
/// Nodes the batch has removed and not since re-added, so a lookup answers with the state the ops so
/// far have produced rather than the state the batch started from.
removed: HashSet<document_graph_storage::NodeId>,
/// Resources the batch's own input writes reference, keyed by the node written to. The stored node
/// still holds its pre-batch inputs, so liveness would otherwise miss both the reference these writes
/// create and the orphan they leave when that node is later removed.
input_resources: HashMap<document_graph_storage::NodeId, HashSet<ResourceId>>,
}
impl<'a> BatchRegistry<'a> {
@@ -577,17 +714,38 @@ impl<'a> BatchRegistry<'a> {
Self {
working,
added: HashMap::new(),
added_networks: HashMap::new(),
added_resources: HashMap::new(),
by_network,
removed: HashSet::new(),
input_resources: HashMap::new(),
}
}
/// Records that an input write on `owner` references `resource`.
fn record_input_resource(&mut self, owner: document_graph_storage::NodeId, resource: ResourceId) {
self.input_resources.entry(owner).or_default().insert(resource);
}
/// Records a node an earlier delta in this batch added, so a later one can read it back.
fn record_addition(&mut self, id: document_graph_storage::NodeId, node: document_graph_storage::Node) {
self.by_network.entry(node.network()).or_default().push(id);
self.removed.remove(&id);
self.added.insert(id, node);
}
/// Records a node this batch removed, so a later delta reading it back finds it gone.
fn record_removal(&mut self, id: document_graph_storage::NodeId) {
self.added.remove(&id);
self.removed.insert(id);
}
/// Records a network an earlier delta in this batch added, so removing the node that owns it finds
/// the network to remove alongside it.
fn record_network(&mut self, id: document_graph_storage::NetworkId, network: document_graph_storage::Network) {
self.added_networks.insert(id, network);
}
/// Records a resource this batch added. Returns whether it is new to the batch, so the caller emits
/// one addition for a resource several nodes reference.
fn record_resource(&mut self, id: ResourceId, entry: document_graph_storage::ResourceEntry) -> bool {
@@ -595,9 +753,29 @@ impl<'a> BatchRegistry<'a> {
}
fn node(&self, id: document_graph_storage::NodeId) -> Option<&document_graph_storage::Node> {
if self.removed.contains(&id) {
return None;
}
self.added.get(&id).or_else(|| self.working.node_instances.get(&id))
}
/// Every node the batch leaves in place, which is what the working registry held plus what the batch
/// added, less what it removed.
fn live_nodes(&self) -> impl Iterator<Item = (document_graph_storage::NodeId, &document_graph_storage::Node)> {
self.working
.node_instances
.keys()
.chain(self.added.keys())
.copied()
.collect::<HashSet<_>>()
.into_iter()
.filter_map(|id| Some((id, self.node(id)?)))
}
fn network(&self, id: document_graph_storage::NetworkId) -> Option<&document_graph_storage::Network> {
self.added_networks.get(&id).or_else(|| self.working.networks.get(&id))
}
fn resource(&self, id: ResourceId) -> Option<&document_graph_storage::ResourceEntry> {
self.added_resources.get(&id).or_else(|| self.working.resources.get(&id))
}
@@ -662,8 +840,10 @@ impl NodeMetadataSource for InputMetadataSource<'_> {
self.persistent(input_index)?.widget_override.as_deref()
}
fn input_data(&self, _network_path: &[NodeId], _local_id: NodeId, input_index: usize) -> HashMap<String, serde_json::Value> {
self.persistent(input_index).map(|metadata| metadata.input_data.clone()).unwrap_or_default()
fn input_data(&self, _network_path: &[NodeId], _local_id: NodeId, input_index: usize) -> HashMap<String, Value> {
self.persistent(input_index)
.map(|metadata| metadata.input_data.iter().map(|(key, value)| (key.clone(), value.clone().into())).collect())
.unwrap_or_default()
}
}
@@ -753,10 +933,10 @@ impl document_graph_storage::NodeMetadataSource for MetadataCopySource<'_> {
.and_then(|input| input.persistent_metadata.widget_override.as_deref())
}
fn input_data(&self, metadata_path: &[NodeId], node_id: NodeId, input_index: usize) -> std::collections::HashMap<String, serde_json::Value> {
fn input_data(&self, metadata_path: &[NodeId], node_id: NodeId, input_index: usize) -> std::collections::HashMap<String, Value> {
self.metadata_for(metadata_path, node_id)
.and_then(|metadata| metadata.input_metadata.get(input_index))
.map(|input| input.persistent_metadata.input_data.clone())
.map(|input| input.persistent_metadata.input_data.iter().map(|(key, value)| (key.clone(), value.clone().into())).collect())
.unwrap_or_default()
}
@@ -78,7 +78,7 @@ async fn set_input_value_constructs_the_exact_diff_op() {
let node = editor.create_node_by_name(rectangle_definition()).await;
let working = convert(&editor);
let input = NodeInput::value(TaggedValue::F64(42.), false);
let input = NodeInput::value(TaggedValue::Number(42.), false);
editor.active_document_mut().network_interface.set_input(&InputConnector::node_at_index(node, 1), input.clone(), &[]);
let delta = EditorDelta::Graph(RuntimeDelta::SetInput {
@@ -195,9 +195,8 @@ async fn per_field_metadata_edits_match_the_diff() {
assert_same_stored_effect(&working, constructed, diffed, "per-field metadata edits");
}
/// The encoding spells "unset" as an absent attribute, so a field set back to its unset value has to
/// clear the key rather than write a sentinel. The wholesale copy got this by omitting the key; a
/// per-field delta has to say it, and saying it wrong leaves the old value stored.
/// The encoding spells "unset" as an absent attribute, so a per-field delta that sets a field back to
/// its unset value must clear the key rather than write a sentinel.
#[tokio::test]
async fn clearing_a_metadata_field_removes_the_attribute() {
let mut editor = EditorTestUtils::create();
@@ -227,9 +226,9 @@ async fn clearing_a_metadata_field_removes_the_attribute() {
assert_same_stored_effect(&working, constructed, diffed, "cleared metadata fields");
}
/// The gate emission exists for: what the store says it wrote has to be what a whole-document
/// conversion of the result would show. Hand-written deltas cannot catch a setter that forgets to
/// emit, or emits the wrong field; taking them from the interface after a real edit can.
/// The deltas the interface emits for a real edit must store what a whole-document conversion of the
/// result would. Taking them from the interface rather than writing them by hand is what catches a
/// setter that forgets to emit, or emits the wrong field.
#[tokio::test]
async fn emitted_deltas_reproduce_the_diff() {
let mut editor = EditorTestUtils::create();
@@ -338,7 +337,7 @@ async fn emitted_deltas_reproduce_the_diff_for_an_arity_change() {
editor
.active_document_mut()
.network_interface
.add_import(TaggedValue::F64(7.), true, -1, "Added", "An added import", &[group]);
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
let emitted = editor.active_document_mut().network_interface.take_deltas();
assert!(!emitted.is_empty(), "adding an import should have emitted deltas");
@@ -379,7 +378,7 @@ async fn an_arity_change_keeps_an_earlier_edit_to_the_same_node() {
editor
.active_document_mut()
.network_interface
.add_import(TaggedValue::F64(7.), true, -1, "Added", "An added import", &[group]);
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
let emitted = editor.active_document_mut().network_interface.take_deltas();
let constructed = construct(&editor, &emitted, &working);
@@ -387,10 +386,9 @@ async fn an_arity_change_keeps_an_earlier_edit_to_the_same_node() {
assert_same_stored_effect(&working, constructed, diffed, "rename then arity change");
}
/// The gate replay exists for: what the store recorded has to be enough to reproduce the write that
/// produced it. Clone the interface before an edit, apply what the edit recorded onto the clone, and
/// the two should agree. Something the store failed to record, or recorded wrongly, surfaces here
/// rather than as drift on another peer.
/// What an edit records must be enough to reproduce it: applying the recorded deltas to a clone of the
/// interface taken before the edit must yield the edited interface. A write recorded wrongly or not at
/// all surfaces here rather than as drift on another peer.
async fn assert_replay_reproduces(edit: impl FnOnce(&mut EditorTestUtils)) {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
@@ -454,7 +452,7 @@ async fn replaying_an_arity_change_reproduces_the_interface() {
editor
.active_document_mut()
.network_interface
.add_import(TaggedValue::F64(7.), true, -1, "Added", "An added import", &[group]);
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
})
.await;
}
@@ -552,3 +550,85 @@ async fn removing_a_nested_network_node_matches_the_diff() {
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "nested network removal");
}
/// A group carries a nested network, so adding and removing one inside a batch has to cancel out the
/// network as well as the nodes. The proto-node case above does not reach this, since a proto node has
/// no network of its own.
#[tokio::test]
async fn a_group_added_and_removed_in_one_batch_leaves_nothing_behind() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
let working = convert(&editor);
editor.active_document_mut().network_interface.discard_deltas();
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: crate::messages::portfolio::document::utility_types::misc::GroupFolderType::Layer,
})
.await;
let group = only_group(&editor);
editor.active_document_mut().network_interface.delete_nodes(vec![group], true, &[]);
let emitted = editor.active_document_mut().network_interface.take_deltas();
let constructed = construct(&editor, &emitted, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "group added then removed in one batch");
}
/// Swapping a node's implementation must not restate the node's own metadata: the swap did not write it,
/// and asserting it would overwrite whatever a concurrent peer set for the node's name, lock or pin.
#[tokio::test]
async fn swapping_an_implementation_leaves_the_node_in_place() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
let working = convert(&editor);
let deltas = {
let interface = &mut editor.active_document_mut().network_interface;
interface.discard_deltas();
let Some(mut cursor) = interface.node_mut(super::NodeLocator::new(node, &[])) else {
panic!("the node should resolve")
};
cursor.replace_implementation(graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), None);
interface.take_deltas()
};
let ops = construct(&editor, &deltas, &working);
assert!(
ops.iter().any(|op| matches!(op, RegistryDelta::SetNodeImplementation { .. })),
"the swap should update the implementation in place"
);
assert!(
!ops.iter().any(|op| matches!(op, RegistryDelta::RemoveNode { .. })),
"the node itself should not be rebuilt, since that would clear the attributes it carries"
);
assert!(
!deltas.iter().any(|delta| matches!(delta, EditorDelta::NodeMetadataSnapshot { node_id, .. } if *node_id == node)),
"the node's own metadata should not be restated by a swap that did not write it"
);
// The slots that survive the swap keep the names and descriptions the registry holds for them.
let Some((id, inputs)) = ops.iter().find_map(|op| match op {
RegistryDelta::SetNodeInputs { id, inputs } => Some((id, inputs)),
_ => None,
}) else {
panic!("the swap should restate the slots")
};
let held: Vec<_> = working.node_instances[id]
.inputs()
.iter()
.take(inputs.len())
.flat_map(|slot| document_graph_storage::attributes::live(&slot.attributes).filter(|(key, _)| key.starts_with("ui::")))
.collect();
assert!(!held.is_empty(), "the surviving slots should hold ui attributes for this to check anything");
for (index, slot) in inputs.iter().enumerate() {
for (key, value) in document_graph_storage::attributes::live(&working.node_instances[id].inputs()[index].attributes).filter(|(key, _)| key.starts_with("ui::")) {
assert_eq!(slot.attributes.get(key), Some(value), "slot {index} lost {key}");
}
}
}
@@ -21,7 +21,6 @@ impl NodeNetworkInterface {
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
let mut port_click_targets = Ports::new();
let document_node_click_targets = if !node_metadata.persistent_metadata.is_layer() {
// Create input/output click targets
let mut input_row_count = 0;
for (input_index, input) in document_node.inputs.iter().enumerate() {
if input.is_exposed() {
@@ -59,7 +58,6 @@ impl NodeNetworkInterface {
node_type_metadata: NodeTypeClickTargets::Node,
}
} else {
// Layer inputs
port_click_targets.insert_layer_input(0, node_top_left);
if document_node.inputs.iter().filter(|input| input.is_exposed()).count() > 1 {
port_click_targets.insert_layer_input(1, node_top_left);
@@ -67,7 +65,7 @@ impl NodeNetworkInterface {
port_click_targets.insert_layer_output(node_top_left);
let layer_width_cells = self.layer_width(node_id, network_path).unwrap_or_else(|| {
log::error!("Could not get layer width in load_node_click_targets");
log::error!("Could not get layer width in compute_node_click_targets");
0
});
let width = layer_width_cells * GRID_SIZE;
@@ -79,7 +77,6 @@ impl NodeNetworkInterface {
const LAYER_VERTICAL_CENTER: f64 = GRID_SIZE as f64;
const ICON_HALF_EXTENT: f64 = HALF_GRID_SIZE as f64;
// Update visibility button click target
let visibility_offset = node_top_left + DVec2::new(width as f64, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + visibility_offset,
@@ -101,8 +98,7 @@ impl NodeNetworkInterface {
None
};
// Update grip button click target, which is positioned to the left of the leftmost icon.
// The grip is 8px wide but spans the full layer-vertical-center band.
// The grip sits to the left of the leftmost icon, 8px wide but spanning the full layer-vertical-center band
const GRIP_WIDTH: f64 = 8.;
let icons_width = if locked { GRID_SIZE as f64 } else { 0. };
let grip_offset_right_edge = node_top_left + DVec2::new(width as f64 - ICON_HALF_EXTENT - icons_width, LAYER_VERTICAL_CENTER);
@@ -113,8 +109,8 @@ impl NodeNetworkInterface {
);
let grip_click_target = ClickTarget::new_with_path(path, 0.);
// Update display-name text click target, used to detect double-click rename. Sized to the text bounds
// (not the surrounding `.details` area) so the rest of the layer still drills into the subgraph on double-click.
// The double-click rename target is sized to the text bounds, not the surrounding `.details` area,
// so the rest of the layer still drills into the subgraph on double-click
/// `.layer` margin-left (= 12), for chain layers the negative margin-left and positive padding-left cancel out, keeping content at this same offset
const LAYER_LEFT_MARGIN: f64 = HALF_GRID_SIZE as f64;
@@ -147,7 +143,7 @@ impl NodeNetworkInterface {
}
};
// Create layer click target, which is contains the layer and the chain background
// The layer click target spans the layer and its chain background
let chain_width_grid_spaces = self.chain_width(node_id, network_path);
let node_bottom_right = node_top_left + DVec2::new(width as f64, height as f64);
@@ -180,7 +176,7 @@ impl NodeNetworkInterface {
let ports_built = self.with_import_export_ports(network_path, |import_exports| {
for (import_index, import_click_target) in import_exports.output_ports() {
let Some(import_bounding_box) = import_click_target.bounding_box() else {
log::error!("Could not get export bounding box in load_modify_import_export");
log::error!("Could not get export bounding box in compute_modify_import_export");
continue;
};
let reorder_import_center = (import_bounding_box[0] + import_bounding_box[1]) / 2. + DVec2::new(-12., 0.);
@@ -200,7 +196,7 @@ impl NodeNetworkInterface {
for (export_index, export_click_target) in import_exports.input_ports() {
let Some(export_bounding_box) = export_click_target.bounding_box() else {
log::error!("Could not get export bounding box in load_modify_import_export");
log::error!("Could not get export bounding box in compute_modify_import_export");
continue;
};
let reorder_export_center = (export_bounding_box[0] + export_bounding_box[1]) / 2. + DVec2::new(12., 0.);
@@ -275,16 +271,16 @@ impl NodeNetworkInterface {
}
pub fn import_export_position(&self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> {
let Some(all_nodes_bounding_box) = self.all_nodes_bounding_box(network_path) else {
log::error!("Could not get all nodes bounding box in load_export_ports");
log::error!("Could not get all nodes bounding box in import_export_position");
return None;
};
let Some(network) = self.nested_network(network_path) else {
log::error!("Could not get current network in load_export_ports");
log::error!("Could not get current network in import_export_position");
return None;
};
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in load_export_ports");
log::error!("Could not get nested network_metadata in import_export_position");
return None;
};
let node_graph_to_viewport = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport;
@@ -9,19 +9,14 @@ impl NodeNetworkInterface {
/// Unloads everything a node's position feeds: its own geometry, the geometry of every node placed
/// relative to it, and the network bounds. A chain node also sets the width of the layer encapsulating
/// its chain, so that layer reloads too.
///
/// Takes the changed nodes as a batch, so a run of moves walks the upstream cone once.
pub(crate) fn invalidate_positions(&mut self, node_ids: Vec<NodeId>, network_path: &[NodeId]) {
let encapsulating_layers = node_ids
.iter()
.filter(|node_id| self.is_chain(node_id, network_path))
.filter_map(|node_id| self.downstream_layer_for_chain_node(node_id, network_path))
.collect::<Vec<_>>();
for downstream_layer in encapsulating_layers {
pub(crate) fn invalidate_position(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
if self.is_chain(node_id, network_path)
&& let Some(downstream_layer) = self.downstream_layer_for_chain_node(node_id, network_path)
{
self.unload_node_click_targets(&downstream_layer, network_path);
}
self.unload_upstream_node_click_targets(node_ids, network_path);
self.unload_upstream_node_click_targets(vec![*node_id], network_path);
self.unload_all_nodes_bounding_box(network_path);
}
Loaded 100 of 279 files, more files were not shown because too many files have changed in this diff. Show more