Compare commits

...
Author SHA1 Message Date
Timon 0cfe3cd053 Fix 2026-07-05 18:24:58 +00:00
YohYamasakiandKeavon Chambers 6a54dcb5da Remove the legacy Fill, Gradient, and PathStyle types now that paints live in attributes (#4297)
* Remove `Stroke.color`

* Remove legacy Gradient struct usage

* Fix gradient tool tests

* Remove `Fill` enum

* Fix direction of `gradient_orientation_rightward`

* Remove `Gradient` struct

* Remove `PathStyle` struct

* Fix old `VectorData` migration

* Refactor

- Remove unnecessary wrapper functions
- Use `as_ref` instead of `clone` for stroke if possible
- Comment cleanup

* Clean up stale style comments and bindings left by the paint attribute migration

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-07-04 23:08:06 -07:00
YohYamasakiandKeavon Chambers 9f9899cfd0 Refactor the 'Fill' and 'Stroke' nodes to set "fill" and "stroke" attributes for paints (#4257)
* Allow using any graphics type for fill

* Adapt gradient/fill property panels and tools to handle List<T>

* Make the initial gradient transform covers the target's bounding box

* Introduce AnyGraphicListDyn to avoid combinatorial explosion

* Allow using any graphics type for stroke paint

* Add FIll node migration

* Add `for_each_vector_list_mut` instead of `set_paint_attribute`

* Adapt paint flow to read and write attributes instead of legacy Fill/Stroke.color

* Fix responsibilities of paint related node input setters

* Fix Morph by storing List<Graphic> for attributes rather than the concrete types

Store fill/stroke paints as List<Graphic> so Color/Gradient transitions
do not hit set_attribute_value_dyn's type-mismatch fallback to default paint.

* Preserve paint attributes in vector editing ops

* Enhance the clarity between direct and chained fill gradients

* Update demo arts

* Consolidate Fill node gradient appearance inputs

* Fix after the cubic review

* Revert "Consolidate Fill node gradient appearance inputs"

This reverts commit 9622feb20196e2c4da99e98ca95dcc2e34c2c98e.

* Replace AnyGraphicListDyn with generic paint connectors on the Fill and Stroke nodes

* Canonicalize paint attribute storage to List<Graphic> with a single write helper

* Fix Solidify Stroke missing fills stored in the legacy style

* Fix Solidify Stroke producing invisible strokes for legacy-only stroke colors

* Fix the initial gradient transform ignoring the bounding box's vertical extent

* Step paint at the morph midpoint instead of dropping it for unmixable pairings

* Remove migration-stage comments

* Clarify the initial gradient transform helper's doc and name

* Correct the bake_paint_transforms doc and prune dead tolerance arms

* Delete the unused Gradient::lerp

* Fix a comment typo

* Thread network paths through the legacy gradient bake so nested fills migrate

* Restore the legacy fill fallback in Expand Fill and Stroke

* Read gradient stops from the node's own input in the Fill properties panel

* Use the transform input constant instead of a hardcoded index

* Remove the unreachable wired color fallback in the Fill properties solid branch

* Narrow the fill overlay redraw check to actual fill inputs

* Coalesce the fill setter's graph runs into a single dispatch

* Position the Gradient Value node inserted for gradient stops

* Bake backup gradient placement during migration

* Persist pending gradient bakes so unfinished migrations retry on reopen

* Migrate the backup gradient's type and spread method

* Harden the gradient-migration pass against document switches and stale bakes

* Keep the Fill properties UI for layerless and nested Fill nodes

* Leave a wired gradient transform input connected instead of overwriting it

* Refuse to start a gradient chain ahead of existing layer content

* Decode a Fill node's gradient through one shared reader

* Nudge a degenerate bounding box so the Fill gradient transform stays invertible

* Broadcast Fill and Stroke paint with a single attribute-column pass

* Fix Morph stepping the target's stroke in near the source instead of the target

* Tidy conventions: clippy get_first, comment periods, sentence-case test messages

* Reattach the gradient orientation doc to its function

* Re-save demo artwork

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-07-04 23:08:21 +00:00
Keavon Chambers f82b0a8fca Switch production builds from -Os to -Oz to avoid 25 MB deployment limit (#4309) 2026-07-04 14:25:38 -07:00
Dennis KobertandTimon 540a4ff273 Integrate document-format storage into the editor (#4265)
* Integrate document-format storage into the editor

* Address review feedback: drop redundant clones and dedupe metadata traversal

* Extract DocumentHistory and move storage-metadata tests to their own file

* Extract storage diffing/IO, gate validation and .gdd save behind preferences, restructure tests

* Address PR review: save-format/path consistency, autosave persistence, and view-settings/diff fixes

* Skip storage remount on .gdd open and split value/timestamp drift in attribute diff

* Rename storage tests module and surface .gdd open failures with per-resource diff detail

* Add debug-menu toggle to hide the storage preferences section

* Hopefully fix async tests

* Shorten comments

* Fix tests

* Review

* Review

* Review

* Block on future mesages in tests

* Review

* Shorten comments

---------

Co-authored-by: Timon <[email protected]>
2026-07-04 19:27:00 +00:00
Timon 294952e152 Desktop: Use dirty rects for UI texture uploads (#4305) 2026-07-04 16:25:16 +00:00
Keavon Chambers f05a644bd9 Revamp the syntax to #[hard(a..b)] and #[soft(a..b)] bounds on node definitions (#4307)
* Revamp the syntax to #[hard(a..b)] and #[soft(a..b)] bounds on node definitions

* Address review feedback: error on empty bounds ranges and remove redundant count clamps

* Fix NaN transform from Repeat Array with a count of 1

* Remove redundant manual clamps already enforced by #[hard(...)] bounds
2026-07-03 18:48:58 -07:00
98 changed files with 5565 additions and 2268 deletions

No files matched your search

+7 -20
View File
@@ -2,25 +2,10 @@
let
version = "149.0.5+g6770623+chromium-149.0.7827.197";
hashes = {
aarch64-linux = "sha256-cBAvcvs1rAg5EKJkCt81RZYupCWpUNIC/nLt3PJow7Q=";
x86_64-linux = "sha256-OPGMBJmvvLiLdBDniBQwx7LmTGGI59AcesJdILSeqcs=";
};
selectSystem =
attrs:
attrs.${pkgs.stdenv.hostPlatform.system}
or (throw "Unsupported system ${pkgs.stdenv.hostPlatform.system}");
src = pkgs.fetchurl {
url = "https://cef-builds.spotifycdn.com/cef_binary_${version}_${
selectSystem {
aarch64-linux = "linuxarm64";
x86_64-linux = "linux64";
}
}_minimal.tar.bz2";
hash = selectSystem hashes;
};
# Local custom CEF build (tarball) instead of the Spotify CDN download.
# Absolute path outside the flake source tree, so this needs `nix develop --impure`.
src = /home/timon/tmp/cef-build/dist/cef_149_7827_x86-64_linux_fixed_buffer_usage.tar.xz;
in
pkgs.cef-binary.overrideAttrs (finalAttrs: {
version = builtins.head (builtins.split "\\+" version);
@@ -33,12 +18,14 @@ pkgs.cef-binary.overrideAttrs (finalAttrs: {
mv ./Resources/* $out/
mv ./include $out/
cat ./CREDITS.html | ${pkgs.xz}/bin/xz -9 -e -c > $out/CREDITS.html.xz
if [ -f ./CREDITS.html ]; then
cat ./CREDITS.html | ${pkgs.xz}/bin/xz -9 -e -c > $out/CREDITS.html.xz
fi
echo '${
builtins.toJSON {
type = "minimal";
name = builtins.baseNameOf finalAttrs.src.url;
name = "cef_binary_${version}_linux64_minimal.tar.xz";
sha1 = "";
}
}' > $out/archive.json
Generated
+3
View File
@@ -2282,11 +2282,14 @@ dependencies = [
"bitflags 2.11.0",
"color",
"derivative",
"document-container",
"document-format",
"dyn-any",
"env_logger",
"futures",
"glam",
"graph-craft",
"graph-storage",
"graphene-hash",
"graphene-std",
"graphite-proc-macros",
+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":{"Fill":{"Solid":{"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":{"FillGradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"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}]},"gradient_type":"Linear","start":[9.606221358397944,-69.72678572415595],"end":[9.606221358397944,-162.2641409381776],"spread_method":"Pad","absolute":true,"transform":[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":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<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::ToGraphicNode"}},"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::WrapGraphicNode"}},"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":false,"context_features":{"extract":"","inject":""}}],[1789832635968548900,{"inputs":[{"NLine 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":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"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}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[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":{"name":"core_types::list::List<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::ToGraphicNode"}},"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::WrapGraphicNode"}},"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":false,"contextLine 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::ToGraphicNode"}},"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::WrapGraphicNode"}},"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":""}}],[183952488591282082,{"inputs":[{"Node":{"node_id":17965270694495451178,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,-6.0]},"exposed":false}},{"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":{"exportsLine 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::ToGraphicNode"}},"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::WrapGraphicNode"}},"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":""}}],[183952488591282082,{"inputs":[{"Node":{"node_id":17965270694495451178,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,-6.0]},"exposed":false}},{"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":{"exportsLine 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":{"Gradient":{"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5],"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}]}},"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":{"Gradient":{"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5],"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}]}},"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_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_valLine 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":{"Gradient":{"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5],"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}]}},"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":{"Gradient":{"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5],"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}]}},"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_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_valLine 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":{"Fill":{"Solid":{"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":{"FillGradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"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}]},"gradient_type":"Linear","start":[-10.0,0.0],"end":[10.0,0.0],"spread_method":"Pad","absolute":true,"transform":[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":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<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":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":4}},{"Import":{"import_type":{"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::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_Line 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":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"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}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[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":{"name":"core_types::list::List<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":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":4}},{"Import":{"import_type":{"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::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphiLine 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":{"name":"core_types::list::List<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::ToGraphicNode"}},"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::WrapGraphicNode"}},"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":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"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":"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":{"FillGradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"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}]},"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5],"spread_method":"Pad","absolute":true,"transform":[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,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::contLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<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::ToGraphicNode"}},"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::WrapGraphicNode"}},"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":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"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":"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":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"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}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":null},"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,"output_index":0}}],"call_argument":{"Concrete":Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":6559102076450693000,"output_index":0}},{"Value":{"tagged_value":{"Fill":{"Gradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"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}]},"gradient_type":"Radial","start":[-0.22577926355610423,34.981204988590605],"end":[-0.11953019835323353,66.53737705977504],"spread_method":"Pad","absolute":true,"transform":[0.0033669629737862325,-0.9999943317641021,0.9999943317641021,0.0033669629737862325,-35.2060257800042,34.63764658282962]}}},"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":{"FillGradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"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}]},"gradient_type":"Radial","start":[-0.22577926355610423,34.981204988590605],"end":[-0.11953019835323353,66.53737705977504],"spread_method":"Pad","absolute":true,"transform":[0.0033669629737862325,-0.9999943317641021,0.9999943317641021,0.0033669629737862325,-35.2060257800042,34.63764658282962]}},"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::ToGraphicNode"}},"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::WrapGraphicNode"}},"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":{"name":"core_types::list::List<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,2Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":6559102076450693000,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"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}]}},"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":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"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}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[31.556350940025634,-2.7755575615628914e-17,2.7755575615628914e-17,31.556350940025634,-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::ToGraphicNode"}},"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::WrapGraphicNode"}},"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":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0Line 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":{"name":"core_types::list::List<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":{"Concrete":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"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":{"Fill":{"Solid":{"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":{"FillGradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"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}]},"gradient_type":"Linear","start":[604.9565968314213,108.54930650815423],"end":[607.1269623532997,108.54930650815423],"spread_method":"Pad","absolute":true,"transform":[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":""}}],[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::ToGraphicNode"}},"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::WrapGraphicNode"}},"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_indLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<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":{"Concrete":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"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":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"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}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[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::ToGraphicNode"}},"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::WrapGraphicNode"}},"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":{"StrinLine 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::ToGraphicNode"}},"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::WrapGraphicNode"}},"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::ToGraphicNode"}},"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::WrapGraphicNode"}},"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":""}}]],"scLine 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::ToGraphicNode"}},"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::WrapGraphicNode"}},"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::ToGraphicNode"}},"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::WrapGraphicNode"}},"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":""}}]],"scLine truncated
+1 -1
View File
@@ -100,7 +100,7 @@ impl App {
let wake = Arc::new(move || {
wake_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Wake));
});
let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), wgpu_context.clone(), wake);
let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), dirs::app_autosave_documents_dir(), wgpu_context.clone(), wake);
Self {
render_state: None,
+8 -60
View File
@@ -21,9 +21,8 @@ use std::sync::{Arc, Mutex};
use std::time::Instant;
use crate::event::{AppEvent, AppEventScheduler};
use crate::render::FrameBufferRef;
use crate::window::Cursor;
use crate::wrapper::{WgpuContext, deserialize_editor_message};
use crate::wrapper::deserialize_editor_message;
mod consts;
mod context;
@@ -32,17 +31,14 @@ mod internal;
mod ipc;
mod platform;
mod utility;
#[cfg(feature = "accelerated_paint")]
use cef::osr_texture_import::SharedTextureHandle;
mod view;
pub(crate) use context::{CefContext, CefContextBuilder, InitError};
pub(crate) use view::View;
pub(crate) trait CefEventHandler: Send + Sync + 'static {
fn view_info(&self) -> ViewInfo;
fn draw<'a>(&self, frame_buffer: FrameBufferRef<'a>);
#[cfg(feature = "accelerated_paint")]
fn draw_gpu(&self, shared_texture: SharedTextureHandle);
fn draw(&self, view: &View);
fn load_resource(&self, path: PathBuf) -> Option<Resource>;
fn cursor_change(&self, cursor: Cursor);
/// Schedule the main event loop to run the CEF event loop after the timeout.
@@ -120,15 +116,13 @@ impl Read for ResourceReader {
}
pub(crate) struct CefHandler {
wgpu_context: WgpuContext,
app_event_scheduler: AppEventScheduler,
view_info_receiver: Arc<Mutex<ViewInfoReceiver>>,
}
impl CefHandler {
pub(crate) fn new(wgpu_context: WgpuContext, app_event_scheduler: AppEventScheduler, view_info_receiver: Receiver<ViewInfoUpdate>) -> Self {
pub(crate) fn new(app_event_scheduler: AppEventScheduler, view_info_receiver: Receiver<ViewInfoUpdate>) -> Self {
Self {
wgpu_context,
app_event_scheduler,
view_info_receiver: Arc::new(Mutex::new(ViewInfoReceiver::new(view_info_receiver))),
}
@@ -147,55 +141,10 @@ impl CefEventHandler for CefHandler {
}
*view_info
}
fn draw<'a>(&self, frame_buffer: FrameBufferRef<'a>) {
let width = frame_buffer.width() as u32;
let height = frame_buffer.height() as u32;
let texture = self.wgpu_context.device.create_texture(&wgpu::TextureDescriptor {
label: Some("CEF Texture"),
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Bgra8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
self.wgpu_context.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
frame_buffer.buffer(),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(4 * width),
rows_per_image: Some(height),
},
wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
);
self.app_event_scheduler.schedule(AppEvent::UiUpdate(texture));
}
#[cfg(feature = "accelerated_paint")]
fn draw_gpu(&self, shared_texture: SharedTextureHandle) {
match shared_texture.import_texture(&self.wgpu_context.device) {
Ok(texture) => {
self.app_event_scheduler.schedule(AppEvent::UiUpdate(texture));
}
Err(e) => {
tracing::error!("Failed to import shared texture: {}", e);
}
fn draw(&self, view: &View) {
if let Some(texture) = view.texture() {
self.app_event_scheduler.schedule(AppEvent::UiUpdate(texture));
}
}
@@ -279,7 +228,6 @@ impl CefEventHandler for CefHandler {
Self: Sized,
{
Self {
wgpu_context: self.wgpu_context.clone(),
app_event_scheduler: self.app_event_scheduler.clone(),
view_info_receiver: self.view_info_receiver.clone(),
}
+7 -6
View File
@@ -13,6 +13,7 @@ use crate::cef::consts::{RESOURCE_DOMAIN, RESOURCE_SCHEME};
use crate::cef::input::InputState;
use crate::cef::internal::{BrowserProcessAppImpl, BrowserProcessClientImpl, RenderProcessAppImpl, SchemeHandlerFactoryImpl};
use crate::dirs::TempDir;
use crate::wrapper::WgpuContext;
pub(crate) struct CefContextBuilder<H: CefEventHandler> {
pub(crate) args: Args,
@@ -67,19 +68,19 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
}
#[cfg(target_os = "macos")]
pub(crate) fn create(self, event_handler: H, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
pub(crate) fn create(self, event_handler: H, wgpu_context: WgpuContext, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
let instance_dir = TempDir::new().expect("Failed to create temporary directory for CEF instance");
let accelerated_paint = accelerated_paint(disable_gpu_acceleration);
self.build_inner(&event_handler, instance_dir.as_ref(), accelerated_paint)?;
create_browser(event_handler, instance_dir, accelerated_paint)
create_browser(event_handler, wgpu_context, instance_dir, accelerated_paint)
}
#[cfg(not(target_os = "macos"))]
pub(crate) fn create(self, event_handler: H, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
pub(crate) fn create(self, event_handler: H, wgpu_context: WgpuContext, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
let instance_dir = TempDir::new().expect("Failed to create temporary directory for CEF instance");
let accelerated_paint = accelerated_paint(disable_gpu_acceleration);
self.build_inner(&event_handler, instance_dir.as_ref(), accelerated_paint)?;
super::multithreaded::run_on_ui_thread(move || match create_browser(event_handler, instance_dir, accelerated_paint) {
super::multithreaded::run_on_ui_thread(move || match create_browser(event_handler, wgpu_context, instance_dir, accelerated_paint) {
Ok(context) => super::multithreaded::CONTEXT.with(|b| *b.borrow_mut() = Some(context)),
Err(e) => panic!("Failed to initialize CEF context: {:?}", e),
});
@@ -149,8 +150,8 @@ fn platform_settings(instance_dir: &Path) -> Settings {
}
}
fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: TempDir, accelerated_paint: bool) -> Result<SingleThreadedCefContext, InitError> {
let mut client = Client::new(BrowserProcessClientImpl::new(&event_handler));
fn create_browser<H: CefEventHandler>(event_handler: H, wgpu_context: WgpuContext, instance_dir: TempDir, accelerated_paint: bool) -> Result<SingleThreadedCefContext, InitError> {
let mut client = Client::new(BrowserProcessClientImpl::new(&event_handler, wgpu_context));
let window_info = WindowInfo {
windowless_rendering_enabled: 1,
@@ -4,6 +4,7 @@ use cef::{ContextMenuHandler, DisplayHandler, ImplClient, LifeSpanHandler, LoadH
use crate::cef::CefEventHandler;
use crate::cef::ipc::{MessageType, UnpackMessage, UnpackedMessage};
use crate::wrapper::WgpuContext;
use super::context_menu_handler::ContextMenuHandlerImpl;
use super::display_handler::DisplayHandlerImpl;
@@ -21,12 +22,12 @@ pub(crate) struct BrowserProcessClientImpl<H: CefEventHandler> {
request_handler: RequestHandler,
}
impl<H: CefEventHandler> BrowserProcessClientImpl<H> {
pub(crate) fn new(event_handler: &H) -> Self {
pub(crate) fn new(event_handler: &H, wgpu_context: WgpuContext) -> Self {
Self {
object: std::ptr::null_mut(),
event_handler: event_handler.duplicate(),
load_handler: LoadHandler::new(LoadHandlerImpl::new(event_handler.duplicate())),
render_handler: RenderHandler::new(RenderHandlerImpl::new(event_handler.duplicate())),
render_handler: RenderHandler::new(RenderHandlerImpl::new(event_handler.duplicate(), wgpu_context)),
display_handler: DisplayHandler::new(DisplayHandlerImpl::new(event_handler.duplicate())),
request_handler: RequestHandler::new(RequestHandlerImpl::new()),
}
+19 -19
View File
@@ -2,18 +2,20 @@ use cef::rc::{Rc, RcImpl};
use cef::sys::{_cef_render_handler_t, cef_base_ref_counted_t};
use cef::{Browser, ImplRenderHandler, PaintElementType, Rect, WrapRenderHandler};
use crate::cef::CefEventHandler;
use crate::render::FrameBufferRef;
use crate::cef::{CefEventHandler, View};
use crate::wrapper::WgpuContext;
pub(crate) struct RenderHandlerImpl<H: CefEventHandler> {
object: *mut RcImpl<_cef_render_handler_t, Self>,
event_handler: H,
view: View,
}
impl<H: CefEventHandler> RenderHandlerImpl<H> {
pub(crate) fn new(event_handler: H) -> Self {
pub(crate) fn new(event_handler: H, wgpu_context: WgpuContext) -> Self {
Self {
object: std::ptr::null_mut(),
event_handler,
view: View::new(wgpu_context),
}
}
}
@@ -31,29 +33,26 @@ impl<H: CefEventHandler> ImplRenderHandler for RenderHandlerImpl<H> {
}
}
fn on_paint(&self, _browser: Option<&mut Browser>, _type_: PaintElementType, _dirty_rects: Option<&[Rect]>, buffer: *const u8, width: std::ffi::c_int, height: std::ffi::c_int) {
let buffer_size = (width * height * 4) as usize;
let buffer_slice = unsafe { std::slice::from_raw_parts(buffer, buffer_size) };
let frame_buffer = FrameBufferRef::new(buffer_slice, width as usize, height as usize).expect("Failed to create frame buffer");
self.event_handler.draw(frame_buffer)
}
#[cfg(feature = "accelerated_paint")]
fn on_accelerated_paint(&self, _browser: Option<&mut Browser>, type_: PaintElementType, _dirty_rects: Option<&[Rect]>, info: Option<&cef::AcceleratedPaintInfo>) {
use cef::osr_texture_import::SharedTextureHandle;
fn on_paint(&self, _browser: Option<&mut Browser>, type_: PaintElementType, dirty_rects: Option<&[Rect]>, buffer: *const u8, width: std::ffi::c_int, height: std::ffi::c_int) {
if type_ != PaintElementType::default() {
return;
}
let shared_handle = SharedTextureHandle::new(info.unwrap());
if let SharedTextureHandle::Unsupported = shared_handle {
tracing::error!("Platform does not support accelerated painting");
let buffer_size = (width * height * 4) as usize;
let buffer_slice = unsafe { std::slice::from_raw_parts(buffer, buffer_size) };
self.view.upload_frame_buffer(buffer_slice, width as u32, height as u32, dirty_rects.unwrap_or(&[]));
self.event_handler.draw(&self.view)
}
#[cfg(feature = "accelerated_paint")]
fn on_accelerated_paint(&self, _browser: Option<&mut Browser>, type_: PaintElementType, _dirty_rects: Option<&[Rect]>, info: Option<&cef::AcceleratedPaintInfo>) {
if type_ != PaintElementType::default() {
return;
}
self.event_handler.draw_gpu(shared_handle);
self.view.import_shared_texture(info.unwrap());
self.event_handler.draw(&self.view)
}
fn get_raw(&self) -> *mut _cef_render_handler_t {
@@ -70,6 +69,7 @@ impl<H: CefEventHandler> Clone for RenderHandlerImpl<H> {
Self {
object: self.object,
event_handler: self.event_handler.duplicate(),
view: self.view.clone(),
}
}
}
+8 -1
View File
@@ -1,6 +1,6 @@
use cef::rc::{Rc, RcImpl};
use cef::sys::{_cef_request_handler_t, cef_base_ref_counted_t};
use cef::{AuthCallback, Browser, CefString, Frame, ImplRequest, ImplRequestHandler, Request, ResourceRequestHandler, WrapRequestHandler};
use cef::{AuthCallback, Browser, CefString, Frame, ImplRequest, ImplRequestHandler, Request, ResourceRequestHandler, TerminationStatus, WrapRequestHandler};
use std::ffi::c_int;
use super::resource_request_handler::ResourceRequestHandlerImpl;
@@ -55,6 +55,13 @@ impl ImplRequestHandler for RequestHandlerImpl {
0
}
fn on_render_process_terminated(&self, _browser: Option<&mut Browser>, status: TerminationStatus, error_code: c_int, error_string: Option<&CefString>) {
tracing::error!(
"CEF render process terminated: status={status:?}, error_code={error_code}, error={}",
error_string.map(|error| error.to_string()).unwrap_or_default()
);
}
fn get_raw(&self) -> *mut _cef_request_handler_t {
self.object.cast()
}
+108
View File
@@ -0,0 +1,108 @@
use cef::Rect;
use std::sync::{Arc, Mutex};
use crate::wrapper::WgpuContext;
#[derive(Clone)]
pub(crate) struct View {
context: WgpuContext,
texture: Arc<Mutex<Option<wgpu::Texture>>>,
}
impl View {
pub(crate) fn new(context: WgpuContext) -> Self {
Self {
context,
texture: Arc::new(Mutex::new(None)),
}
}
pub(crate) fn texture(&self) -> Option<wgpu::Texture> {
let Ok(texture) = self.texture.lock() else {
tracing::error!("Failed to lock view texture");
return None;
};
texture.clone()
}
pub(super) fn upload_frame_buffer(&self, buffer: &[u8], width: u32, height: u32, dirty_rects: &[Rect]) {
debug_assert_eq!(buffer.len(), width as usize * height as usize * 4);
let Ok(mut slot) = self.texture.lock() else {
tracing::error!("Failed to lock view texture");
return;
};
let needs_new_texture = slot.as_ref().is_none_or(|texture| texture.width() != width || texture.height() != height);
if needs_new_texture {
*slot = Some(self.context.device.create_texture(&wgpu::TextureDescriptor {
label: Some("CEF Texture"),
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Bgra8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
}));
}
let texture = slot.as_ref().expect("Texture was just created");
let full_frame = [Rect {
x: 0,
y: 0,
width: width as i32,
height: height as i32,
}];
let rects = if needs_new_texture || dirty_rects.is_empty() { &full_frame } else { dirty_rects };
for rect in rects {
let x = (rect.x.max(0) as u32).min(width);
let y = (rect.y.max(0) as u32).min(height);
let rect_width = (rect.width.max(0) as u32).min(width - x);
let rect_height = (rect.height.max(0) as u32).min(height - y);
if rect_width == 0 || rect_height == 0 {
continue;
}
self.context.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture,
mip_level: 0,
origin: wgpu::Origin3d { x, y, z: 0 },
aspect: wgpu::TextureAspect::All,
},
buffer,
wgpu::TexelCopyBufferLayout {
offset: 4 * (y as u64 * width as u64 + x as u64),
bytes_per_row: Some(4 * width),
rows_per_image: None,
},
wgpu::Extent3d {
width: rect_width,
height: rect_height,
depth_or_array_layers: 1,
},
);
}
}
#[cfg(feature = "accelerated_paint")]
pub(super) fn import_shared_texture(&self, info: &cef::AcceleratedPaintInfo) {
let texture = match cef::osr_texture_import::SharedTextureHandle::new(info).import_texture(&self.context.device) {
Ok(texture) => texture,
Err(e) => {
tracing::error!("Failed to import shared texture: {e}");
return;
}
};
let Ok(mut slot) = self.texture.lock() else {
tracing::error!("Failed to lock view texture");
return;
};
*slot = Some(texture);
}
}
+2 -2
View File
@@ -96,8 +96,8 @@ pub fn start() {
println!("UI acceleration is disabled");
}
let cef_handler = cef::CefHandler::new(wgpu_context.clone(), app_event_scheduler.clone(), cef_view_info_receiver);
let cef_context = match cef_context_builder.create(cef_handler, prefs.disable_ui_acceleration) {
let cef_handler = cef::CefHandler::new(app_event_scheduler.clone(), cef_view_info_receiver);
let cef_context = match cef_context_builder.create(cef_handler, wgpu_context.clone(), prefs.disable_ui_acceleration) {
Ok(context) => {
tracing::info!("CEF initialized successfully");
context
-3
View File
@@ -1,5 +1,2 @@
mod frame_buffer_ref;
pub(crate) use frame_buffer_ref::FrameBufferRef;
mod state;
pub(crate) use state::{RenderError, RenderState};
-53
View File
@@ -1,53 +0,0 @@
use thiserror::Error;
pub(crate) struct FrameBufferRef<'a> {
buffer: &'a [u8],
width: usize,
height: usize,
}
impl<'a> FrameBufferRef<'a> {
pub(crate) fn new(buffer: &'a [u8], width: usize, height: usize) -> Result<Self, FrameBufferError> {
let fb = Self { buffer, width, height };
fb.validate_size()?;
Ok(fb)
}
pub(crate) fn buffer(&self) -> &[u8] {
self.buffer
}
pub(crate) fn width(&self) -> usize {
self.width
}
pub(crate) fn height(&self) -> usize {
self.height
}
fn validate_size(&self) -> Result<(), FrameBufferError> {
if self.buffer.len() != self.width * self.height * 4 {
Err(FrameBufferError::InvalidSize {
buffer_size: self.buffer.len(),
expected_size: self.width * self.height * 4,
width: self.width,
height: self.height,
})
} else {
Ok(())
}
}
}
impl<'a> std::fmt::Debug for FrameBufferRef<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FrameBuffer")
.field("width", &self.width)
.field("height", &self.height)
.field("len", &self.buffer.len())
.finish()
}
}
#[derive(Error, Debug)]
pub(crate) enum FrameBufferError {
#[error("Invalid buffer size {buffer_size}, expected {expected_size} for width {width} multiplied with height {height} multiplied by 4 channels")]
InvalidSize { buffer_size: usize, expected_size: usize, width: usize, height: usize },
}
+6 -2
View File
@@ -206,8 +206,12 @@ impl RenderState {
self.update_bindgroup();
}
pub(crate) fn bind_ui_texture(&mut self, bind_ui_texture: wgpu::Texture) {
self.ui_texture = Some(bind_ui_texture);
pub(crate) fn bind_ui_texture(&mut self, ui_texture: wgpu::Texture) {
if self.ui_texture.as_ref() == Some(&ui_texture) {
self.surface_outdated = true;
return;
}
self.ui_texture = Some(ui_texture);
self.update_bindgroup();
}
@@ -37,13 +37,14 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
if let Some(path) = path {
dispatcher.respond(DesktopFrontendMessage::WriteFile { path, content });
} else {
let extension = std::path::Path::new(&name).extension().and_then(|extension| extension.to_str()).unwrap_or("*").to_string();
dispatcher.respond(DesktopFrontendMessage::SaveFileDialog {
title: "Save Document".to_string(),
default_filename: name,
default_folder: folder,
filters: vec![FileFilter {
name: "Graphite".to_string(),
extensions: vec!["graphite".to_string()],
name: "Graphite Document".to_string(),
extensions: vec![extension],
}],
context: SaveFileDialogContext::Document { document_id, content },
});
+2 -2
View File
@@ -26,7 +26,7 @@ pub struct DesktopWrapper {
}
impl DesktopWrapper {
pub fn new(uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self {
pub fn new(uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, working_copy_root: std::path::PathBuf, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self {
#[cfg(target_os = "windows")]
let host = Host::Windows;
#[cfg(target_os = "macos")]
@@ -37,7 +37,7 @@ impl DesktopWrapper {
let application_io = PlatformApplicationIo::new_with_context(wgpu_context);
Self {
editor: Editor::new(env, uuid_random_seed, resource_storage, application_io, schedule_wake),
editor: Editor::new(env, uuid_random_seed, resource_storage, Some(working_copy_root), application_io, schedule_wake),
}
}
+3
View File
@@ -19,6 +19,9 @@ gpu = ["interpreted-executor/gpu", "dep:wgpu-executor"]
# Local dependencies
graphite-proc-macros = { workspace = true }
graph-craft = { workspace = true }
graph-storage = { workspace = true, features = ["conversion"] }
document-format = { workspace = true }
document-container = { workspace = true }
graphene-hash = { workspace = true }
interpreted-executor = { workspace = true }
graphene-std = { workspace = true } # NOTE: `core-types` should not be added here because `graphene-std` re-exports its contents
+9 -2
View File
@@ -10,11 +10,18 @@ pub struct Editor {
}
impl Editor {
pub fn new(environment: Environment, uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, mut application_io: PlatformApplicationIo, wake: Wake) -> Self {
pub fn new(
environment: Environment,
uuid_random_seed: u64,
resource_storage: Arc<dyn ResourceStorage>,
working_copy_root: Option<std::path::PathBuf>,
mut application_io: PlatformApplicationIo,
wake: Wake,
) -> Self {
ENVIRONMENT.set(environment).expect("Editor shoud only be initialized once");
graphene_std::uuid::set_uuid_seed(uuid_random_seed);
let mut dispatcher = Dispatcher::new(resource_storage);
let mut dispatcher = Dispatcher::new(resource_storage, working_copy_root);
dispatcher.message_handlers.future_message_handler.set_wake(wake);
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
crate::node_graph_executor::replace_application_io(application_io);
+3
View File
@@ -176,6 +176,9 @@ pub const COLOR_OVERLAY_BLACK_75: &str = "#000000bf";
// DOCUMENT
pub const FILE_EXTENSION: &str = "graphite";
/// New document container format. Save writes a `.gdd` with the legacy `.graphite` embedded as a fallback
/// during the dual-write soak; `.graphite` stays a supported open/import input.
pub const GDD_FILE_EXTENSION: &str = "gdd";
pub const DEFAULT_DOCUMENT_NAME: &str = "Untitled Document";
pub const MAX_UNDO_HISTORY_LEN: usize = 100; // TODO: Add this to user preferences
pub const AUTO_SAVE_TIMEOUT_SECONDS: u64 = 1;
+3 -1
View File
@@ -89,9 +89,10 @@ 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>) -> Self {
pub fn new(resource_storage: Arc<dyn ResourceStorage>, working_copy_root: Option<std::path::PathBuf>) -> Self {
let mut s = Self::default();
s.message_handlers.resource_storage_message_handler = ResourceStorageMessageHandler::new(resource_storage);
s.message_handlers.portfolio_message_handler.set_working_copy_root(working_copy_root);
s
}
@@ -271,6 +272,7 @@ impl Dispatcher {
menu_bar_message_handler.properties_panel_open = layout.is_panel_present(PanelType::Properties);
menu_bar_message_handler.message_logging_verbosity = self.message_handlers.debug_message_handler.message_logging_verbosity;
menu_bar_message_handler.reset_node_definitions_on_open = self.message_handlers.portfolio_message_handler.reset_node_definitions_on_open;
menu_bar_message_handler.show_storage_preferences = self.message_handlers.preferences_message_handler.show_storage_preferences;
if let Some(document) = self
.message_handlers
@@ -402,11 +402,11 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
});
// Add default fill and stroke to the layer
let fill = graphene_std::vector::style::Fill::solid(Color::WHITE);
responses.add(GraphOperationMessage::FillSet { layer, fill });
responses.add(GraphOperationMessage::FillColorSet { layer, color: Some(Color::WHITE) });
let stroke = graphene_std::vector::style::Stroke::new(Some(Color::BLACK), DEFAULT_STROKE_WIDTH);
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
let color = Some(Color::BLACK);
let stroke = graphene_std::vector::style::Stroke::new(DEFAULT_STROKE_WIDTH);
responses.add(GraphOperationMessage::StrokeSet { layer, color, stroke });
// Create new point ids and add those into the existing Vector path
let mut points_map = HashMap::new();
@@ -303,6 +303,62 @@ impl PreferencesDialogMessageHandler {
rows.extend_from_slice(&[header, node_graph_wires_label, graph_wire_style, brush_tool]);
}
// =========
// DOCUMENTS
// =========
// Soak-only `.gdd` storage options, hidden unless enabled from the developer debug menu.
if preferences.show_storage_preferences {
let header = vec![TextLabel::new("Documents").italic(true).widget_instance()];
let save_as_gdd_description = "
Save documents in the new .gdd container format (with the legacy .graphite file embedded as a recovery fallback) instead of a plain .graphite file. The .gdd format is still being validated, so this is opt-in for now.\n\
\n\
*Default: Off.*
"
.trim();
let save_as_gdd_checkbox_id = CheckboxId::new();
let save_as_gdd = vec![
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(preferences.save_as_gdd)
.tooltip_label("Save as .gdd")
.tooltip_description(save_as_gdd_description)
.on_update(|checkbox_input: &CheckboxInput| PreferencesMessage::SaveAsGdd { enabled: checkbox_input.checked }.into())
.for_label(save_as_gdd_checkbox_id)
.widget_instance(),
TextLabel::new("Save as .gdd")
.tooltip_label("Save as .gdd")
.tooltip_description(save_as_gdd_description)
.for_checkbox(save_as_gdd_checkbox_id)
.widget_instance(),
];
let validate_description = "
Validate every document save, open, and undo by round-tripping it through the .gdd storage format and comparing against the legacy path, logging any mismatch. Useful for debugging the .gdd format during its soak, but the per-edit round-trip has a performance cost.\n\
\n\
*Default: Off.*
"
.trim();
let validate_checkbox_id = CheckboxId::new();
let validate_storage_round_trip = vec![
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(preferences.validate_storage_round_trip)
.tooltip_label("Validate Storage Round-Trip")
.tooltip_description(validate_description)
.on_update(|checkbox_input: &CheckboxInput| PreferencesMessage::ValidateStorageRoundTrip { enabled: checkbox_input.checked }.into())
.for_label(validate_checkbox_id)
.widget_instance(),
TextLabel::new("Validate Storage Round-Trip")
.tooltip_label("Validate Storage Round-Trip")
.tooltip_description(validate_description)
.for_checkbox(validate_checkbox_id)
.widget_instance(),
];
rows.extend_from_slice(&[header, save_as_gdd, validate_storage_round_trip]);
}
// =============
// COMPATIBILITY
// =============
@@ -73,8 +73,10 @@ pub struct FutureMessageContext {}
#[derive(ExtractField)]
pub struct FutureMessageHandler {
#[cfg_attr(test, expect(dead_code))]
spawner: Arc<dyn MessageSpawner>,
wake: Wake,
#[cfg_attr(test, expect(dead_code))]
results_sender: UnboundedSender<Message>,
results_receiver: UnboundedReceiver<Message>,
}
@@ -119,7 +121,15 @@ impl MessageHandler<FutureMessage, FutureMessageContext> for FutureMessageHandle
fn process_message(&mut self, message: FutureMessage, _responses: &mut VecDeque<Message>, _context: FutureMessageContext) {
match message {
FutureMessage::Await { future } => {
#[cfg(not(test))]
self.spawner.spawn(future.into_future(), self.results_sender.clone(), self.wake.clone());
// For tests, block on the future to ensure the result is available when validating editor state afterwards.
#[cfg(test)]
{
let message = futures::executor::block_on(future.into_future());
_responses.push_back(message);
}
}
FutureMessage::Wake => {
// Tick-only message: the dispatcher's top-of-tick drain handles the real work.
@@ -17,6 +17,7 @@ pub struct MenuBarMessageHandler {
pub has_selection_history: (bool, bool),
pub message_logging_verbosity: MessageLoggingVerbosity,
pub reset_node_definitions_on_open: bool,
pub show_storage_preferences: bool,
pub make_path_editable_is_allowed: bool,
pub data_panel_open: bool,
pub layers_panel_open: bool,
@@ -50,6 +51,7 @@ impl LayoutHolder for MenuBarMessageHandler {
let message_logging_verbosity_names = self.message_logging_verbosity == MessageLoggingVerbosity::Names;
let message_logging_verbosity_contents = self.message_logging_verbosity == MessageLoggingVerbosity::Contents;
let reset_node_definitions_on_open = self.reset_node_definitions_on_open;
let show_storage_preferences = self.show_storage_preferences;
let make_path_editable_is_allowed = self.make_path_editable_is_allowed;
let about = MenuListEntry::new("About Graphite…")
@@ -718,6 +720,10 @@ impl LayoutHolder for MenuBarMessageHandler {
.label("Reset Nodes to Definitions on Open")
.icon(if reset_node_definitions_on_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
.on_commit(|_| PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen.into()),
MenuListEntry::new("Show Storage Preferences")
.label("Show Storage Preferences")
.icon(if show_storage_preferences { "CheckboxChecked" } else { "CheckboxUnchecked" })
.on_commit(|_| PreferencesMessage::ToggleShowStoragePreferences.into()),
],
vec![
MenuListEntry::new("Print Trace Logs")
@@ -13,7 +13,7 @@ use graphene_std::list::List;
use graphene_std::memo::IORecord;
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::vector::Vector;
use graphene_std::vector::style::{Fill, FillChoice, FillChoiceUI, GradientSpreadMethod, GradientType};
use graphene_std::vector::style::{FillChoice, FillChoiceUI, GradientSpreadMethod, GradientType};
use graphene_std::{Artboard, Color, Context, Graphic};
use std::any::Any;
use std::sync::Arc;
@@ -385,61 +385,7 @@ impl TableItemLayout for Vector {
VectorTableTab::Properties => {
table_rows.push(column_headings(&["property", "value"]));
match self.style.fill.clone() {
Fill::None => table_rows.push(vec![
TextLabel::new("Fill").narrow(true).widget_instance(),
ColorInput::new(FillChoiceUI::None)
.disabled(true)
.menu_direction(Some(MenuDirection::Top))
.narrow(true)
.widget_instance(),
]),
Fill::Solid(color) => table_rows.push(vec![
TextLabel::new("Fill").narrow(true).widget_instance(),
ColorInput::new(FillChoiceUI::from(&FillChoice::Solid(color)))
.disabled(true)
.menu_direction(Some(MenuDirection::Top))
.narrow(true)
.widget_instance(),
]),
Fill::Gradient(gradient) => {
table_rows.push(vec![
TextLabel::new("Fill").narrow(true).widget_instance(),
ColorInput::new(FillChoiceUI::from(&FillChoice::Gradient(gradient.stops)))
.disabled(true)
.menu_direction(Some(MenuDirection::Top))
.narrow(true)
.widget_instance(),
]);
table_rows.push(vec![
TextLabel::new("Fill Gradient Type").narrow(true).widget_instance(),
TextLabel::new(gradient.gradient_type.to_string()).narrow(true).widget_instance(),
]);
table_rows.push(vec![
TextLabel::new("Fill Gradient Start").narrow(true).widget_instance(),
TextLabel::new(format_dvec2(gradient.start)).narrow(true).widget_instance(),
]);
table_rows.push(vec![
TextLabel::new("Fill Gradient End").narrow(true).widget_instance(),
TextLabel::new(format_dvec2(gradient.end)).narrow(true).widget_instance(),
]);
table_rows.push(vec![
TextLabel::new("Fill Gradient Transform").narrow(true).widget_instance(),
TextLabel::new(format_transform_matrix(gradient.transform)).narrow(true).widget_instance(),
]);
}
}
if let Some(stroke) = self.style.stroke.clone() {
let color = if let Some(color) = stroke.color { FillChoice::Solid(color) } else { FillChoice::None };
table_rows.push(vec![
TextLabel::new("Stroke").narrow(true).widget_instance(),
ColorInput::new(FillChoiceUI::from(&color))
.disabled(true)
.menu_direction(Some(MenuDirection::Top))
.narrow(true)
.widget_instance(),
]);
if let Some(stroke) = self.stroke.as_ref() {
table_rows.push(vec![
TextLabel::new("Stroke Weight").narrow(true).widget_instance(),
TextLabel::new(format!("{} px", stroke.weight)).narrow(true).widget_instance(),
@@ -0,0 +1,276 @@
//! Human-readable pretty-printers for the dual-write soak's validation checks: registry-vs-registry and
//! runtime-network-vs-runtime-network diffs. The callers are gated behind the `validate_storage_round_trip`
//! preference, so these ship in release but only run when the soak is turned on.
use std::fmt::Write;
pub(crate) fn diff_registries(stored: &graph_storage::Registry, target: &graph_storage::Registry) -> String {
let mut out = String::new();
let stored_node_ids: std::collections::BTreeSet<_> = stored.node_instances.keys().copied().collect();
let target_node_ids: std::collections::BTreeSet<_> = target.node_instances.keys().copied().collect();
let missing_nodes: Vec<_> = target_node_ids.difference(&stored_node_ids).collect();
let extra_nodes: Vec<_> = stored_node_ids.difference(&target_node_ids).collect();
let shared_node_diffs: Vec<_> = stored_node_ids
.intersection(&target_node_ids)
.filter(|id| !stored.node_instances[id].value_equal(&target.node_instances[id]))
.collect();
let stored_network_ids: std::collections::BTreeSet<_> = stored.networks.keys().copied().collect();
let target_network_ids: std::collections::BTreeSet<_> = target.networks.keys().copied().collect();
let missing_networks: Vec<_> = target_network_ids.difference(&stored_network_ids).collect();
let extra_networks: Vec<_> = stored_network_ids.difference(&target_network_ids).collect();
let shared_network_diffs: Vec<_> = stored_network_ids
.intersection(&target_network_ids)
.filter(|id| !stored.networks[id].value_equal(&target.networks[id]))
.collect();
let _ = writeln!(out, " nodes: stored={} target={}", stored_node_ids.len(), target_node_ids.len());
if !missing_nodes.is_empty() {
let _ = writeln!(out, " missing from stored: {missing_nodes:?}");
}
if !extra_nodes.is_empty() {
let _ = writeln!(out, " extra in stored: {extra_nodes:?}");
}
if !shared_node_diffs.is_empty() {
let _ = writeln!(out, " differing payloads: {shared_node_diffs:?}");
for id in &shared_node_diffs {
let stored_node = &stored.node_instances[id];
let target_node = &target.node_instances[id];
let _ = writeln!(out, " node {id}:");
diff_node(&mut out, stored_node, target_node);
}
}
let _ = writeln!(out, " networks: stored={} target={}", stored_network_ids.len(), target_network_ids.len());
if !missing_networks.is_empty() {
let _ = writeln!(out, " missing from stored: {missing_networks:?}");
}
if !extra_networks.is_empty() {
let _ = writeln!(out, " extra in stored: {extra_networks:?}");
}
if !shared_network_diffs.is_empty() {
let _ = writeln!(out, " differing payloads: {shared_network_diffs:?}");
for id in &shared_network_diffs {
let stored_network = &stored.networks[id];
let target_network = &target.networks[id];
let _ = writeln!(out, " network {id}:");
diff_network(&mut out, stored_network, target_network);
}
}
let stored_resources: std::collections::BTreeSet<_> = stored.resources.keys().copied().collect();
let target_resources: std::collections::BTreeSet<_> = target.resources.keys().copied().collect();
let missing_resources: Vec<_> = target_resources.difference(&stored_resources).collect();
let extra_resources: Vec<_> = stored_resources.difference(&target_resources).collect();
let shared_resource_diffs: Vec<_> = stored_resources
.intersection(&target_resources)
.filter(|id| !resource_value_equal(&stored.resources[id], &target.resources[id]))
.collect();
if !missing_resources.is_empty() || !extra_resources.is_empty() || !shared_resource_diffs.is_empty() {
let _ = writeln!(out, " resources: stored={} target={}", stored_resources.len(), target_resources.len());
if !missing_resources.is_empty() {
let _ = writeln!(out, " missing from stored: {missing_resources:?}");
}
if !extra_resources.is_empty() {
let _ = writeln!(out, " extra in stored: {extra_resources:?}");
}
if !shared_resource_diffs.is_empty() {
let _ = writeln!(out, " differing payloads: {shared_resource_diffs:?}");
for id in &shared_resource_diffs {
let _ = writeln!(out, " resource {id}:");
diff_resource(&mut out, &stored.resources[id], &target.resources[id]);
}
}
}
if stored.attributes != target.attributes {
diff_attributes(&mut out, " document attributes", &stored.attributes, &target.attributes);
}
out
}
fn diff_node(out: &mut String, stored: &graph_storage::Node, target: &graph_storage::Node) {
if stored.implementation() != target.implementation() {
let _ = writeln!(out, " implementation: stored={:?} target={:?}", stored.implementation(), target.implementation());
}
if stored.network() != target.network() {
let _ = writeln!(out, " network back-pointer: stored={} target={}", stored.network(), target.network());
}
let stored_inputs = stored.inputs();
let target_inputs = target.inputs();
if stored_inputs.len() != target_inputs.len() {
let _ = writeln!(out, " inputs.len: stored={} target={}", stored_inputs.len(), target_inputs.len());
}
for (i, (s, t)) in stored_inputs.iter().zip(target_inputs.iter()).enumerate() {
if s != t {
let value_differs = s.input != t.input;
let timestamp_differs = s.timestamp != t.timestamp;
let _ = writeln!(out, " input[{i}]: value_differs={value_differs} timestamp_differs={timestamp_differs}");
if value_differs {
let _ = writeln!(out, " stored.value={:?}\n target.value={:?}", s.input, t.input);
}
if s.attributes != t.attributes {
diff_attributes(out, &format!(" input[{i}].attributes"), &s.attributes, &t.attributes);
}
}
}
if stored.attributes() != target.attributes() {
diff_attributes(out, " attributes", stored.attributes(), target.attributes());
}
}
fn diff_network(out: &mut String, stored: &graph_storage::Network, target: &graph_storage::Network) {
if stored.exports.len() != target.exports.len() {
let _ = writeln!(out, " exports.len: stored={} target={}", stored.exports.len(), target.exports.len());
}
for (i, (s, t)) in stored.exports.iter().zip(target.exports.iter()).enumerate() {
if s != t {
let target_differs = s.target != t.target;
let timestamp_differs = s.timestamp != t.timestamp;
let _ = writeln!(out, " export[{i}]: target_differs={target_differs} timestamp_differs={timestamp_differs}");
if target_differs {
let _ = writeln!(out, " stored.target={:?}\n target.target={:?}", s.target, t.target);
}
}
}
if stored.attributes != target.attributes {
diff_attributes(out, " attributes", &stored.attributes, &target.attributes);
}
}
/// Value-level resource comparison (same resolved hash, same source bodies keyed by `SourceKey`),
/// ignoring LWW timestamps. Mirrors `graph_storage`'s internal `resources_value_equal` for a single
/// entry, since that helper is crate-private and only operates over a whole store.
fn resource_value_equal(stored: &graph_storage::ResourceEntry, target: &graph_storage::ResourceEntry) -> bool {
stored.hash == target.hash && stored.sources.len() == target.sources.len() && stored.sources.iter().all(|(key, value)| target.source(key).is_some_and(|other| value.source == other.source))
}
fn diff_resource(out: &mut String, stored: &graph_storage::ResourceEntry, target: &graph_storage::ResourceEntry) {
if stored.hash != target.hash {
let _ = writeln!(out, " hash: stored={:?} target={:?}", stored.hash, target.hash);
}
if stored.sources.len() != target.sources.len() {
let _ = writeln!(out, " sources.len: stored={} target={}", stored.sources.len(), target.sources.len());
}
// Report source bodies that drift for a shared key, plus keys present on only one side.
for (key, value) in &stored.sources {
match target.source(key) {
Some(other) if other.source != value.source => {
let _ = writeln!(out, " source[{key:?}]: stored={:?} target={:?}", value.source, other.source);
}
None => {
let _ = writeln!(out, " source[{key:?}]: only in stored");
}
Some(_) => {}
}
}
for (key, _) in &target.sources {
if stored.source(key).is_none() {
let _ = writeln!(out, " source[{key:?}]: only in target");
}
}
}
fn diff_attributes(out: &mut String, label: &str, stored: &graph_storage::Attributes, target: &graph_storage::Attributes) {
let stored_keys: std::collections::BTreeSet<_> = stored.keys().collect();
let target_keys: std::collections::BTreeSet<_> = target.keys().collect();
let missing: Vec<_> = target_keys.difference(&stored_keys).collect();
let extra: Vec<_> = stored_keys.difference(&target_keys).collect();
// Split value drift from timestamp-only drift: each attribute carries an LWW timestamp, so comparing
// whole records would flag equal-value entries that merely differ in when they were last set.
let (differing_values, differing_timestamps): (Vec<_>, Vec<_>) = stored_keys
.intersection(&target_keys)
.copied()
.filter(|k| stored.get(*k) != target.get(*k))
.partition(|k| stored.get(*k).map(|v| &v.value) != target.get(*k).map(|v| &v.value));
let _ = writeln!(
out,
"{label}: missing_from_stored={missing:?} extra_in_stored={extra:?} differing_values={differing_values:?} differing_timestamps={differing_timestamps:?}"
);
}
/// Human-readable summary of how two networks differ (exports, node set, per-node payloads, scope injections).
pub(crate) fn diff_networks(expected: &graph_craft::document::NodeNetwork, actual: &graph_craft::document::NodeNetwork) -> String {
let mut out = String::new();
if expected.exports != actual.exports {
let _ = writeln!(out, " exports differ: expected={} actual={}", expected.exports.len(), actual.exports.len());
for (i, (exp, act)) in expected.exports.iter().zip(actual.exports.iter()).enumerate() {
if exp != act {
let _ = writeln!(out, " [{i}] expected={exp:?}\n actual= {act:?}");
}
}
}
let expected_ids: std::collections::BTreeSet<_> = expected.nodes.keys().copied().collect();
let actual_ids: std::collections::BTreeSet<_> = actual.nodes.keys().copied().collect();
let missing: Vec<_> = expected_ids.difference(&actual_ids).collect();
let extra: Vec<_> = actual_ids.difference(&expected_ids).collect();
let differing: Vec<_> = expected_ids.intersection(&actual_ids).filter(|id| expected.nodes.get(id) != actual.nodes.get(id)).collect();
if !missing.is_empty() || !extra.is_empty() || !differing.is_empty() {
let _ = writeln!(out, " nodes: expected={} actual={}", expected_ids.len(), actual_ids.len());
if !missing.is_empty() {
let _ = writeln!(out, " missing from actual: {missing:?}");
}
if !extra.is_empty() {
let _ = writeln!(out, " extra in actual: {extra:?}");
}
if !differing.is_empty() {
let _ = writeln!(out, " differing payloads: {differing:?}");
for id in &differing {
if let (Some(exp), Some(act)) = (expected.nodes.get(id), actual.nodes.get(id)) {
let _ = writeln!(out, " node {id}:");
diff_document_node(&mut out, exp, act);
}
}
}
}
if expected.scope_injections != actual.scope_injections {
let _ = writeln!(out, " scope_injections differ");
}
out
}
/// Field-level diff between two runtime `DocumentNode`s with the same ID, so the compare-on-open log
/// names *which* field diverged rather than just the node ID. `original_location` is `#[serde(skip)]`
/// and recomputed at load, so it's a likely culprit for a payload mismatch that doesn't affect behavior.
fn diff_document_node(out: &mut String, expected: &graph_craft::document::DocumentNode, actual: &graph_craft::document::DocumentNode) {
if expected.inputs != actual.inputs {
let _ = writeln!(out, " inputs differ (len expected={} actual={})", expected.inputs.len(), actual.inputs.len());
for (i, (e, a)) in expected.inputs.iter().zip(actual.inputs.iter()).enumerate() {
if e != a {
let _ = writeln!(out, " input[{i}]: expected={e:?}\n actual= {a:?}");
}
}
}
if expected.call_argument != actual.call_argument {
let _ = writeln!(out, " call_argument: expected={:?} actual={:?}", expected.call_argument, actual.call_argument);
}
if expected.implementation != actual.implementation {
let _ = writeln!(out, " implementation: expected={:?} actual={:?}", expected.implementation, actual.implementation);
}
if expected.visible != actual.visible {
let _ = writeln!(out, " visible: expected={} actual={}", expected.visible, actual.visible);
}
if expected.skip_deduplication != actual.skip_deduplication {
let _ = writeln!(out, " skip_deduplication: expected={} actual={}", expected.skip_deduplication, actual.skip_deduplication);
}
if expected.context_features != actual.context_features {
let _ = writeln!(out, " context_features: expected={:?} actual={:?}", expected.context_features, actual.context_features);
}
if expected.original_location != actual.original_location {
let _ = writeln!(out, " original_location differs (recomputed at load, not stored):");
let _ = writeln!(out, " expected={:?}\n actual= {:?}", expected.original_location, actual.original_location);
}
}
@@ -0,0 +1,267 @@
use std::collections::VecDeque;
use std::collections::{BTreeMap, HashSet};
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry, ResourceStorage};
use graph_storage::Registry;
use super::utility_types::network_interface::NodeNetworkInterface;
use super::utility_types::network_interface::storage_metadata::{StorageMetadataView, collect_network_view_settings};
/// Per-document undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor that is
/// becoming the authoritative history. Owns the dual-stack bookkeeping push/pop/clear and the cursor's stage/retire/move/verify
/// lifecycle, so the handler drives history through one surface rather than three loose fields.
///
/// Not serialized: the legacy stacks are runtime-only, and a clone shares the working-copy container by
/// `Arc`, so it keeps reading the live working copy.
#[derive(derivative::Derivative)]
#[derivative(Clone, Debug, Default)]
pub struct DocumentHistory {
/// Stack of document network snapshots for previous history states.
lagacy_undo_stack: VecDeque<NodeNetworkInterface>,
/// Stack of document network snapshots for future history states.
lagacy_redo_stack: VecDeque<NodeNetworkInterface>,
/// The `Gdd` working copy: owns the CRDT `Session` and mirrors edits to disk. `None` until the mount
/// future built by `load_document` resolves.
#[derivative(Debug = "ignore")]
storage: Option<document_format::GddV1>,
}
impl DocumentHistory {
// ===== Legacy snapshot stacks =====
/// Push a snapshot onto the undo stack, evicting the oldest entry past the history cap.
pub fn push_undo(&mut self, snapshot: NodeNetworkInterface) {
Self::push_capped(&mut self.lagacy_undo_stack, snapshot);
}
/// Push a snapshot onto the redo stack, evicting the oldest entry past the history cap.
pub fn push_redo(&mut self, snapshot: NodeNetworkInterface) {
Self::push_capped(&mut self.lagacy_redo_stack, snapshot);
}
/// Pop the most recent undo snapshot, or `None` when the stack is empty.
pub fn pop_undo(&mut self) -> Option<NodeNetworkInterface> {
self.lagacy_undo_stack.pop_back()
}
/// Pop the most recent redo snapshot, or `None` when the stack is empty.
pub fn pop_redo(&mut self) -> Option<NodeNetworkInterface> {
self.lagacy_redo_stack.pop_back()
}
/// Drop the most recently pushed undo snapshot (used to cancel a transaction that ended up unmodified).
pub fn discard_last_undo(&mut self) {
self.lagacy_undo_stack.pop_back();
}
/// Clear the redo stack, called when a fresh edit invalidates the redo future.
pub fn clear_redo(&mut self) {
self.lagacy_redo_stack.clear();
}
/// Add the resources referenced by every snapshot in both history stacks into `resources`, so
/// history-only resources stay alive for legacy undo/redo.
pub fn collect_used_resources(&self, resources: &mut HashSet<ResourceId>) {
for interface in self.lagacy_undo_stack.iter().chain(&self.lagacy_redo_stack) {
interface.collect_used_resources(resources);
}
}
// ===== Gdd working-copy cursor =====
/// The `Gdd` working copy, `None` until the mount future resolves.
pub fn storage(&self) -> Option<&document_format::GddV1> {
self.storage.as_ref()
}
/// Mutable access to the `Gdd` working copy.
pub fn storage_mut(&mut self) -> Option<&mut document_format::GddV1> {
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;
}
/// Retire the pending staged hot ops into durable Gdd history as one undo unit. Called at each undo-step
/// boundary (a new `StartTransaction`) and before undo/redo, so the per-`CommitTransaction` staging
/// coalesces into one interaction aligned with the legacy step. No-op while unmounted.
pub fn retire_storage_interaction(&mut self) {
let Some(storage) = self.storage.as_mut() else { return };
if let Err(error) = storage.retire_pending_interaction() {
log::error!("Storage interaction retirement failed: {error}");
}
}
/// Stage the runtime snapshot into the `Gdd` working copy at each `CommitTransaction`. No-op while
/// unmounted. Proto-node declaration bytes go into `byte_store` (the app-global resource cache). The
/// staged hot ops are retired by [`retire_storage_interaction`](Self::retire_storage_interaction) at
/// undo-step boundaries. `validate` (the `validate_storage_round_trip` preference) gates the per-commit
/// round-trip check, off by default for its perf cost.
pub fn stage_snapshot(
&mut self,
interface: &NodeNetworkInterface,
registry: &ResourceRegistry,
view_settings: BTreeMap<String, serde_json::Value>,
legacy_document: &str,
byte_store: &dyn ResourceStorage,
) {
let Some(storage) = self.storage.as_mut() else { return };
let network = interface.document_network();
let metadata_view = StorageMetadataView::new(interface);
let network_view_settings = storage
.network_ids(network, &metadata_view)
.ok()
.map(|network_ids| collect_network_view_settings(interface, &network_ids));
// Stage without retiring: a tool drag fires several `CommitTransaction`s but is one legacy undo
// step, so the deltas accumulate as hot ops and coalesce at the next undo-step boundary.
if let Err(error) = storage.stage_runtime_snapshot(network, &metadata_view, registry, byte_store) {
log::error!("Storage snapshot staging failed: {error}");
return;
}
if let Err(error) = storage.set_view_settings(view_settings) {
log::error!("Persisting view settings failed: {error}");
}
if let Some(network_view_settings) = network_view_settings
&& let Err(error) = storage.set_network_view_settings(network_view_settings)
{
log::error!("Persisting per-network view settings failed: {error}");
}
// Dual-write soak: embed the legacy `.graphite` bytes so the new format
// can be validated against (and recovered from) the old one on open.
if let Err(error) = storage.store_legacy_document(legacy_document.as_bytes()) {
log::error!("Embedding legacy document into working copy failed: {error}");
}
}
/// Move the `Gdd` undo/redo cursor along the retired interaction chain, flushing any open interaction
/// first. Returns a clone of the post-move `Gdd` (`Arc`-shared) so a `'static` rebuild future can read
/// the rewound state while the live document keeps its cursor. `None` when there is nothing to move to,
/// unmounted, or the move failed.
pub fn move_cursor(&mut self, undo: bool) -> Option<document_format::GddV1> {
self.retire_storage_interaction();
let storage = self.storage.as_mut()?;
let moved = if undo {
if !storage.can_undo() {
return None;
}
storage.undo().map(|_| ())
} else {
if !storage.can_redo() {
return None;
}
storage.redo().map(|_| ())
};
if let Err(error) = moved {
log::error!("Storage undo/redo cursor move failed: {error}");
return None;
}
Some(storage.clone())
}
// Soak round-trip verification (runtime-gated by `validate_storage_round_trip`)
// These log drift rather than panicking, since the soak can run in release where a crash is
// unacceptable; tests still fail loud via the `#[cfg(test)]` panics.
/// Soak check: the stored registry should equal a fresh `from_runtime`, and a `to_runtime` of it should
/// equal the original network.
pub fn verify_round_trip(&self, interface: &NodeNetworkInterface, registry: &ResourceRegistry) {
use super::diff_networks;
use super::document_diff::diff_registries;
let Some(storage) = &self.storage else { return };
let peer = storage.session().peer();
let network = interface.document_network();
let metadata_view = StorageMetadataView::new(interface);
let conversion = match Registry::convert_from_runtime(network, &metadata_view, registry, peer) {
Ok(conversion) => conversion,
Err(error) => {
log::error!("storage round-trip: from_runtime failed: {error}");
return;
}
};
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 stored = storage.registry();
if !stored.value_equal(target) {
log::error!("storage round-trip: registry value drift after commit\n{}", diff_registries(stored, target));
#[cfg(test)]
panic!("storage round-trip: registry value drift after commit");
}
if !stored.order_consistent(target) {
log::error!("storage round-trip: timestamp order inconsistent between stored and target");
#[cfg(test)]
panic!("storage round-trip: timestamp order inconsistent between stored and target");
}
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}");
return;
}
};
if &round_tripped != network {
log::error!("storage round-trip: network drift after to_runtime\n{}", diff_networks(network, &round_tripped));
#[cfg(test)]
panic!("storage round-trip: network drift after to_runtime");
}
}
/// Soak check: after a cursor move, the cursor's registry should equal a fresh `from_runtime` of the
/// current (legacy-restored) interface. `current_resources` are the resources the live network
/// references; history-only resources the cursor dropped are expected, not drift.
pub fn verify_cursor_matches_runtime(&self, interface: &NodeNetworkInterface, registry: &ResourceRegistry, current_resources: &HashSet<ResourceId>) {
use super::document_diff::diff_registries;
let Some(storage) = &self.storage else { return };
let peer = storage.session().peer();
let network = interface.document_network();
let metadata_view = StorageMetadataView::new(interface);
let Ok(mut conversion) = Registry::convert_from_runtime(network, &metadata_view, registry, peer) else {
log::error!("undo/redo shadow: from_runtime failed");
return;
};
let stored = storage.registry();
// The cursor reverts the interaction's `AddResource` while the runtime keeps the resource alive for
// legacy redo, so a history-only resource the cursor dropped is expected. Drop those before comparing.
conversion.registry.resources.retain(|id, _| stored.resources.contains_key(id) || current_resources.contains(id));
if !stored.value_equal(&conversion.registry) {
log::error!(
"undo/redo shadow: cursor registry diverged from the restored interface\n{}",
diff_registries(stored, &conversion.registry)
);
}
}
fn push_capped(stack: &mut VecDeque<NodeNetworkInterface>, snapshot: NodeNetworkInterface) {
stack.push_back(snapshot);
if stack.len() > crate::consts::MAX_UNDO_HISTORY_LEN {
stack.pop_front();
}
}
}
@@ -1,3 +1,5 @@
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};
@@ -5,7 +7,7 @@ use super::utility_types::network_interface::{self, NodeNetworkInterface, Transa
use super::utility_types::nodes::{CollapsedLayers, LayerStructureEntry, SelectedNodes};
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, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH, SCALE_EFFECT, SCROLLBAR_SPACING,
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,
VIEWPORT_ROTATE_SNAP_INTERVAL,
};
use crate::messages::input_mapper::utility_types::macros::action_shortcut;
@@ -35,14 +37,15 @@ use graph_craft::application_io::wgpu_available;
use graph_craft::descriptor;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork};
use graphene_std::graphic::is_paint_present;
use graphene_std::math::quad::Quad;
use graphene_std::path_bool_nodes::boolean_intersect;
use graphene_std::raster::BlendMode;
use graphene_std::subpath::Subpath;
use graphene_std::vector::PointId;
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
use graphene_std::vector::misc::dvec2_to_point;
use graphene_std::vector::style::{Fill, RenderMode};
use graphene_std::vector::style::RenderMode;
use graphene_std::vector::{PointId, graphic_types};
use kurbo::{Affine, BezPath, Line, PathSeg};
use std::collections::HashSet;
use std::path::PathBuf;
@@ -64,7 +67,8 @@ pub struct DocumentMessageContext<'a> {
pub fonts: &'a FontsMessageHandler,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ExtractField)]
#[derive(derivative::Derivative, serde::Serialize, serde::Deserialize, ExtractField)]
#[derivative(Clone, Debug)]
#[serde(default)]
pub struct DocumentMessageHandler {
// ======================
@@ -116,6 +120,12 @@ pub struct DocumentMessageHandler {
pub graph_view_overlay_open: bool,
/// The current opacity of the faded node graph background that covers up the artwork.
pub graph_fade_artwork_percentage: f64,
// TODO: Eventually remove this document upgrade code
/// Fill nodes whose decomposed legacy gradient still awaits its bounding box measurement, each recorded as its enclosing
/// network path, the node itself, and its original relative gradient. The deferred migration removes each entry as its bake lands.
/// Transient migration state, but persisted in the saved document so unfinished bakes retry on the next open instead of losing placement.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(crate) pending_gradient_bbox_bake: Vec<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::Gradient)>,
// =============================================
// Fields omitted from the saved document format
@@ -127,23 +137,15 @@ pub struct DocumentMessageHandler {
/// The path of the to the document file.
#[serde(skip)]
pub(crate) path: Option<PathBuf>,
// TODO: Eventually remove this document upgrade code
/// Set when a freshly-opened document still has legacy bounding-box-relative gradients; the deferred gradient
/// migration converts them to absolute after the first graph run (when geometry bounds are available) and clears this.
#[serde(skip)]
pub(crate) pending_gradient_migration: bool,
/// Path to network currently viewed in the node graph overlay. This will eventually be stored in each panel, so that multiple panels can refer to different networks
#[serde(skip)]
breadcrumb_network_path: Vec<NodeId>,
/// Path to network that is currently selected. Updated based on the most recently clicked panel.
#[serde(skip)]
selection_network_path: Vec<NodeId>,
/// Stack of document network snapshots for previous history states.
/// Undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor.
#[serde(skip)]
document_undo_history: VecDeque<NodeNetworkInterface>,
/// Stack of document network snapshots for future history states.
#[serde(skip)]
document_redo_history: VecDeque<NodeNetworkInterface>,
history: DocumentHistory,
/// Hash of the document snapshot that was most recently saved to disk by the user.
#[serde(skip)]
saved_hash: Option<u64>,
@@ -185,17 +187,16 @@ impl Default for DocumentMessageHandler {
graph_view_overlay_open: false,
snapping_state: SnappingState::default(),
graph_fade_artwork_percentage: 80.,
// TODO: Eventually remove this document upgrade code
pending_gradient_bbox_bake: Vec::new(),
// =============================================
// Fields omitted from the saved document format
// =============================================
name: DEFAULT_DOCUMENT_NAME.to_string(),
path: None,
// TODO: Eventually remove this document upgrade code
pending_gradient_migration: false,
breadcrumb_network_path: Vec::new(),
selection_network_path: Vec::new(),
document_undo_history: VecDeque::new(),
document_redo_history: VecDeque::new(),
history: DocumentHistory::default(),
saved_hash: None,
auto_saved_hash: None,
layer_range_selection_reference: None,
@@ -402,8 +403,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![] });
self.layer_range_selection_reference = None;
}
DocumentMessage::DocumentHistoryBackward => self.undo_with_history(viewport, responses),
DocumentMessage::DocumentHistoryForward => self.redo_with_history(viewport, responses),
DocumentMessage::DocumentHistoryBackward => self.undo_with_history(document_id, viewport, resource_storage, responses),
DocumentMessage::DocumentHistoryForward => self.redo_with_history(document_id, viewport, resource_storage, responses),
DocumentMessage::DocumentStructureChanged => {
if layers_panel_open {
self.network_interface.load_structure();
@@ -823,7 +824,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
let layer_node_id = NodeId::new();
let layer_id = LayerNodeIdentifier::new_unchecked(layer_node_id);
responses.add(DocumentMessage::AddTransaction);
responses.add(DocumentMessage::StartTransaction);
let layer = graph_modification_utils::new_image_layer(image, layer_node_id, layer_parent, responses);
@@ -832,7 +833,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
node_id: layer.to_node(),
network_path: Vec::new(),
alias: name,
skip_adding_history_step: false,
// Fold the name into the paste's single transaction so the whole paste is one undo step.
skip_adding_history_step: true,
});
}
if let Some((parent, insert_index)) = parent_and_insert_index {
@@ -853,6 +855,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
skip_rerender: false,
});
responses.add(DocumentMessage::CommitTransaction);
// Force chosen tool to be Select Tool after importing image.
responses.add(ToolMessage::ActivateTool { tool_type: ToolType::Select });
}
@@ -890,7 +894,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
node_id: layer.to_node(),
network_path: Vec::new(),
alias: name,
skip_adding_history_step: false,
// Fold the name into the paste's single transaction so the whole paste is one undo step.
skip_adding_history_step: true,
});
}
if let Some((parent, insert_index)) = parent_and_insert_index {
@@ -1024,28 +1029,63 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
DocumentMessage::SaveDocument | DocumentMessage::SaveDocumentAs => {
responses.add(PortfolioMessage::AutoSaveActiveDocument);
let name = format!("{}.{}", self.name.clone(), FILE_EXTENSION);
let path = if let DocumentMessage::SaveDocumentAs = message { None } else { self.path.clone() };
// Save as a `.gdd` container or a plain legacy `.graphite`, per the editor preference.
let save_as_gdd = preferences.save_as_gdd;
let extension = if save_as_gdd { GDD_FILE_EXTENSION } else { FILE_EXTENSION };
let name = format!("{}.{}", self.name.clone(), extension);
// Keep the path's extension in sync with the chosen format so bytes and filename agree.
let path = match message {
DocumentMessage::SaveDocumentAs => None,
_ => self.path.clone().map(|path| path.with_extension(extension)),
};
if path.is_some() {
responses.add(DocumentMessage::MarkAsSaved);
}
let folder = self.path.as_ref().and_then(|path| path.parent()).map(|parent| parent.to_path_buf());
// The clone shares the working-copy container (Arc), so it reads the state the queued
// AutoSaveActiveDocument just committed.
let mut document = self.clone();
let resources_load_handle = resource_storage.resources();
let export_load_handle = resource_storage.resources();
responses.add(async move {
document.resources.collect_garbage(document.used_resources(false).as_ref());
document.resources.embed_resources(resources_load_handle).await;
let content = document.serialize_document().into_bytes().into();
// Legacy .graphite blob with resources embedded inline, so it is self-contained and also
// serves as the .gdd recovery fallback.
let legacy_document = document.serialize_document().into_bytes();
// A .gdd exports the working copy with the legacy blob embedded, falling back to the bare
// blob when there is no working copy or the export fails.
let content = match (save_as_gdd, document.history.storage()) {
(false, _) => legacy_document,
(true, Some(storage)) => storage
.export_to_bytes(
document_format::ExportFormat::Xz,
document_format::ExportOptions::default(),
export_load_handle.as_ref(),
Some(&legacy_document),
)
.await
.unwrap_or_else(|error| {
log::error!("Save: building .gdd export failed, falling back to legacy .graphite: {error}");
legacy_document
}),
(true, None) => {
log::warn!("Save: working copy not mounted yet, saving legacy .graphite only");
legacy_document
}
};
Message::Frontend(FrontendMessage::TriggerSaveDocument {
document_id,
name,
path,
folder,
content,
content: content.into(),
})
});
}
@@ -1057,8 +1097,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
// Update the name to match the file stem
let document_name_from_path = self.path.as_ref().and_then(|path| {
if path.extension().is_some_and(|e| e == FILE_EXTENSION) {
path.file_stem().map(|n| n.to_string_lossy().to_string())
if path.extension().is_some_and(|extension| extension == FILE_EXTENSION || extension == GDD_FILE_EXTENSION) {
path.file_stem().map(|stem| stem.to_string_lossy().to_string())
} else {
None
}
@@ -1291,12 +1331,10 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
}
// Note: A transaction should never be started in a scope that mutates the network interface, since it will only be run after that scope ends.
DocumentMessage::StartTransaction => {
self.retire_storage_interaction();
self.network_interface.start_transaction();
let network_interface_clone = self.network_interface.clone();
self.document_undo_history.push_back(network_interface_clone);
if self.document_undo_history.len() > crate::consts::MAX_UNDO_HISTORY_LEN {
self.document_undo_history.pop_front();
}
self.history.push_undo(self.network_interface.clone());
// Push the UpdateOpenDocumentsList message to the bus in order to update the save status of the open documents
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
}
@@ -1312,14 +1350,17 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
},
DocumentMessage::CancelTransaction => {
self.network_interface.finish_transaction();
self.document_undo_history.pop_back();
self.history.discard_last_undo();
}
DocumentMessage::CommitTransaction => {
if self.network_interface.transaction_status() == TransactionStatus::Finished {
return;
}
self.network_interface.finish_transaction();
self.document_redo_history.clear();
self.history.clear_redo();
self.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
}
DocumentMessage::AbortTransaction => match self.network_interface.transaction_status() {
@@ -1754,6 +1795,35 @@ 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 {
let mut document = Self {
network_interface: interface,
name,
path,
..Default::default()
};
document.apply_stored_document_settings(storage.view_settings());
match storage.registry().to_resource_registry() {
Ok(resource_registry) => document.resources.registry = resource_registry,
Err(error) => log::error!("Opening .gdd: failed to rebuild resource registry: {error}"),
}
document.history.set_storage(Some(storage));
document
}
/// Post-load fixups for a document built from storage.
pub fn finalize_storage_load(&mut self) {
for (node_id, node, path) in self.network_interface.document_network().clone().recursive_nodes() {
self.network_interface.validate_input_metadata(node_id, node, &path);
self.network_interface.validate_output_names(node_id, node, &path);
}
self.network_interface.load_structure();
}
/// Translates a viewport mouse position to a document-space transform, or uses the viewport center if no mouse position is given.
fn document_transform_from_mouse(&self, mouse: Option<(f64, f64)>, viewport: &ViewportMessageHandler) -> DAffine2 {
let viewport_pos: DVec2 = mouse.map_or_else(|| viewport.center_in_viewport_space().into_dvec2() + viewport.offset().into_dvec2(), |pos| pos.into());
@@ -1929,6 +1999,133 @@ impl DocumentMessageHandler {
&self.selection_network_path
}
/// The `Gdd` working copy, `None` until the mount future resolves.
pub fn storage(&self) -> Option<&document_format::GddV1> {
self.history.storage()
}
/// Mutable access to the `Gdd` working copy.
pub fn storage_mut(&mut self) -> Option<&mut document_format::GddV1> {
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);
}
/// Retire the pending staged hot ops into durable Gdd history as one undo unit.
pub(crate) fn retire_storage_interaction(&mut self) {
self.history.retire_storage_interaction();
}
/// Stages the runtime network into the `Gdd` working copy.
pub fn commit_storage_snapshot(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage, validate: bool) {
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::DocumentSettings;
if self.history.storage().is_none() {
return;
}
let view_settings = DocumentSettings {
document_ptz: &self.document_ptz,
render_mode: &self.render_mode,
overlays_visibility: &self.overlays_visibility_settings,
rulers_visible: self.rulers_visible,
snapping_state: &self.snapping_state,
collapsed: &self.collapsed,
}
.to_view_map();
let legacy_document = self.serialize_document();
self.history
.stage_snapshot(&self.network_interface, &self.resources.registry, view_settings, legacy_document.as_str(), byte_store);
if validate {
self.history.verify_round_trip(&self.network_interface, &self.resources.registry);
}
}
/// Restore `view_settings` map into the document.
pub fn apply_stored_document_settings(&mut self, view_settings: &std::collections::BTreeMap<String, serde_json::Value>) {
use 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())
}
if let Some(value) = decode(view_settings, doc::PTZ) {
self.document_ptz = value;
}
if let Some(value) = decode(view_settings, doc::RENDER_MODE) {
self.render_mode = value;
}
if let Some(value) = decode(view_settings, doc::OVERLAYS) {
self.overlays_visibility_settings = value;
}
if let Some(value) = decode(view_settings, doc::RULERS_VISIBLE) {
self.rulers_visible = value;
}
if let Some(value) = decode(view_settings, doc::SNAPPING) {
self.snapping_state = value;
}
if let Some(value) = decode(view_settings, doc::COLLAPSED) {
self.collapsed = value;
}
}
/// Move the `Gdd` undo/redo cursor and spawn the async future that rebuilds the
/// interface from the cursor and swaps it in. `had_oracle` records whether the legacy snapshot already
/// applied, so the completion can compare; it travels with the spawned message. Returns whether the
/// cursor moved, so callers know a rebuild is pending.
fn drive_storage_undo_redo(&mut self, document_id: DocumentId, resource_storage: &ResourceStorageMessageHandler, had_oracle: bool, undo: bool, responses: &mut VecDeque<Message>) -> bool {
let Some(gdd) = self.history.move_cursor(undo) else { return false };
responses.add(crate::messages::portfolio::document_storage_io::rebuild_gdd_cursor(
gdd,
resource_storage.resources_mut(),
document_id,
had_oracle,
));
true
}
/// Swap in the interface rebuilt from the `Gdd` cursor. Always overwrites the interface.
pub(crate) fn apply_gdd_cursor_rebuild(&mut self, mut rebuilt: NodeNetworkInterface, had_oracle: bool, validate: bool, responses: &mut VecDeque<Message>) {
rebuilt.copy_all_transient_view_state(&self.network_interface);
std::mem::swap(&mut rebuilt.resolved_types, &mut self.network_interface.resolved_types);
rebuilt.load_structure();
if validate && had_oracle {
self.compare_rebuild_against_legacy(&rebuilt);
}
self.network_interface = rebuilt;
if validate {
let current_resources: std::collections::HashSet<_> = self.used_resources(false).iter().copied().collect();
self.history.verify_cursor_matches_runtime(&self.network_interface, &self.resources.registry, &current_resources);
}
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(NodeGraphMessage::SelectedNodesUpdated);
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::SendWires);
}
/// Check if the rebuilt network equals the legacy-restored one. Logs drift (panics in tests).
fn compare_rebuild_against_legacy(&self, rebuilt: &NodeNetworkInterface) {
let legacy = self.network_interface.document_network();
let candidate = rebuilt.document_network();
if candidate != legacy {
log::error!("undo/redo rebuild diverged from the legacy snapshot\n{}", diff_networks(legacy, candidate));
#[cfg(test)]
panic!("undo/redo rebuild diverged from the legacy snapshot")
}
}
pub fn serialize_document(&self) -> String {
let val = serde_json::to_string(self);
// We fully expect the serialization to succeed
@@ -2206,18 +2403,20 @@ impl DocumentMessageHandler {
paths
}
pub fn undo_with_history(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) {
let Some(previous_network) = self.undo(viewport, responses) else { return };
pub fn undo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, resource_storage: &ResourceStorageMessageHandler, responses: &mut VecDeque<Message>) {
let legacy_applied = if let Some(previous_network) = self.undo(viewport, responses) {
self.history.push_redo(previous_network);
true
} else {
false
};
self.document_redo_history.push_back(previous_network);
if self.document_redo_history.len() > crate::consts::MAX_UNDO_HISTORY_LEN {
self.document_redo_history.pop_front();
}
self.drive_storage_undo_redo(document_id, resource_storage, legacy_applied, true, responses);
}
pub fn undo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
// If there is no history return and don't broadcast SelectionChanged
let mut network_interface = self.document_undo_history.pop_back()?;
let mut network_interface = self.history.pop_undo()?;
// Set the previous network navigation metadata to the current navigation metadata
network_interface.copy_all_navigation_metadata(&self.network_interface);
@@ -2242,19 +2441,20 @@ impl DocumentMessageHandler {
Some(previous_network)
}
pub fn redo_with_history(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) {
// Push the UpdateOpenDocumentsList message to the queue in order to update the save status of the open documents
let Some(previous_network) = self.redo(viewport, responses) else { return };
pub fn redo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, resource_storage: &ResourceStorageMessageHandler, responses: &mut VecDeque<Message>) {
let legacy_applied = if let Some(previous_network) = self.redo(viewport, responses) {
self.history.push_undo(previous_network);
true
} else {
false
};
self.document_undo_history.push_back(previous_network);
if self.document_undo_history.len() > crate::consts::MAX_UNDO_HISTORY_LEN {
self.document_undo_history.pop_front();
}
self.drive_storage_undo_redo(document_id, resource_storage, legacy_applied, false, responses);
}
pub fn redo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
// If there is no history return and don't broadcast SelectionChanged
let mut network_interface = self.document_redo_history.pop_back()?;
let mut network_interface = self.history.pop_redo()?;
// Set the previous network navigation metadata to the current navigation metadata
network_interface.copy_all_navigation_metadata(&self.network_interface);
@@ -2563,29 +2763,20 @@ impl DocumentMessageHandler {
let mut resulting_layers: Vec<NodeId> = Vec::new();
for layer in selected_layers {
let style = self.network_interface.document_metadata().layer_vector_data.get(&layer).map(|arc| arc.style.clone());
let Some(style) = style else {
let Some(vector_data) = self.network_interface.document_metadata().layer_vector_data.get(&layer) else {
resulting_layers.push(layer.to_node());
continue;
};
let stroke = vector_data.stroke.as_ref();
let fill_graphic_list = self.network_interface.document_metadata().layer_fill_attributes.get(&layer);
let stroke_graphic_list = self.network_interface.document_metadata().layer_stroke_attributes.get(&layer);
let has_fill = if let Some(list) = fill_graphic_list {
list.element(0).is_some()
} else {
!matches!(style.fill, Fill::None)
};
// `style.stroke` is `Some` whenever a `Stroke` node is in the chain, even with weight 0 or a transparent color.
// So `is_some()` would treat invisibly-stroked fill-only layers as having a stroke.
// `ATTR_STROKE` is the source of truth when set; fall back to `style.stroke.color` only when no attribute is present.
let stroke_visible = if let Some(list) = stroke_graphic_list {
list.element(0).is_some_and(|g| !g.is_fully_transparent())
} else {
style.stroke.as_ref().and_then(|s| s.color()).is_some_and(|c| c.a() != 0.)
};
let has_stroke = style.stroke.as_ref().is_some_and(|s| s.has_renderable_stroke()) && stroke_visible;
let has_fill = fill_graphic_list.is_some_and(|list| is_paint_present(list));
// `Vector.stroke` captures stroke geometry, even with weight 0 or transparent paint.
// So stroke visibility must be checked from `ATTR_STROKE`, the paint source of truth.
let stroke_visible = stroke_graphic_list.is_some_and(|list| list.element(0).is_some_and(|g| !g.is_fully_transparent()));
let has_stroke = stroke.as_ref().is_some_and(|s| s.has_renderable_stroke()) && stroke_visible;
// No stroke means there's nothing to solidify. Fill-only layers are already in the desired form, so skip.
if !has_stroke {
@@ -3589,8 +3780,7 @@ impl DocumentMessageHandler {
let mut resources = HashSet::new();
self.network_interface.collect_used_resources(&mut resources);
if include_history {
self.document_undo_history.iter().for_each(|interface| interface.collect_used_resources(&mut resources));
self.document_redo_history.iter().for_each(|interface| interface.collect_used_resources(&mut resources));
self.history.collect_used_resources(&mut resources);
}
resources.into_iter().collect::<Vec<_>>().into_boxed_slice()
}
@@ -3814,6 +4004,21 @@ mod document_message_handler_tests {
use super::*;
use crate::test_utils::test_prelude::*;
#[test]
fn pending_gradient_bakes_round_trip_through_serialization() {
let document = DocumentMessageHandler {
pending_gradient_bbox_bake: vec![(vec![NodeId(7)], NodeId(42), graphic_types::migrations::legacy::Gradient::default())],
..Default::default()
};
let serialized = document.serialize_document();
let deserialized = DocumentMessageHandler::deserialize_document(&serialized).expect("Document with pending gradient bakes should deserialize");
assert_eq!(deserialized.pending_gradient_bbox_bake, document.pending_gradient_bbox_bake);
// The common empty case must not add the field to saved files
assert!(!DocumentMessageHandler::default().serialize_document().contains("pending_gradient_bbox_bake"));
}
#[tokio::test]
async fn test_layer_selection_with_shift_and_ctrl() {
let mut editor = EditorTestUtils::create();
@@ -10,15 +10,22 @@ use graphene_std::raster::BlendMode;
use graphene_std::raster_types::Image;
use graphene_std::subpath::Subpath;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::style::{Fill, GradientSpreadMethod, GradientType, Stroke};
use graphene_std::vector::style::{GradientSpreadMethod, GradientType, Stroke};
use graphene_std::vector::{GradientStops, PointId, VectorModificationType};
#[impl_message(Message, DocumentMessage, GraphOperation)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum GraphOperationMessage {
FillSet {
FillColorSet {
layer: LayerNodeIdentifier,
fill: Fill,
color: Option<Color>,
},
FillGradientSet {
layer: LayerNodeIdentifier,
gradient: GradientStops,
gradient_type: GradientType,
spread_method: GradientSpreadMethod,
transform: DAffine2,
},
BlendingFillSet {
layer: LayerNodeIdentifier,
@@ -28,10 +35,9 @@ pub enum GraphOperationMessage {
layer: LayerNodeIdentifier,
stops: GradientStops,
},
GradientLineSet {
GradientTransformSet {
layer: LayerNodeIdentifier,
start: DVec2,
end: DVec2,
transform: DAffine2,
},
GradientTypeSet {
layer: LayerNodeIdentifier,
@@ -54,6 +60,7 @@ pub enum GraphOperationMessage {
},
StrokeSet {
layer: LayerNodeIdentifier,
color: Option<Color>,
stroke: Stroke,
},
TransformChange {
@@ -13,7 +13,7 @@ use graph_craft::document::{NodeId, NodeInput};
use graphene_std::list::List;
use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::style::{Fill, Gradient, GradientSpreadMethod, GradientStop, GradientStops, GradientType, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::style::{GradientSpreadMethod, GradientStop, GradientStops, GradientType, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::{Artboard, Color};
#[derive(ExtractField)]
@@ -34,9 +34,20 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
let GraphOperationMessageContext { network_interface, .. } = context;
match message {
GraphOperationMessage::FillSet { layer, fill } => {
GraphOperationMessage::FillColorSet { layer, color } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.fill_set(fill);
modify_inputs.fill_color_set(color);
}
}
GraphOperationMessage::FillGradientSet {
layer,
gradient,
gradient_type,
spread_method,
transform,
} => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.fill_gradient_set(gradient, gradient_type, spread_method, transform);
}
}
GraphOperationMessage::BlendingFillSet { layer, fill } => {
@@ -49,9 +60,9 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
modify_inputs.gradient_stops_set(stops);
}
}
GraphOperationMessage::GradientLineSet { layer, start, end } => {
GraphOperationMessage::GradientTransformSet { layer, transform } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.gradient_line_set(start, end);
modify_inputs.gradient_transform_set(transform);
}
}
GraphOperationMessage::GradientTypeSet { layer, gradient_type } => {
@@ -80,9 +91,9 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
modify_inputs.clip_mode_toggle(clip_mode);
}
}
GraphOperationMessage::StrokeSet { layer, stroke } => {
GraphOperationMessage::StrokeSet { layer, color, stroke } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.stroke_set(stroke);
modify_inputs.stroke_set(color, stroke);
}
}
GraphOperationMessage::TransformChange {
@@ -622,7 +633,7 @@ fn import_usvg_node(
usvg::Node::Text(text) => {
let font = Font::new(graphene_std::consts::DEFAULT_FONT_FAMILY.to_string(), graphene_std::consts::DEFAULT_FONT_STYLE.to_string());
modify_inputs.insert_text(text.chunks().iter().map(|chunk| chunk.text()).collect(), font, TypesettingConfig::default(), layer);
modify_inputs.fill_set(Fill::Solid(Color::BLACK));
modify_inputs.fill_color_set(Some(Color::BLACK));
}
}
}
@@ -674,7 +685,7 @@ fn import_usvg_node_inner(
usvg::Node::Text(text) => {
let font = Font::new(graphene_std::consts::DEFAULT_FONT_FAMILY.to_string(), graphene_std::consts::DEFAULT_FONT_STYLE.to_string());
modify_inputs.insert_text(text.chunks().iter().map(|chunk| chunk.text()).collect(), font, TypesettingConfig::default(), layer);
modify_inputs.fill_set(Fill::Solid(Color::BLACK));
modify_inputs.fill_color_set(Some(Color::BLACK));
0
}
}
@@ -762,27 +773,29 @@ fn set_import_child_positions(
fn apply_usvg_stroke(stroke: &usvg::Stroke, modify_inputs: &mut ModifyInputsContext, transform: DAffine2) {
if let usvg::Paint::Color(color) = &stroke.paint() {
modify_inputs.stroke_set(Stroke {
color: Some(usvg_color(*color, stroke.opacity().get())),
weight: stroke.width().get() as f64,
dash_lengths: stroke.dasharray().as_ref().map(|lengths| lengths.iter().map(|&length| length as f64).collect()).unwrap_or_default(),
dash_offset: stroke.dashoffset() as f64,
cap: match stroke.linecap() {
usvg::LineCap::Butt => StrokeCap::Butt,
usvg::LineCap::Round => StrokeCap::Round,
usvg::LineCap::Square => StrokeCap::Square,
modify_inputs.stroke_set(
Some(usvg_color(*color, stroke.opacity().get())),
Stroke {
weight: stroke.width().get() as f64,
dash_lengths: stroke.dasharray().as_ref().map(|lengths| lengths.iter().map(|&length| length as f64).collect()).unwrap_or_default(),
dash_offset: stroke.dashoffset() as f64,
cap: match stroke.linecap() {
usvg::LineCap::Butt => StrokeCap::Butt,
usvg::LineCap::Round => StrokeCap::Round,
usvg::LineCap::Square => StrokeCap::Square,
},
join: match stroke.linejoin() {
usvg::LineJoin::Miter => StrokeJoin::Miter,
usvg::LineJoin::MiterClip => StrokeJoin::Miter,
usvg::LineJoin::Round => StrokeJoin::Round,
usvg::LineJoin::Bevel => StrokeJoin::Bevel,
},
join_miter_limit: stroke.miterlimit().get() as f64,
align: StrokeAlign::Center,
paint_order: PaintOrder::StrokeAbove,
transform,
},
join: match stroke.linejoin() {
usvg::LineJoin::Miter => StrokeJoin::Miter,
usvg::LineJoin::MiterClip => StrokeJoin::Miter,
usvg::LineJoin::Round => StrokeJoin::Round,
usvg::LineJoin::Bevel => StrokeJoin::Bevel,
},
join_miter_limit: stroke.miterlimit().get() as f64,
align: StrokeAlign::Center,
paint_order: PaintOrder::StrokeAbove,
transform,
})
)
}
}
@@ -795,16 +808,18 @@ fn convert_spread_method(spread_method: usvg::SpreadMethod) -> GradientSpreadMet
}
fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, graphite_gradient_stops: &HashMap<String, GradientStops>) {
modify_inputs.fill_set(match &fill.paint() {
usvg::Paint::Color(color) => Fill::solid(usvg_color(*color, fill.opacity().get())),
match &fill.paint() {
usvg::Paint::Color(color) => modify_inputs.fill_color_set(Some(usvg_color(*color, fill.opacity().get()))),
usvg::Paint::LinearGradient(linear) => {
let gradient_transform = usvg_transform(linear.transform());
let (start, end) = (DVec2::new(linear.x1() as f64, linear.y1() as f64), DVec2::new(linear.x2() as f64, linear.y2() as f64));
let (start, end) = (gradient_transform.transform_point2(start), gradient_transform.transform_point2(end));
let direction = end - start;
let transform = DAffine2::from_cols(direction, direction.perp(), start);
let gradient_type = GradientType::Linear;
let stops = match graphite_gradient_stops.get(linear.id()) {
let gradient = match graphite_gradient_stops.get(linear.id()) {
Some(graphite_stops) => graphite_stops.clone(),
None => {
let stops = linear.stops().iter().map(|stop| GradientStop {
@@ -816,27 +831,19 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
}
};
let spread_method = convert_spread_method(linear.spread_method());
Fill::Gradient(Gradient {
start,
end,
gradient_type,
stops,
spread_method,
// TODO: Eventually remove this document upgrade code
absolute: true,
transform: DAffine2::IDENTITY,
})
modify_inputs.fill_gradient_set(gradient, gradient_type, spread_method, transform);
}
usvg::Paint::RadialGradient(radial) => {
let gradient_transform = usvg_transform(radial.transform());
let center = DVec2::new(radial.cx() as f64, radial.cy() as f64);
let edge = center + DVec2::X * radial.r().get() as f64;
let (start, end) = (gradient_transform.transform_point2(center), gradient_transform.transform_point2(edge));
let direction = end - start;
let transform = DAffine2::from_cols(direction, direction.perp(), start);
let gradient_type = GradientType::Radial;
let stops = match graphite_gradient_stops.get(radial.id()) {
let gradient = match graphite_gradient_stops.get(radial.id()) {
Some(graphite_stops) => graphite_stops.clone(),
None => {
let stops = radial.stops().iter().map(|stop| GradientStop {
@@ -849,20 +856,8 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
};
let spread_method = convert_spread_method(radial.spread_method());
Fill::Gradient(Gradient {
start,
end,
gradient_type,
stops,
spread_method,
// TODO: Eventually remove this document upgrade code
absolute: true,
transform: DAffine2::IDENTITY,
})
modify_inputs.fill_gradient_set(gradient, gradient_type, spread_method, transform);
}
usvg::Paint::Pattern(_) => {
warn!("SVG patterns are not currently supported");
return;
}
});
usvg::Paint::Pattern(_) => warn!("SVG patterns are not currently supported"),
};
}
@@ -4,7 +4,7 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, OutputConnector};
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::{get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input};
use glam::{DAffine2, DVec2};
use glam::{DAffine2, DVec2, IVec2};
use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
@@ -15,7 +15,7 @@ use graphene_std::raster::BlendMode;
use graphene_std::raster_types::Image;
use graphene_std::subpath::Subpath;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::style::{Fill, GradientSpreadMethod, GradientType, Stroke};
use graphene_std::vector::style::{GradientSpreadMethod, GradientType, Stroke};
use graphene_std::vector::{GradientStops, PointId, Vector, VectorModification, VectorModificationType};
use graphene_std::{Artboard, Color, Graphic, NodeInputDecleration};
@@ -453,30 +453,59 @@ impl<'a> ModifyInputsContext<'a> {
Some(node_id)
}
pub fn fill_set(&mut self, fill: Fill) {
let fill_index = 1;
let backup_color_index = 2;
let backup_gradient_index = 3;
pub fn fill_color_set(&mut self, color: Option<Color>) {
let Some(fill_node_id) = self.existing_proto_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true) else {
return;
};
match &fill {
Fill::None => {
let input_connector = InputConnector::node(fill_node_id, backup_color_index);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(None), false), true);
}
Fill::Solid(color) => {
let input_connector = InputConnector::node(fill_node_id, backup_color_index);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(Some(*color)), false), true);
}
Fill::Gradient(gradient) => {
let input_connector = InputConnector::node(fill_node_id, backup_gradient_index);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::FillGradient(gradient.clone()), false), true);
}
let input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX);
let backup_input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::BackupColorInput::INDEX);
self.set_input_with_refresh(backup_input_connector, NodeInput::value(TaggedValue::Color(color), false), true);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(color), false), false);
}
pub fn fill_gradient_set(&mut self, gradient: GradientStops, gradient_type: GradientType, spread_method: GradientSpreadMethod, transform: DAffine2) {
let Some(fill_node_id) = self.existing_proto_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true) else {
return;
};
let backup_input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::BackupGradientInput::INDEX);
self.set_input_with_refresh(backup_input_connector, NodeInput::value(TaggedValue::Gradient(gradient.clone()), false), true);
// Skip the rerender on all but the last input so the whole update triggers a single graph run
self.set_input_with_refresh(
InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX),
NodeInput::value(TaggedValue::Gradient(gradient), false),
true,
);
// Reposition the gradient only when the transform is a plain value, leaving a wired transform source connected
let transform_is_value = self
.network_interface
.document_network()
.nodes
.get(&fill_node_id)
.and_then(|node| node.inputs.get(graphene_std::vector::fill::TransformInput::INDEX))
.is_some_and(|input| input.as_value().is_some());
if transform_is_value {
self.set_input_with_refresh(
InputConnector::node(fill_node_id, graphene_std::vector::fill::TransformInput::INDEX),
NodeInput::value(TaggedValue::OptionalDAffine2(Some(transform)), false),
true,
);
}
let input_connector = InputConnector::node(fill_node_id, fill_index);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Fill(fill), false), false);
self.set_input_with_refresh(
InputConnector::node(fill_node_id, graphene_std::vector::fill::GradientTypeInput::INDEX),
NodeInput::value(TaggedValue::GradientType(gradient_type), false),
true,
);
self.set_input_with_refresh(
InputConnector::node(fill_node_id, graphene_std::vector::fill::SpreadMethodInput::INDEX),
NodeInput::value(TaggedValue::GradientSpreadMethod(spread_method), false),
false,
);
}
pub fn blend_mode_set(&mut self, blend_mode: BlendMode) {
@@ -536,18 +565,52 @@ impl<'a> ModifyInputsContext<'a> {
/// Write the gradient stops to the 'Gradient Value' node feeding the layer.
pub fn gradient_stops_set(&mut self, stops: GradientStops) {
let Some(output_layer) = self.get_output_layer() else { return };
let Some(gradient_value_id) = get_upstream_gradient_value_node_id(output_layer, self.network_interface) else {
return;
let gradient_value_id = match get_upstream_gradient_value_node_id(output_layer, self.network_interface) {
Some(id) => id,
None => {
let target = gradient_chain_target_input(output_layer, self.network_interface);
let starts_layer_chain = target == InputConnector::node(output_layer.to_node(), 1);
// The Gradient Value node discards its primary input, so starting a chain ahead of existing layer content would drop that content; refuse instead
if starts_layer_chain && self.network_interface.upstream_output_connector(&target, &[]).is_some() {
log::error!("Refusing to start a gradient chain ahead of existing layer content");
return;
}
let Some(node_definition) = resolve_proto_node_type(graphene_std::math_nodes::gradient_value::IDENTIFIER) else {
return;
};
let node_id = NodeId::new();
self.network_interface.insert_node(node_id, node_definition.default_node_template(), &[]);
if starts_layer_chain {
// No Fill node: the new node starts the layer's chain
self.network_interface.move_node_to_chain_start(&node_id, output_layer, &[], self.import);
} else {
// Feeding a Fill node's paint input: wire it up and place it one chain-width left and a step below the Fill
self.network_interface.set_input(&target, NodeInput::node(node_id, 0), &[]);
if let Some(target_node_id) = target.node_id()
&& let Some(target_position) = self.network_interface.position(&target_node_id, &[])
{
let node_position = self.network_interface.position(&node_id, &[]).unwrap_or_default();
let desired_position = target_position + IVec2::new(-crate::consts::NODE_CHAIN_WIDTH, 2);
self.network_interface.shift_absolute_node_position(&node_id, desired_position - node_position, &[]);
}
}
node_id
}
};
let input_connector = InputConnector::node(gradient_value_id, graphene_std::math_nodes::gradient_value::GradientInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Gradient(stops), false), false);
}
/// Update the gradient line so its endpoints are at `new_start` and `new_end`.
/// Update the transform to map the unit gradient ((0,0), (1, 0)) to the geometry's local space.
/// With multiple `Transform` nodes the last one (closest to the layer) is modified so the chain still composes to the target.
/// With none, one is inserted unless the target is the identity.
pub fn gradient_line_set(&mut self, new_start: DVec2, new_end: DVec2) {
pub fn gradient_transform_set(&mut self, transform: DAffine2) {
let Some(output_layer) = self.get_output_layer() else { return };
let walk_from = if let Some(fill_input_node_id) = get_fill_input_node_id(output_layer, self.network_interface) {
@@ -583,14 +646,9 @@ impl<'a> ModifyInputsContext<'a> {
.map_or(acc, |document_node| acc * transform_utils::get_current_transform(&document_node.inputs))
})
};
let composed_old = compose(&upstream_transforms);
let prior_combined = compose(prior_transforms);
// Rebuild the y-axis from the new x-axis using the old (parallel, perpendicular) decomposition and length ratio,
// so the gradient's aspect ratio and skew survive an endpoint drag (so an ellipse stays the same ellipse) instead of
// the old y-axis vector remaining fixed while x changes
let new_composed = build_transform_with_y_preservation(composed_old, new_start, new_end);
let last_transform_value = new_composed * prior_combined.inverse();
let last_transform_value = transform * prior_combined.inverse();
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let transform_node_id = if let Some(id) = last_transform_node_id {
@@ -615,6 +673,7 @@ impl<'a> ModifyInputsContext<'a> {
/// from the default (`Linear`).
pub fn gradient_type_set(&mut self, gradient_type: GradientType) {
let Some(output_layer) = self.get_output_layer() else { return };
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let identifier = graphene_std::math_nodes::gradient_type::IDENTIFIER;
let create_if_nonexistent = gradient_type != GradientType::default();
@@ -630,6 +689,7 @@ impl<'a> ModifyInputsContext<'a> {
/// from the default (`Pad`).
pub fn gradient_spread_method_set(&mut self, spread_method: GradientSpreadMethod) {
let Some(output_layer) = self.get_output_layer() else { return };
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let identifier = graphene_std::math_nodes::spread_method::IDENTIFIER;
let create_if_nonexistent = spread_method != GradientSpreadMethod::default();
@@ -650,13 +710,13 @@ impl<'a> ModifyInputsContext<'a> {
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Bool(clip), false), false);
}
pub fn stroke_set(&mut self, stroke: Stroke) {
pub fn stroke_set(&mut self, color: Option<Color>, stroke: Stroke) {
let Some(stroke_node_id) = self.existing_proto_node_id(graphene_std::vector::stroke::IDENTIFIER, true) else {
return;
};
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::ColorInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(stroke.color), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintInput::<List<Graphic>>::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(color), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::WeightInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.weight), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::AlignInput::INDEX);
@@ -804,40 +864,3 @@ impl<'a> ModifyInputsContext<'a> {
}
}
}
/// Rebuild the y-axis so its (parallel, perpendicular) components in the x-axis-aligned frame stay constant, both
/// rescaled by `|new_x| / |old_x|`. This holds the (x, y) parallelogram's aspect ratio and skew fixed across an endpoint
/// drag, so a radial ellipse stays the same shape (just rotated and resized) instead of distorting as x grows or shrinks.
/// Falls back to a +90° rotation of `new_x` when `old_x` is degenerate.
fn scale_y_axis_to_match_new_x(old_x: DVec2, old_y: DVec2, new_x: DVec2) -> DVec2 {
let old_x_length = old_x.length();
if old_x_length < 1e-9 {
return DVec2::new(-new_x.y, new_x.x);
}
let ex_old = old_x / old_x_length;
let ey_old = DVec2::new(-ex_old.y, ex_old.x);
let new_x_length = new_x.length();
if new_x_length < 1e-9 {
return DVec2::ZERO;
}
let ex_new = new_x / new_x_length;
let ey_new = DVec2::new(-ex_new.y, ex_new.x);
let parallel = old_y.dot(ex_old);
let perpendicular = old_y.dot(ey_old);
let scale = new_x_length / old_x_length;
scale * (parallel * ex_new + perpendicular * ey_new)
}
/// Build a new affine that maps canonical (0,0) -> (1,0) to (new_start, new_end), preserving the y-axis
/// shape of `old` proportionally to the x-axis length change.
fn build_transform_with_y_preservation(old: DAffine2, new_start: DVec2, new_end: DVec2) -> DAffine2 {
let new_x_axis = new_end - new_start;
let preserved_y_axis = scale_y_axis_to_match_new_x(old.matrix2.x_axis, old.matrix2.y_axis, new_x_axis);
DAffine2 {
matrix2: glam::DMat2::from_cols(new_x_axis, preserved_y_axis),
translation: new_start,
}
}
@@ -1,5 +1,9 @@
pub(crate) mod document_diff;
mod document_history;
mod document_message;
mod document_message_handler;
#[cfg(test)]
mod storage_tests;
pub mod data_panel;
pub mod graph_operation;
@@ -10,6 +14,8 @@ pub mod properties_panel;
pub mod resource;
pub mod utility_types;
pub(crate) use document_diff::diff_networks;
pub(crate) use document_history::DocumentHistory;
#[doc(inline)]
pub use document_message::{DocumentMessage, DocumentMessageDiscriminant};
#[doc(inline)]
@@ -1664,15 +1664,18 @@ fn static_input_properties() -> InputProperties {
if let Some(unit) = field.unit {
number_input = number_input.unit(unit);
}
if let Some(number_min) = field.number_min {
number_input = number_input.min(number_min);
// Typing is clamped only by the hard bounds; the slider extent prefers the soft bounds (see `property_from_type`)
if let Some(hard_min) = field.number_hard_min {
number_input = number_input.min(hard_min);
}
if let Some(number_max) = field.number_max {
number_input = number_input.max(number_max);
if let Some(hard_max) = field.number_hard_max {
number_input = number_input.max(hard_max);
}
if let Some((range_min, range_max)) = field.number_mode_range {
number_input = number_input.range_min(Some(range_min));
number_input = number_input.range_max(Some(range_max));
if field.number_mode_range {
number_input = number_input
.mode_range()
.range_min(field.number_soft_min.or(field.number_hard_min))
.range_max(field.number_soft_max.or(field.number_hard_max));
}
number_input = number_input.is_integer(false);
if let Some(number_step) = field.number_step {
@@ -1765,11 +1765,11 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
NodeGraphMessage::SetInputValue { node_id, input_index, value } => {
use graphene_std::vector::generator_nodes::*;
let is_fill = matches!(value, TaggedValue::Fill(_));
let reference = network_interface.reference(&node_id, selection_network_path);
let is_text_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER));
let is_stroke_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER));
let is_fill_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER));
let is_fill_input = is_fill_node && input_index == graphene_std::vector::fill::FillInput::<graphene_std::list::List<Graphic>>::INDEX;
let is_shape_generator_node = reference.as_ref().is_some_and(|r| {
[regular_polygon::IDENTIFIER, star::IDENTIFIER, arc::IDENTIFIER, spiral::IDENTIFIER, grid::IDENTIFIER, arrow::IDENTIFIER]
.into_iter()
@@ -1782,7 +1782,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
input,
});
responses.add(PropertiesPanelMessage::Refresh);
if is_fill {
if is_fill_input {
responses.add(OverlaysMessage::Draw);
}
if is_stroke_node || is_fill_node || is_shape_generator_node || is_text_node {
@@ -16,9 +16,11 @@ use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
use graph_craft::{Type, concrete};
use graphene_std::Graphic;
use graphene_std::NodeInputDecleration;
use graphene_std::animation::RealTimeMode;
use graphene_std::brush::brush_stroke::BrushStroke;
use graphene_std::color::SRGBA8;
use graphene_std::extract_xy::XY;
use graphene_std::list::List;
use graphene_std::raster::{
@@ -31,7 +33,9 @@ use graphene_std::text_nodes::StringCapitalization;
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
use graphene_std::vector::misc::BooleanOperation;
use graphene_std::vector::misc::{ArcType, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType};
use graphene_std::vector::style::{Fill, FillChoice, FillChoiceUI, GradientSpreadMethod, GradientStops, GradientStopsUI, GradientType, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::style::{
FillChoice, FillChoiceUI, GradientSpreadMethod, GradientStops, GradientStopsUI, GradientType, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, build_transform_with_y_preservation,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
pub(crate) fn string_properties(text: &str) -> Vec<LayoutGroup> {
@@ -149,22 +153,36 @@ pub fn start_widgets(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<Widget
widgets
}
/// The numeric bounds and widget mode of a number parameter, sourced from the node's field metadata.
#[derive(Clone, Copy, Default)]
pub(crate) struct NumberOptions {
pub soft_min: Option<f64>,
pub soft_max: Option<f64>,
pub hard_min: Option<f64>,
pub hard_max: Option<f64>,
pub slider: bool,
}
pub(crate) fn property_from_type(
node_id: NodeId,
index: usize,
ty: &Type,
number_options: (Option<f64>, Option<f64>, Option<(f64, f64)>),
number_options: NumberOptions,
unit: Option<&str>,
display_decimal_places: Option<u32>,
step: Option<f64>,
context: &mut NodePropertiesContext,
) -> Result<Vec<LayoutGroup>, Vec<LayoutGroup>> {
let (mut number_min, mut number_max, range) = number_options;
let NumberOptions {
soft_min,
soft_max,
hard_min,
hard_max,
slider,
} = number_options;
let mut number_input = NumberInput::default();
if let Some((range_start, range_end)) = range {
number_min = Some(range_start);
number_max = Some(range_end);
number_input = number_input.mode_range().min(range_start).max(range_end);
if slider {
number_input = number_input.mode_range();
}
if let Some(unit) = unit {
number_input = number_input.unit(unit);
@@ -176,8 +194,22 @@ pub(crate) fn property_from_type(
number_input = number_input.step(step);
}
let min = |x: f64| number_min.unwrap_or(x);
let max = |x: f64| number_max.unwrap_or(x);
// Applies the parameter's typing clamp and slider extent to the widget, given the type's own default bounds.
// Per end: the clamp is the hard bound (or unbounded if only a soft bound is given, since soft is a suggested
// extent rather than a limit), and the slider extent is the soft bound, each falling back to the hard bound
// and then to the type default when unspecified. An end with any explicit bound ignores the type default.
let bounded = |number_input: NumberInput, type_min: f64, type_max: f64| {
let clamp_min = hard_min.unwrap_or(if soft_min.is_some() { f64::NEG_INFINITY } else { type_min });
let clamp_max = hard_max.unwrap_or(if soft_max.is_some() { f64::INFINITY } else { type_max });
let extent_min = soft_min.or(hard_min).unwrap_or(type_min);
let extent_max = soft_max.or(hard_max).unwrap_or(type_max);
number_input
.min(clamp_min)
.max(clamp_max)
.range_min(Some(extent_min).filter(|bound| bound.is_finite()))
.range_max(Some(extent_max).filter(|bound| bound.is_finite()))
};
let default_info = ParameterWidgetsInfo::new(node_id, index, true, context);
@@ -186,16 +218,16 @@ pub(crate) fn property_from_type(
Type::Concrete(concrete_type) => {
match concrete_type.alias.as_ref().map(|x| x.as_ref()) {
// Aliased types (ambiguous values)
Some("Percentage") | Some("PercentageF32") => number_widget(default_info, number_input.percentage().min(min(0.)).max(max(100.))).into(),
Some("SignedPercentage") | Some("SignedPercentageF32") => number_widget(default_info, number_input.percentage().min(min(-100.)).max(max(100.))).into(),
Some("Angle") | Some("AngleF32") => number_widget(default_info, number_input.mode_range().min(min(-180.)).max(max(180.)).unit(unit.unwrap_or("°"))).into(),
Some("Multiplier") => number_widget(default_info, number_input.unit(unit.unwrap_or("x"))).into(),
Some("PixelLength") => number_widget(default_info, number_input.min(min(0.)).unit(unit.unwrap_or(" px"))).into(),
Some("Length") => number_widget(default_info, number_input.min(min(0.))).into(),
Some("Fraction") => number_widget(default_info, number_input.mode_range().min(min(0.)).max(max(1.))).into(),
Some("Progression") => progression_widget(default_info, number_input.min(min(0.))).into(),
Some("SignedInteger") => number_widget(default_info, number_input.int()).into(),
Some("SeedValue") => number_widget(default_info, number_input.int().min(min(0.))).into(),
Some("Percentage") | Some("PercentageF32") => number_widget(default_info, bounded(number_input.percentage(), 0., 100.)).into(),
Some("SignedPercentage") | Some("SignedPercentageF32") => number_widget(default_info, bounded(number_input.percentage(), -100., 100.)).into(),
Some("Angle") | Some("AngleF32") => number_widget(default_info, bounded(number_input.mode_range(), -180., 180.).unit(unit.unwrap_or("°"))).into(),
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_widget(default_info, bounded(number_input.mode_range(), 0., 1.)).into(),
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(),
@@ -206,9 +238,9 @@ pub(crate) fn property_from_type(
// ===============
// PRIMITIVE TYPES
// ===============
Some(x) if x == TypeId::of::<f64>() || x == TypeId::of::<f32>() => number_widget(default_info, number_input.min(min(f64::NEG_INFINITY)).max(max(f64::INFINITY))).into(),
Some(x) if x == TypeId::of::<u32>() => number_widget(default_info, number_input.int().min(min(0.)).max(max(f64::from(u32::MAX)))).into(),
Some(x) if x == TypeId::of::<u64>() => number_widget(default_info, number_input.int().min(min(0.))).into(),
Some(x) if x == TypeId::of::<f64>() || x == TypeId::of::<f32>() => number_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(),
Some(x) if x == TypeId::of::<u32>() => number_widget(default_info, bounded(number_input.int(), 0., f64::from(u32::MAX))).into(),
Some(x) if x == TypeId::of::<u64>() => number_widget(default_info, bounded(number_input.int(), 0., f64::INFINITY)).into(),
Some(x) if x == TypeId::of::<bool>() => bool_widget(default_info, CheckboxInput::default()).into(),
Some(x) if x == TypeId::of::<String>() => text_widget(default_info).into(),
Some(x) if x == TypeId::of::<DVec2>() => vec2_widget(default_info, "X", "Y", "", None, false),
@@ -2295,7 +2327,7 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
return Vec::new();
};
let mut number_options = (None, None, None);
let mut number_options = NumberOptions::default();
let mut display_decimal_places = None;
let mut step = None;
let mut unit_suffix = None;
@@ -2307,7 +2339,13 @@ 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 = (field.number_min, field.number_max, field.number_mode_range);
number_options = NumberOptions {
soft_min: field.number_soft_min,
soft_max: field.number_soft_max,
hard_min: field.number_hard_min,
hard_max: field.number_hard_max,
slider: field.number_mode_range,
};
display_decimal_places = field.number_display_decimal_places;
unit_suffix = field.unit;
step = field.number_step;
@@ -2378,60 +2416,111 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
LayoutGroup::section(name, description, visible, pinned, expanded, node_id.0, Layout(layout))
}
/// The layer that a chain node ultimately feeds, if any. Returns `None` in a nested network since the layer metadata structure
/// is only loaded for the root document network, so a `LayerNodeIdentifier` can't be constructed there.
fn root_layer_for_chain_node(node_id: NodeId, context: &mut NodePropertiesContext) -> Option<LayerNodeIdentifier> {
if !context.selection_network_path.is_empty() {
return None;
}
let layer_node = context.network_interface.downstream_layer_for_chain_node(&node_id, context.selection_network_path)?;
Some(LayerNodeIdentifier::new(layer_node, context.network_interface))
}
/// Resolve the viewport-space orientation of a Fill node's gradient by walking downstream to its owning layer
/// and reusing the same helper the Gradient tool uses, so canvas tilt and layer transforms behave identically.
fn gradient_orientation_in_fill_node(node_id: NodeId, gradient: &graphene_std::vector::style::Gradient, context: &mut NodePropertiesContext) -> Option<bool> {
let layer_node = context.network_interface.downstream_layer_for_chain_node(&node_id, context.selection_network_path)?;
let layer = LayerNodeIdentifier::new(layer_node, context.network_interface);
fn gradient_orientation_in_fill_node(node_id: NodeId, gradient_transform: DAffine2, context: &mut NodePropertiesContext) -> Option<bool> {
let layer = root_layer_for_chain_node(node_id, context)?;
let transform = graph_modification_utils::gradient_space_transform(layer, context.network_interface);
Some(graph_modification_utils::gradient_orientation_rightward(gradient.start, gradient.end, transform))
Some(graph_modification_utils::gradient_orientation_rightward(transform * gradient_transform))
}
/// Fill Node Widgets LayoutGroup
pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesContext) -> Vec<LayoutGroup> {
use graphene_std::vector::fill::*;
#[derive(Debug, Clone)]
enum ResolvedFill {
Solid(Option<Color>),
Gradient {
gradient: GradientStops,
gradient_type: GradientType,
spread_method: GradientSpreadMethod,
transform: DAffine2,
/// Whether the transform input holds a plain value (so the "Reverse Direction" button may write to it) rather than a wire.
transform_is_value: bool,
},
Other,
}
let connector = InputConnector::node(node_id, FillInput::<List<Graphic>>::INDEX);
let input_type = context.network_interface.input_type(&connector, context.selection_network_path);
// Pass blank_assist=false because the assist slot is filled below ("Reverse Stops" button when in gradient mode)
let mut widgets_first_row = start_widgets(ParameterWidgetsInfo::new(node_id, FillInput::<Color>::INDEX, false, context));
let mut widgets_first_row = start_widgets(ParameterWidgetsInfo::new(node_id, FillInput::<List<Graphic>>::INDEX, false, 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 fill_properties: {err}");
return Vec::new();
}
};
let (fill, backup_color, backup_gradient) = if let (Some(TaggedValue::Fill(fill)), Some(TaggedValue::Color(backup_color)), Some(TaggedValue::FillGradient(backup_gradient))) = (
&document_node.inputs[FillInput::<Color>::INDEX].as_value(),
&document_node.inputs[BackupColorInput::INDEX].as_value(),
&document_node.inputs[BackupGradientInput::INDEX].as_value(),
) {
(fill, backup_color, backup_gradient)
} else {
if get_document_node(node_id, context).is_ok_and(|node| node.inputs.get(FillInput::<List<Graphic>>::INDEX).is_some_and(|input| input.is_exposed())) {
return vec![LayoutGroup::row(widgets_first_row)];
}
// A Fill node not attached to a layer (or living in a nested network) still shows its full fill UI; only the gradient's
// bounding-box default transform needs the layer, and it falls back to a unit box when there isn't one.
let layer = root_layer_for_chain_node(node_id, context);
let fill = match input_type.compiled_nested_type() {
Some(ty) if ty == &concrete!(List<Color>) => {
if let Ok(document_node) = get_document_node(node_id, context) {
let color = match document_node.inputs[FillInput::<List<Graphic>>::INDEX].as_value() {
Some(&TaggedValue::Color(c)) => c,
_ => None,
};
ResolvedFill::Solid(color)
} else {
ResolvedFill::Other
}
}
Some(ty) if ty == &concrete!(List<GradientStops>) => {
// Read this node's own inputs rather than the layer's nearest Fill, which may be a different node when Fills are chained
if let Ok(document_node) = get_document_node(node_id, context)
&& let Some(gradient) = graph_modification_utils::read_fill_node_gradient(document_node, || {
layer.map_or([DVec2::ZERO, DVec2::ONE], |layer| context.network_interface.document_metadata().nonzero_bounding_box(layer))
}) {
ResolvedFill::Gradient {
gradient: gradient.stops,
gradient_type: gradient.gradient_type,
spread_method: gradient.spread_method,
transform: gradient.transform,
transform_is_value: gradient.transform_is_value,
}
} else {
ResolvedFill::Other
}
}
_ => ResolvedFill::Other,
};
let fill2 = fill.clone();
let backup_color_fill: Fill = (*backup_color).into();
let backup_gradient_fill: Fill = backup_gradient.clone().into();
let (backup_color, backup_gradient) = match get_document_node(node_id, context) {
Ok(document_node) => {
let backup_color = match document_node.inputs[BackupColorInput::INDEX].as_value() {
Some(&TaggedValue::Color(color)) => color,
_ => None,
};
let backup_stops = match document_node.inputs[BackupGradientInput::INDEX].as_value() {
Some(TaggedValue::Gradient(stops)) => stops.clone(),
_ => GradientStops::default(),
};
(backup_color, backup_stops)
}
Err(_) => (None, GradientStops::default()),
};
match &fill {
ResolvedFill::Gradient { gradient: stops, .. } => {
let stops = stops.clone();
match fill {
Fill::Gradient(gradient) => {
let reverse_button = IconButton::new("Reverse", 24)
.tooltip_label("Reverse Stops")
.tooltip_description("Reverse the gradient color stops.")
.on_update(update_value(
{
let gradient = gradient.clone();
move |_| {
let mut gradient = gradient.clone();
gradient.stops = gradient.stops.reversed();
TaggedValue::Fill(Fill::Gradient(gradient))
}
},
node_id,
FillInput::<Color>::INDEX,
))
.on_update(update_value(move |_| TaggedValue::Gradient(stops.reversed()), node_id, FillInput::<List<Graphic>>::INDEX))
.widget_instance();
widgets_first_row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
widgets_first_row.push(reverse_button);
@@ -2439,32 +2528,65 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
_ => add_blank_assist(&mut widgets_first_row),
}
let fill_choice_ui = match &fill {
ResolvedFill::Solid(color) => {
if let Some(color) = color {
FillChoiceUI::Solid(SRGBA8::from(*color))
} else {
FillChoiceUI::None
}
}
ResolvedFill::Gradient { gradient: stops, .. } => FillChoiceUI::Gradient(GradientStopsUI::from(stops)),
ResolvedFill::Other => FillChoiceUI::None,
};
let solid_set_messages = move |color: Option<Color>| Message::Batched {
messages: Box::new([
NodeGraphMessage::SetInputValue {
node_id,
input_index: FillInput::<List<Graphic>>::INDEX,
value: TaggedValue::Color(color),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: BackupColorInput::INDEX,
value: TaggedValue::Color(color),
}
.into(),
]),
};
let gradient_set_messages = move |gradient: GradientStops| Message::Batched {
messages: Box::new([
NodeGraphMessage::SetInputValue {
node_id,
input_index: FillInput::<List<Graphic>>::INDEX,
value: TaggedValue::Gradient(gradient.clone()),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: BackupGradientInput::INDEX,
value: TaggedValue::Gradient(gradient),
}
.into(),
]),
};
widgets_first_row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
widgets_first_row.push(
ColorInput::default()
.value(FillChoiceUI::from(&FillChoice::from(fill.clone())))
.on_update(move |x: &ColorInput| {
let new_fill = FillChoice::from(&x.value).to_fill(fill2.as_gradient());
let (backup_index, backup_value) = match &new_fill {
Fill::None => (BackupColorInput::INDEX, TaggedValue::Color(None)),
Fill::Solid(color) => (BackupColorInput::INDEX, TaggedValue::Color(Some(*color))),
Fill::Gradient(gradient) => (BackupGradientInput::INDEX, TaggedValue::FillGradient(gradient.clone())),
};
Message::Batched {
messages: Box::new([
NodeGraphMessage::SetInputValue {
node_id,
input_index: backup_index,
value: backup_value,
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: FillInput::<Color>::INDEX,
value: TaggedValue::Fill(new_fill),
}
.into(),
]),
.value(fill_choice_ui)
.on_update(move |x: &ColorInput| match &x.value {
FillChoiceUI::None => solid_set_messages(None),
FillChoiceUI::Solid(srgba8) => {
let color = Some(Color::from(*srgba8));
solid_set_messages(color)
}
FillChoiceUI::Gradient(gradient_stops_ui) => {
let gradient = GradientStops::from(gradient_stops_ui);
gradient_set_messages(gradient)
}
})
.on_commit(commit_value)
@@ -2480,61 +2602,50 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
let entries = vec![
RadioEntryData::new("solid")
.label("Solid")
.on_update(update_value(move |_| TaggedValue::Fill(backup_color_fill.clone()), node_id, FillInput::<Color>::INDEX))
.on_update(update_value(move |_| TaggedValue::Color(backup_color), node_id, FillInput::<List<Graphic>>::INDEX))
.on_commit(commit_value),
RadioEntryData::new("gradient")
.label("Gradient")
.on_update(update_value(move |_| TaggedValue::Fill(backup_gradient_fill.clone()), node_id, FillInput::<Color>::INDEX))
.on_update(update_value(move |_| TaggedValue::Gradient(backup_gradient.clone()), node_id, FillInput::<List<Graphic>>::INDEX))
.on_commit(commit_value),
];
row.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
RadioInput::new(entries).selected_index(Some(if fill.as_gradient().is_some() { 1 } else { 0 })).widget_instance(),
RadioInput::new(entries)
.selected_index(Some(if matches!(fill, ResolvedFill::Gradient { .. }) { 1 } else { 0 }))
.widget_instance(),
]);
LayoutGroup::row(row)
};
widgets.push(fill_type_switch);
if let Fill::Gradient(gradient) = fill.clone() {
if let ResolvedFill::Gradient {
gradient_type,
spread_method,
transform,
transform_is_value,
..
} = fill.clone()
{
// Linear/Radial radio: blank assist (the "Reverse Direction" button has been moved down to the spread method row)
let mut row = vec![TextLabel::new("").widget_instance()];
add_blank_assist(&mut row);
let gradient_for_closure = gradient.clone();
let entries = [GradientType::Linear, GradientType::Radial]
.iter()
.map(|&grad_type| {
let gradient = gradient_for_closure.clone();
let set_input_value = update_value(
move |_: &()| {
let mut new_gradient = gradient.clone();
new_gradient.gradient_type = grad_type;
TaggedValue::Fill(Fill::Gradient(new_gradient))
},
node_id,
FillInput::<Color>::INDEX,
);
RadioEntryData::new(format!("{:?}", grad_type))
.label(format!("{:?}", grad_type))
.on_update(move |_| Message::Batched {
messages: Box::new([
set_input_value(&()),
GradientToolMessage::UpdateOptions {
options: GradientOptionsUpdate::Type(grad_type),
}
.into(),
]),
})
.on_update(update_value(move |_| TaggedValue::GradientType(grad_type), node_id, GradientTypeInput::INDEX))
.on_commit(commit_value)
})
.collect();
row.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
RadioInput::new(entries).selected_index(Some(gradient.gradient_type as u32)).widget_instance(),
RadioInput::new(entries).selected_index(Some(gradient_type as u32)).widget_instance(),
]);
widgets.push(LayoutGroup::row(row));
@@ -2543,75 +2654,41 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
// space so canvas tilt and layer transforms behave the same as in the Gradient tool's control bar.
let mut spread_methods_row = vec![TextLabel::new("").widget_instance()];
let orientation_rightward = gradient_orientation_in_fill_node(node_id, &gradient, context).unwrap_or(true);
let reverse_direction_button = IconButton::new(if orientation_rightward { "ReverseRadialGradientToRight" } else { "ReverseRadialGradientToLeft" }, 24)
.tooltip_label("Reverse Direction")
.tooltip_description(if gradient.gradient_type == GradientType::Radial {
"Reverse which end the gradient radiates from."
} else {
"Swap the start and end points of the gradient line."
})
.on_update(update_value(
{
let gradient = gradient.clone();
move |_| {
let mut gradient = gradient.clone();
std::mem::swap(&mut gradient.start, &mut gradient.end);
TaggedValue::Fill(Fill::Gradient(gradient))
}
},
node_id,
FillInput::<Color>::INDEX,
))
.widget_instance();
spread_methods_row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
spread_methods_row.push(reverse_direction_button);
// The button writes a value into the transform input, so only offer it when the input isn't wired
if transform_is_value {
let start = transform.transform_point2(DVec2::ZERO);
let end = transform.transform_point2(DVec2::X);
let new_transform = build_transform_with_y_preservation(transform, end, start);
let orientation_rightward = gradient_orientation_in_fill_node(node_id, transform, context).unwrap_or(true);
let reverse_direction_button = IconButton::new(if orientation_rightward { "ReverseRadialGradientToRight" } else { "ReverseRadialGradientToLeft" }, 24)
.tooltip_label("Reverse Direction")
.tooltip_description(if gradient_type == GradientType::Radial {
"Reverse which end the gradient radiates from."
} else {
"Swap the start and end points of the gradient line."
})
.on_update(update_value(move |_| TaggedValue::OptionalDAffine2(Some(new_transform)), node_id, TransformInput::INDEX))
.widget_instance();
spread_methods_row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
spread_methods_row.push(reverse_direction_button);
} else {
add_blank_assist(&mut spread_methods_row);
}
let spread_method_entries = [GradientSpreadMethod::Pad, GradientSpreadMethod::Reflect, GradientSpreadMethod::Repeat]
.iter()
.map(|&spread_method| {
let gradient_for_input = gradient_for_closure.clone();
let gradient_for_backup = gradient_for_closure.clone();
let set_input_value = update_value(
move |_: &()| {
let mut new_gradient = gradient_for_input.clone();
new_gradient.spread_method = spread_method;
TaggedValue::Fill(Fill::Gradient(new_gradient))
},
node_id,
FillInput::<Color>::INDEX,
);
let set_backup_value = update_value(
move |_: &()| {
let mut new_gradient = gradient_for_backup.clone();
new_gradient.spread_method = spread_method;
TaggedValue::FillGradient(new_gradient)
},
node_id,
BackupGradientInput::INDEX,
);
RadioEntryData::new(format!("{:?}", spread_method))
.label(format!("{:?}", spread_method))
.on_update(move |_| Message::Batched {
messages: Box::new([
set_input_value(&()),
set_backup_value(&()),
GradientToolMessage::UpdateOptions {
options: GradientOptionsUpdate::SetSpreadMethod(spread_method),
}
.into(),
]),
})
.on_update(update_value(move |_| TaggedValue::GradientSpreadMethod(spread_method), node_id, SpreadMethodInput::INDEX))
.on_commit(commit_value)
})
.collect();
spread_methods_row.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
RadioInput::new(spread_method_entries).selected_index(Some(gradient.spread_method as u32)).widget_instance(),
RadioInput::new(spread_method_entries).selected_index(Some(spread_method as u32)).widget_instance(),
]);
widgets.push(LayoutGroup::row(spread_methods_row));
@@ -2626,7 +2703,7 @@ pub fn stroke_properties(node_id: NodeId, context: &mut NodePropertiesContext) -
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 fill_properties: {err}");
log::error!("Could not get document node in stroke_properties: {err}");
return Vec::new();
}
};
@@ -2642,7 +2719,7 @@ pub fn stroke_properties(node_id: NodeId, context: &mut NodePropertiesContext) -
let miter_limit_disabled = join_value != &StrokeJoin::Miter;
let color = color_widget(
ParameterWidgetsInfo::new(node_id, ColorInput::INDEX, true, context),
ParameterWidgetsInfo::new(node_id, PaintInput::<List<Graphic>>::INDEX, true, context),
crate::messages::layout::utility_types::widgets::button_widgets::ColorInput::default(),
);
let weight = number_widget(ParameterWidgetsInfo::new(node_id, WeightInput::INDEX, true, context), NumberInput::default().unit(" px").min(0.));
@@ -27,7 +27,7 @@ impl FrontendGraphDataType {
match TaggedValue::from_type_or_none(input) {
TaggedValue::U32(_) | TaggedValue::U64(_) | TaggedValue::F32(_) | TaggedValue::F64(_) | TaggedValue::DVec2(_) | TaggedValue::F64Array(_) | TaggedValue::DAffine2(_) => Self::Number,
TaggedValue::Color(_) => Self::Color,
TaggedValue::FillGradient(_) | TaggedValue::Gradient(_) => Self::Gradient,
TaggedValue::LegacyGradient(_) | TaggedValue::Gradient(_) => Self::Gradient,
TaggedValue::String(_) => Self::Typography,
// Types whose `TaggedValue` variant has been removed are routed through `TypeDefault` and identified by the descriptor's type name.
TaggedValue::TypeDefault(td) => match td.name.as_ref() {
@@ -0,0 +1,313 @@
//! Conversion-level round-trip tests for the [`storage_metadata`](crate::messages::portfolio::document::utility_types::network_interface::storage_metadata)
//! bridge: drive a demo `.graphite` document through `Registry` (and back through
//! `build_interface_from_storage`) without an actual save/reopen, asserting the editor's `ui::*`
//! metadata survives the conversion. The end-to-end save/reopen pipeline is covered separately in
//! [`round_trip_tests`](super::round_trip_tests).
use std::collections::HashMap;
use graph_storage::{NodeMetadataSource, PeerId, Registry};
use super::test_support::{load_demo, node_paths};
use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler;
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::{DocumentSettings, StorageMetadataView, build_interface_from_storage};
use crate::messages::portfolio::document::utility_types::nodes::CollapsedLayers;
use graph_craft::document::NodeId;
use graphene_std::vector::style::RenderMode;
/// Loads a demo artwork, round-trips its `NodeNetwork + NodeNetworkInterface metadata` through
/// `Registry`, and asserts every node's `ui::*` attributes survive unchanged.
///
/// Uses one demo (rather than the full set) because this is an exhaustive per-node check.
#[test]
fn editor_metadata_round_trip_against_demo() {
let document = load_demo("changing-seasons.graphite");
let interface = &document.network_interface;
let source = StorageMetadataView::new(interface);
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 registry = conversion.registry;
let (_converted_network, entries) = registry.to_runtime_with_metadata(&declarations).expect("to_runtime_with_metadata failed");
// Index emitted entries by their (network_path, local_id) address.
let entries_by_address: HashMap<(Vec<NodeId>, NodeId), &graph_storage::NodeMetadataEntry> = entries.iter().map(|e| ((e.network_path.clone(), e.local_id), e)).collect();
let mut checked_any_position = false;
let mut checked_any_layer = false;
let mut checked_any_input_metadata = false;
for (network_path, local_id) in node_paths(interface) {
let expected_position = source.position(&network_path, local_id);
let expected_is_layer = source.is_layer(&network_path, local_id);
let expected_display = source.display_name(&network_path, local_id).map(str::to_owned);
let expected_locked = source.locked(&network_path, local_id);
let expected_pinned = source.pinned(&network_path, local_id);
let expected_output_names = source.output_names(&network_path, local_id);
// Use the node's input count as the slot-by-slot iteration bound for the per-input metadata checks.
let input_count = interface.document_node(&local_id, &network_path).map(|node| node.inputs.len()).unwrap_or(0);
let any_input_metadata_present = (0..input_count).any(|i| {
source.input_name(&network_path, local_id, i).is_some_and(|s| !s.is_empty())
|| source.input_description(&network_path, local_id, i).is_some_and(|s| !s.is_empty())
|| source.widget_override(&network_path, local_id, i).is_some()
|| !source.input_data(&network_path, local_id, i).is_empty()
});
let any_metadata = expected_position.is_some()
|| expected_is_layer
|| expected_display.as_deref().is_some_and(|s| !s.is_empty())
|| expected_locked
|| expected_pinned
|| any_input_metadata_present
|| !expected_output_names.is_empty();
if !any_metadata {
assert!(
!entries_by_address.contains_key(&(network_path.clone(), local_id)),
"node {local_id:?} in network {network_path:?} has no editor metadata but produced an entry"
);
continue;
}
let entry = entries_by_address
.get(&(network_path.clone(), local_id))
.unwrap_or_else(|| panic!("missing entry for node {local_id:?} in network {network_path:?}"));
assert_eq!(entry.position, expected_position, "position mismatch for node {local_id:?} in network {network_path:?}");
assert_eq!(entry.is_layer, expected_is_layer, "is_layer mismatch for node {local_id:?} in network {network_path:?}");
// The trait round-trip drops empty display names (treats them as "unset") so the entry's
// `display_name` is `None` when the runtime carries `""`. Normalize before comparing.
let normalized_expected_display = expected_display.as_deref().filter(|s| !s.is_empty()).map(str::to_owned);
assert_eq!(
entry.display_name, normalized_expected_display,
"display_name mismatch for node {local_id:?} in network {network_path:?}"
);
assert_eq!(entry.locked, expected_locked, "locked mismatch for node {local_id:?} in network {network_path:?}");
assert_eq!(entry.pinned, expected_pinned, "pinned mismatch for node {local_id:?} in network {network_path:?}");
assert_eq!(entry.output_names, expected_output_names, "output_names mismatch for node {local_id:?} in network {network_path:?}");
// Per-input metadata: the entry's `input_metadata` has one slot per input, each matching the trait's
// per-field view (same "empty string ↔ None" normalization as `display_name`).
assert_eq!(
entry.input_metadata.len(),
input_count,
"input_metadata length mismatch for node {local_id:?} in network {network_path:?}: entry has {}, node has {input_count}",
entry.input_metadata.len(),
);
for (index, input_entry) in entry.input_metadata.iter().enumerate() {
let expected_name = source.input_name(&network_path, local_id, index).filter(|s| !s.is_empty()).map(str::to_owned);
let expected_description = source.input_description(&network_path, local_id, index).filter(|s| !s.is_empty()).map(str::to_owned);
let expected_widget = source.widget_override(&network_path, local_id, index).map(str::to_owned);
let expected_data = source.input_data(&network_path, local_id, index);
assert_eq!(
input_entry.input_name, expected_name,
"input_name mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
input_entry.input_description, expected_description,
"input_description mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
input_entry.widget_override, expected_widget,
"widget_override mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
input_entry.input_data, expected_data,
"input_data mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
}
if entry.position.is_some() {
checked_any_position = true;
}
if entry.is_layer {
checked_any_layer = true;
}
if any_input_metadata_present {
checked_any_input_metadata = true;
}
}
// Sanity: a real artwork should exercise at least these two shapes; otherwise the test is
// just iterating empty metadata and proving nothing.
assert!(checked_any_position, "demo artwork produced no positioned nodes: fixture is wrong or extraction is broken");
assert!(checked_any_layer, "demo artwork produced no layer nodes: fixture is wrong or extraction is broken");
// Demo artworks always have some custom widget overrides / input names; if not, the
// per-input round-trip isn't actually being exercised here.
assert!(checked_any_input_metadata, "demo artwork produced no per-input metadata: fixture is wrong or extraction is broken");
}
/// Full editor-side round-trip: original interface → Registry → (NodeNetwork, Vec<entry>) →
/// freshly-built interface. Asserts the rebuilt interface presents the same `ui::*` state as
/// the original when read through `StorageMetadataView`.
#[test]
fn editor_interface_rebuild_round_trip() {
let document = load_demo("changing-seasons.graphite");
let original = &document.network_interface;
let original_view = StorageMetadataView::new(original);
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 registry = conversion.registry;
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime_with_full_metadata failed");
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage failed");
let rebuilt_view = StorageMetadataView::new(&rebuilt);
// Every node the original carried must also resolve identically through the rebuilt view.
// Iterating over the *rebuilt* interface verifies that the rebuild covered every node, not
// just the ones the entries vec mentioned.
for (network_path, local_id) in node_paths(&rebuilt) {
assert_eq!(
rebuilt_view.position(&network_path, local_id),
original_view.position(&network_path, local_id),
"position mismatch for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
rebuilt_view.is_layer(&network_path, local_id),
original_view.is_layer(&network_path, local_id),
"is_layer mismatch for node {local_id:?} in network {network_path:?}"
);
// Original display names are returned by the source as-is (including `""`). After
// round-trip the rebuilt interface also stores `""` for nodes that had no name set,
// so this comparison is exact.
assert_eq!(
rebuilt_view.display_name(&network_path, local_id),
original_view.display_name(&network_path, local_id),
"display_name mismatch for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
rebuilt_view.locked(&network_path, local_id),
original_view.locked(&network_path, local_id),
"locked mismatch for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
rebuilt_view.pinned(&network_path, local_id),
original_view.pinned(&network_path, local_id),
"pinned mismatch for node {local_id:?} in network {network_path:?}"
);
// Per-input metadata: walk both interfaces' input slots in lockstep.
let original_inputs = original.document_node(&local_id, &network_path).map(|n| n.inputs.len()).unwrap_or(0);
let rebuilt_inputs = rebuilt.document_node(&local_id, &network_path).map(|n| n.inputs.len()).unwrap_or(0);
assert_eq!(
rebuilt_inputs, original_inputs,
"input count mismatch for node {local_id:?} in network {network_path:?}: rebuilt={rebuilt_inputs} original={original_inputs}"
);
for index in 0..rebuilt_inputs {
assert_eq!(
rebuilt_view.input_name(&network_path, local_id, index),
original_view.input_name(&network_path, local_id, index),
"input_name mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
rebuilt_view.input_description(&network_path, local_id, index),
original_view.input_description(&network_path, local_id, index),
"input_description mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
rebuilt_view.widget_override(&network_path, local_id, index),
original_view.widget_override(&network_path, local_id, index),
"widget_override mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
rebuilt_view.input_data(&network_path, local_id, index),
original_view.input_data(&network_path, local_id, index),
"input_data mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
}
assert_eq!(
rebuilt_view.output_names(&network_path, local_id),
original_view.output_names(&network_path, local_id),
"output_names mismatch for node {local_id:?} in network {network_path:?}"
);
}
// Symmetric: every node in the original must also exist in the rebuilt interface.
for (network_path, local_id) in node_paths(original) {
assert!(
rebuilt.nested_network(&network_path).and_then(|n| n.nodes.get(&local_id)).is_some(),
"original node {local_id:?} in network {network_path:?} missing after rebuild"
);
}
// Per-network metadata: every nested network path (including the root) must resolve to the same
// `reference` in the rebuilt interface. Node-graph nav + previewing are per-peer view state that
// lives in `session.json`, not the registry, so they're not round-tripped here.
let mut network_paths_to_check: Vec<Vec<NodeId>> = vec![Vec::new()];
for (network_path, local_id) in node_paths(original) {
let mut child = network_path.clone();
child.push(local_id);
if original.nested_network(&child).is_some() {
network_paths_to_check.push(child);
}
}
let mut checked_any_reference = false;
for path in &network_paths_to_check {
assert_eq!(rebuilt_view.reference(path), original_view.reference(path), "reference mismatch for network {path:?}");
if original_view.reference(path).is_some() {
checked_any_reference = true;
}
}
assert!(checked_any_reference, "demo artwork produced no reference metadata: fixture is wrong or extraction is broken");
}
/// Per-peer view settings (`ui::doc::*`) survive the `session.json` round-trip: serialize them into
/// the view map, then apply it onto a fresh handler and confirm each field matches.
#[test]
fn document_settings_round_trip() {
let mut document = load_demo("changing-seasons.graphite");
// Set distinctive, non-default values so the round-trip proves real data moved, not defaults.
document.render_mode = RenderMode::Outline;
document.rulers_visible = false;
document.collapsed = CollapsedLayers(vec![vec![NodeId(7)], vec![NodeId(7), NodeId(42)]]);
let view_settings = DocumentSettings {
document_ptz: &document.document_ptz,
render_mode: &document.render_mode,
overlays_visibility: &document.overlays_visibility_settings,
rulers_visible: document.rulers_visible,
snapping_state: &document.snapping_state,
collapsed: &document.collapsed,
}
.to_view_map();
// Apply the serialized view settings onto a fresh handler and compare each field's serialized
// form (avoids requiring `PartialEq` on every setting type).
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!(
serde_json::to_value(restored.rulers_visible).unwrap(),
serde_json::to_value(document.rulers_visible).unwrap(),
"rulers_visible"
);
assert_eq!(
serde_json::to_value(restored.document_ptz).unwrap(),
serde_json::to_value(document.document_ptz).unwrap(),
"document_ptz"
);
assert_eq!(
serde_json::to_value(restored.overlays_visibility_settings).unwrap(),
serde_json::to_value(document.overlays_visibility_settings).unwrap(),
"overlays"
);
assert_eq!(
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");
}
@@ -0,0 +1,9 @@
//! Integration tests for the `.gdd` document-storage layer, split by altitude:
//! - [`metadata_tests`] drives a demo document through the conversion bridge in-process (no save/reopen).
//! - [`round_trip_tests`] drives real editor edits through a full `Gdd` save/reopen pipeline.
//!
//! Shared fixtures live in [`test_support`].
mod metadata_tests;
mod round_trip_tests;
mod test_support;
@@ -0,0 +1,710 @@
//! 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
//! `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 graph_craft::application_io::resource::HashMapResourceStorage;
use graph_storage::{NodeMetadataSource, PeerId};
use super::test_support::{RoundTrip, node_paths, round_trip_through_gdd};
use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler;
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::{StorageMetadataView, build_interface_from_storage};
use crate::test_utils::test_prelude::*;
use graphene_std::vector::style::RenderMode;
/// Every node addressable in `original` resolves identically through the round-tripped interface:
/// the compute graph itself, then per-node positions, layer flags, names, locked/pinned.
fn assert_documents_match(original: &NodeNetworkInterface, round_trip: &RoundTrip) {
let original_view = StorageMetadataView::new(original);
let rebuilt_view = StorageMetadataView::new(&round_trip.rebuilt);
assert_eq!(
round_trip.rebuilt.document_network(),
original.document_network(),
"compute graph drifted through the storage round-trip"
);
for (network_path, local_id) in node_paths(original) {
let at = format!("node {local_id:?} in network {network_path:?}");
assert_eq!(rebuilt_view.position(&network_path, local_id), original_view.position(&network_path, local_id), "position: {at}");
assert_eq!(rebuilt_view.is_layer(&network_path, local_id), original_view.is_layer(&network_path, local_id), "is_layer: {at}");
assert_eq!(
rebuilt_view.display_name(&network_path, local_id),
original_view.display_name(&network_path, local_id),
"display_name: {at}"
);
assert_eq!(rebuilt_view.locked(&network_path, local_id), original_view.locked(&network_path, local_id), "locked: {at}");
assert_eq!(rebuilt_view.pinned(&network_path, local_id), original_view.pinned(&network_path, local_id), "pinned: {at}");
}
}
#[tokio::test]
async fn round_trip_drawn_shapes() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(100., 200., 300., 400.).await;
editor.draw_ellipse(120., 220., 280., 380.).await;
editor.draw_polygon(50., 60., 250., 360.).await;
let document = editor.active_document();
let round_trip = round_trip_through_gdd(document).await;
assert_documents_match(&document.network_interface, &round_trip);
}
#[tokio::test]
async fn round_trip_after_reorder() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
editor.draw_rect(50., 50., 150., 150.).await;
editor.draw_rect(100., 100., 200., 200.).await;
// Reorder: raise the bottom layer so the layer stack differs from creation order.
let bottom = editor.active_document().metadata().all_layers().next_back().expect("at least one layer");
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![bottom.to_node()] }).await;
editor.handle_message(DocumentMessage::SelectedLayersRaise).await;
let document = editor.active_document();
let round_trip = round_trip_through_gdd(document).await;
assert_documents_match(&document.network_interface, &round_trip);
}
#[tokio::test]
async fn round_trip_grouped_into_nested_network() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
editor.draw_ellipse(50., 50., 150., 150.).await;
// Group both layers into a folder (a nested network), exercising flat-Registry addressing across
// depth and `NetworkId` round-tripping.
let layers: Vec<_> = editor.active_document().metadata().all_layers().map(|layer| layer.to_node()).collect();
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: layers }).await;
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: GroupFolderType::Layer,
})
.await;
let document = editor.active_document();
let round_trip = round_trip_through_gdd(document).await;
assert_documents_match(&document.network_interface, &round_trip);
}
/// Reproduces the first-commit-after-open failure: after reopening a `.gdd` and rebuilding the
/// runtime, re-converting that runtime with `from_runtime` must reproduce the reopened registry.
/// This is exactly what `verify_storage_round_trip` does on the first autosave after opening a `.gdd`.
/// Uses a grouped document (nested network) because the bug is `from_runtime` assigning `NetworkId`s
/// by traversal order rather than reproducing the stored ones, which cascades into node-path hashes.
#[tokio::test]
async fn recommit_after_open_is_stable() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
editor.draw_ellipse(50., 50., 150., 150.).await;
let layers: Vec<_> = editor.active_document().metadata().all_layers().map(|layer| layer.to_node()).collect();
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: layers }).await;
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: GroupFolderType::Layer,
})
.await;
let document = editor.active_document();
let round_trip = round_trip_through_gdd(document).await;
// Re-convert the rebuilt runtime and assert it reproduces the reopened registry. `round_trip_through_gdd`
// builds the `Gdd` with `PeerId(1)`, which the reopened registry inherits, so the re-conversion must use
// that same peer for deterministic node-ID derivation.
let rebuilt_network = round_trip.rebuilt.document_network().clone();
let view = StorageMetadataView::new(&round_trip.rebuilt);
let reconverted = graph_storage::Registry::convert_from_runtime(&rebuilt_network, &view, &Default::default(), PeerId(1)).expect("re-convert from_runtime");
assert!(
round_trip.registry.value_equal(&reconverted.registry),
"re-converting the reopened runtime drifted from the reopened registry (network/node IDs not stable across to_runtime -> from_runtime)\n{}",
crate::messages::portfolio::document::document_diff::diff_registries(&round_trip.registry, &reconverted.registry)
);
}
/// Reproduces the live "edit after opening a .gdd fails to commit" bug: build a grouped document,
/// persist + reopen it as the editor does (registry -> runtime), then edit and commit through the
/// reopened document. The commit must not fail with "Target node does not exist".
#[tokio::test]
async fn edit_after_open_commits_cleanly() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
editor.draw_ellipse(50., 50., 150., 150.).await;
let layers: Vec<_> = editor.active_document().metadata().all_layers().map(|layer| layer.to_node()).collect();
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: layers }).await;
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: GroupFolderType::Layer,
})
.await;
// Persist the document into a fresh Gdd and reopen it, then build a runtime document from the
// reopened registry: the editor's .gdd-open path.
let byte_store = HashMapResourceStorage::new();
let 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 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)
.expect("commit_from_runtime");
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.expect("open_in");
let declarations = reopened.declarations(&byte_store).await;
let (rebuilt_network, node_entries, network_entries) = reopened.registry().to_runtime_with_full_metadata(&declarations).expect("to_runtime");
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage");
// Install the rebuilt interface + reopened storage and finalize like the editor's open path does.
{
let document = editor.active_document_mut();
document.network_interface = rebuilt;
document.set_storage(Some(reopened));
document.finalize_storage_load();
}
// Mirror the live sequence via the real `commit_storage_snapshot`: initial commit after open, then a
// deletion, then commit again. Deletion (not addition) is the trigger, since it emits a `RemoveNode`
// whose retire/reverse is where "Target node does not exist" surfaced live.
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let layer = editor.active_document().metadata().all_layers().next().expect("at least one layer");
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
editor.handle_message(DocumentMessage::DeleteSelectedLayers).await;
// `commit_storage_snapshot` only logs commit failures, so assert on the underlying `commit_from_runtime`
// result directly to make the deletion commit a hard test failure rather than a silent log line.
let document = editor.active_document_mut();
// Clone the interface for the metadata view so it doesn't borrow `document` across the mutable
// `storage_mut()` borrow below.
let interface = document.network_interface.clone();
let network = interface.document_network().clone();
let view = StorageMetadataView::new(&interface);
document
.storage_mut()
.expect("storage mounted")
.commit_from_runtime(&network, &view, &Default::default(), &byte_store)
.expect("commit after deleting a layer post-open must not fail");
}
/// Drives the per-interaction undo/redo cursor: commit two interactions into a `Gdd`, then undo back to the
/// one-interaction state and redo forward, asserting the registry's node set matches at each cursor
/// position. Exercises `Gdd::commit_from_runtime` (inline interaction-end mark) + `Session::undo/redo`.
#[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");
// Commit the active document's current runtime state as one interaction.
async fn commit_interaction(gdd: &mut GddV1, document: &DocumentMessageHandler, byte_store: &HashMapResourceStorage) {
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
gdd.commit_from_runtime(&network, &view, &document.resources.registry, byte_store).expect("commit_from_runtime");
}
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
commit_interaction(&mut gdd, editor.active_document(), &byte_store).await;
let nodes_after_one: std::collections::BTreeSet<_> = gdd.registry().node_instances.keys().copied().collect();
editor.draw_ellipse(50., 50., 150., 150.).await;
commit_interaction(&mut gdd, editor.active_document(), &byte_store).await;
let nodes_after_two: std::collections::BTreeSet<_> = gdd.registry().node_instances.keys().copied().collect();
assert!(nodes_after_two.len() > nodes_after_one.len(), "second interaction should add nodes");
assert!(gdd.can_undo(), "two committed interactions should be undoable");
assert!(!gdd.can_redo());
// Undo the second interaction: registry returns to the one-interaction node set.
gdd.undo().expect("undo");
let undone: std::collections::BTreeSet<_> = gdd.registry().node_instances.keys().copied().collect();
assert_eq!(undone, nodes_after_one, "undo should restore the post-first-interaction node set");
assert!(gdd.can_redo(), "after undo, redo must be available");
// Redo: back to the two-interaction state.
gdd.redo().expect("redo");
let redone: std::collections::BTreeSet<_> = gdd.registry().node_instances.keys().copied().collect();
assert_eq!(redone, nodes_after_two, "redo should restore the post-second-interaction node set");
// A new edit after undo clears the redo stack.
gdd.undo().expect("undo");
editor.draw_rect(200., 200., 300., 300.).await;
commit_interaction(&mut gdd, editor.active_document(), &byte_store).await;
assert!(!gdd.can_redo(), "a new edit after undo must abandon the redo branch");
}
/// Reopen must restore the cursor *and* a working registry consistent with it. `Session::load` trusts
/// the persisted `registry.bin` to match the persisted `head`, so an undo that rewinds the working
/// registry has to re-snapshot it. Repro of the live "undo acts like redo after reload" bug: commit
/// three interactions, undo one (registry at two), reopen, and assert the reopened registry is the
/// two-interaction state (not the three-interaction state the last retirement wrote) and that undo from there
/// still walks back to the one-interaction node set.
#[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");
async fn commit_interaction(gdd: &mut GddV1, document: &DocumentMessageHandler, byte_store: &HashMapResourceStorage) {
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
gdd.commit_from_runtime(&network, &view, &document.resources.registry, byte_store).expect("commit_from_runtime");
}
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
commit_interaction(&mut gdd, editor.active_document(), &byte_store).await;
let nodes_one: std::collections::BTreeSet<_> = gdd.registry().node_instances.keys().copied().collect();
editor.draw_ellipse(50., 50., 150., 150.).await;
commit_interaction(&mut gdd, editor.active_document(), &byte_store).await;
let nodes_two: std::collections::BTreeSet<_> = gdd.registry().node_instances.keys().copied().collect();
editor.draw_rect(200., 200., 300., 300.).await;
commit_interaction(&mut gdd, editor.active_document(), &byte_store).await;
let nodes_three: std::collections::BTreeSet<_> = gdd.registry().node_instances.keys().copied().collect();
// Undo the third interaction: the in-memory registry is back at the two-interaction state, but the last
// retirement wrote the three-interaction registry to disk. The undo must re-snapshot it.
gdd.undo().expect("undo");
assert_eq!(gdd.registry().node_instances.keys().copied().collect::<std::collections::BTreeSet<_>>(), nodes_two);
// Reopen from the same container: the cursor and the working registry are read back from disk.
let (working, layout) = gdd.into_storage();
let mut reopened = GddV1::open_in(working, layout).await.expect("open_in");
assert_eq!(
reopened.registry().node_instances.keys().copied().collect::<std::collections::BTreeSet<_>>(),
nodes_two,
"reopened registry must match the undone (two-interaction) state, not the three-interaction state on disk"
);
assert!(reopened.can_undo(), "head is still above the first interaction, so undo is available after reopen");
assert!(reopened.can_redo(), "the undone third interaction is still redoable after reopen");
// Redo after reopen: the persisted redo stack must still reach the three-interaction state (redo across
// reopen must not be capped at the open point).
reopened.redo().expect("redo after reopen");
assert_eq!(
reopened.registry().node_instances.keys().copied().collect::<std::collections::BTreeSet<_>>(),
nodes_three,
"redo after reopen must restore the third interaction, not stop at the reopened (two-interaction) state"
);
// Undo twice from there: back through the third interaction to the one-interaction state, not a redo.
reopened.undo().expect("first undo after reopen redo");
reopened.undo().expect("second undo after reopen redo");
assert_eq!(
reopened.registry().node_instances.keys().copied().collect::<std::collections::BTreeSet<_>>(),
nodes_one,
"undo after reopen must rewind toward the one-interaction state, not act like a redo"
);
}
/// Drives the *live* shadow path: a real edit through the message pipeline (which fires
/// `CommitTransaction`, committing one interaction into the `Gdd`), then a real `DocumentMessage::Undo`
/// (which runs `shadow_storage_undo_redo` + the debug cursor-vs-runtime check). A clean run asserts
/// the `Gdd` undo cursor reproduces the legacy-restored interface.
#[tokio::test]
async fn live_undo_shadows_storage_cursor() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
let byte_store = mount_in_memory_storage(&mut editor).await;
// Capture the loaded state as the base interaction, then make a real edit (fires CommitTransaction).
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let before_edit = editor.active_document().network_interface.document_network().clone();
editor.draw_ellipse(50., 50., 150., 150.).await;
let after_edit = editor.active_document().network_interface.document_network().clone();
assert_ne!(&before_edit, &after_edit, "edit should change the network");
// Real undo: the shadow drives gdd.undo() and (debug) asserts the cursor matches the restored interface.
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(editor.active_document().network_interface.document_network(), &before_edit, "undo should restore the pre-edit network");
// Real redo: the shadow drives gdd.redo() and must reproduce the post-edit network.
editor.handle_message(DocumentMessage::Redo).await;
assert_eq!(editor.active_document().network_interface.document_network(), &after_edit, "redo should restore the post-edit network");
}
#[tokio::test]
async fn round_trip_document_settings() {
use graph_storage::attr::session::doc;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
// Set distinctive, non-default document-level settings so the round-trip proves real values move.
{
let document = editor.active_document_mut();
document.render_mode = RenderMode::Outline;
document.rulers_visible = false;
document.snapping_state.snapping_enabled = !document.snapping_state.snapping_enabled;
}
let document = editor.active_document();
let round_trip = round_trip_through_gdd(document).await;
assert_documents_match(&document.network_interface, &round_trip);
// 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");
}
/// The exported `.gdd` archive must carry `session.json` so view settings (notably the document PTZ)
/// survive a save/open on another machine. `session.json` is working-copy-only otherwise, so without it
/// the archive opens with empty `view_settings` and the viewport resets to default. Exports to an archive
/// and reopens via `open_from_archive`, asserting the PTZ round-trips.
#[tokio::test]
async fn gdd_archive_round_trips_view_settings() {
use 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");
// 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())]);
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.
let archive = gdd
.export_to_bytes(document_format::ExportFormat::Zip, document_format::ExportOptions::default(), &byte_store, None)
.await
.expect("export_to_bytes");
let reopened = GddV1::open_from_archive(&archive, AnyContainer::Memory(MemoryBackend::new()), GddV1Layout)
.await
.expect("open_from_archive");
assert_eq!(
reopened.view_settings().get(doc::PTZ),
Some(&serde_json::to_value(ptz).unwrap()),
"the document PTZ must survive a .gdd archive export/open (session.json travels in the archive)"
);
}
/// Per-network node-graph navigation is per-peer view state: it must round-trip through `session.json`
/// (keyed by stable `NetworkId`), not the registry/history. Sets a distinctive node-graph PTZ on the root
/// network, persists + reopens through a `Gdd`, and asserts the nav is restored on the rebuilt interface
/// while being absent from the stored registry's attributes.
#[tokio::test]
async fn per_network_navigation_round_trips_via_session_not_registry() {
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::{apply_network_view_settings, collect_network_view_settings, network_ids_from_entries};
use graph_storage::attr::session::network;
let byte_store = HashMapResourceStorage::new();
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
// Set a distinctive node-graph PTZ on the root network (path `[]`).
let ptz = editor.active_document_mut().network_interface.node_graph_ptz_mut(&[]).expect("root network ptz");
ptz.pan = glam::DVec2::new(-321., 654.);
ptz.set_zoom(0.75);
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 document = editor.active_document();
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
gdd.commit_from_runtime(&network, &view, &document.resources.registry, &byte_store).expect("commit_from_runtime");
let network_ids = gdd.network_ids(&network, &view).expect("network_ids");
let network_view_settings = collect_network_view_settings(&document.network_interface, &network_ids);
assert!(!network_view_settings.is_empty(), "the root network's non-default nav should be collected");
gdd.set_network_view_settings(network_view_settings).expect("set_network_view_settings");
// The registry must NOT carry the node-graph nav (it's per-peer, not document content).
let root_network = gdd.registry().networks.get(&graph_storage::ROOT_NETWORK).expect("root network in registry");
assert!(!root_network.attributes.contains_key(network::NAV_PTZ), "node-graph nav must not be stored in the registry attributes");
// Reopen, rebuild the interface, and apply the persisted per-network view state.
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.expect("open_in");
let declarations = reopened.declarations(&byte_store).await;
let (rebuilt_network, node_entries, network_entries) = reopened.registry().to_runtime_with_full_metadata(&declarations).expect("to_runtime");
let mut rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries.clone()).expect("build_interface_from_storage");
let reopened_ids = network_ids_from_entries(&network_entries);
apply_network_view_settings(&mut rebuilt, &reopened_ids, reopened.network_view_settings());
assert_eq!(
rebuilt.node_graph_ptz(&[]).map(|ptz| ptz.pan),
Some(expected_pan),
"the node-graph PTZ must be restored from session.json on reopen"
);
}
/// 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
/// (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;
// Mount-time snapshot: capture the new-document graph as the base interaction.
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let before_rect = editor.active_document().network_interface.document_network().clone();
editor.draw_rect(0., 0., 100., 100.).await;
assert_ne!(&before_rect, editor.active_document().network_interface.document_network(), "drawing a rect should change the network");
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(editor.active_document().network_interface.document_network(), &before_rect, "undo should restore the pre-rect network");
}
/// Pasting an image is one user action and must be one undo step: the paste handler brackets the layer add,
/// name set, reparent, and transform in a single transaction. Were the name set to open its own nested
/// transaction (a historical wart), the first undo would revert only the name and leave the layer behind, so
/// this asserts the layer count returns to its pre-paste value after exactly one undo.
#[tokio::test]
async fn paste_image_with_name_is_one_undo_step() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let layers_before = editor.active_document().metadata().all_layers().count();
// Paste with a name so the handler emits the `SetDisplayName` sub-step that historically opened its
// own transaction. `create_raster_image` passes `name: None` and so wouldn't exercise this path.
let image = Image::new(2, 2, Color::WHITE);
editor
.handle_message(PortfolioMessage::InsertImage {
name: Some("pasted".into()),
image,
mouse: None,
parent_and_insert_index: None,
})
.await;
assert_eq!(
editor.active_document().metadata().all_layers().count(),
layers_before + 1,
"pasting an image should add exactly one layer"
);
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(
editor.active_document().metadata().all_layers().count(),
layers_before,
"one undo should remove the whole pasted layer, not just its name"
);
}
/// Undoing an image paste reverts the interaction's `AddResource` in the `Gdd` cursor while the runtime keeps
/// the resource alive for legacy redo, so the cursor legitimately holds fewer resources than a fresh
/// `from_runtime`. Drives the relaxed comparison: every resource the current network references must be in
/// the cursor, and any extra the runtime carries must be history-only.
#[tokio::test]
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;
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let image = Image::new(2, 2, Color::WHITE);
editor
.handle_message(PortfolioMessage::InsertImage {
name: Some("pasted".into()),
image,
mouse: None,
parent_and_insert_index: None,
})
.await;
editor.handle_message(DocumentMessage::Undo).await;
let document = editor.active_document();
let storage = document.storage().expect("storage mounted");
let stored: std::collections::BTreeSet<_> = storage.registry().resources.keys().copied().collect();
// Every resource the restored network still references must be in the cursor.
let current: std::collections::BTreeSet<_> = document.used_resources(false).iter().copied().collect();
assert!(
current.is_subset(&stored),
"cursor is missing a resource the restored network references: current={current:?} stored={stored:?}"
);
// The runtime, which retains the undone paste's resource for redo, may carry strictly more.
let runtime: std::collections::BTreeSet<_> = document.resources.registry.ids().collect();
assert!(stored.is_subset(&runtime), "cursor holds a resource the runtime dropped: stored={stored:?} runtime={runtime:?}");
}
/// Two edits (draw, then paste) on an opened document are two undo steps; undoing twice must step the `Gdd`
/// cursor back two interactions in lockstep with the legacy path. The loaded base is not itself an undo
/// step, so the mount-time base must not become an undoable `Gdd` interaction, or the cursor lags the legacy
/// path by one once undo reaches the base. Reproduces the live "open, draw, paste image, undo twice" divergence.
#[tokio::test]
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;
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let base = editor.active_document().network_interface.document_network().clone();
editor.draw_rect(0., 0., 100., 100.).await;
let after_rect = editor.active_document().network_interface.document_network().clone();
let image = Image::new(2, 2, Color::WHITE);
editor
.handle_message(PortfolioMessage::InsertImage {
name: Some("pasted".into()),
image,
mouse: None,
parent_and_insert_index: None,
})
.await;
// First undo: removes the paste, back to the post-rectangle network. Cursor and legacy must agree.
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(
editor.active_document().network_interface.document_network(),
&after_rect,
"first undo should restore the post-rectangle network (paste removed)"
);
assert_cursor_matches_runtime(editor.active_document(), "after first undo");
// Re-stage after the undo (the live editor re-evaluates the graph). The pasted image's resource is still
// cached for redo though its node is gone, so a naive snapshot would re-detect it as a new `AddResource`
// and retire a phantom interaction, knocking the cursor out of lockstep. Scoping the snapshot to
// network-referenced resources must keep this a no-op.
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
// Second undo: removes the rectangle, back to the loaded base. The cursor must step a second interaction
// and land on the base, not one short.
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(
editor.active_document().network_interface.document_network(),
&base,
"second undo should restore the loaded base network"
);
assert_cursor_matches_runtime(editor.active_document(), "after second undo");
// Back at the loaded base, neither path can undo further: the load is not an undo step. Had the `Gdd`
// retired the mount base as its own interaction, the cursor could still undo here, the off-by-one.
let storage = editor.active_document().storage().expect("storage mounted");
assert!(!storage.can_undo(), "cursor must not undo past the loaded base (the load is not an undo step)");
}
/// Assert the `Gdd` cursor's stored registry matches a fresh `from_runtime` of the current interface (node
/// set, network set, per-network export wiring), mirroring the live `verify_cursor_matches_runtime` check.
/// The runtime's resource set may be a superset (it keeps undone resources alive for redo), but every
/// resource the current network references must be present.
fn assert_cursor_matches_runtime(document: &DocumentMessageHandler, at: &str) {
let storage = document.storage().expect("storage mounted");
let peer = storage.session().peer();
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
let target = graph_storage::Registry::convert_from_runtime(&network, &view, &document.resources.registry, peer).expect("from_runtime");
let stored = storage.registry();
let stored_nodes: std::collections::BTreeSet<_> = stored.node_instances.keys().copied().collect();
let target_nodes: std::collections::BTreeSet<_> = target.registry.node_instances.keys().copied().collect();
assert_eq!(stored_nodes, target_nodes, "cursor node set diverged from the restored interface {at}");
let stored_networks: std::collections::BTreeSet<_> = stored.networks.keys().copied().collect();
let target_networks: std::collections::BTreeSet<_> = target.registry.networks.keys().copied().collect();
assert_eq!(stored_networks, target_networks, "cursor network set diverged from the restored interface {at}");
// Compare export wiring per network: the paste rewires the document export, and undo must revert it.
for (id, stored_network) in &stored.networks {
let target_network = target.registry.networks.get(id).expect("network present in both (checked above)");
let stored_targets: Vec<_> = stored_network.exports.iter().map(|export| export.target.clone()).collect();
let target_targets: Vec<_> = target_network.exports.iter().map(|export| export.target.clone()).collect();
assert_eq!(stored_targets, target_targets, "cursor export wiring diverged for network {id} {at}");
}
}
/// 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));
HashMapResourceStorage::new()
}
/// Open a real demo artwork, mount storage, edit it, and trigger autosave. The autosave runs
/// `verify_storage_round_trip`, which panics in tests on any conversion or round-trip drift, so a clean run
/// is itself the assertion that the whole pipeline holds on real document data. Also checks that committing
/// edits grows the retired-delta history and that undo reverts the modification.
#[tokio::test]
async fn demo_artwork_edit_autosaves_and_round_trips() {
let mut editor = EditorTestUtils::create();
// Open a real demo artwork through the normal open path and let it render.
let content = std::fs::read_to_string("../demo-artwork/changing-seasons.graphite").expect("read demo artwork");
editor
.handle_message(PortfolioMessage::OpenFile {
path: "changing-seasons.graphite".into(),
content: content.bytes().collect(),
})
.await;
let byte_store = mount_in_memory_storage(&mut editor).await;
// First autosave: captures the loaded document. `verify_storage_round_trip` panics on drift.
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let history_after_open = editor.active_document().storage().unwrap().session().history().count();
// Snapshot the network, then make a real modification.
let before_edit = editor.active_document().network_interface.document_network().clone();
editor.draw_rect(64., 64., 192., 192.).await;
let after_edit = editor.active_document().network_interface.document_network().clone();
assert_ne!(before_edit, after_edit, "drawing a rectangle should change the document network");
// Second autosave: again verifies the round-trip, and the edit must produce new retired history.
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let history_after_edit = editor.active_document().storage().unwrap().session().history().count();
assert!(
history_after_edit > history_after_open,
"committing an edit should append retired deltas: {history_after_open} -> {history_after_edit}"
);
// The editor's undo stack reverts the modification on a real document.
editor.handle_message(DocumentMessage::Undo).await;
let after_undo = editor.active_document().network_interface.document_network().clone();
assert_eq!(after_undo, before_edit, "undo should restore the pre-edit network");
// Autosaving the undone state still round-trips cleanly (no drift panic).
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
}
@@ -0,0 +1,88 @@
//! Shared helpers for the storage integration tests ([`metadata_tests`](super::metadata_tests) and
//! [`round_trip_tests`](super::round_trip_tests)): loading demo artwork, walking every addressable
//! node, and pushing a document through a real `Gdd` save/reopen.
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::document::{DocumentNodeImplementation, NodeId};
use graph_storage::PeerId;
use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::{DocumentSettings, StorageMetadataView, build_interface_from_storage};
/// Load a demo `.graphite` straight into a `DocumentMessageHandler` for inspection.
pub fn load_demo(file_name: &str) -> DocumentMessageHandler {
let path = format!("../demo-artwork/{file_name}");
let content = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("Failed to read {path}: {e}"));
DocumentMessageHandler::deserialize_document(&content).unwrap_or_else(|e| panic!("Failed to deserialize {path}: {e:?}"))
}
/// Walk every node in every nested network and collect `(network_path, local_id)` pairs, so a test can
/// iterate every node addressable from the metadata side.
pub fn node_paths(interface: &NodeNetworkInterface) -> Vec<(Vec<NodeId>, NodeId)> {
fn walk(interface: &NodeNetworkInterface, path: Vec<NodeId>, out: &mut Vec<(Vec<NodeId>, NodeId)>) {
let Some(network) = interface.nested_network(&path) else { return };
for (&local_id, node) in &network.nodes {
out.push((path.clone(), local_id));
if matches!(node.implementation, DocumentNodeImplementation::Network(_)) {
let mut child = path.clone();
child.push(local_id);
walk(interface, child, out);
}
}
}
let mut out = Vec::new();
walk(interface, Vec::new(), &mut out);
out
}
/// Result of round-tripping a document through a `Gdd`: the runtime interface rebuilt from the reopened
/// storage, the reopened registry, and the reopened per-peer view settings (`ui::doc::*`).
pub struct RoundTrip {
pub rebuilt: NodeNetworkInterface,
pub registry: graph_storage::Registry,
pub view_settings: std::collections::BTreeMap<String, serde_json::Value>,
}
/// Push `document`'s current runtime state through a fresh in-memory `Gdd` and reopen it. The commit goes
/// through `commit_from_runtime` (the real autosave path: stage hot ops -> retire -> persist); the reopen
/// reads the working copy back from the same container bytes, exercising the whole codec / file / replay
/// pipeline rather than just the in-memory conversion.
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 network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
gdd.commit_from_runtime(&network, &view, &document.resources.registry, &byte_store).expect("commit_from_runtime");
// Per-peer view settings persist in session.json, separate from the registry commit.
let view_settings = DocumentSettings {
document_ptz: &document.document_ptz,
render_mode: &document.render_mode,
overlays_visibility: &document.overlays_visibility_settings,
rulers_visible: document.rulers_visible,
snapping_state: &document.snapping_state,
collapsed: &document.collapsed,
}
.to_view_map();
gdd.set_view_settings(view_settings).expect("set_view_settings");
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.expect("open_in");
let declarations = reopened.declarations(&byte_store).await;
let registry = reopened.registry().clone();
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime_with_full_metadata");
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage");
let view_settings = reopened.view_settings().clone();
RoundTrip { rebuilt, registry, view_settings }
}
@@ -1,6 +1,7 @@
mod deserialization;
mod memo_network;
mod resolved_types;
pub mod storage_metadata;
use super::document_metadata::{DocumentMetadata, LayerNodeIdentifier, NodeRelations};
use super::misc::PTZ;
@@ -3452,22 +3453,67 @@ impl NodeNetworkInterface {
// Public mutable methods
impl NodeNetworkInterface {
pub fn copy_all_navigation_metadata(&mut self, other_interface: &NodeNetworkInterface) {
/// Walk every network at every nesting level, invoking `visit` with each network's path and a mutable
/// reference to its metadata. Only nodes that contain a nested network are recursed into.
fn for_each_network_metadata_mut(&mut self, mut visit: impl FnMut(&[NodeId], &mut NodeNetworkMetadata)) {
let mut stack = vec![vec![]];
while let Some(path) = stack.pop() {
let Some(self_network_metadata) = self.network_metadata_mut(&path) else {
continue;
};
if let Some(other_network_metadata) = other_interface.network_metadata(&path) {
visit(&path, self_network_metadata);
// Only nodes that contain a nested network have metadata to recurse into, so skip leaf nodes.
stack.extend(
self_network_metadata
.persistent_metadata
.node_metadata
.iter()
.filter(|(_, node_metadata)| node_metadata.persistent_metadata.network_metadata.is_some())
.map(|(node_id, _)| {
let mut current_path: Vec<NodeId> = path.clone();
current_path.push(*node_id);
current_path
}),
);
}
}
pub fn copy_all_navigation_metadata(&mut self, other_interface: &NodeNetworkInterface) {
self.for_each_network_metadata_mut(|path, self_network_metadata| {
if let Some(other_network_metadata) = other_interface.network_metadata(path) {
self_network_metadata.persistent_metadata.navigation_metadata = other_network_metadata.persistent_metadata.navigation_metadata.clone();
}
});
}
stack.extend(self_network_metadata.persistent_metadata.node_metadata.keys().map(|node_id| {
let mut current_path: Vec<NodeId> = path.clone();
current_path.push(*node_id);
current_path
}));
}
/// Copy all transient view and selection state from `other_interface` onto `self` at every nesting level:
/// navigation metadata (pan/zoom), selection undo/redo history, and the document-to-viewport camera. Lets
/// an interface rebuilt from storage keep the user's current view rather than reset it. `resolved_types`
/// is a separate runtime cache the caller handles.
pub fn copy_all_transient_view_state(&mut self, other_interface: &NodeNetworkInterface) {
self.for_each_network_metadata_mut(|path, self_network_metadata| {
if let Some(other_network_metadata) = other_interface.network_metadata(path) {
let self_persistent = &mut self_network_metadata.persistent_metadata;
let other_persistent = &other_network_metadata.persistent_metadata;
self_persistent.navigation_metadata = other_persistent.navigation_metadata.clone();
// The live preview root may name a node that the rebuilt-from-storage network no longer contains
// (e.g. after a storage undo), so only carry it over when the root still exists; otherwise drop it.
self_persistent.previewing = match other_persistent.previewing {
Previewing::Yes {
root_node_to_restore: Some(root_node),
} if !self_persistent.node_metadata.contains_key(&root_node.node_id) => Previewing::No,
previewing => previewing,
};
self_persistent.selection_undo_history = other_persistent.selection_undo_history.clone();
self_persistent.selection_redo_history = other_persistent.selection_redo_history.clone();
}
});
self.document_metadata.document_to_viewport = other_interface.document_metadata.document_to_viewport;
}
pub fn set_transform(&mut self, transform: DAffine2, network_path: &[NodeId]) {
@@ -6858,6 +6904,9 @@ impl NodePersistentMetadata {
pub fn new(position: NodePosition) -> Self {
Self { position }
}
pub fn position(&self) -> &NodePosition {
&self.position
}
}
/// A layer can either be position as Absolute or in a Stack
@@ -61,7 +61,7 @@ impl TypeSource {
FrontendGraphDataType::Number
}
TaggedValue::Color(_) => FrontendGraphDataType::Color,
TaggedValue::FillGradient(_) | TaggedValue::Gradient(_) => FrontendGraphDataType::Gradient,
TaggedValue::LegacyGradient(_) | TaggedValue::Gradient(_) => FrontendGraphDataType::Gradient,
TaggedValue::String(_) => FrontendGraphDataType::Typography,
// Types whose `TaggedValue` variant has been removed are routed through `TypeDefault` and identified by the descriptor's type name.
TaggedValue::TypeDefault(td) => match td.name.as_ref() {
@@ -0,0 +1,392 @@
//! Bridge between `NodeNetworkInterface` and `graph-storage`'s `NodeMetadataSource` trait.
//! Conversion round-trip tests live in `storage_metadata_tests`.
//!
//! The trait impl lives on the [`StorageMetadataView`] wrapper (not on `NodeNetworkInterface`
//! directly) because several trait method names collide with inherent methods, and Rust silently
//! resolves bare calls to the inherent ones.
use std::collections::{BTreeMap, HashMap};
use glam::IVec2;
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeNetwork};
use graph_storage::attr::session;
use graph_storage::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry, NodeMetadataSource, Position};
use graphene_std::vector::style::RenderMode;
use super::memo_network::MemoNetwork;
use super::{
DocumentNodePersistentMetadata, DocumentNodeTransientMetadata, InputMetadata, InputPersistentMetadata, LayerPosition, NavigationMetadata, NodeNetworkInterface, NodeNetworkMetadata,
NodePersistentMetadata, NodePosition, NodeTypePersistentMetadata, PTZ, Previewing,
};
use crate::messages::portfolio::document::overlays::utility_types::OverlaysVisibilitySettings;
use crate::messages::portfolio::document::utility_types::misc::SnappingState;
use crate::messages::portfolio::document::utility_types::nodes::CollapsedLayers;
/// Fired when the storage entry list disagrees with the converted `NodeNetwork`.
#[derive(Debug, thiserror::Error)]
pub enum InterfaceRebuildError {
#[error("input_metadata length {got} does not match inputs length {expected} for node {node:?} in network {network_path:?}")]
InputMetadataLengthMismatch { node: NodeId, network_path: Vec<NodeId>, expected: usize, got: usize },
}
/// Per-peer view settings persisted in `session.json` under `ui::doc::*` (viewport view, render mode,
/// overlay/ruler visibility, snapping, collapsed layers). Not part of the registry/CRDT/history; see
/// [`DocumentSettings::to_view_map`].
pub struct DocumentSettings<'a> {
pub document_ptz: &'a PTZ,
pub render_mode: &'a RenderMode,
pub overlays_visibility: &'a OverlaysVisibilitySettings,
pub rulers_visible: bool,
pub snapping_state: &'a SnappingState,
pub collapsed: &'a CollapsedLayers,
}
/// Adapts a `&NodeNetworkInterface` to `graph-storage`'s `NodeMetadataSource` (node/network metadata
/// only; document-level view settings live in `session.json`, not the registry).
pub struct StorageMetadataView<'a> {
interface: &'a NodeNetworkInterface,
}
impl<'a> StorageMetadataView<'a> {
pub fn new(interface: &'a NodeNetworkInterface) -> Self {
Self { interface }
}
}
impl StorageMetadataView<'_> {
fn persistent(&self, network_path: &[NodeId], local_id: NodeId) -> Option<&DocumentNodePersistentMetadata> {
Some(&self.interface.node_metadata(&local_id, network_path)?.persistent_metadata)
}
fn input_persistent(&self, network_path: &[NodeId], local_id: NodeId, input_index: usize) -> Option<&InputPersistentMetadata> {
Some(&self.persistent(network_path, local_id)?.input_metadata.get(input_index)?.persistent_metadata)
}
}
impl NodeMetadataSource for StorageMetadataView<'_> {
fn position(&self, network_path: &[NodeId], local_id: NodeId) -> Option<Position> {
match &self.persistent(network_path, local_id)?.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer) => match layer.position {
LayerPosition::Absolute(v) => Some(Position::Absolute([v.x, v.y])),
LayerPosition::Stack(offset) => Some(Position::Stack(offset)),
},
NodeTypePersistentMetadata::Node(node) => match *node.position() {
NodePosition::Absolute(v) => Some(Position::Absolute([v.x, v.y])),
NodePosition::Chain => Some(Position::Chain),
},
}
}
fn is_layer(&self, network_path: &[NodeId], local_id: NodeId) -> bool {
self.persistent(network_path, local_id)
.is_some_and(|p| matches!(p.node_type_metadata, NodeTypePersistentMetadata::Layer(_)))
}
fn display_name(&self, network_path: &[NodeId], local_id: NodeId) -> Option<&str> {
Some(self.persistent(network_path, local_id)?.display_name.as_str())
}
fn locked(&self, network_path: &[NodeId], local_id: NodeId) -> bool {
self.persistent(network_path, local_id).is_some_and(|p| p.locked)
}
fn pinned(&self, network_path: &[NodeId], local_id: NodeId) -> bool {
self.persistent(network_path, local_id).is_some_and(|p| p.pinned)
}
fn input_name(&self, network_path: &[NodeId], local_id: NodeId, input_index: usize) -> Option<&str> {
Some(self.input_persistent(network_path, local_id, input_index)?.input_name.as_str())
}
fn input_description(&self, network_path: &[NodeId], local_id: NodeId, input_index: usize) -> Option<&str> {
Some(self.input_persistent(network_path, local_id, input_index)?.input_description.as_str())
}
fn widget_override(&self, network_path: &[NodeId], local_id: NodeId, input_index: usize) -> Option<&str> {
self.input_persistent(network_path, local_id, 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.input_persistent(network_path, local_id, input_index).map(|p| p.input_data.clone()).unwrap_or_default()
}
fn output_names(&self, network_path: &[NodeId], local_id: NodeId) -> Vec<String> {
self.persistent(network_path, local_id).map(|p| p.output_names.clone()).unwrap_or_default()
}
fn reference(&self, network_path: &[NodeId]) -> Option<&str> {
let network_metadata = self.interface.network_metadata.nested_metadata(network_path)?;
network_metadata.persistent_metadata.reference.as_deref()
}
}
impl DocumentSettings<'_> {
/// Serialize the per-peer view settings into the `ui::doc::*`-keyed map persisted in `session.json`
/// (via `Gdd::set_view_settings`). A field that fails to serialize is skipped, not fatal.
pub fn to_view_map(&self) -> BTreeMap<String, serde_json::Value> {
let entries = [
(session::doc::PTZ, serde_json::to_value(self.document_ptz)),
(session::doc::RENDER_MODE, serde_json::to_value(self.render_mode)),
(session::doc::OVERLAYS, serde_json::to_value(self.overlays_visibility)),
(session::doc::RULERS_VISIBLE, serde_json::to_value(self.rulers_visible)),
(session::doc::SNAPPING, serde_json::to_value(self.snapping_state)),
(session::doc::COLLAPSED, serde_json::to_value(self.collapsed)),
];
entries
.into_iter()
.filter_map(|(key, value)| match value {
Ok(value) => Some((key.to_string(), value)),
Err(error) => {
log::error!("Failed to serialize document setting {key}: {error}");
None
}
})
.collect()
}
}
/// Inverse of the position extraction in `NodeMetadataSource::position`.
/// `(Stack, !is_layer)` and `(Chain, is_layer)` shouldn't arise from a faithful round-trip; they fall back to a default of the matching variant.
pub fn position_to_runtime(position: Position, is_layer: bool) -> NodeTypePersistentMetadata {
match (position, is_layer) {
(Position::Absolute([x, y]), true) => NodeTypePersistentMetadata::layer(IVec2::new(x, y)),
(Position::Absolute([x, y]), false) => NodeTypePersistentMetadata::node(IVec2::new(x, y)),
(Position::Stack(offset), _) => {
let mut metadata = NodeTypePersistentMetadata::layer(IVec2::ZERO);
if let NodeTypePersistentMetadata::Layer(layer) = &mut metadata {
layer.position = LayerPosition::Stack(offset);
}
metadata
}
(Position::Chain, _) => NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Chain)),
}
}
/// Builds a `NodeNetworkInterface` from a `NodeNetwork` plus the metadata vecs `Registry::to_runtime_with_full_metadata` emits.
///
/// Sets private fields directly (rather than via public setters) because we're constructing a fresh self-consistent snapshot;
/// the setters' transient-cache invalidation isn't needed.
pub fn build_interface_from_storage(network: NodeNetwork, node_entries: Vec<NodeMetadataEntry>, network_entries: Vec<NetworkMetadataEntry>) -> Result<NodeNetworkInterface, InterfaceRebuildError> {
let mut network_metadata = NodeNetworkMetadata::default();
seed_metadata_tree(&network, &mut network_metadata);
apply_entries_into_tree(&network, &mut network_metadata, node_entries)?;
apply_network_entries_into_tree(&mut network_metadata, network_entries);
let interface = NodeNetworkInterface {
network: MemoNetwork::new(network),
network_metadata,
..Default::default()
};
Ok(interface)
}
/// Build the runtime-`network_path` -> stable-`NetworkId` map from the `NetworkMetadataEntry`s that
/// `to_runtime_with_full_metadata` emits, so the open path can apply per-network view settings.
pub fn network_ids_from_entries(network_entries: &[NetworkMetadataEntry]) -> HashMap<Vec<NodeId>, graph_storage::NetworkId> {
network_entries.iter().map(|entry| (entry.network_path.clone(), entry.network_id)).collect()
}
/// Collect the per-network, per-peer view state (node-graph nav + previewing) from `interface` into a
/// `session.json` map keyed by the stable storage [`NetworkId`](graph_storage::NetworkId), which
/// `network_ids` resolves from each runtime `network_path`. Networks at their default nav with no preview
/// produce no entry.
pub fn collect_network_view_settings(
interface: &NodeNetworkInterface,
network_ids: &HashMap<Vec<NodeId>, graph_storage::NetworkId>,
) -> BTreeMap<graph_storage::NetworkId, BTreeMap<String, serde_json::Value>> {
let mut out = BTreeMap::new();
for (network_path, &network_id) in network_ids {
let Some(network_metadata) = interface.network_metadata.nested_metadata(network_path) else {
continue;
};
let navigation = &network_metadata.persistent_metadata.navigation_metadata;
let default_navigation = NavigationMetadata::default();
// Only persist nav fields that diverge from the default, so a network at its default view stays out
// of `session.json` (the `if !settings.is_empty()` guard below skips it entirely).
let mut settings = BTreeMap::new();
if navigation.node_graph_ptz != default_navigation.node_graph_ptz
&& let Ok(value) = serde_json::to_value(navigation.node_graph_ptz)
{
settings.insert(session::network::NAV_PTZ.to_string(), value);
}
if navigation.node_graph_to_viewport != default_navigation.node_graph_to_viewport
&& let Ok(value) = serde_json::to_value(navigation.node_graph_to_viewport)
{
settings.insert(session::network::NAV_TRANSFORM.to_string(), value);
}
if navigation.node_graph_width != default_navigation.node_graph_width
&& let Ok(value) = serde_json::to_value(navigation.node_graph_width)
{
settings.insert(session::network::NAV_WIDTH.to_string(), value);
}
// Skip the inert `Previewing::No` default so a network that has never been previewed stays empty.
if !matches!(network_metadata.persistent_metadata.previewing, Previewing::No)
&& let Ok(value) = serde_json::to_value(network_metadata.persistent_metadata.previewing)
{
settings.insert(session::network::PREVIEWING.to_string(), value);
}
if !settings.is_empty() {
out.insert(network_id, settings);
}
}
out
}
/// Apply persisted per-network view state (node-graph nav + previewing) from `session.json` onto
/// `interface`. Inverse of [`collect_network_view_settings`]: `network_ids` resolves each runtime
/// `network_path` to its [`NetworkId`](graph_storage::NetworkId), and the matching inner map is decoded
/// back onto the network's navigation/previewing metadata.
pub fn apply_network_view_settings(
interface: &mut NodeNetworkInterface,
network_ids: &HashMap<Vec<NodeId>, graph_storage::NetworkId>,
network_view_settings: &BTreeMap<graph_storage::NetworkId, BTreeMap<String, serde_json::Value>>,
) {
for (network_path, network_id) in network_ids {
let Some(settings) = network_view_settings.get(network_id) else { continue };
let Some(network_metadata) = interface.network_metadata.nested_metadata_mut(network_path) else {
continue;
};
let persistent = &mut network_metadata.persistent_metadata;
if let Some(value) = settings.get(session::network::NAV_PTZ)
&& let Ok(ptz) = serde_json::from_value::<PTZ>(value.clone())
{
persistent.navigation_metadata.node_graph_ptz = ptz;
}
if let Some(value) = settings.get(session::network::NAV_TRANSFORM)
&& let Ok(transform) = serde_json::from_value(value.clone())
{
persistent.navigation_metadata.node_graph_to_viewport = transform;
}
if let Some(value) = settings.get(session::network::NAV_WIDTH)
&& let Ok(width) = serde_json::from_value(value.clone())
{
persistent.navigation_metadata.node_graph_width = width;
}
if let Some(value) = settings.get(session::network::PREVIEWING)
&& let Ok(previewing) = serde_json::from_value::<Previewing>(value.clone())
{
persistent.previewing = previewing;
}
}
}
/// Entries whose `network_path` doesn't resolve are skipped with a warning (per-network drift is more often a stale path than corruption).
fn apply_network_entries_into_tree(metadata: &mut NodeNetworkMetadata, entries: Vec<NetworkMetadataEntry>) {
for entry in entries {
let Some(network_metadata) = metadata.nested_metadata_mut(&entry.network_path) else {
log::warn!("apply_network_entries_into_tree: nested network at {:?} not found, skipping", entry.network_path);
continue;
};
if let Some(reference) = entry.reference {
network_metadata.persistent_metadata.reference = Some(reference);
}
}
}
/// Walks `network` recursively, ensuring `metadata` has a default `DocumentNodeMetadata` slot for every node at every nesting level.
/// Mirrors the editor invariant that `NodeNetworkPersistentMetadata::node_metadata` contains every document-node key.
fn seed_metadata_tree(network: &NodeNetwork, metadata: &mut NodeNetworkMetadata) {
for (&local_id, node) in &network.nodes {
let node_metadata = metadata.persistent_metadata.node_metadata.entry(local_id).or_default();
if let DocumentNodeImplementation::Network(nested) = &node.implementation {
let child = node_metadata.persistent_metadata.network_metadata.get_or_insert_with(NodeNetworkMetadata::default);
seed_metadata_tree(nested, child);
}
}
}
/// Patches entries onto the metadata tree previously seeded by [`seed_metadata_tree`].
/// Entries with stale `(network_path, local_id)` are skipped with a warning; `input_metadata` length mismatches escalate to `InterfaceRebuildError`.
fn apply_entries_into_tree(network: &NodeNetwork, metadata: &mut NodeNetworkMetadata, entries: Vec<NodeMetadataEntry>) -> Result<(), InterfaceRebuildError> {
// Group entries by network_path so we do one nested_metadata_mut lookup per network.
let mut by_path: HashMap<Vec<NodeId>, Vec<NodeMetadataEntry>> = HashMap::new();
for entry in entries {
by_path.entry(entry.network_path.clone()).or_default().push(entry);
}
for (path, entries) in by_path {
let nested_network = nested_network_at(network, &path);
let Some(network_metadata) = metadata.nested_metadata_mut(&path) else {
log::warn!("apply_entries_into_tree: nested network at {path:?} not found, skipping {} entries", entries.len());
continue;
};
for entry in entries {
let Some(document_node_metadata) = network_metadata.persistent_metadata.node_metadata.get_mut(&entry.local_id) else {
log::warn!("apply_entries_into_tree: node {:?} not seeded under network {path:?}, skipping", entry.local_id);
continue;
};
let persistent = &mut document_node_metadata.persistent_metadata;
if let Some(position) = entry.position {
persistent.node_type_metadata = position_to_runtime(position, entry.is_layer);
} else if entry.is_layer {
persistent.node_type_metadata = NodeTypePersistentMetadata::layer(IVec2::ZERO);
}
if let Some(name) = entry.display_name {
persistent.display_name = name;
}
persistent.locked = entry.locked;
persistent.pinned = entry.pinned;
// The converted runtime is the source of truth for input count; drift indicates a bug worth surfacing.
let expected_inputs = nested_network.and_then(|net| net.nodes.get(&entry.local_id)).map(|doc_node| doc_node.inputs.len());
if let Some(expected) = expected_inputs
&& expected != entry.input_metadata.len()
{
return Err(InterfaceRebuildError::InputMetadataLengthMismatch {
node: entry.local_id,
network_path: path.clone(),
expected,
got: entry.input_metadata.len(),
});
}
persistent.input_metadata = entry.input_metadata.into_iter().map(input_metadata_entry_to_runtime).collect();
if !entry.output_names.is_empty() {
persistent.output_names = entry.output_names;
}
document_node_metadata.transient_metadata = DocumentNodeTransientMetadata::default();
}
}
Ok(())
}
/// `None` when the path is invalid; callers treat that as "skip silently" since the surrounding `nested_metadata_mut` already warns.
fn nested_network_at<'a>(root: &'a NodeNetwork, path: &[NodeId]) -> Option<&'a NodeNetwork> {
let mut current = root;
for segment in path {
let node = current.nodes.get(segment)?;
let DocumentNodeImplementation::Network(nested) = &node.implementation else { return None };
current = nested;
}
Some(current)
}
/// Storage-side `None` restores as `""` (the runtime's "unset" sentinel for `input_name` / `input_description`).
fn input_metadata_entry_to_runtime(entry: InputMetadataEntry) -> InputMetadata {
InputMetadata {
persistent_metadata: InputPersistentMetadata {
input_name: entry.input_name.unwrap_or_default(),
input_description: entry.input_description.unwrap_or_default(),
widget_override: entry.widget_override,
input_data: entry.input_data,
},
..Default::default()
}
}
@@ -5,7 +5,6 @@ use crate::messages::portfolio::document::node_graph::document_node_definitions:
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeTemplate, OutputConnector};
use crate::messages::prelude::DocumentMessageHandler;
use crate::messages::tool::common_functionality::graph_modification_utils;
use glam::{DVec2, IVec2};
use graph_craft::application_io::resource::{DataSource, Resource, ResourceHash, ResourceId};
use graph_craft::descriptor;
@@ -15,6 +14,7 @@ use graphene_std::ProtoNodeIdentifier;
use graphene_std::text::{TextAlign, TypesettingConfig};
use graphene_std::transform::ScaleType;
use graphene_std::uuid::NodeId;
use graphene_std::vector::graphic_types;
use graphene_std::vector::style::{PaintOrder, StrokeAlign};
use std::collections::HashMap;
use std::f64::consts::PI;
@@ -1122,9 +1122,6 @@ pub fn document_migration_replace_resources_referenced_by_hash(document_serializ
pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_node_definitions_on_open: bool) {
document.network_interface.migrate_path_modify_node();
// Legacy `Fill::Gradient`s are converted to absolute by the deferred migration pre-pass that measures each fill's geometry
document.pending_gradient_migration = !graph_modification_utils::legacy_gradient_fill_nodes(&document.network_interface).is_empty();
let network = document.network_interface.document_network().clone();
// Apply string and node replacements to each node
@@ -1575,6 +1572,101 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
inputs_count = 5;
}
// Upgrade the legacy 4-input Fill node (content, fill: Fill, _backup_color, _backup_gradient: Gradient) to the
// value-model 7-input shape (content, fill: generic paint list, _backup_color, _backup_gradient, _gradient_type, _spread_method, _transform).
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER) && inputs_count == 4 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
// Content: no change
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
// Fill: a literal Fill value is decomposed, and a wired input (`List<GradientStops> / List<Color>`) is kept as-is
match old_inputs[1].as_value() {
Some(TaggedValue::LegacyFill(old_fill)) => {
let exposed = old_inputs[1].is_exposed();
let fill_value = match old_fill {
graphic_types::migrations::legacy::Fill::None => TaggedValue::Color(None),
graphic_types::migrations::legacy::Fill::Solid(color) => TaggedValue::Color(Some(*color)),
graphic_types::migrations::legacy::Fill::Gradient(gradient) => TaggedValue::Gradient(gradient.stops.clone()),
};
document
.network_interface
.set_input(&InputConnector::node(*node_id, 1), NodeInput::value(fill_value, exposed), network_path);
// Gradient metadata (4, 5, 6): applies only to a literal gradient, solids/none keep the template defaults
if let graphic_types::migrations::legacy::Fill::Gradient(gradient) = old_fill {
document.network_interface.set_input(
&InputConnector::node(*node_id, 4),
NodeInput::value(TaggedValue::GradientType(gradient.gradient_type), false),
network_path,
);
document.network_interface.set_input(
&InputConnector::node(*node_id, 5),
NodeInput::value(TaggedValue::GradientSpreadMethod(gradient.spread_method), false),
network_path,
);
let transform = if gradient.absolute {
Some(gradient.transform * gradient.to_transform())
} else {
// Baking a legacy bounding-box-relative gradient is deferred until the measurement pre-pass can supply the paint target's bounds
document.pending_gradient_bbox_bake.push((network_path.to_vec(), *node_id, gradient.clone()));
None
};
document
.network_interface
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::OptionalDAffine2(transform), false), network_path);
}
}
// Wired/exposed fill keeps the connection.
// The generic paint connector accepts the existing `List<Color>`/`List<GradientStops>` paint sources directly.
_ => {
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
}
}
// Color backup: no change
document.network_interface.set_input(&InputConnector::node(*node_id, 2), old_inputs[2].clone(), network_path);
// Gradient backup: extract stops
if let Some(TaggedValue::LegacyGradient(g)) = old_inputs[3].as_value() {
document
.network_interface
.set_input(&InputConnector::node(*node_id, 3), NodeInput::value(TaggedValue::Gradient(g.stops.clone()), false), network_path);
// A solid/no-fill node leaves the gradient metadata inputs unused, so seed them from the backup gradient for a later Solid -> Gradient toggle to restore
if matches!(
old_inputs[1].as_value(),
Some(TaggedValue::LegacyFill(
graphic_types::migrations::legacy::Fill::None | graphic_types::migrations::legacy::Fill::Solid(_)
))
) {
document
.network_interface
.set_input(&InputConnector::node(*node_id, 4), NodeInput::value(TaggedValue::GradientType(g.gradient_type), false), network_path);
document.network_interface.set_input(
&InputConnector::node(*node_id, 5),
NodeInput::value(TaggedValue::GradientSpreadMethod(g.spread_method), false),
network_path,
);
let transform = if g.absolute {
Some(g.transform * g.to_transform())
} else {
document.pending_gradient_bbox_bake.push((network_path.to_vec(), *node_id, g.clone()));
None
};
document
.network_interface
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::OptionalDAffine2(transform), false), network_path);
}
}
inputs_count = 7;
}
// Upgrade Stroke node to reorder parameters and add "Align" and "Paint Order" (#2644)
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 8 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
@@ -0,0 +1,231 @@
//! Asynchronous `.gdd` working-copy IO, spawned by `PortfolioMessageHandler` as `FutureMessage`s:
//! building/opening containers, opening `.gdd` archives into documents, and rebuilding the interface
//! from the undo/redo cursor. The `validate` flag is the `validate_storage_round_trip` preference; when
//! set, the registry build is compared against the legacy oracle (logged, not fatal) for the soak.
use document_container::AnyContainer;
use document_format::{Error as DocumentFormatError, GddV1, GddV1Layout};
use graph_craft::application_io::resource::{LoadResource, ResourceStorage};
use graph_craft::document::NodeNetwork;
use super::document::DocumentMessageHandler;
use super::document::diff_networks;
use super::document::utility_types::network_interface::storage_metadata::{apply_network_view_settings, build_interface_from_storage, network_ids_from_entries};
use super::document_migration::document_migration_string_preprocessing;
use super::portfolio_message::PortfolioMessage;
use crate::messages::message::Message;
use crate::messages::portfolio::document::utility_types::misc::DocumentId;
use crate::messages::resource_storage::ResourcesHandle;
/// Build the container backend at `path` (folder on native, OPFS directory name on web) or in-memory
/// when `None`. Also returns whether an existing working copy was found (its `manifest.json` is present).
async fn build_per_document_container(path: Option<&std::path::Path>) -> Result<(AnyContainer, bool), DocumentFormatError> {
let Some(path) = path else {
return Ok((AnyContainer::Memory(document_container::backends::memory::MemoryBackend::new()), false));
};
#[cfg(not(target_family = "wasm"))]
{
use document_container::backends::folder::FolderBackend;
let exists = path.join("manifest.json").is_file();
let backend = if exists { FolderBackend::open(path)? } else { FolderBackend::create(path)? };
Ok((AnyContainer::Folder(backend), exists))
}
#[cfg(target_family = "wasm")]
{
use document_container::AsyncContainer;
use document_container::backends::opfs::OpfsBackend;
let directory_name = path
.to_str()
.ok_or(DocumentFormatError::Container(document_container::ContainerError::InvalidPath(path.display().to_string())))?;
let backend = OpfsBackend::open(directory_name).await?;
let exists = backend.exists("manifest.json").await;
Ok((AnyContainer::Opfs(backend), exists))
}
}
/// Open the existing working copy at `path`, or create a fresh one bound to `peer` (in-memory when
/// `path` is `None`). Returns the working copy plus whether it was reopened (vs freshly created); only a
/// reopen has independently-stored state worth comparing against the legacy load.
pub(super) async fn build_or_open_working_copy(path: Option<&std::path::Path>, peer: graph_storage::PeerId, document_uuid: u64, version: String) -> Result<(GddV1, bool), DocumentFormatError> {
let (container, exists) = build_per_document_container(path).await?;
let gdd = if exists {
GddV1::open_in(container, GddV1Layout).await?
} else {
GddV1::create_in(container, GddV1Layout, peer, document_uuid, version.clone(), version).await?
};
Ok((gdd, exists))
}
/// `FutureMessage` that opens a `.gdd` archive into a document, delivered via
/// [`PortfolioMessage::GddDocumentLoaded`]. See [`build_document_from_gdd`] for the build itself.
pub(super) async fn open_gdd_document(
working_copy_root: Option<std::path::PathBuf>,
document_id: DocumentId,
document_name: Option<String>,
document_path: Option<std::path::PathBuf>,
content: Vec<u8>,
store_handle: ResourcesHandle,
validate: bool,
) -> Message {
let path = working_copy_root.map(|root| root.join(format!("{:x}", document_id.0)));
let document = build_document_from_gdd(path.as_deref(), &content, &store_handle, document_id, validate).await;
Message::Portfolio(PortfolioMessage::GddDocumentLoaded {
document_id,
document_name,
document_path,
document: document.map(Box::new),
})
}
/// `FutureMessage` that rebuilds a document's interface from a post-move `Gdd` cursor snapshot and
/// delivers it via [`PortfolioMessage::GddUndoRedoRebuilt`] (`None` interface on failure, logged here).
pub(crate) async fn rebuild_gdd_cursor(gdd: GddV1, store_handle: ResourcesHandle, document_id: DocumentId, had_oracle: bool) -> Message {
let declarations = gdd.declarations(&store_handle).await;
let interface = match gdd.registry().to_runtime_with_full_metadata(&declarations) {
Ok((network, node_entries, network_entries)) => match build_interface_from_storage(network, node_entries, network_entries) {
Ok(interface) => Some(Box::new(interface)),
Err(error) => {
log::error!("Gdd undo/redo rebuild for {document_id:?}: failed to build interface: {error}");
None
}
},
Err(error) => {
log::error!("Gdd undo/redo rebuild for {document_id:?}: failed to convert registry to runtime: {error}");
None
}
};
Message::Portfolio(PortfolioMessage::GddUndoRedoRebuilt { document_id, had_oracle, interface })
}
/// Core of the `.gdd` open: archive -> working copy -> `Gdd` -> runtime interface. The registry build is
/// authoritative; the embedded legacy blob is the soak oracle and the fallback if the build fails.
/// Returns `None` only if neither the build nor the legacy fallback worked.
async fn build_document_from_gdd(path: Option<&std::path::Path>, content: &[u8], store_handle: &impl ResourceStorage, document_id: DocumentId, validate: bool) -> Option<DocumentMessageHandler> {
let (container, _exists) = match build_per_document_container(path).await {
Ok(result) => result,
Err(error) => {
log::error!("Opening .gdd for {document_id:?}: failed to build working copy container: {error}");
return None;
}
};
let gdd = match GddV1::open_from_archive(content, container, GddV1Layout).await {
Ok(gdd) => gdd,
Err(error) => {
log::error!("Opening .gdd for {document_id:?}: failed to open archive: {error}");
return None;
}
};
// Extract archived resource bytes into the global cache so declarations + runtime resolve.
match gdd.resource_hashes().await {
Ok(hashes) => {
for hash in hashes {
match gdd.read_resource(&hash).await {
Ok(holder) => {
store_handle.store(holder.as_slice());
}
Err(error) => log::error!("Opening .gdd for {document_id:?}: failed to read resource {hash}: {error}"),
}
}
}
Err(error) => log::error!("Opening .gdd for {document_id:?}: failed to list resources: {error}"),
}
let legacy_document = gdd
.read_legacy_document()
.await
.and_then(|holder| String::from_utf8(holder.as_slice().to_vec()).ok())
.and_then(|serialized| DocumentMessageHandler::deserialize_document(&document_migration_string_preprocessing(serialized)).ok());
let declarations = gdd.declarations(store_handle).await;
let interface = match gdd.registry().to_runtime_with_full_metadata(&declarations) {
Ok((network, node_entries, network_entries)) => {
let network_ids = network_ids_from_entries(&network_entries);
match build_interface_from_storage(network, node_entries, network_entries) {
Ok(mut interface) => {
// Per-network view state lives in `session.json`, not the registry, so restore it here.
apply_network_view_settings(&mut interface, &network_ids, gdd.network_view_settings());
Some(interface)
}
Err(error) => {
log::error!("Opening .gdd for {document_id:?}: failed to build interface: {error}");
None
}
}
}
Err(error) => {
log::error!("Opening .gdd for {document_id:?}: failed to convert registry to runtime: {error}");
None
}
};
// Soak compare against the legacy oracle, normalizing the benign generic-vs-resolved `call_argument`.
if let Some(interface) = interface {
if validate && let Some(legacy) = &legacy_document {
let mut built = interface.document_network().clone();
let mut oracle = legacy.network_interface.document_network().clone();
normalize_call_arguments_for_compare(&mut built);
normalize_call_arguments_for_compare(&mut oracle);
if built != oracle {
log::error!(
"Open-.gdd divergence for {document_id:?}: registry-built document differs from the embedded legacy blob\n{}",
diff_networks(&oracle, &built)
);
}
}
return Some(DocumentMessageHandler::from_storage(interface, gdd, String::new(), None));
}
log::warn!("Opening .gdd for {document_id:?}: registry build failed, falling back to embedded legacy document");
if legacy_document.is_none() {
log::error!("Opening .gdd for {document_id:?}: no embedded legacy document to fall back to");
}
legacy_document
}
/// Soak check that the reopened `.gdd`'s stored registry, converted back to a runtime network, matches
/// the legacy load. Logs divergence only (legacy stays authoritative); runs once per open.
pub(super) async fn compare_storage_against_runtime(gdd: &GddV1, legacy_network: &NodeNetwork, byte_store: &dyn LoadResource, document_id: DocumentId) {
let declarations = gdd.declarations(byte_store).await;
let mut candidate = match gdd.registry().to_runtime_with_metadata(&declarations) {
Ok((network, _entries)) => network,
Err(error) => {
log::error!("Compare-on-open for {document_id:?}: .gdd registry failed to convert to runtime: {error}");
return;
}
};
// Normalize the benign generic-vs-resolved `call_argument` on both sides before comparing.
let mut legacy = legacy_network.clone();
normalize_call_arguments_for_compare(&mut legacy);
normalize_call_arguments_for_compare(&mut candidate);
if candidate != legacy {
log::error!(
"Compare-on-open divergence for {document_id:?}: the reopened .gdd does not match the legacy load\n{}",
diff_networks(&legacy, &candidate)
);
}
}
/// Recursively rewrite a concrete `Context` `call_argument` back to the generic `T` storage authored, so
/// the generic-vs-resolved difference (recomputed during compilation) compares equal. Other types untouched.
fn normalize_call_arguments_for_compare(network: &mut NodeNetwork) {
use graph_craft::Type;
let context = graph_craft::concrete!(graphene_std::Context);
for node in network.nodes.values_mut() {
if node.call_argument == context {
node.call_argument = Type::Generic(std::borrow::Cow::Borrowed("T"));
}
if let graph_craft::document::DocumentNodeImplementation::Network(inner) = &mut node.implementation {
normalize_call_arguments_for_compare(inner);
}
}
}
+1
View File
@@ -3,6 +3,7 @@ mod portfolio_message_handler;
pub mod document;
pub mod document_migration;
pub mod document_storage_io;
pub mod fonts;
pub mod persistent_state;
pub mod utility_types;
@@ -8,7 +8,8 @@ use graphene_std::raster::Image;
use std::path::PathBuf;
#[impl_message(Message, Portfolio)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
#[derive(derivative::Derivative, serde::Serialize, serde::Deserialize)]
#[derivative(Clone, Debug, PartialEq)]
pub enum PortfolioMessage {
// Sub-messages
#[child]
@@ -41,6 +42,18 @@ pub enum PortfolioMessage {
DeleteDocument {
document_id: DocumentId,
},
/// Delivers an asynchronously-built `Gdd` working copy into its document, emitted by the mount future
/// spawned in `load_document`. The `gdd` payload is non-serializable and a clone carries none
/// (`clone_to_none`), so it travels exactly once. `reopened` is true when an existing working copy was
/// opened: the persisted cursor is trusted as-is and the mount-time re-commit is skipped, since
/// re-committing would stack a spurious interaction on the restored cursor and make the first undo a no-op.
DocumentStorageMounted {
document_id: DocumentId,
reopened: bool,
#[serde(skip, default)]
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
gdd: Option<document_format::GddV1>,
},
DestroyAllDocuments,
EditorPreferences,
GarbageCollectResources,
@@ -90,6 +103,33 @@ pub enum PortfolioMessage {
document_path: Option<PathBuf>,
document_serialized_content: String,
},
/// Open a `.gdd` document container (archive bytes), building the runtime from its stored registry.
OpenGddDocument {
document_name: Option<String>,
document_path: Option<PathBuf>,
content: Vec<u8>,
},
/// Delivers a document built asynchronously from a `.gdd` archive (registry → runtime, working copy
/// mounted) into the portfolio. Travels once like [`DocumentStorageMounted`](Self::DocumentStorageMounted).
GddDocumentLoaded {
document_id: DocumentId,
document_name: Option<String>,
document_path: Option<PathBuf>,
#[serde(skip, default)]
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
document: Option<Box<DocumentMessageHandler>>,
},
/// Delivers the interface rebuilt from the `Gdd` undo/redo cursor so the async rebuild can swap into the
/// live document. `interface` is `None` if the rebuild failed (logged at the source). `had_oracle` records
/// whether the legacy snapshot applied synchronously, so the swap can debug-compare against it. Travels
/// once like [`DocumentStorageMounted`](Self::DocumentStorageMounted).
GddUndoRedoRebuilt {
document_id: DocumentId,
had_oracle: bool,
#[serde(skip, default)]
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
interface: Option<Box<crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface>>,
},
LoadDocument {
document_id: DocumentId,
document_name: Option<String>,
@@ -180,3 +220,8 @@ pub enum PortfolioMessage {
sizes: Vec<f64>,
},
}
/// Clone helper for the non-serializable `gdd` payload: a cloned mount message carries no `Gdd`.
fn clone_to_none<T>(_: &Option<T>) -> Option<T> {
None
}
@@ -2,7 +2,7 @@ use super::document::utility_types::document_metadata::LayerNodeIdentifier;
use super::persistent_state::{PersistentStateMessage, PersistentStateMessageContext, PersistentStateMessageHandler};
use super::utility_types::{PanelLayoutSubdivision, PanelType, WorkspacePanelLayout};
use crate::application::{Editor, generate_uuid};
use crate::consts::{DEFAULT_DOCUMENT_NAME, FILE_EXTENSION};
use crate::consts::{DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, GDD_FILE_EXTENSION};
use crate::messages::animation::TimingInformation;
use crate::messages::dialog::simple_dialogs;
use crate::messages::frontend::utility_types::{DocumentInfo, PersistedState};
@@ -14,6 +14,7 @@ use crate::messages::portfolio::document::graph_operation::utility_types::Transf
use crate::messages::portfolio::document::node_graph::document_node_definitions;
use crate::messages::portfolio::document::utility_types::network_interface::OutputConnector;
use crate::messages::portfolio::document_migration::*;
use crate::messages::portfolio::document_storage_io::{build_or_open_working_copy, compare_storage_against_runtime, open_gdd_document};
use crate::messages::portfolio::utility_types::FileContent;
use crate::messages::preferences::SelectionMode;
use crate::messages::prelude::*;
@@ -64,6 +65,9 @@ pub struct PortfolioMessageHandler {
pub selection_mode: SelectionMode,
pub reset_node_definitions_on_open: bool,
pub workspace_panel_layout: WorkspacePanelLayout,
working_copy_root: Option<PathBuf>,
/// Number of document not fully loaded. While non-zero, resource GC is skipped.
pending_opens: usize,
}
#[message_handler_data]
@@ -197,7 +201,11 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(PortfolioMessage::GarbageCollectResources);
}
PortfolioMessage::AutoSaveDocument { document_id } => {
let Some(document) = self.document(document_id) else { return };
let validate = preferences.validate_storage_round_trip;
let Some(document) = self.documents.get_mut(&document_id) else { return };
document.commit_storage_snapshot(&resource_storage.resources_mut(), validate);
responses.add(PersistentStateMessage::WriteDocument {
document_id,
document: document.serialize_document(),
@@ -292,6 +300,17 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(PortfolioMessage::SelectDocument { document_id });
}
}
PortfolioMessage::DocumentStorageMounted { document_id, reopened, gdd } => {
let Some(document) = self.documents.get_mut(&document_id) else {
// Document was closed before its working copy finished mounting.
return;
};
document.set_storage(gdd);
if !reopened {
document.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
document.retire_storage_interaction();
}
}
PortfolioMessage::DestroyAllDocuments => {
// Empty the list of internal document data
self.documents.clear();
@@ -307,6 +326,10 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
// We don't know what can be safely garbage collected
return;
}
if self.pending_opens > 0 {
// A document not fully loaded, skip garbage collection.
return;
}
let mut used_resources = HashSet::new();
for (id, info) in self.unloaded_documents.iter() {
@@ -320,6 +343,10 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
for document in self.documents.values_mut() {
document.garbage_collect_resources();
used_resources.extend(document.resources.registry.resolved().filter_map(|info| info.hash.cloned()));
if let Some(storage) = document.storage() {
used_resources.extend(storage.all_referenced_resource_hashes());
}
}
used_resources.extend(self.fonts.used_resources());
responses.add(ResourceStorageMessage::GarbageCollect {
@@ -505,7 +532,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(NavigationMessage::CanvasPan { delta: (0., 0.).into() });
}
self.load_document(new_document, document_id, responses);
self.load_document(new_document, document_id, resource_storage, preferences.validate_storage_round_trip, responses);
responses.add(PortfolioMessage::SelectDocument { document_id });
}
PortfolioMessage::MoveAllPanelTabs {
@@ -642,6 +669,14 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document_serialized_content: content,
});
}
FileContent::GddDocument(content) => {
let document_path = if path.is_absolute() { Some(path) } else { None };
responses.add(PortfolioMessage::OpenGddDocument {
document_name: name,
document_path,
content,
});
}
FileContent::Svg(svg) => {
responses.add(PortfolioMessage::OpenSvg { name, svg });
}
@@ -669,6 +704,13 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document_serialized_content: content,
});
}
FileContent::GddDocument(content) => {
responses.add(PortfolioMessage::OpenGddDocument {
document_name: name,
document_path: Some(path),
content,
});
}
FileContent::Svg(svg) => {
responses.add(PortfolioMessage::InsertSvg {
name,
@@ -710,6 +752,68 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
});
responses.add(PortfolioMessage::SelectDocument { document_id });
}
PortfolioMessage::OpenGddDocument {
document_name,
document_path,
content,
} => {
let document_id = DocumentId(generate_uuid());
// Suppress resource GC until the open completes
self.pending_opens += 1;
responses.add(open_gdd_document(
self.working_copy_root.clone(),
document_id,
document_name,
document_path,
content,
resource_storage.resources_mut(),
preferences.validate_storage_round_trip,
));
}
PortfolioMessage::GddDocumentLoaded {
document_id,
document_name,
document_path,
document,
} => {
self.pending_opens = self.pending_opens.saturating_sub(1);
let Some(mut document) = document.map(|boxed| *boxed) else {
let name = document_name
.filter(|name| !name.trim().is_empty())
.or_else(|| document_path.as_ref().and_then(|path| path.file_stem()).map(|stem| stem.to_string_lossy().into_owned()))
.unwrap_or_default();
simple_dialogs::FailedToOpenDocumentDialog { document_name: name }.send_dialog_to_frontend(responses);
return;
};
document.finalize_storage_load();
document.set_save_state(true);
let name = document_name
.filter(|name| !name.trim().is_empty())
.or_else(|| document_path.as_ref().and_then(|path| path.file_stem()).map(|stem| stem.to_string_lossy().into_owned()))
.unwrap_or_else(|| DEFAULT_DOCUMENT_NAME.to_string());
document.name = self.resolve_document_name(name, None);
document.path = document_path;
// The working copy is already mounted (we opened the .gdd), so skip the async re-mount.
self.load_document(document, document_id, resource_storage, preferences.validate_storage_round_trip, responses);
responses.add(PortfolioMessage::SelectDocument { document_id });
}
PortfolioMessage::GddUndoRedoRebuilt { document_id, had_oracle, interface } => {
let Some(document) = self.documents.get_mut(&document_id) else {
// Document was closed before its undo/redo rebuild completed; drop the payload.
return;
};
let Some(interface) = interface.map(|boxed| *boxed) else {
// The rebuild failed and already logged; leave the live document untouched.
return;
};
document.apply_gdd_cursor_rebuild(interface, had_oracle, preferences.validate_storage_round_trip, responses);
}
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
responses.add(MenuBarMessage::SendLayout);
@@ -836,8 +940,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document.set_save_state(document_is_saved);
let document_name_from_path = document_path.as_ref().and_then(|path| {
if path.extension().is_some_and(|e| e == FILE_EXTENSION) {
path.file_stem().map(|n| n.to_string_lossy().to_string())
if path.extension().is_some_and(|extension| extension == FILE_EXTENSION || extension == GDD_FILE_EXTENSION) {
path.file_stem().map(|stem| stem.to_string_lossy().to_string())
} else {
None
}
@@ -855,7 +959,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document.name = self.resolve_document_name(candidate_name, None);
// Load the document into the portfolio so it opens in the editor
self.load_document(document, document_id, responses);
self.load_document(document, document_id, resource_storage, preferences.validate_storage_round_trip, responses);
responses.add(AppWindowMessage::Focus);
@@ -1387,9 +1491,9 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
let physical_resolution = viewport.size().to_physical().into_dvec2().round().as_uvec2();
// TODO: Eventually remove this document upgrade code
// A freshly-opened document with legacy gradients runs a one-time measurement pre-pass instead of rendering, until every gradient is converted to absolute space
if document.pending_gradient_migration {
self.executor.drive_gradient_migration(document, document_id, physical_resolution, scale, responses);
// A freshly-opened document with legacy gradients (whether newly decomposed or persisted from a save made before every bake landed) runs a
// one-time measurement pre-pass instead of rendering, until every gradient's transform is baked into absolute space
if !document.pending_gradient_bbox_bake.is_empty() && self.executor.drive_gradient_migration(document, document_id, physical_resolution, scale, responses) {
return;
}
@@ -1601,6 +1705,10 @@ impl PortfolioMessageHandler {
Self { executor, ..Default::default() }
}
pub fn set_working_copy_root(&mut self, root: Option<PathBuf>) {
self.working_copy_root = root;
}
pub fn document(&self, document_id: DocumentId) -> Option<&DocumentMessageHandler> {
self.documents.get(&document_id)
}
@@ -1698,6 +1806,7 @@ impl PortfolioMessageHandler {
Ok(content) => FileContent::Document(content),
Err(_) => FileContent::Unsupported,
},
GDD_FILE_EXTENSION => FileContent::GddDocument(content),
"svg" => match String::from_utf8(content) {
Ok(content) => FileContent::Svg(content),
Err(_) => FileContent::Unsupported,
@@ -1717,7 +1826,14 @@ impl PortfolioMessageHandler {
}
}
fn load_document(&mut self, mut new_document: DocumentMessageHandler, document_id: DocumentId, responses: &mut VecDeque<Message>) {
fn load_document(
&mut self,
mut new_document: DocumentMessageHandler,
document_id: DocumentId,
resource_storage: &ResourceStorageMessageHandler,
validate: bool,
responses: &mut VecDeque<Message>,
) {
let is_new_document = !self.document_ids.contains(&document_id);
if is_new_document {
self.document_ids.push_back(document_id);
@@ -1744,6 +1860,64 @@ impl PortfolioMessageHandler {
if is_new_document {
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
}
// Mount the per-document `Gdd` working copy asynchronously.
//
// Only mount for legacy loads: a `.gdd` open already mounted its working copy
// and remounting would overwrite it and drop that history state.
if self.documents.get(&document_id).and_then(|document| document.storage()).is_none() {
let legacy_network = self
.documents
.get(&document_id)
.map(|document| document.network_interface.document_network().clone())
.unwrap_or_default();
responses.add(Self::mount_document_storage(
self.working_copy_root.clone(),
document_id,
legacy_network,
resource_storage.resources(),
validate,
));
}
}
/// With a configured root the working copy lives at `<root>/<id_hex>`; without one it is in-memory.
///
/// On a *reopen* (existing working copy), the freshly-read `.gdd` is converted back to a runtime
/// network and compared against `legacy_network` before
/// the working copy attaches. It validates the `.gdd` *read* path.
fn mount_document_storage(
working_copy_root: Option<std::path::PathBuf>,
document_id: DocumentId,
legacy_network: graph_craft::document::NodeNetwork,
byte_store: Box<dyn graph_craft::application_io::resource::LoadResource>,
validate: bool,
) -> Message {
let path = working_copy_root.map(|root| root.join(format!("{:016x}", document_id.0)));
let editor_version = crate::application::GRAPHITE_GIT_COMMIT_HASH.to_string();
let peer = graph_storage::PeerId(generate_uuid());
let future = async move {
let (gdd, reopened) = match build_or_open_working_copy(path.as_deref(), peer, document_id.0, editor_version).await {
Ok(result) => result,
Err(error) => {
log::error!("Failed to mount document storage for {document_id:?}: {error}");
return Message::NoOp;
}
};
if validate && reopened {
compare_storage_against_runtime(&gdd, &legacy_network, byte_store.as_ref(), document_id).await;
}
Message::Portfolio(PortfolioMessage::DocumentStorageMounted {
document_id,
reopened,
gdd: Some(gdd),
})
};
future.into()
}
/// Returns an iterator over the open documents in order.
@@ -789,8 +789,10 @@ impl PanelLayoutSubdivision {
}
pub enum FileContent {
/// A Graphite document.
/// A legacy `.graphite` document (serialized runtime JSON).
Document(String),
/// A `.gdd` document container (archive bytes).
GddDocument(Vec<u8>),
/// A bitmap image.
Image(Image<Color>),
/// An SVG file string.
@@ -36,6 +36,13 @@ pub enum PreferencesMessage {
DisableUIAcceleration {
disable_ui_acceleration: bool,
},
ValidateStorageRoundTrip {
enabled: bool,
},
SaveAsGdd {
enabled: bool,
},
ToggleShowStoragePreferences,
#[cfg(target_os = "macos")]
VSync {
vsync: bool,
@@ -23,6 +23,9 @@ pub struct PreferencesMessageHandler {
pub ui_scale: f64,
pub max_render_region_size: u32,
pub disable_ui_acceleration: bool,
pub validate_storage_round_trip: bool,
pub save_as_gdd: bool,
pub show_storage_preferences: bool,
#[cfg(target_os = "macos")]
pub vsync: bool,
}
@@ -66,6 +69,9 @@ impl Default for PreferencesMessageHandler {
ui_scale: UI_SCALE_DEFAULT,
max_render_region_size: EditorPreferences::default().max_render_region_size,
disable_ui_acceleration: cfg!(target_os = "linux"), // TODO: Set this back to false once we have ui acceleration working more reliably on linux
validate_storage_round_trip: false,
save_as_gdd: false,
show_storage_preferences: false,
#[cfg(target_os = "macos")]
vsync: false,
}
@@ -132,6 +138,16 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
PreferencesMessage::DisableUIAcceleration { disable_ui_acceleration } => {
self.disable_ui_acceleration = disable_ui_acceleration;
}
PreferencesMessage::ValidateStorageRoundTrip { enabled } => {
self.validate_storage_round_trip = enabled;
}
PreferencesMessage::SaveAsGdd { enabled } => {
self.save_as_gdd = enabled;
}
PreferencesMessage::ToggleShowStoragePreferences => {
self.show_storage_preferences = !self.show_storage_preferences;
responses.add(MenuBarMessage::SendLayout);
}
#[cfg(target_os = "macos")]
PreferencesMessage::VSync { vsync } => {
self.vsync = vsync;
@@ -13,6 +13,20 @@ impl LoadResource for ResourcesHandle {
}
}
impl ResourceStorage for ResourcesHandle {
fn store(&self, data: &[u8]) -> ResourceHash {
self.inner.store(data)
}
fn contains(&self, hash: &ResourceHash) -> bool {
self.inner.contains(hash)
}
fn garbage_collect(&self, used: &[ResourceHash]) {
self.inner.garbage_collect(used)
}
}
#[derive(ExtractField)]
pub struct ResourceStorageMessageHandler {
storage: Option<Arc<dyn ResourceStorage>>,
@@ -28,6 +42,12 @@ impl ResourceStorageMessageHandler {
inner: self.storage.clone().expect("Resource storage not initialized"),
})
}
pub fn resources_mut(&self) -> ResourcesHandle {
ResourcesHandle {
inner: self.storage.clone().expect("Resource storage not initialized"),
}
}
}
impl std::fmt::Debug for ResourceStorageMessageHandler {
@@ -60,8 +60,7 @@ impl ToolColorOptions {
return;
}
if let Some(FillChoice::Solid(color)) = &self.fill_choice {
let fill = graphene_std::vector::style::Fill::Solid(*color);
responses.add(GraphOperationMessage::FillSet { layer, fill });
responses.add(GraphOperationMessage::FillColorSet { layer, color: Some(*color) });
}
}
@@ -70,8 +69,9 @@ impl ToolColorOptions {
return;
}
if let Some(FillChoice::Solid(color)) = &self.fill_choice {
let stroke = graphene_std::vector::style::Stroke::new(Some(*color), weight);
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
let color = Some(*color);
let stroke = graphene_std::vector::style::Stroke::new(weight);
responses.add(GraphOperationMessage::StrokeSet { layer, color, stroke });
}
}
@@ -175,8 +175,8 @@ impl DrawingToolState {
return;
}
let Some(FillChoice::Solid(color)) = &self.stroke.fill_choice else { return };
let color = Some(*color);
let stroke = graphene_std::vector::style::Stroke {
color: Some(*color),
weight: self.effective_line_weight(),
align: self.stroke_align.unwrap_or_default(),
cap: self.stroke_cap.unwrap_or_default(),
@@ -187,7 +187,7 @@ impl DrawingToolState {
dash_offset: self.dash_offset.unwrap_or(0.),
transform: glam::DAffine2::IDENTITY,
};
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
responses.add(GraphOperationMessage::StrokeSet { layer, color, stroke });
}
}
@@ -5,9 +5,8 @@ use crate::messages::portfolio::document::utility_types::network_interface::{Flo
use crate::messages::prelude::*;
use glam::{DAffine2, DVec2};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graph_craft::document::{DocumentNode, NodeId, NodeInput};
use graph_craft::{ProtoNodeIdentifier, concrete};
use graphene_std::Color;
use graphene_std::NodeInputDecleration;
use graphene_std::list::List;
use graphene_std::raster::BlendMode;
@@ -15,8 +14,9 @@ use graphene_std::raster_types::{CPU, GPU, Image, Raster};
use graphene_std::subpath::Subpath;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::misc::ManipulatorPointId;
use graphene_std::vector::style::{Fill, FillChoice, Gradient, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::{GradientStops, PointId, SegmentId, VectorModificationType};
use graphene_std::vector::style::{FillChoice, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, initial_gradient_transform_for_bounding_box};
use graphene_std::vector::{GradientSpreadMethod, GradientStops, GradientType, PointId, SegmentId, VectorModificationType};
use graphene_std::{Color, Graphic};
use std::collections::VecDeque;
/// Returns the ID of the first Spline node in the horizontal flow which is not followed by a `Path` node, or `None` if none exists.
@@ -271,11 +271,18 @@ pub fn get_viewport_center(layer: LayerNodeIdentifier, network_interface: &NodeN
network_interface.document_metadata().transform_to_viewport(layer).transform_point2(min + (max - min) * center)
}
/// Get the closest Fill node's ID to the provided layer, if any.
pub fn get_fill_node_id_with_direct_fill_input(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
let fill_node_id = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
let fill_node = network_interface.document_network().nodes.get(&fill_node_id)?;
matches!(fill_node.inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)?, NodeInput::Value { .. }).then_some(fill_node_id)
}
/// Determine the input connector where the gradient chain enters the layer.
/// Returns Fill's fill input if the layer has a "Fill" node, otherwise returns the layer's content input.
pub fn gradient_chain_target_input(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> InputConnector {
if let Some(fill_node_id) = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER)) {
InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::<Fill>::INDEX)
InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)
} else {
InputConnector::node(layer.to_node(), 1)
}
@@ -292,89 +299,29 @@ pub fn get_upstream_gradient_value_node_id(layer: LayerNodeIdentifier, network_i
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_value::IDENTIFIER)))
}
// TODO: Eventually remove this document upgrade code
/// Get the layer's "Fill" node itself (whose `fill` input holds the paint value), not the node feeding that input.
pub fn get_fill_node_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))
}
/// Get the node connected to Fill's fill input, if any.
pub fn get_fill_input_node_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
let fill_node_id = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
let fill_node = network_interface.document_network().nodes.get(&fill_node_id)?;
let NodeInput::Node { node_id, .. } = fill_node.inputs.get(graphene_std::vector::fill::FillInput::<Fill>::INDEX)? else {
let NodeInput::Node { node_id, .. } = fill_node.inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)? else {
return None;
};
Some(*node_id)
}
/// Get the current gradient of a layer from the closest "Fill" node.
pub fn get_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Gradient> {
let fill_index = 1;
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
let TaggedValue::Fill(Fill::Gradient(gradient)) = inputs.get(fill_index)?.as_value()? else {
return None;
};
Some(gradient.clone())
}
// TODO: Eventually remove this document upgrade code
/// The legacy bounding-box-relative gradient (`absolute == false`) in a "Fill" node's active `fill` input, if any.
fn legacy_active_gradient_in_fill_node(fill_node_id: NodeId, network_interface: &NodeNetworkInterface) -> Option<Gradient> {
let node = network_interface.document_network().nodes.get(&fill_node_id)?;
let TaggedValue::Fill(Fill::Gradient(gradient)) = node.inputs.get(graphene_std::vector::fill::FillInput::<Fill>::INDEX)?.as_value()? else {
return None;
};
(!gradient.absolute).then(|| gradient.clone())
}
// TODO: Eventually remove this document upgrade code
/// The legacy bounding-box-relative gradient (`absolute == false`) stashed in a "Fill" node's `_backup_gradient` input, if any.
/// The backup is inert until the fill is toggled back to a gradient, at which point it becomes the active fill, so it needs converting too.
fn legacy_backup_gradient_in_fill_node(fill_node_id: NodeId, network_interface: &NodeNetworkInterface) -> Option<Gradient> {
let node = network_interface.document_network().nodes.get(&fill_node_id)?;
let TaggedValue::FillGradient(gradient) = node.inputs.get(graphene_std::vector::fill::BackupGradientInput::INDEX)?.as_value()? else {
return None;
};
(!gradient.absolute).then(|| gradient.clone())
}
// TODO: Eventually remove this document upgrade code
/// Convert a "Fill" node's legacy gradients (the active `fill` and/or the stashed `_backup_gradient`) to absolute space using
/// the geometry's measured bounding box, writing each back in place. The active fill is written as a `Fill`, the backup as a bare `FillGradient`.
pub fn migrate_fill_node_gradients_to_absolute(fill_node_id: NodeId, network_interface: &mut NodeNetworkInterface, bounding_box: DAffine2, layer_transform: DAffine2) {
if let Some(gradient) = legacy_active_gradient_in_fill_node(fill_node_id, network_interface) {
let absolute = gradient.to_absolute(bounding_box, layer_transform);
let input = InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::<Fill>::INDEX);
network_interface.set_input(&input, NodeInput::value(TaggedValue::Fill(Fill::Gradient(absolute)), false), &[]);
}
if let Some(gradient) = legacy_backup_gradient_in_fill_node(fill_node_id, network_interface) {
let absolute = gradient.to_absolute(bounding_box, layer_transform);
let input = InputConnector::node(fill_node_id, graphene_std::vector::fill::BackupGradientInput::INDEX);
network_interface.set_input(&input, NodeInput::value(TaggedValue::FillGradient(absolute), false), &[]);
}
}
// TODO: Eventually remove this document upgrade code
/// Find every root-network "Fill" node holding a legacy bounding-box-relative gradient, either as its active `fill` or as its `_backup_gradient`.
///
/// Scans the document network structurally instead of walking each layer's primary flow, so it also catches fills on
/// secondary inputs and in hidden, disabled, or orphaned branches. Fills nested inside subgraph node networks are skipped.
pub fn legacy_gradient_fill_nodes(network_interface: &NodeNetworkInterface) -> Vec<NodeId> {
let fill_identifier = DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER);
network_interface
.document_network()
.nodes
.keys()
.copied()
.filter(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&fill_identifier))
.filter(|&node_id| legacy_active_gradient_in_fill_node(node_id, network_interface).is_some() || legacy_backup_gradient_in_fill_node(node_id, network_interface).is_some())
.collect()
}
/// Get the gradient stops of a layer, if any.
pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<GradientStops> {
// Try to find the gradient stops value that is created by a Fill node first
if let Some(fill_node_id) = get_fill_node_id_with_direct_fill_input(layer, network_interface) {
return network_interface
.document_network()
.nodes
.get(&fill_node_id)
.and_then(|node| node.inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX))
.and_then(|input| input.as_value())
.and_then(|value| if let TaggedValue::Gradient(gradient) = value { Some(gradient.clone()) } else { None });
}
let gradient_value_node = network_interface.document_network().nodes.get(&get_upstream_gradient_value_node_id(layer, network_interface)?)?;
let TaggedValue::Gradient(stops) = gradient_value_node.inputs.get(graphene_std::math_nodes::gradient_value::GradientInput::INDEX)?.as_value()? else {
return None;
@@ -383,8 +330,8 @@ pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNe
}
/// Compute the transform from a gradient's local space to viewport space for the given layer. For a `List<GradientStops>`
/// layer this is the layer's incoming footprint transform; for the legacy `Fill::Gradient` path it composes the layer's
/// viewport transform with the [0,1]² → bounding-box mapping.
/// layer this is the layer's incoming footprint transform; for a Fill-owned gradient value it composes the layer's viewport
/// transform with the [0,1]² → bounding-box mapping.
pub fn gradient_space_transform(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> glam::DAffine2 {
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
@@ -398,22 +345,14 @@ pub fn gradient_space_transform(layer: LayerNodeIdentifier, network_interface: &
.unwrap_or(metadata.document_to_viewport);
}
// TODO: Eventually remove this document upgrade code
// Only an existing legacy `Fill::Gradient` is in (0, 0)..(1, 1) bounding-box space; migrated and newly-created gradients are absolute (layer space).
if get_gradient(layer, network_interface).is_some_and(|gradient| !gradient.absolute) {
let bounds = metadata.nonzero_bounding_box(layer);
let bound_transform = glam::DAffine2::from_scale_angle_translation(bounds[1] - bounds[0], 0., bounds[0]);
return metadata.transform_to_viewport(layer) * bound_transform;
}
metadata.transform_to_viewport(layer)
}
/// True when start→end (mapped through `transform` into viewport space) points predominantly rightward. For purely
/// vertical lines we fall back to a stable tiebreaker on (x + y) so the choice doesn't flicker between equal alternatives.
pub fn gradient_orientation_rightward(start: glam::DVec2, end: glam::DVec2, transform: glam::DAffine2) -> bool {
let viewport_start = transform.transform_point2(start);
let viewport_end = transform.transform_point2(end);
pub fn gradient_orientation_rightward(transform: glam::DAffine2) -> bool {
let viewport_start = transform.transform_point2(DVec2::ZERO);
let viewport_end = transform.transform_point2(DVec2::X);
if (viewport_end.x - viewport_start.x).abs() > f64::EPSILON * 1e6 {
viewport_end.x > viewport_start.x
} else {
@@ -423,13 +362,11 @@ pub fn gradient_orientation_rightward(start: glam::DVec2, end: glam::DVec2, tran
/// Get the current fill of a layer from the closest "Fill" node.
pub fn get_fill_color(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Color> {
let fill_index = 1;
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
let &TaggedValue::Fill(Fill::Solid(color)) = inputs.get(fill_index)?.as_value()? else {
let &TaggedValue::Color(color) = inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? else {
return None;
};
Some(color)
color
}
/// Get the current blend mode of a layer from the closest upstream "Blend Mode" node.
@@ -680,22 +617,55 @@ pub fn set_stroke_weight_for_selected_layers(weight: f64, document: &DocumentMes
let value = TaggedValue::F64(weight);
responses.add(NodeGraphMessage::SetInputValue { node_id, input_index, value });
} else if weight > 0. {
let color = Some(Color::BLACK);
let stroke = graphene_std::vector::style::Stroke::default().with_weight(weight);
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
responses.add(GraphOperationMessage::StrokeSet { layer, color, stroke });
}
}
}
/// Returns the `Fill` value from a layer's upstream Fill node.
pub fn get_fill_value(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Fill> {
let fill_index = graphene_std::vector::fill::FillInput::<Fill>::INDEX;
let tagged = NodeGraphLayer::new(layer, network_interface).find_input(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER), fill_index)?;
if let TaggedValue::Fill(fill) = tagged { Some(fill.clone()) } else { None }
/// A Fill node's decoded gradient inputs, with the transform kept in its raw form (not yet baked into `start`/`end`).
pub struct FillNodeGradient {
pub stops: GradientStops,
pub gradient_type: GradientType,
pub spread_method: GradientSpreadMethod,
pub transform: DAffine2,
/// Whether the transform input holds a plain value (so it may be written to) rather than a wire.
pub transform_is_value: bool,
}
/// Decode a Fill node's gradient metadata inputs, resolving an unset transform to the default over `bounding_box`. Returns `None` when the fill input isn't a gradient value.
pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOnce() -> [DVec2; 2]) -> Option<FillNodeGradient> {
use graphene_std::vector::fill;
let TaggedValue::Gradient(stops) = fill_node.inputs.get(fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? else {
return None;
};
let gradient_type = match fill_node.inputs.get(fill::GradientTypeInput::INDEX).and_then(|input| input.as_value()) {
Some(&TaggedValue::GradientType(value)) => value,
_ => GradientType::default(),
};
let spread_method = match fill_node.inputs.get(fill::SpreadMethodInput::INDEX).and_then(|input| input.as_value()) {
Some(&TaggedValue::GradientSpreadMethod(value)) => value,
_ => GradientSpreadMethod::default(),
};
let transform_input = fill_node.inputs.get(fill::TransformInput::INDEX).and_then(|input| input.as_value());
let transform = match transform_input {
Some(&TaggedValue::OptionalDAffine2(value)) => value.unwrap_or_else(|| initial_gradient_transform_for_bounding_box(bounding_box())),
_ => DAffine2::IDENTITY,
};
Some(FillNodeGradient {
stops: stops.clone(),
gradient_type,
spread_method,
transform,
transform_is_value: transform_input.is_some(),
})
}
/// Returns the stroke color from a layer's upstream Stroke node.
pub fn get_stroke_color(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Option<Color>> {
let color_index = graphene_std::vector::stroke::ColorInput::INDEX;
let color_index = graphene_std::vector::stroke::PaintInput::<List<Graphic>>::INDEX;
let tagged = NodeGraphLayer::new(layer, network_interface).find_input(&DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER), color_index)?;
if let TaggedValue::Color(color) = tagged { Some(*color) } else { None }
}
@@ -722,10 +692,21 @@ pub struct SelectedStrokeState {
pub fn selected_fill_state(document: &DocumentMessageHandler) -> Option<SelectedFillState> {
let selected_nodes = document.network_interface.selected_nodes();
let mut per_layer = selected_nodes.selected_layers_except_artboards(&document.network_interface).map(|layer| {
if get_fill_id(layer, &document.network_interface).is_none() {
let Some(fill_node_id) = get_fill_id(layer, &document.network_interface) else {
return (false, FillChoice::None);
}
let fill_choice = get_fill_value(layer, &document.network_interface).map_or(FillChoice::None, FillChoice::from);
};
let fill_choice = (|| {
let fill_node = document.network_interface.document_network().nodes.get(&fill_node_id)?;
match fill_node.inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? {
&TaggedValue::Color(color) => Some(color.map_or(FillChoice::None, FillChoice::Solid)),
TaggedValue::Gradient(stops) => Some(FillChoice::Gradient(stops.clone())),
_ => None,
}
})()
.unwrap_or(FillChoice::None);
(true, fill_choice)
});
@@ -800,12 +781,40 @@ pub fn selected_stroke_state(document: &DocumentMessageHandler) -> Option<Select
pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
for layer in layers {
let existing_gradient = get_fill_value(layer, &document.network_interface).and_then(|f| match f {
Fill::Gradient(g) => Some(g),
_ => None,
});
let fill = fill_choice.clone().to_fill(existing_gradient.as_ref());
responses.add(GraphOperationMessage::FillSet { layer, fill });
match &fill_choice {
FillChoice::None => responses.add(GraphOperationMessage::FillColorSet { layer, color: None }),
FillChoice::Solid(color) => responses.add(GraphOperationMessage::FillColorSet { layer, color: Some(*color) }),
FillChoice::Gradient(stops) => {
let fill_node = NodeGraphLayer::new(layer, &document.network_interface)
.upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))
.and_then(|id| document.network_interface.document_network().nodes.get(&id));
let read = |index: usize| fill_node.and_then(|node| node.inputs.get(index)).and_then(|input| input.as_value());
let gradient_type = match read(graphene_std::vector::fill::GradientTypeInput::INDEX) {
Some(TaggedValue::GradientType(value)) => *value,
_ => GradientType::default(),
};
let spread_method = match read(graphene_std::vector::fill::SpreadMethodInput::INDEX) {
Some(TaggedValue::GradientSpreadMethod(value)) => *value,
_ => GradientSpreadMethod::default(),
};
let transform = match read(graphene_std::vector::fill::TransformInput::INDEX) {
Some(TaggedValue::OptionalDAffine2(value)) => {
value.unwrap_or_else(|| initial_gradient_transform_for_bounding_box(document.network_interface.document_metadata().nonzero_bounding_box(layer)))
}
_ => DAffine2::IDENTITY,
};
responses.add(GraphOperationMessage::FillGradientSet {
layer,
gradient: stops.clone(),
gradient_type,
spread_method,
transform,
});
}
}
}
}
@@ -816,12 +825,12 @@ pub fn set_stroke_color_for_selected_layers(color: Option<Color>, weight: f64, d
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
for layer in layers {
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
let input_index = graphene_std::vector::stroke::ColorInput::INDEX;
let input_index = graphene_std::vector::stroke::PaintInput::<List<Graphic>>::INDEX;
let value = TaggedValue::Color(color);
responses.add(NodeGraphMessage::SetInputValue { node_id, input_index, value });
} else {
let stroke = graphene_std::vector::style::Stroke::new(color, weight);
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
let stroke = graphene_std::vector::style::Stroke::new(weight);
responses.add(GraphOperationMessage::StrokeSet { layer, color, stroke });
}
}
}
@@ -4,7 +4,7 @@ use crate::messages::tool::common_functionality::color_selector::solid;
use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer;
use graphene_std::color::SRGBA8;
use graphene_std::raster::color::Color;
use graphene_std::vector::style::{Fill, FillChoiceUI};
use graphene_std::vector::style::FillChoiceUI;
#[derive(Default, ExtractField)]
pub struct FillTool {
@@ -161,14 +161,17 @@ impl Fsm for FillToolFsmState {
if NodeGraphLayer::is_raster_layer(layer_identifier, &mut document.network_interface) {
return self;
}
let fill = match color_event {
FillToolMessage::FillPrimaryColor => Fill::Solid(global_tool_data.primary_color),
FillToolMessage::FillSecondaryColor => Fill::Solid(global_tool_data.secondary_color),
let color = match color_event {
FillToolMessage::FillPrimaryColor => global_tool_data.primary_color,
FillToolMessage::FillSecondaryColor => global_tool_data.secondary_color,
_ => return self,
};
responses.add(DocumentMessage::AddTransaction);
responses.add(GraphOperationMessage::FillSet { layer: layer_identifier, fill });
responses.add(GraphOperationMessage::FillColorSet {
layer: layer_identifier,
color: Some(color),
});
FillToolFsmState::Filling
}
@@ -203,16 +206,16 @@ impl Fsm for FillToolFsmState {
mod test_fill {
pub use crate::test_utils::test_prelude::*;
use graphene_std::color::SRGBA8;
use graphene_std::list::List;
use graphene_std::vector::fill;
use graphene_std::vector::style::Fill;
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<Fill> {
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<List<Color>> {
let instrumented = match editor.eval_graph().await {
Ok(instrumented) => instrumented,
Err(e) => panic!("Failed to evaluate graph: {e}"),
};
instrumented.grab_all_input::<fill::FillInput<Fill>>(&editor.runtime).collect()
instrumented.grab_all_input::<fill::FillInput<List<Color>>>(&editor.runtime).collect()
}
#[tokio::test]
@@ -242,7 +245,8 @@ mod test_fill {
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::empty()).await;
let fills = get_fills(&mut editor).await;
assert_eq!(fills.len(), 1);
assert_eq!(SRGBA8::from(fills[0].as_solid().unwrap()), SRGBA8::from(Color::GREEN));
let color = fills.first().unwrap().element(0).expect("Color is stored in the list");
assert_eq!(SRGBA8::from(*color), SRGBA8::from(Color::GREEN));
}
#[tokio::test]
@@ -254,6 +258,7 @@ mod test_fill {
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::SHIFT).await;
let fills = get_fills(&mut editor).await;
assert_eq!(fills.len(), 1);
assert_eq!(SRGBA8::from(fills[0].as_solid().unwrap()), SRGBA8::from(Color::YELLOW));
let color = fills.first().unwrap().element(0).expect("Color is stored in the list");
assert_eq!(SRGBA8::from(*color), SRGBA8::from(Color::YELLOW));
}
}
File diff suppressed because it is too large. Load diff
@@ -2837,11 +2837,11 @@ impl Fsm for PathToolFsmState {
let layer = graph_modification_utils::new_custom(NodeId::new(), nodes, parent, responses);
// Defaults chosen because the pasted geometry has no inherent associated style
let stroke = graphene_std::vector::style::Stroke::new(Some(Color::BLACK), DEFAULT_STROKE_WIDTH);
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
let color = Some(Color::BLACK);
let stroke = graphene_std::vector::style::Stroke::new(DEFAULT_STROKE_WIDTH);
responses.add(GraphOperationMessage::StrokeSet { layer, color, stroke });
let fill = graphene_std::vector::style::Fill::solid(Color::WHITE);
responses.add(GraphOperationMessage::FillSet { layer, fill });
responses.add(GraphOperationMessage::FillColorSet { layer, color: Some(Color::WHITE) });
new_layers.push(layer);
@@ -24,7 +24,7 @@ use graphene_std::choice_type::ChoiceTypeStatic;
use graphene_std::color::SRGBA8;
use graphene_std::renderer::Quad;
use graphene_std::text::{Font, TextAlign, TypesettingConfig, lines_clipping};
use graphene_std::vector::style::{Fill, FillChoice, FillChoiceUI};
use graphene_std::vector::style::{FillChoice, FillChoiceUI};
use graphene_std::{Color, NodeInputDecleration};
#[derive(Default, ExtractField)]
@@ -571,9 +571,9 @@ impl TextToolData {
parent: document.new_layer_parent(true),
insert_index: 0,
});
responses.add(GraphOperationMessage::FillSet {
responses.add(GraphOperationMessage::FillColorSet {
layer: self.layer,
fill: editing_text.color.map_or(Fill::None, Fill::Solid),
color: editing_text.color,
});
let transform = editing_text.transform;
self.editing_text = Some(editing_text);
+148 -49
View File
@@ -1,10 +1,10 @@
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils;
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::EditorPreferences;
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
use graph_craft::proto::GraphErrors;
use graphene_std::application_io::{ExportFormat, NodeGraphUpdateMessage, RenderConfig, TimingInformation};
use graphene_std::bounds::RenderBoundingBox;
@@ -14,8 +14,8 @@ use graphene_std::memo::IORecord;
use graphene_std::raster::{CPU, Raster};
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
use graphene_std::transform::Footprint;
use graphene_std::vector::Vector;
use graphene_std::{ATTR_TRANSFORM, Context, Graphic};
use graphene_std::vector::{Vector, graphic_types};
use graphene_std::{ATTR_TRANSFORM, Context, Graphic, NodeInputDecleration};
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
use std::any::Any;
use std::sync::Arc;
@@ -68,6 +68,10 @@ pub struct NodeGraphExecutor {
// TODO: Eventually remove this document upgrade code
/// In-progress one-time pre-pass that converts legacy bounding-box-relative gradients to absolute space, if any.
gradient_migration: Option<GradientMigration>,
// TODO: Eventually remove this document upgrade code
/// Documents whose gradient migration pass already ran this session, so entries that failed to measure
/// (kept pending for a retry on the next open) don't re-run the pass on every render request.
gradient_migration_attempted: HashSet<DocumentId>,
}
#[derive(Debug, Clone)]
@@ -75,18 +79,20 @@ struct ExecutionContext {
export_config: Option<ExportConfig>,
document_id: DocumentId,
// TODO: Eventually remove this document upgrade code
/// Set when this execution is a gradient-migration measurement run for the given "Fill" node, whose evaluated geometry
/// is read back from the inspect result to size the gradient; such runs never touch the visible artwork.
measure_fill: Option<NodeId>,
/// Set when this execution is a gradient-migration measurement run, carrying the "Fill" node (addressed by its enclosing
/// network path) and its original relative gradient. The evaluated geometry is read back from the inspect result to size the
/// gradient; such runs never touch the visible artwork. Carrying the entry keeps a stale re-dispatched response paired with the fill it measured.
measure_fill: Option<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::Gradient)>,
}
// TODO: Eventually remove this document upgrade code
/// State for the deferred legacy-gradient migration: a queue of root-network "Fill" nodes still holding bounding-box-relative
/// gradients, measured one at a time by redirecting the document export to each so even hidden/orphaned branches evaluate.
/// State for the deferred legacy-gradient migration: a queue of "Fill" nodes (each addressed by its enclosing network path)
/// whose decomposed gradient still needs its transform baked, each paired with its original relative gradient and measured
/// one at a time by redirecting the document export so even hidden/orphaned/nested branches evaluate.
#[derive(Debug, Clone)]
struct GradientMigration {
document_id: DocumentId,
remaining: VecDeque<NodeId>,
remaining: VecDeque<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::Gradient)>,
resolution: UVec2,
scale: f64,
}
@@ -106,6 +112,7 @@ impl NodeGraphExecutor {
current_execution_id: 0,
previous_node_to_inspect: Vec::new(),
gradient_migration: None,
gradient_migration_attempted: HashSet::new(),
};
(node_runtime, node_executor)
}
@@ -342,6 +349,12 @@ impl NodeGraphExecutor {
}
pub fn poll_node_graph_evaluation(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, responses: &mut VecDeque<Message>) -> Result<(), String> {
// TODO: Eventually remove this document upgrade code
// A gradient migration belongs to one document; if the active document changed away from it, cancel so its stale in-flight response is ignored and revisiting restarts a fresh pass
if self.gradient_migration.as_ref().is_some_and(|migration| migration.document_id != document_id) {
self.cancel_gradient_migration();
}
let results = self.runtime_io.receive().collect::<Vec<_>>();
for response in results {
match response {
@@ -370,9 +383,9 @@ impl NodeGraphExecutor {
// TODO: Eventually remove this document upgrade code
// Gradient-migration measurement runs only read back the fill's evaluated geometry; they never render to the artwork.
// Apply only to the active document's in-progress migration, dropping responses left over from a document switch.
if let Some(fill_node_id) = execution_context.measure_fill {
if let Some(bake_target) = execution_context.measure_fill {
if execution_context.document_id == document_id && self.gradient_migration.as_ref().is_some_and(|migration| migration.document_id == document_id) {
self.handle_gradient_measurement(document, document_id, fill_node_id, result.ok().and(inspect_result), responses);
self.handle_gradient_measurement(document, document_id, bake_target, result.ok().and(inspect_result), responses);
}
continue;
}
@@ -463,20 +476,25 @@ impl NodeGraphExecutor {
// TODO: Eventually remove this document upgrade code
/// Kick off the one-time pre-pass converting legacy bounding-box gradients to absolute space, or no-op if already running.
pub(crate) fn drive_gradient_migration(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, resolution: UVec2, scale: f64, responses: &mut VecDeque<Message>) {
/// Returns false when the render should proceed normally instead: the pass already ran this session, so any entries still
/// pending are unmeasurable ones kept to retry on the next open.
pub(crate) fn drive_gradient_migration(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, resolution: UVec2, scale: f64, responses: &mut VecDeque<Message>) -> bool {
if self.gradient_migration_attempted.contains(&document_id) {
return false;
}
match &self.gradient_migration {
// Already running for this document
Some(migration) if migration.document_id == document_id => return,
Some(migration) if migration.document_id == document_id => return true,
// A different document's migration is in progress; cancel it so this one can run (the other restarts when revisited)
Some(_) => self.gradient_migration = None,
None => {}
}
let remaining: VecDeque<NodeId> = graph_modification_utils::legacy_gradient_fill_nodes(&document.network_interface).into_iter().collect();
let Some(&first_fill) = remaining.front() else {
document.pending_gradient_migration = false;
responses.add(NodeGraphMessage::RunDocumentGraph);
return;
// Snapshot the queue but leave `pending_gradient_bbox_bake` populated, so subsequent render requests keep deferring here (and hit the guard above); each entry is removed from the document as its bake lands.
let remaining: VecDeque<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::Gradient)> = document.pending_gradient_bbox_bake.iter().cloned().collect();
let Some((first_network_path, first_fill, first_gradient)) = remaining.front().cloned() else {
return false;
};
self.gradient_migration = Some(GradientMigration {
@@ -485,36 +503,39 @@ impl NodeGraphExecutor {
resolution,
scale,
});
self.dispatch_gradient_measurement(document, document_id, first_fill, resolution, scale, responses);
self.dispatch_gradient_measurement(document, document_id, first_network_path, first_fill, first_gradient, resolution, scale, responses);
true
}
// TODO: Eventually remove this document upgrade code
/// Run the graph with its export redirected to `fill_node_id` (so its branch evaluates even when hidden or orphaned) and
/// that node inspected, so its evaluated geometry returns in the execution response without touching the visible artwork.
/// Run the graph with its export chain redirected down to the (possibly nested) Fill at `network_path`/`fill_node_id`
/// (so its branch evaluates even when hidden or orphaned) and that node inspected, so its evaluated geometry returns
/// in the execution response without touching the visible artwork.
#[allow(clippy::too_many_arguments)]
fn dispatch_gradient_measurement(
&mut self,
document: &mut DocumentMessageHandler,
document_id: DocumentId,
network_path: Vec<NodeId>,
fill_node_id: NodeId,
gradient: graphic_types::migrations::legacy::Gradient,
resolution: UVec2,
scale: f64,
responses: &mut VecDeque<Message>,
) {
let mut network = document.network_interface.document_network().clone();
// On this throwaway clone, un-hide just the Fill so it's measured as a real Fill rather than a passthrough.
// On this throwaway clone, redirect each level's export down to the Fill, un-hiding the Fill and its enclosing subnetworks so it's measured as a real Fill rather than a passthrough.
// But upstream generators keep their visibility, so a hidden one intentionally contributes no geometry.
if let Some(node) = network.nodes.get_mut(&fill_node_id) {
node.visible = true;
}
let Some(export) = network.exports.first_mut() else {
// No export to redirect through, so skip this Fill rather than leaving the migration stuck
log::warn!("Gradient migration: document network has no export to redirect");
let full_path: Vec<NodeId> = network_path.iter().copied().chain(std::iter::once(fill_node_id)).collect();
if !redirect_export_chain(&mut network, &full_path) {
// The fill was deleted or is otherwise unreachable, so drop its stale entry instead of retrying it on every open
log::warn!("Gradient migration: could not redirect the document network's export chain to fill node {fill_node_id:?}; dropping its pending gradient bake");
remove_pending_gradient_bake(document, &network_path, fill_node_id);
self.advance_gradient_migration(document, document_id, responses);
return;
};
*export = NodeInput::node(fill_node_id, 0);
}
let resources = document.resources.registry.clone();
if self
@@ -522,7 +543,7 @@ impl NodeGraphExecutor {
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
node_to_inspect: vec![fill_node_id],
node_to_inspect: full_path.clone(),
}))
.is_err()
{
@@ -533,7 +554,7 @@ impl NodeGraphExecutor {
// Force the next normal render to recompile and re-send the real, non-redirected network
self.node_graph_hash = 0;
self.previous_node_to_inspect = vec![fill_node_id];
self.previous_node_to_inspect = full_path;
let viewport = Footprint {
transform: document.metadata().document_to_viewport,
@@ -556,26 +577,50 @@ impl NodeGraphExecutor {
ExecutionContext {
export_config: None,
document_id,
measure_fill: Some(fill_node_id),
measure_fill: Some((network_path, fill_node_id, gradient)),
},
));
}
// TODO: Eventually remove this document upgrade code
/// Convert the just-measured fill's legacy gradients to absolute space using its evaluated geometry, then advance the queue.
/// Bake the just-measured fill's gradient transform into absolute space using its evaluated geometry, then advance the queue.
fn handle_gradient_measurement(
&mut self,
document: &mut DocumentMessageHandler,
document_id: DocumentId,
fill_node_id: NodeId,
bake_target: (Vec<NodeId>, NodeId, graphic_types::migrations::legacy::Gradient),
inspect_result: Option<InspectResult>,
responses: &mut VecDeque<Message>,
) {
let measured = inspect_result.and_then(|mut result| result.take_data()).and_then(|data| measure_fill_geometry(&data));
let (network_path, fill_node_id, gradient) = bake_target;
match measured {
Some((bounding_box, item_transform)) => graph_modification_utils::migrate_fill_node_gradients_to_absolute(fill_node_id, &mut document.network_interface, bounding_box, item_transform),
None => log::warn!("Gradient migration could not measure geometry for fill node {fill_node_id:?}; leaving it in legacy space"),
// Ignore a stale response whose fill is no longer the one being measured (a re-dispatch after a document switch can leave two measurements in flight for the same entry)
let is_current = self
.gradient_migration
.as_ref()
.and_then(|migration| migration.remaining.front())
.is_some_and(|(front_path, front_fill, _)| *front_fill == fill_node_id && *front_path == network_path);
if !is_current {
return;
}
match inspect_result.and_then(|mut result| result.take_data()).and_then(|data| measure_fill_geometry(&data)) {
Some((bounding_box, item_transform)) => {
// Skip the bake if the user already placed this gradient themselves, but drop the now-superseded entry either way
if fill_transform_unbaked(document, &network_path, fill_node_id) {
let absolute_gradient = gradient.to_absolute(bounding_box, item_transform);
let gradient_transform = absolute_gradient.transform * absolute_gradient.to_transform();
let input = InputConnector::node(fill_node_id, graphene_std::vector::fill::TransformInput::INDEX);
document
.network_interface
.set_input(&input, NodeInput::value(TaggedValue::OptionalDAffine2(Some(gradient_transform)), false), &network_path);
}
// The transform is settled, so its entry no longer needs to persist for a retry on the next open
remove_pending_gradient_bake(document, &network_path, fill_node_id);
}
// Leave the entry pending so the next open retries it
None => log::warn!("Gradient migration could not measure geometry for fill node {fill_node_id:?}; leaving its transform unbaked and pending a retry on the next open"),
}
self.advance_gradient_migration(document, document_id, responses);
@@ -584,23 +629,30 @@ impl NodeGraphExecutor {
// TODO: Eventually remove this document upgrade code
/// Move to the next queued fill, or finish the migration and trigger a normal render once the queue is empty.
fn advance_gradient_migration(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, responses: &mut VecDeque<Message>) {
let next_fill = self.gradient_migration.as_mut().and_then(|migration| {
let next = self.gradient_migration.as_mut().and_then(|migration| {
migration.remaining.pop_front();
migration.remaining.front().copied()
migration.remaining.front().cloned()
});
if let Some(next_fill) = next_fill {
if let Some((next_network_path, next_fill, next_gradient)) = next {
let (resolution, scale) = self.gradient_migration.as_ref().map(|migration| (migration.resolution, migration.scale)).unwrap_or((UVec2::ONE, 1.));
self.dispatch_gradient_measurement(document, document_id, next_fill, resolution, scale, responses);
self.dispatch_gradient_measurement(document, document_id, next_network_path, next_fill, next_gradient, resolution, scale, responses);
} else {
self.gradient_migration = None;
self.previous_node_to_inspect = Vec::new();
self.node_graph_hash = 0;
document.pending_gradient_migration = false;
// Entries still pending failed to measure; they stay persisted for the next open while this marker stops re-runs this session
self.cancel_gradient_migration();
self.gradient_migration_attempted.insert(document_id);
responses.add(NodeGraphMessage::RunDocumentGraph);
}
}
// TODO: Eventually remove this document upgrade code
/// Tear down the in-progress migration and clear the stale inspect target and hash so the next normal render recompiles the real network.
fn cancel_gradient_migration(&mut self) {
self.gradient_migration = None;
self.previous_node_to_inspect = Vec::new();
self.node_graph_hash = 0;
}
fn process_node_graph_output(&mut self, node_graph_output: TaggedValue, responses: &mut VecDeque<Message>) -> Result<(), String> {
let TaggedValue::RenderOutput(render_output) = node_graph_output else {
return Err(format!("Invalid node graph output type: {node_graph_output:#?}"));
@@ -768,6 +820,53 @@ impl NodeGraphExecutor {
}
}
// TODO: Eventually remove this document upgrade code
/// Whether the fill node's transform input is still the unset `OptionalDAffine2(None)` placeholder that the migration leaves
/// behind, meaning its gradient placement has not yet been baked (or set by the user), so a measured bake may safely be written.
fn fill_transform_unbaked(document: &DocumentMessageHandler, network_path: &[NodeId], fill_node_id: NodeId) -> bool {
let Some(network) = document.network_interface.document_network().nested_network(network_path) else {
return false;
};
let Some(node) = network.nodes.get(&fill_node_id) else { return false };
matches!(
node.inputs.get(graphene_std::vector::fill::TransformInput::INDEX).and_then(|input| input.as_value()),
Some(TaggedValue::OptionalDAffine2(None))
)
}
// TODO: Eventually remove this document upgrade code
/// Remove a fill's entry from the document's persisted pending-bake list, either because its bake landed or because it is stale.
fn remove_pending_gradient_bake(document: &mut DocumentMessageHandler, network_path: &[NodeId], fill_node_id: NodeId) {
if let Some(index) = document
.pending_gradient_bbox_bake
.iter()
.position(|(path, node_id, _)| *node_id == fill_node_id && path == network_path)
{
document.pending_gradient_bbox_bake.remove(index);
}
}
// TODO: Eventually remove this document upgrade code
/// Redirect the primary export at each level of `network` down through the subnetwork nodes named by `full_path`,
/// un-hiding each so the innermost node's branch evaluates. Returns false if any step is missing or not a subnetwork.
fn redirect_export_chain(network: &mut NodeNetwork, full_path: &[NodeId]) -> bool {
let Some((node_id, deeper_path)) = full_path.split_first() else { return true };
let Some(export) = network.exports.first_mut() else { return false };
*export = NodeInput::node(*node_id, 0);
let Some(node) = network.nodes.get_mut(node_id) else { return false };
node.visible = true;
if deeper_path.is_empty() {
return true;
}
match &mut node.implementation {
DocumentNodeImplementation::Network(nested) => redirect_export_chain(nested, deeper_path),
_ => false,
}
}
// TODO: Eventually remove this document upgrade code
/// Turn a measured fill node's evaluated geometry into a `[0,1]² -> bounding box` affine plus the geometry's item transform.
fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2, DAffine2)> {
+4
View File
@@ -28,6 +28,10 @@ impl EditorTestUtils {
editor.handle_message(PortfolioMessage::Init);
// Enable the dual-write soak validation in tests so storage round-trip drift fails loud, matching
// the previous always-on-in-debug behavior now that it is gated by a preference.
editor.handle_message(PreferencesMessage::ValidateStorageRoundTrip { enabled: true });
Self { editor, runtime }
}
+1 -1
View File
@@ -94,7 +94,7 @@ export function createPortfolioStore(subscriptions: SubscriptionsRouter, editor:
});
subscriptions.subscribeFrontendMessage("TriggerOpen", async () => {
const files = await upload(`image/*,.${editor.fileExtension()}`, "data", true);
const files = await upload(`image/*,.${editor.fileExtension()},.${editor.gddFileExtension()}`, "data", true);
files.forEach((file) => editor.openFile(file.filename, file.content));
});
+11 -2
View File
@@ -13,7 +13,7 @@ use crate::{EDITOR_HAS_CRASHED, Error, FRONTEND_READY, MESSAGE_BUFFER};
#[cfg(not(feature = "native"))]
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
use editor::application::{Editor, Environment, Host, Platform};
use editor::consts::FILE_EXTENSION;
use editor::consts::{FILE_EXTENSION, GDD_FILE_EXTENSION};
use editor::messages::clipboard::utility_types::ClipboardContentRaw;
use editor::messages::input_mapper::utility_types::input_keyboard::ModifierKeys;
use editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, ScrollDelta};
@@ -95,7 +95,10 @@ impl EditorWrapper {
let application_io = PlatformApplicationIo::new().await;
let wake = crate::helpers::async_wake_callback();
let editor = Editor::new(Environment { platform: Platform::Web, host }, uuid_random_seed, storage, application_io, wake);
// On web the working-copy root is an OPFS directory name (no real filesystem path); each
// document mounts under `documents/<id_hex>`.
let working_copy_root = Some(std::path::PathBuf::from("documents"));
let editor = Editor::new(Environment { platform: Platform::Web, host }, uuid_random_seed, storage, working_copy_root, application_io, wake);
if EDITOR.with(|slot| slot.lock().ok().map(|mut guard| *guard = Some(editor))).is_none() {
log::error!("Attempted to initialize the editor more than once");
@@ -333,6 +336,12 @@ impl EditorWrapper {
FILE_EXTENSION.into()
}
/// Get the constant `GDD_FILE_EXTENSION`
#[wasm_bindgen(js_name = gddFileExtension)]
pub fn gdd_file_extension(&self) -> String {
GDD_FILE_EXTENSION.into()
}
/// Update the value of a given UI widget, but don't commit it to the history (unless `commit_layout()` is called, which handles that)
#[wasm_bindgen(js_name = widgetValueUpdate)]
pub fn widget_value_update(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
+2 -2
View File
@@ -102,7 +102,7 @@ Instead of manually implementing the `Node` trait with complex generics, one can
```rs
#[node_macro::node(category("Raster: Adjustments"))]
fn opacity(_input: (), #[default(424242)] color: Color, #[soft_min(0.1)] opacity_multiplier: f64) -> Color {
fn opacity(_input: (), #[default(424242)] color: Color, #[range] #[soft(0..100)] opacity_multiplier: f64) -> Color {
let opacity_multiplier = opacity_multiplier as f32 / 100.;
Color::from_rgbaf32_unchecked(color.r(), color.g(), color.b(), color.a() * opacity_multiplier)
}
@@ -110,7 +110,7 @@ fn opacity(_input: (), #[default(424242)] color: Color, #[soft_min(0.1)] opacity
## Additional Macro Options
The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `min`, `max` and `range_mode` attributes to influence how the properties are generated.
The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, and `range` attributes to influence how the properties are generated. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`.
## Executing a document `NodeNetwork`
+12 -8
View File
@@ -13,7 +13,7 @@ pub use dyn_any::StaticType;
pub use glam::{DAffine2, DVec2, IVec2, UVec2};
use graphene_application_io::resource::ResourceHash;
use graphic_types::raster_types::{CPU, Image, Raster};
use graphic_types::vector_types::vector::style::{Fill, Gradient, GradientStops};
use graphic_types::vector_types::vector::style::GradientStops;
use graphic_types::vector_types::vector::{self, ReferencePoint};
use graphic_types::{Artboard, Graphic, Vector};
use rendering::RenderMetadata;
@@ -65,7 +65,7 @@ macro_rules! tagged_value {
#[serde(alias = "ColorTable", alias = "OptionalColor", alias = "ColorNotInTable")]
Color(Option<Color>),
/// Stored compactly as a `GradientStops`, materializes as a single-row `List<GradientStops>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
/// (Old documents that stored a full `Gradient` struct under this same `"Gradient"` tag are routed to `FillGradient` by `deserialize_tagged_value_with_legacy_migration`.)
/// (Old documents that stored a full `Gradient` struct under this same `"Gradient"` tag are routed to `LegacyGradient` by `deserialize_tagged_value_with_legacy_migration`.)
#[serde(deserialize_with = "graphic_types::vector_types::gradient::migrate_to_gradient_stops")] // TODO: Eventually remove this migration document upgrade code
#[serde(alias = "GradientTable", alias = "GradientPositions", alias = "GradientStops")]
Gradient(GradientStops),
@@ -402,7 +402,9 @@ tagged_value! {
DVec2(DVec2),
#[serde(alias = "Affine2")]
DAffine2(DAffine2),
FillGradient(Gradient),
OptionalDAffine2(Option<DAffine2>),
#[serde(alias = "FillGradient")]
LegacyGradient(graphic_types::migrations::legacy::Gradient),
Font(Font),
Footprint(Footprint),
VectorModification(Box<VectorModification>),
@@ -411,7 +413,8 @@ tagged_value! {
// ==========
// ENUM TYPES
// ==========
Fill(vector::style::Fill),
#[serde(alias = "Fill")]
LegacyFill(graphic_types::migrations::legacy::Fill),
BlendMode(core_types::blending::BlendMode),
LuminanceCalculation(raster_nodes::adjustments::LuminanceCalculation),
QRCodeErrorCorrectionLevel(vector_nodes::generator_nodes::QRCodeErrorCorrectionLevel),
@@ -583,8 +586,9 @@ impl TaggedValue {
// `Color` (not in a `List`) is still currently needed by `BlackAndWhiteNode` and `ColorOverlayNode` GPU `shader_node(PerPixelAdjust)` variants
() if ty == TypeId::of::<Color>() => to_color(string).map(|color| TaggedValue::Color(Some(color)))?,
() if ty == TypeId::of::<List<Color>>() => to_color(string).map(|color| TaggedValue::Color(Some(color)))?,
// The Fill and Stroke nodes' paint connectors default to `List<Graphic>`, their first registered implementation row
() if ty == TypeId::of::<List<Graphic>>() => to_color(string).map(|color| TaggedValue::Color(Some(color)))?,
() if ty == TypeId::of::<List<GradientStops>>() => to_gradient(string).map(TaggedValue::Gradient)?,
() if ty == TypeId::of::<Fill>() => to_color(string).map(|color| TaggedValue::Fill(Fill::solid(color)))?,
() if ty == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?,
_ => return None,
};
@@ -652,11 +656,11 @@ pub fn deserialize_tagged_value_with_legacy_migration<'de, D: serde::Deserialize
}
return Ok(MemoHash::new(TaggedValue::TypeDefault(descriptor!(List<Vector>))));
}
// The `Gradient` tag was reused: it used to carry a full `Gradient` struct (now `FillGradient`), and now carries an `Option<GradientStops>`.
// The `Gradient` tag was reused: it used to carry a full `Gradient` struct (now `LegacyGradient`), and now carries an `Option<GradientStops>`.
// Disambiguate by payload shape: a Gradient struct has `start`/`end` keys; a `GradientStops` has none of those (it has `position`/`midpoint`/`color`).
"Gradient" if content.as_object().is_some_and(|c| c.contains_key("start") && c.contains_key("end")) => {
let gradient: Gradient = serde_json::from_value(content.clone()).map_err(serde::de::Error::custom)?;
return Ok(MemoHash::new(TaggedValue::FillGradient(gradient)));
let gradient: graphic_types::migrations::legacy::Gradient = serde_json::from_value(content.clone()).map_err(serde::de::Error::custom)?;
return Ok(MemoHash::new(TaggedValue::LegacyGradient(gradient)));
}
_ => {}
}
@@ -127,6 +127,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => IVec2]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => DVec2]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => DAffine2]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Option<DAffine2>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => bool]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => f64]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => u32]),
@@ -136,13 +137,11 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::application_io::resource::Resource]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::transform::ReferencePoint]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::BooleanOperation]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::Fill]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeCap]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeJoin]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::PaintOrder]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeAlign]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::Stroke]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::Gradient]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Box<graphene_std::vector::VectorModification>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::CentroidType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::PointSpacingType]),
@@ -249,14 +248,12 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => glam::f32::Vec2]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => glam::f32::Affine2]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::Stroke]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::Gradient]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::text::Font]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<BrushStroke>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => DocumentNode]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::ContextFeatures]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::Footprint]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Box<graphene_std::vector::VectorModification>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::Fill]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::blending::BlendMode]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::LuminanceCalculation]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::QRCodeErrorCorrectionLevel]),
@@ -673,6 +673,21 @@ impl ItemAttributeValues {
}
self.0.push((to_key, value));
}
/// Clones the attribute with `key` from `source`, replacing any existing attribute with the same key.
pub fn insert_cloned_from(&mut self, source: &Self, key: &str) {
let Some((_, value)) = source.0.iter().find(|(existing_key, _)| existing_key == key) else {
return;
};
let value = value.clone();
if let Some((_, existing_value)) = self.0.iter_mut().find(|(existing_key, _)| existing_key == key) {
*existing_value = value;
} else {
self.0.push((key.to_string(), value));
}
}
}
// ==========
@@ -30,9 +30,13 @@ pub struct FieldMetadata {
pub widget_override: RegistryWidgetOverride,
pub value_source: RegistryValueSource,
pub default_type: Option<Type>,
pub number_min: Option<f64>,
pub number_max: Option<f64>,
pub number_mode_range: Option<(f64, f64)>,
/// The slider's suggested extent, from `#[soft(a..b)]`. Typed values may exceed it.
pub number_soft_min: Option<f64>,
pub number_soft_max: Option<f64>,
/// The enforced clamp, from `#[hard(a..b)]`. Applied to typed values and at eval time.
pub number_hard_min: Option<f64>,
pub number_hard_max: Option<f64>,
pub number_mode_range: bool,
pub number_display_decimal_places: Option<u32>,
pub number_step: Option<f64>,
pub unit: Option<&'static str>,
+55 -126
View File
@@ -1,17 +1,16 @@
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::graphene_hash::CacheHash;
use core_types::list::{ATTR_FILL, ATTR_STROKE, Item, List};
use core_types::list::{ATTR_FILL, ATTR_STROKE, ItemAttributeValues, List};
use core_types::ops::{FromAnchorPosition, ListConvert};
use core_types::render_complexity::RenderComplexity;
use core_types::uuid::NodeId;
use core_types::{ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_GRADIENT_TYPE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_SPREAD_METHOD, ATTR_TRANSFORM, Color};
use core_types::{ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
use dyn_any::DynAny;
use glam::{DAffine2, DVec2};
use raster_types::{CPU, GPU, Raster};
use std::borrow::Cow;
use vector_types::GradientStops;
pub use vector_types::Vector;
use vector_types::vector::style::Fill;
/// The possible forms of graphical content that can be rendered by the Render node into either an image or SVG syntax.
#[derive(Clone, Debug, CacheHash, PartialEq, DynAny)]
@@ -191,133 +190,64 @@ fn flatten_graphic_list<T>(content: List<Graphic>, extract_variant: fn(Graphic)
output
}
/// Converts a `Fill` enum into the `List<Graphic>` representation used as paint storage.
/// TODO: Remove once all fill paint sources flow through `List<Graphic>` directly without going through the `Fill` enum.
pub fn fill_to_graphic_list(fill: &Fill) -> Option<List<Graphic>> {
match fill {
Fill::None => None,
Fill::Solid(color) => Some(List::new_from_element((*color).into())),
Fill::Gradient(gradient) => {
let gradient_item = Item::new_from_element(gradient.stops.clone())
.with_attribute(ATTR_TRANSFORM, gradient.transform * gradient.to_transform())
.with_attribute(ATTR_GRADIENT_TYPE, gradient.gradient_type)
.with_attribute(ATTR_SPREAD_METHOD, gradient.spread_method);
let gradient_list = List::new_from_item(gradient_item);
Some(List::new_from_element(Graphic::Gradient(gradient_list)))
}
}
/// Whether a normalized paint graphic list actually carries renderable paint.
/// A 0-item list, or a list whose first graphic is empty, is treated as no paint.
pub fn is_paint_present(graphic_list: &List<Graphic>) -> bool {
graphic_list.element(0).is_some_and(|graphic| !graphic.is_empty())
}
/// Converts a `Color` into the `List<Graphic>` representation used as paint storage.
/// TODO: Remove once all stroke paint sources flow through `List<Graphic>` directly without going through `Stroke.color`.
pub fn color_to_graphic_list(color: Option<Color>) -> Option<List<Graphic>> {
color.as_ref().map(|color| List::new_from_element((*color).into()))
}
/// Look up the paint graphics stored under attribute for a vector item, normalizing any graphic list type to `List<Graphic>`.
/// Look up the paint graphics stored under attribute for a vector item, in the canonical `List<Graphic>` form.
pub fn graphic_list_at<'a>(list: &'a List<Vector>, index: usize, attribute: &str) -> Option<Cow<'a, List<Graphic>>> {
list.attribute::<List<Graphic>>(attribute, index)
.map(Cow::Borrowed)
.or_else(|| list.attribute::<List<Color>>(attribute, index).map(|c| Cow::Owned(c.clone().into_graphic_list())))
.or_else(|| list.attribute::<List<GradientStops>>(attribute, index).map(|g| Cow::Owned(g.clone().into_graphic_list())))
.or_else(|| list.attribute::<List<Vector>>(attribute, index).map(|v| Cow::Owned(v.clone().into_graphic_list())))
.or_else(|| list.attribute::<List<Raster<CPU>>>(attribute, index).map(|r| Cow::Owned(r.clone().into_graphic_list())))
.or_else(|| list.attribute::<List<Raster<GPU>>>(attribute, index).map(|r| Cow::Owned(r.clone().into_graphic_list())))
// Treat a blank attribute as absent so consumers fall back to the legacy `style` instead of masking it.
.filter(|graphic_list| graphic_list.element(0).is_some_and(|graphic| !graphic.is_empty()))
// Treat a blank paint attribute as absent so an empty attribute doesn't count as painted
.filter(|graphic_list| is_paint_present(graphic_list))
}
/// Whether the item carries a non-blank paint attribute in any representation (`Graphic`, `Color`,
/// `GradientStops`, `Vector`, or raster), checked by borrowing without cloning the renderable list.
/// Whether the item carries a non-blank canonical `List<Graphic>` paint attribute,
/// checked by borrowing without cloning the renderable list.
pub fn has_paint_at(list: &List<Vector>, index: usize, attribute: &str) -> bool {
list.attribute::<List<Graphic>>(attribute, index)
.is_some_and(|graphics| graphics.element(0).is_some_and(|graphic| !graphic.is_empty()))
|| list.attribute::<List<Color>>(attribute, index).is_some_and(|paint_list| !paint_list.is_empty())
|| list.attribute::<List<GradientStops>>(attribute, index).is_some_and(|paint_list| !paint_list.is_empty())
|| list.attribute::<List<Vector>>(attribute, index).is_some_and(|paint_list| !paint_list.is_empty())
|| list.attribute::<List<Raster<CPU>>>(attribute, index).is_some_and(|paint_list| !paint_list.is_empty())
|| list.attribute::<List<Raster<GPU>>>(attribute, index).is_some_and(|paint_list| !paint_list.is_empty())
list.attribute::<List<Graphic>>(attribute, index).is_some_and(is_paint_present)
}
/// Look up the fill paint graphics for a vector item, falling back to the legacy
/// `style.fill` when the attribute is absent or empty.
/// TODO: Remove once all fill paint sources flow through `List<Graphic>` directly without going through the `Fill` enum.
pub fn fill_graphic_list_at(list: &List<Vector>, index: usize) -> Option<Cow<'_, List<Graphic>>> {
graphic_list_at(list, index, ATTR_FILL).or_else(|| {
let vector = list.element(index)?;
fill_to_graphic_list(vector.style.fill()).map(Cow::Owned)
})
/// Stores a paint attribute in its canonical `List<Graphic>` form, the only representation paint readers accept.
pub fn set_paint_attribute(attributes: &mut ItemAttributeValues, key: &str, paint: impl IntoGraphicList) {
attributes.insert(key, paint.into_graphic_list());
}
/// Look up the stroke paint graphics for a vector item, falling back to the legacy
/// `style.stroke.color` when the attribute is absent or empty.
/// TODO: Remove once all stroke paint sources flow through `List<Graphic>` directly without going through `Stroke.color`.
pub fn stroke_graphic_list_at(list: &List<Vector>, index: usize) -> Option<Cow<'_, List<Graphic>>> {
graphic_list_at(list, index, ATTR_STROKE).or_else(|| {
let vector = list.element(index)?;
color_to_graphic_list(vector.style.stroke().and_then(|s| s.color())).map(Cow::Owned)
})
/// Stores a paint attribute at a list index in its canonical `List<Graphic>` form, the only representation paint readers accept.
pub fn set_paint_attribute_at<T>(list: &mut List<T>, index: usize, key: &str, paint: impl IntoGraphicList) {
list.set_attribute(key, index, paint.into_graphic_list());
}
/// Check whether the fill paint for a vector item is fully opaque, falling back to
/// the legacy `style.fill` when the attribute is absent.
/// This avoids the `List<Graphic>` allocation that the legacy `Fill` fallback path performs.
/// TODO: Remove once all fill paint sources flow through `List<Graphic>` directly without going through the `Fill` enum.
pub fn is_fill_opaque_at(list: &List<Vector>, index: usize) -> bool {
if let Some(graphic_list) = graphic_list_at(list, index, ATTR_FILL) {
return graphic_list.element(0).is_some_and(|graphic| graphic.is_opaque());
/// Bake the provided transform into the per-item transforms of the paint graphics stored under the
/// canonical `List<Graphic>` fill and stroke attributes.
pub fn bake_paint_transforms(attributes: &mut ItemAttributeValues, transform: DAffine2) {
fn bake_list_transform<T>(list: &mut List<T>, transform: DAffine2) {
for item_transform in list.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
*item_transform = transform * *item_transform;
}
}
let Some(vector) = list.element(index) else { return false };
match vector.style.fill() {
Fill::None => false,
Fill::Solid(color) => color.is_opaque(),
Fill::Gradient(gradient) => gradient.stops.iter().all(|stop| stop.color.is_opaque()),
}
}
/// Check whether the fill paint for a vector item is fully transparent, falling back to
/// the legacy `style.fill` when the attribute is absent.
/// This avoids the `List<Graphic>` allocation that the legacy `Fill` fallback path performs.
/// TODO: Remove once all fill paint sources flow through `List<Graphic>` directly without going through the `Fill` enum.
pub fn is_fill_fully_transparent_at(list: &List<Vector>, index: usize) -> bool {
if let Some(graphic_list) = graphic_list_at(list, index, ATTR_FILL) {
return graphic_list.element(0).is_none_or(|graphic| graphic.is_fully_transparent());
fn bake_graphic_paint_transform(graphics: &mut List<Graphic>, transform: DAffine2) {
for graphic in graphics.iter_element_values_mut() {
match graphic {
Graphic::Graphic(list) => bake_list_transform(list, transform),
Graphic::Vector(list) => bake_list_transform(list, transform),
Graphic::RasterCPU(list) => bake_list_transform(list, transform),
Graphic::RasterGPU(list) => bake_list_transform(list, transform),
Graphic::Gradient(list) => bake_list_transform(list, transform),
Graphic::Text(list) => bake_list_transform(list, transform),
Graphic::Color(_) => {}
}
}
}
let Some(vector) = list.element(index) else { return false };
match vector.style.fill() {
Fill::None => true,
Fill::Solid(color) => color.a() == 0.,
Fill::Gradient(gradient) => gradient.stops.iter().all(|stop| stop.color.a() == 0.),
}
}
/// Check whether the stroke paint for a vector item is fully opaque, falling back to
/// the legacy `style.stroke.color` when the attribute is absent.
/// This avoids the `List<Graphic>` allocation that the legacy `Stroke.color` fallback path performs.
/// TODO: Remove once all stroke paint sources flow through `List<Graphic>` directly without going through `Stroke.color`.
pub fn is_stroke_opaque_at(list: &List<Vector>, index: usize) -> bool {
if let Some(graphic_list) = graphic_list_at(list, index, ATTR_STROKE) {
return graphic_list.element(0).is_some_and(|graphic| graphic.is_opaque());
for paint_key in [ATTR_FILL, ATTR_STROKE] {
if let Some(graphics) = attributes.get_mut::<List<Graphic>>(paint_key) {
bake_graphic_paint_transform(graphics, transform);
}
}
let Some(color) = list.element(index).and_then(|vector| vector.style.stroke()).and_then(|stroke| stroke.color()) else {
return false;
};
color.is_opaque()
}
/// Check whether the stroke paint for a vector item is fully transparent, falling back to
/// the legacy `style.stroke.color` when the attribute is absent.
/// This avoids the `List<Graphic>` allocation that the legacy `Stroke.color` fallback path performs.
/// TODO: Remove once all stroke paint sources flow through `List<Graphic>` directly without going through `Stroke.color`.
pub fn is_stroke_fully_transparent_at(list: &List<Vector>, index: usize) -> bool {
if let Some(graphic_list) = graphic_list_at(list, index, ATTR_STROKE) {
return graphic_list.element(0).is_none_or(|graphic| graphic.is_fully_transparent());
}
let Some(color) = list.element(index).and_then(|vector| vector.style.stroke()).and_then(|stroke| stroke.color()) else {
return true;
};
color.a() == 0.
}
/// Maps from a concrete element type to its corresponding `Graphic` enum variant,
@@ -357,7 +287,7 @@ impl TryFromGraphic for String {
}
// Local trait to convert types to List<Graphic> (avoids orphan rule issues)
pub trait IntoGraphicList {
pub trait IntoGraphicList: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static {
fn into_graphic_list(self) -> List<Graphic>;
/// Deeply flattens any content of type `T` within a `List<Graphic>`, discarding all other content, and returning a flat `List<T>`.
@@ -509,17 +439,10 @@ impl Graphic {
let Some(element) = vector.element(index) else { return false };
let opacity: f64 = vector.attribute_cloned_or(ATTR_OPACITY, index, 1.);
let fill_opaque_or_absent = match graphic_list_at(vector, index, ATTR_FILL) {
Some(graphic_list) => graphic_list.element(0).is_none_or(|graphic| graphic.is_opaque()),
None => element.style.fill().is_opaque(),
};
let fill_opaque_or_absent = graphic_list_at(vector, index, ATTR_FILL).is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_opaque()));
let stroke_invisible_or_transparent = element.style.stroke().is_none_or(|stroke| !stroke.has_renderable_stroke())
|| if let Some(graphic_list) = graphic_list_at(vector, index, ATTR_STROKE) {
graphic_list.element(0).is_none_or(|graphic| graphic.is_fully_transparent())
} else {
element.style.stroke().and_then(|stroke| stroke.color()).is_none_or(|color| color.a() == 0.)
};
let stroke_invisible_or_transparent = element.stroke.as_ref().is_none_or(|stroke| !stroke.has_renderable_stroke())
|| graphic_list_at(vector, index, ATTR_STROKE).is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_fully_transparent()));
opacity > 1. - f64::EPSILON && fill_opaque_or_absent && stroke_invisible_or_transparent
}),
@@ -531,13 +454,15 @@ impl Graphic {
match self {
Graphic::Graphic(list) => !list.is_empty() && list.iter_element_values().all(Graphic::is_opaque),
Graphic::Vector(list) => {
let is_paint_opaque_at = |key: &str, index: usize| graphic_list_at(list, index, key).is_some_and(|graphic_list| graphic_list.element(0).is_some_and(|graphic| graphic.is_opaque()));
!list.is_empty()
&& (0..list.len()).all(|i| {
let Some(vector) = list.element(i) else { return false };
let opacity: f64 = list.attribute_cloned_or(ATTR_OPACITY, i, 1.);
let opacity_fill: f64 = list.attribute_cloned_or(ATTR_OPACITY_FILL, i, 1.);
let fill_opaque = opacity_fill >= 1. - f64::EPSILON && is_fill_opaque_at(list, i);
let stroke_opaque_or_invisible = vector.style.stroke().is_none_or(|stroke| !stroke.has_renderable_stroke()) || is_stroke_opaque_at(list, i);
let fill_opaque = opacity_fill >= 1. - f64::EPSILON && is_paint_opaque_at(ATTR_FILL, i);
let stroke_opaque_or_invisible = vector.stroke.as_ref().is_none_or(|stroke| !stroke.has_renderable_stroke()) || is_paint_opaque_at(ATTR_STROKE, i);
opacity >= 1. - f64::EPSILON && fill_opaque && stroke_opaque_or_invisible
})
}
@@ -552,13 +477,16 @@ impl Graphic {
Graphic::Graphic(list) => list.iter_element_values().all(Graphic::is_fully_transparent),
Graphic::Vector(list) => (0..list.len()).all(|i| {
let Some(vector) = list.element(i) else { return false };
let is_paint_fully_transparent_at =
|key: &str, index: usize| graphic_list_at(list, index, key).is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_fully_transparent()));
let opacity: f64 = list.attribute_cloned_or(ATTR_OPACITY, i, 1.);
if opacity <= f64::EPSILON {
return true;
}
let opacity_fill: f64 = list.attribute_cloned_or(ATTR_OPACITY_FILL, i, 1.);
let fill_invisible = opacity_fill <= f64::EPSILON || is_fill_fully_transparent_at(list, i);
let stroke_invisible = vector.style.stroke().is_none_or(|stroke| !stroke.has_renderable_stroke()) || is_stroke_fully_transparent_at(list, i);
let fill_invisible = opacity_fill <= f64::EPSILON || is_paint_fully_transparent_at(ATTR_FILL, i);
let stroke_invisible = vector.stroke.as_ref().is_none_or(|stroke| !stroke.has_renderable_stroke()) || is_paint_fully_transparent_at(ATTR_STROKE, i);
fill_invisible && stroke_invisible
}),
Graphic::Color(list) => list.iter_element_values().all(|color| color.a() == 0.),
@@ -750,6 +678,7 @@ mod tests {
#[cfg(test)]
mod graphic_is_opaque_tests {
use core_types::ATTR_SPREAD_METHOD;
use vector_types::{GradientSpreadMethod, GradientStop};
use super::*;
+141 -17
View File
@@ -11,50 +11,174 @@ pub use artboard::Artboard;
pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector};
pub mod migrations {
use vector_types::vector::{PathStyle, PointDomain, RegionDomain, SegmentDomain, misc::HandleId};
use crate::Vector;
// Storing legacy structs that are only used in document migration.
// TODO: Eventually remove this migration document upgrade code
/// Returns the first `Vector` recovered from any of the legacy on-disk shapes (a single `Vector`, the old `OldVectorData` flat struct, or any of the historical `List<Vector>` variants).
pub fn migrate_to_optional_vector<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<Vector>, D::Error> {
use serde::Deserialize;
pub mod legacy {
use core_types::Color;
use dyn_any::DynAny;
use glam::{DAffine2, DVec2};
use vector_types::vector::{PointDomain, RegionDomain, SegmentDomain, misc::HandleId, style::Stroke};
use vector_types::{GradientStops, Vector, vector};
#[derive(Default, Debug, Clone, PartialEq, graphene_hash::CacheHash, DynAny, serde::Serialize, serde::Deserialize)]
pub struct Gradient {
pub stops: GradientStops,
pub gradient_type: vector::style::GradientType,
pub start: DVec2,
pub end: DVec2,
#[serde(default)]
pub spread_method: vector::style::GradientSpreadMethod,
#[serde(default)]
pub absolute: bool,
#[serde(default)]
pub transform: DAffine2,
}
impl Gradient {
/// Converts a legacy bounding-box-relative gradient (`start`/`end` in [0,1]) into an absolute one in the geometry's local space.
/// `bounding_box` maps [0,1] onto the geometry's bounding box; `layer_transform` is the layer's own transform,
/// used to bake the elliptical adjustment that reproduces the legacy isotropic radial through a non-uniform layer.
pub fn to_absolute(&self, bounding_box: DAffine2, layer_transform: DAffine2) -> Gradient {
let start = bounding_box.transform_point2(self.start);
let end = bounding_box.transform_point2(self.end);
let direction = end - start;
// The legacy radial drew as a circle in the layer's own space; bake the adjustment that, composed with the
// endpoint frame, makes the new pipeline reproduce that circle through the (possibly non-uniform) layer transform.
let radial_invertible = self.gradient_type == vector::style::GradientType::Radial
&& layer_transform.is_finite()
&& layer_transform.matrix2.determinant().recip().is_finite()
&& direction.length_squared() > 1e-20;
let transform = if radial_invertible {
let radius = (layer_transform.matrix2 * direction).length();
let circle = DAffine2 {
matrix2: glam::DMat2::from_diagonal(DVec2::splat(radius)),
translation: layer_transform.transform_point2(start),
};
let base = DAffine2::from_cols(direction, direction.perp(), start);
(layer_transform.inverse() * circle) * base.inverse()
} else {
DAffine2::IDENTITY
};
Gradient {
start,
end,
transform,
absolute: true,
..self.clone()
}
}
/// Builds the affine that places the gradient endpoints at `start` and `end` when applied to canonical gradient space (0, 0) -> (1, 0).
pub fn to_transform(&self) -> DAffine2 {
let direction = self.end - self.start;
DAffine2::from_cols(direction, direction.perp(), self.start)
}
}
#[derive(Default, Debug, Clone, PartialEq, graphene_hash::CacheHash, DynAny, serde::Serialize, serde::Deserialize)]
pub enum Fill {
#[default]
None,
Solid(Color),
Gradient(Gradient),
}
/// The legacy `fill` field is intentionally omitted because vector payload migration only
/// recovers editable vector data. The fill/stroke paints are migrated from the the node inputs.
#[derive(serde::Deserialize)]
#[cfg_attr(test, derive(Default, serde::Serialize))]
pub(super) struct PathStyle {
pub stroke: Option<Stroke>,
}
/// Old documents stored a `Vector` flattened with list attributes (`transform`, `alpha_blending`, `upstream_graphic_group`); only the geometry fields are recovered.
#[derive(serde::Deserialize)]
struct OldVectorData {
style: PathStyle,
colinear_manipulators: Vec<[HandleId; 2]>,
point_domain: PointDomain,
segment_domain: SegmentDomain,
region_domain: RegionDomain,
#[cfg_attr(test, derive(Default, serde::Serialize))]
pub(super) struct VectorData {
pub style: PathStyle,
pub colinear_manipulators: Vec<[HandleId; 2]>,
pub point_domain: PointDomain,
pub segment_domain: SegmentDomain,
pub region_domain: RegionDomain,
}
#[derive(serde::Deserialize)]
struct LegacyTable {
pub(super) struct Table {
#[serde(alias = "instances", alias = "instance")]
element: Vec<Vector>,
pub element: Vec<Vector>,
}
}
// TODO: Eventually remove this migration document upgrade code
/// Returns the first `Vector` recovered from any of the legacy on-disk shapes (the legacy `VectorData` flat struct, a single `Vector`, or any of the historical `List<Vector>` variants).
pub fn migrate_to_optional_vector<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<Vector>, D::Error> {
use serde::Deserialize;
#[derive(serde::Deserialize)]
#[serde(untagged)]
#[allow(clippy::large_enum_variant)]
enum VectorFormat {
// Old vector data must be tried first. Serde would otherwise ignore its `style` field and
// deserialize the missing optional `stroke` field as `None` in the current `Vector`.
OldVectorData(legacy::VectorData),
Vector(Vector),
OldVectorData(OldVectorData),
List(LegacyTable),
List(legacy::Table),
}
Ok(match VectorFormat::deserialize(deserializer)? {
VectorFormat::Vector(vector) => Some(vector),
VectorFormat::OldVectorData(old) => Some(Vector {
style: old.style,
stroke: old.style.stroke,
colinear_manipulators: old.colinear_manipulators,
point_domain: old.point_domain,
segment_domain: old.segment_domain,
region_domain: old.region_domain,
}),
VectorFormat::Vector(vector) => Some(vector),
VectorFormat::List(list) => list.element.into_iter().next(),
})
}
#[cfg(test)]
mod migration_tests {
use super::*;
use vector_types::vector::style::Stroke;
#[test]
fn preserves_stroke_from_old_vector_data_style() {
let old_vector = legacy::VectorData {
style: legacy::PathStyle { stroke: Some(Stroke::new(12.)) },
..Default::default()
};
let mut value = serde_json::to_value(old_vector).unwrap();
value
.as_object_mut()
.unwrap()
.get_mut("style")
.unwrap()
.as_object_mut()
.unwrap()
.insert("fill".into(), serde_json::to_value(legacy::Fill::default()).unwrap());
let migrated = migrate_to_optional_vector(value).unwrap().unwrap();
assert_eq!(migrated.stroke.unwrap().weight, 12.);
}
#[test]
fn preserves_stroke_from_current_vector_data() {
let vector = Vector {
stroke: Some(Stroke::new(12.)),
..Default::default()
};
let value = serde_json::to_value(&vector).unwrap();
let migrated = migrate_to_optional_vector(value).unwrap().unwrap();
assert_eq!(migrated.stroke.unwrap().weight, 12.);
}
}
}
+38 -38
View File
@@ -21,12 +21,12 @@ use dyn_any::DynAny;
use glam::{DAffine2, DMat2, DVec2};
use graphene_hash::CacheHashWrapper;
use graphene_resource::Resource;
use graphic_types::graphic::{fill_graphic_list_at, graphic_list_at, has_paint_at, stroke_graphic_list_at};
use graphic_types::graphic::{graphic_list_at, has_paint_at, is_paint_present, set_paint_attribute};
use graphic_types::raster_types::{BitmapMut, CPU, GPU, Image, Raster};
use graphic_types::vector_types::gradient::{GradientStops, GradientType};
use graphic_types::vector_types::subpath::Subpath;
use graphic_types::vector_types::vector::click_target::{ClickTarget, FreePoint};
use graphic_types::vector_types::vector::style::{Fill, PaintOrder, RenderMode, StrokeAlign, StrokeCap, StrokeJoin};
use graphic_types::vector_types::vector::style::{PaintOrder, RenderMode, StrokeAlign, StrokeCap, StrokeJoin};
use graphic_types::{Artboard, Graphic, Vector};
use kurbo::{Affine, BezPath, Cap, Join, Shape, StrokeOpts};
use num_traits::Zero;
@@ -459,12 +459,10 @@ pub struct RenderMetadata {
pub text_frames: HashMap<NodeId, DAffine2>,
pub clip_targets: HashSet<NodeId>,
pub vector_data: HashMap<NodeId, Arc<Vector>>,
/// Per-layer `ATTR_FILL` row attribute, exposed so message handlers can read paint
/// information that lives on the list rather than on `PathStyle.fill`.
/// Per-layer `ATTR_FILL` row attribute, exposed so message handlers can read it.
#[cfg_attr(feature = "serde", serde(skip))]
pub fill_attributes: HashMap<NodeId, Arc<List<Graphic>>>,
/// Per-layer `ATTR_STROKE` row attribute, exposed so message handlers can read
/// stroke paint information that lives on the list rather than on `Stroke.color`.
/// Per-layer `ATTR_STROKE` row attribute, exposed so message handlers can read it.
#[cfg_attr(feature = "serde", serde(skip))]
pub stroke_attributes: HashMap<NodeId, Arc<List<Graphic>>>,
pub backgrounds: Vec<Background>,
@@ -1067,7 +1065,7 @@ impl Render for List<Vector> {
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
// Only consider strokes with non-zero weight, since default strokes with zero weight would prevent assigning the correct stroke transform
let has_real_stroke = vector.style.stroke().filter(|stroke| stroke.weight() > 0.);
let has_real_stroke = vector.stroke.as_ref().filter(|stroke| stroke.weight() > 0.);
let set_stroke_transform = has_real_stroke.map(|stroke| stroke.transform).filter(|transform| transform_is_invertible(*transform));
let applied_stroke_transform = set_stroke_transform.unwrap_or(item_transform);
let applied_stroke_transform = render_params.alignment_parent_transform.unwrap_or(applied_stroke_transform);
@@ -1087,26 +1085,26 @@ impl Render for List<Vector> {
path.push_str(bezpath.to_svg().as_str());
}
let mask_type = if vector.style.stroke().map(|x| x.align) == Some(StrokeAlign::Inside) {
let mask_type = if vector.stroke.as_ref().map(|x| x.align) == Some(StrokeAlign::Inside) {
MaskType::Clip
} else {
MaskType::Mask
};
let fill_graphic_list = fill_graphic_list_at(self, index);
let fill_graphic_list = graphic_list_at(self, index, ATTR_FILL);
let fill_graphic = fill_graphic_list.as_ref().and_then(|l| l.element(0));
let stroke_graphic_list = stroke_graphic_list_at(self, index);
let stroke_graphic_list = graphic_list_at(self, index, ATTR_STROKE);
let stroke_graphic = stroke_graphic_list.as_ref().and_then(|l| l.element(0));
let path_is_closed = vector.stroke_bezier_paths().all(|path| path.closed());
let can_draw_aligned_stroke = path_is_closed
&& vector.style.stroke().is_some_and(|stroke| stroke.has_renderable_stroke() && stroke.align.is_not_centered())
&& vector.stroke.as_ref().is_some_and(|stroke| stroke.has_renderable_stroke() && stroke.align.is_not_centered())
&& stroke_graphic.is_some_and(|graphic| !graphic.is_fully_transparent());
let can_use_paint_order = !(fill_graphic.is_none_or(|graphic| !graphic.covers_opaquely()) || mask_type == MaskType::Clip);
let needs_separate_alignment_fill = can_draw_aligned_stroke && !can_use_paint_order;
let wants_stroke_below = vector.style.stroke().map(|s| s.paint_order) == Some(PaintOrder::StrokeBelow);
let wants_stroke_below = vector.stroke.as_ref().map(|s| s.paint_order) == Some(PaintOrder::StrokeBelow);
let override_paint_order = can_draw_aligned_stroke && can_use_paint_order;
let use_face_fill = vector.use_face_fill();
@@ -1127,12 +1125,13 @@ impl Render for List<Vector> {
let id = format!("alignment-{}", generate_uuid());
let mut cloned_vector = vector.clone();
cloned_vector.style.clear_stroke();
cloned_vector.style.set_fill(Fill::solid(Color::BLACK));
cloned_vector.stroke = None;
// The mask must draw at full alpha so the SVG `<mask>`/`<clipPath>` fully zeroes the path interior.
// The wrapping SVG group (above) handles the user-set opacity.
let vector_item = List::new_from_item(Item::new_from_element(cloned_vector).with_attribute(ATTR_TRANSFORM, item_transform));
let mut mask_item = Item::new_from_element(cloned_vector).with_attribute(ATTR_TRANSFORM, item_transform);
set_paint_attribute(mask_item.attributes_mut(), ATTR_FILL, List::new_from_element(Color::BLACK));
let vector_item = List::new_from_item(mask_item);
(id, mask_type, vector_item)
});
@@ -1166,7 +1165,7 @@ impl Render for List<Vector> {
if let Some((ref id, mask_type, ref vector_item)) = push_id {
let mut svg = SvgRender::new();
vector_item.render_svg(&mut svg, &render_params.for_alignment(applied_stroke_transform));
let stroke = vector.style.stroke().unwrap();
let stroke = vector.stroke.as_ref().unwrap();
// `push_id` is only `Some` when `can_draw_aligned_stroke`, which is gated on `path_is_closed`
let (largest_scale, _) = singular_values(applied_stroke_transform);
let inflation = stroke.max_aabb_inflation(true) * largest_scale;
@@ -1194,10 +1193,10 @@ impl Render for List<Vector> {
render_params.override_paint_order = override_paint_order;
let stroke_shape_attribute = vector
.style
.stroke()
.stroke
.as_ref()
.map(|stroke| {
if stroke_graphic_list.as_ref().and_then(|l| l.element(0)).is_some() {
if stroke_graphic_list.as_deref().is_some_and(is_paint_present) {
stroke.render(defs, item_transform, element_transform, applied_stroke_transform, bounds_matrix, &render_params, PaintTarget::Stroke)
} else {
String::new()
@@ -1206,7 +1205,7 @@ impl Render for List<Vector> {
.unwrap_or_default();
// Need to avoid generating only paint attribute, otherwise SVG uses 1px width stroke as a fallback
let stroke_visible = vector.style.stroke().is_some_and(|stroke| stroke.has_renderable_stroke()) && stroke_graphic.is_some_and(|g| !g.is_fully_transparent());
let stroke_visible = vector.stroke.as_ref().is_some_and(|stroke| stroke.has_renderable_stroke()) && stroke_graphic.is_some_and(|g| !g.is_fully_transparent());
let stroke_attribute = if stroke_visible {
stroke_graphic_list
.as_deref()
@@ -1281,7 +1280,7 @@ impl Render for List<Vector> {
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
let multiplied_transform = parent_transform * item_transform;
let has_real_stroke = element.style.stroke().filter(|stroke| stroke.weight() > 0.);
let has_real_stroke = element.stroke.as_ref().filter(|stroke| stroke.weight() > 0.);
let set_stroke_transform = has_real_stroke.map(|stroke| stroke.transform).filter(|transform| transform_is_invertible(*transform));
let mut applied_stroke_transform = set_stroke_transform.unwrap_or(multiplied_transform);
let mut element_transform = set_stroke_transform
@@ -1305,8 +1304,8 @@ impl Render for List<Vector> {
}
}
let fill_graphic_list = fill_graphic_list_at(self, index);
let stroke_graphic_list = stroke_graphic_list_at(self, index);
let fill_graphic_list = graphic_list_at(self, index, ATTR_FILL);
let stroke_graphic_list = graphic_list_at(self, index, ATTR_STROKE);
// If we're using opacity or a blend mode, we need to push a layer
let blend_mode = match render_params.render_mode {
@@ -1318,10 +1317,10 @@ impl Render for List<Vector> {
// Whether the renderer will engage the stroke-alignment compositing trick (non-Center align on a fully closed path).
// Used by both the blend-layer clip rect inflation below (as `max_aabb_inflation`'s `path_is_closed` arg, equivalent here since
// the function ignores the arg for Center align) and the `SrcIn`/`SrcOut` aligned-stroke branch further down.
let stroke = element.style.stroke();
let stroke = element.stroke.as_ref();
let stroke_fully_transparent = stroke_graphic_list.as_ref().is_none_or(|l| l.element(0).is_none_or(|g| g.is_fully_transparent()));
let can_draw_aligned_stroke =
!stroke_fully_transparent && stroke.as_ref().is_some_and(|s| s.has_renderable_stroke() && s.align.is_not_centered()) && element.stroke_bezier_paths().all(|p| p.closed());
!stroke_fully_transparent && stroke.is_some_and(|s| s.has_renderable_stroke() && s.align.is_not_centered()) && element.stroke_bezier_paths().all(|p| p.closed());
let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32;
if opacity < 1. || blend_mode_attr != BlendMode::default() {
@@ -1329,7 +1328,7 @@ impl Render for List<Vector> {
// `max_aabb_inflation` is in `applied_stroke_transform`-space; `layer_bounds` is path-local and `push_layer` re-applies `multiplied_transform`.
// Divide by the smaller axial scale to cover the stroke in both axes after Vello's transform. Skip on a degenerate transform.
let (_, smallest_scale) = singular_values(applied_stroke_transform);
let stroke_inflation = stroke.as_ref().map_or(0., |s| s.max_aabb_inflation(can_draw_aligned_stroke));
let stroke_inflation = stroke.map_or(0., |s| s.max_aabb_inflation(can_draw_aligned_stroke));
let inflate_amount = if smallest_scale > 0. { stroke_inflation / smallest_scale } else { 0. };
let quad = Quad::from_box(layer_bounds).inflate(inflate_amount);
let layer_bounds = quad.bounding_box();
@@ -1343,7 +1342,7 @@ impl Render for List<Vector> {
}
let use_layer = can_draw_aligned_stroke;
let wants_stroke_below = stroke.as_ref().is_some_and(|s| s.paint_order == vector::style::PaintOrder::StrokeBelow);
let wants_stroke_below = stroke.is_some_and(|s| s.paint_order == vector::style::PaintOrder::StrokeBelow);
let do_fill_path = |scene: &mut Scene, context: &mut RenderContext, path: &kurbo::BezPath, fill_rule: peniko::Fill| {
let Some(fill_graphic) = fill_graphic_list.as_deref() else { return };
@@ -1400,7 +1399,7 @@ impl Render for List<Vector> {
let do_stroke = |scene: &mut Scene, width_scale: f64, context: &mut RenderContext| {
let Some(stroke_graphic_list) = stroke_graphic_list.as_deref() else { return };
let Some(stroke) = element.style.stroke() else { return };
let Some(stroke) = stroke else { return };
for paint_index in 0..stroke_graphic_list.len() {
let Some(stroke_graphic) = stroke_graphic_list.element(paint_index) else {
@@ -1473,22 +1472,23 @@ impl Render for List<Vector> {
_ => {
if use_layer {
let mut cloned_element = element.clone();
cloned_element.style.clear_stroke();
cloned_element.style.set_fill(Fill::solid(Color::BLACK));
cloned_element.stroke = None;
// The mask must draw at full alpha so `SrcOut` fully zeroes the path interior.
// The outer opacity/blend layer (above) handles the user-set opacity.
let vector_list = List::new_from_item(Item::new_from_element(cloned_element).with_attribute(ATTR_TRANSFORM, item_transform));
let mut mask_item = Item::new_from_element(cloned_element).with_attribute(ATTR_TRANSFORM, item_transform);
set_paint_attribute(mask_item.attributes_mut(), ATTR_FILL, List::new_from_element(Color::BLACK));
let vector_list = List::new_from_item(mask_item);
let bounds = element.bounding_box_with_transform(multiplied_transform).unwrap_or(layer_bounds);
// This branch is gated on `can_draw_aligned_stroke`, which already requires every subpath is closed
let inflation = element.style.stroke().as_ref().map_or(0., |stroke| stroke.max_aabb_inflation(true));
let inflation = stroke.map_or(0., |stroke| stroke.max_aabb_inflation(true));
let (largest_scale, _) = singular_values(applied_stroke_transform);
let quad = Quad::from_box(bounds).inflate(inflation * largest_scale);
let bounds = quad.bounding_box();
let rect = kurbo::Rect::new(bounds[0].x, bounds[0].y, bounds[1].x, bounds[1].y);
let compose = if element.style.stroke().is_some_and(|x| x.align == StrokeAlign::Outside) {
let compose = if stroke.is_some_and(|x| x.align == StrokeAlign::Outside) {
peniko::Compose::SrcOut
} else {
peniko::Compose::SrcIn
@@ -1525,7 +1525,7 @@ impl Render for List<Vector> {
Stroke,
}
let order = match element.style.stroke().is_some_and(|stroke| !stroke.paint_order.is_default()) {
let order = match stroke.is_some_and(|stroke| !stroke.paint_order.is_default()) {
true => [Op::Stroke, Op::Fill],
false => [Op::Fill, Op::Stroke], // Default
};
@@ -1594,9 +1594,9 @@ impl Render for List<Vector> {
accumulated_outlines.entry(element_id).or_default().extend(outlines_unwrapped.into_iter().map(Arc::new));
// Source geometry (not the click-target override) so editing tools work on letterforms.
// Recorded together with `vector_data` from the same (first) row so `style` stays consistent with the paint.
// Recorded together with `vector_data` from the same (first) row so stroke geometry stays consistent with the paint.
// Only item 0 is recorded since editing tools can only target a single item currently.
// If that row has no paint attribute, none is recorded and consumers fall back to `style`.
// If that row has no paint attribute, none is recorded.
if let std::collections::hash_map::Entry::Vacant(e) = metadata.vector_data.entry(element_id) {
e.insert(Arc::new(source.clone()));
@@ -1666,14 +1666,14 @@ impl Render for List<Vector> {
/// Build one `CompoundPath` (non-zero fill rule, so holes like the inside of an "O" work
/// correctly) plus one `FreePoint` per disconnected anchor, apply the transform, and append.
fn extend_targets_from_vector(targets: &mut Vec<ClickTarget>, vector_list: &List<Vector>, index: usize, geometry: &Vector, transform: DAffine2) {
let filled = has_paint_at(vector_list, index, ATTR_FILL) || vector_list.element(index).is_some_and(|vector| !matches!(vector.style.fill(), Fill::None));
let filled = has_paint_at(vector_list, index, ATTR_FILL);
let mut subpaths: Vec<Subpath<_>> = geometry.stroke_bezier_paths().collect();
let all_subpaths_closed = subpaths.iter().all(|subpath| subpath.closed());
// Inside/Outside-aligned strokes reach `weight` from the centerline rather than `weight / 2` per side,
// so they need double the click inflation. Alignment is only honored by the renderer for fully-closed paths.
let stroke_width = geometry.style.stroke().map_or(0., |stroke| {
let stroke_width = geometry.stroke.as_ref().map_or(0., |stroke| {
if stroke.align.is_not_centered() && all_subpaths_closed {
stroke.weight * 2.
} else {
+50 -198
View File
@@ -2,7 +2,7 @@ use core_types::Color;
use core_types::color::SRGBA8;
use core_types::render_complexity::RenderComplexity;
use dyn_any::DynAny;
use glam::{DAffine2, DMat2, DVec2};
use glam::{DAffine2, DVec2};
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, Hash, graphene_hash::CacheHash, DynAny, node_macro::ChoiceType)]
@@ -458,6 +458,15 @@ impl GradientStops {
result
}
pub fn lerp(&self, other: &Self, time: f64) -> Self {
let stops = self.iter().zip(other.iter()).map(|(a, b)| {
let position = a.position + (b.position - a.position) * time;
let color = a.color.lerp(&b.color, time as f32);
GradientStop { position, midpoint: 0.5, color }
});
GradientStops::new(stops)
}
}
#[repr(C)]
@@ -482,184 +491,51 @@ impl GradientSpreadMethod {
}
}
/// A gradient fill.
///
/// Contains the start and end points, along with the colors at varying points along the length.
#[repr(C)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Debug, Clone, PartialEq, graphene_hash::CacheHash, DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Gradient {
pub stops: GradientStops,
pub gradient_type: GradientType,
pub start: DVec2,
pub end: DVec2,
#[cfg_attr(feature = "serde", serde(default))]
pub spread_method: GradientSpreadMethod,
// TODO: Eventually remove this document upgrade code
/// Whether `start`/`end` are absolute (layer-space) rather than in the legacy [0,1] bounding-box space.
/// Documents predating the gradient migration deserialize this as `false`; the deferred migration converts
/// them and sets it `true`. Once all documents are migrated, the legacy rendering path can be removed.
#[cfg_attr(feature = "serde", serde(default))]
pub absolute: bool,
// TODO: Eventually remove this document upgrade code
/// An extra frame adjustment composed onto the `start`/`end` frame (`transform * to_transform()`), letting the gradient
/// describe shapes the endpoint pair cannot, such as an elliptical radial. It defaults to identity, so existing documents
/// (which only have `start`/`end`) are unaffected; the migration stores a non-identity value only where it's needed.
#[cfg_attr(feature = "serde", serde(default))]
pub transform: DAffine2,
/// Rebuild the y-axis so its (parallel, perpendicular) components in the x-axis-aligned frame stay constant, both
/// rescaled by `|new_x| / |old_x|`. This holds the (x, y) parallelogram's aspect ratio and skew fixed across an endpoint
/// drag, so a radial ellipse stays the same shape (just rotated and resized) instead of distorting as x grows or shrinks.
/// Falls back to a +90° rotation of `new_x` when `old_x` is degenerate.
fn scale_y_axis_to_match_new_x(old_x: DVec2, old_y: DVec2, new_x: DVec2) -> DVec2 {
let old_x_length = old_x.length();
if old_x_length < 1e-9 {
return DVec2::new(-new_x.y, new_x.x);
}
let ex_old = old_x / old_x_length;
let ey_old = DVec2::new(-ex_old.y, ex_old.x);
let new_x_length = new_x.length();
if new_x_length < 1e-9 {
return DVec2::ZERO;
}
let ex_new = new_x / new_x_length;
let ey_new = DVec2::new(-ex_new.y, ex_new.x);
let parallel = old_y.dot(ex_old);
let perpendicular = old_y.dot(ey_old);
let scale = new_x_length / old_x_length;
scale * (parallel * ex_new + perpendicular * ey_new)
}
impl Default for Gradient {
fn default() -> Self {
Self {
stops: GradientStops::default(),
gradient_type: GradientType::Linear,
start: DVec2::new(0., 0.5),
end: DVec2::new(1., 0.5),
spread_method: GradientSpreadMethod::Pad,
// TODO: Eventually remove this document upgrade code
absolute: true,
transform: DAffine2::IDENTITY,
}
/// Build a new affine that maps canonical (0,0) -> (1,0) to (new_start, new_end), preserving the y-axis
/// shape of `old` proportionally to the x-axis length change.
pub fn build_transform_with_y_preservation(old: DAffine2, new_start: DVec2, new_end: DVec2) -> DAffine2 {
let new_x_axis = new_end - new_start;
let preserved_y_axis = scale_y_axis_to_match_new_x(old.matrix2.x_axis, old.matrix2.y_axis, new_x_axis);
DAffine2 {
matrix2: glam::DMat2::from_cols(new_x_axis, preserved_y_axis),
translation: new_start,
}
}
impl std::fmt::Display for Gradient {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let round = |x: f64| (x * 1e3).round() / 1e3;
let stops = self
.stops
.iter()
.map(|stop| format!("[{}%: #{}]", round(stop.position * 100.), SRGBA8::from(stop.color).to_rgba_hex()))
.collect::<Vec<_>>()
.join(", ");
write!(f, "{} Gradient: {stops}", self.gradient_type)
}
}
impl Gradient {
// TODO: Eventually remove this document upgrade code
/// Converts a legacy bounding-box-relative gradient (`start`/`end` in [0,1]) into an absolute one in the geometry's local space.
/// `bounding_box` maps [0,1] onto the geometry's bounding box; `layer_transform` is the layer's own transform,
/// used to bake the elliptical adjustment that reproduces the legacy isotropic radial through a non-uniform layer.
pub fn to_absolute(&self, bounding_box: DAffine2, layer_transform: DAffine2) -> Gradient {
let start = bounding_box.transform_point2(self.start);
let end = bounding_box.transform_point2(self.end);
let direction = end - start;
// The legacy radial drew as a circle in the layer's own space; bake the adjustment that, composed with the
// endpoint frame, makes the new pipeline reproduce that circle through the (possibly non-uniform) layer transform.
let radial_invertible =
self.gradient_type == GradientType::Radial && layer_transform.is_finite() && layer_transform.matrix2.determinant().recip().is_finite() && direction.length_squared() > 1e-20;
let transform = if radial_invertible {
let radius = (layer_transform.matrix2 * direction).length();
let circle = DAffine2 {
matrix2: DMat2::from_diagonal(DVec2::splat(radius)),
translation: layer_transform.transform_point2(start),
};
let base = DAffine2::from_cols(direction, direction.perp(), start);
(layer_transform.inverse() * circle) * base.inverse()
} else {
DAffine2::IDENTITY
};
Gradient {
start,
end,
transform,
// TODO: Eventually remove this document upgrade code
absolute: true,
..self.clone()
}
}
/// Constructs a new gradient with the colors at 0 and 1 specified.
pub fn new(start: DVec2, start_color: Color, end: DVec2, end_color: Color, gradient_type: GradientType, spread_method: GradientSpreadMethod) -> Self {
let stops = GradientStops::new([
GradientStop {
position: 0.,
midpoint: 0.5,
color: start_color,
},
GradientStop {
position: 1.,
midpoint: 0.5,
color: end_color,
},
]);
Self {
start,
end,
stops,
gradient_type,
spread_method,
// TODO: Eventually remove this document upgrade code
absolute: true,
transform: DAffine2::IDENTITY,
}
}
pub fn lerp(&self, other: &Self, time: f64) -> Self {
let start = self.start + (other.start - self.start) * time;
let end = self.end + (other.end - self.end) * time;
let stops = self.stops.iter().zip(other.stops.iter()).map(|(a, b)| {
let position = a.position + (b.position - a.position) * time;
let color = a.color.lerp(&b.color, time as f32);
GradientStop { position, midpoint: 0.5, color }
});
let stops = GradientStops::new(stops);
let gradient_type = if time < 0.5 { self.gradient_type } else { other.gradient_type };
let spread_method = if time < 0.5 { self.spread_method } else { other.spread_method };
Self {
start,
end,
stops,
gradient_type,
spread_method,
// TODO: Eventually remove this document upgrade code
absolute: self.absolute,
transform: if time < 0.5 { self.transform } else { other.transform },
}
}
/// Insert a stop into the gradient, the index if successful
pub fn insert_stop(&mut self, mouse: DVec2, transform: DAffine2) -> Option<usize> {
// Transform the start and end positions to the same coordinate space as the mouse.
let (start, end) = (transform.transform_point2(self.start), transform.transform_point2(self.end));
// Calculate the new position by finding the closest point on the line
let new_position = ((end - start).angle_to(mouse - start)).cos() * start.distance(mouse) / start.distance(end);
// Don't insert point past end of line
if !(0. ..=1.).contains(&new_position) {
return None;
}
// Compute the color of the inserted stop using evaluate (which respects midpoints)
let new_color = self.stops.evaluate(new_position);
// Compute the correct index to keep the positions in order
let mut index = 0;
while self.stops.len() > index && self.stops.position[index] <= new_position {
index += 1;
}
// Insert the new stop, duplicating the midpoint ratio of the interval being split
let inherited_midpoint = if index > 0 { self.stops.midpoint[index - 1] } else { 0.5 };
self.stops.position.insert(index, new_position);
self.stops.midpoint.insert(index, inherited_midpoint);
self.stops.color.insert(index, new_color);
Some(index)
}
/// Builds the affine that places the gradient endpoints at `start` and `end` when applied to canonical gradient space (0, 0) -> (1, 0).
pub fn to_transform(&self) -> DAffine2 {
let direction = self.end - self.start;
DAffine2::from_cols(direction, direction.perp(), self.start)
/// Build the default transform for a gradient not yet given one: a horizontal gradient spanning the
/// bounding box's width, running through its vertical middle.
pub fn initial_gradient_transform_for_bounding_box(bounds: [DVec2; 2]) -> DAffine2 {
let [min, max] = bounds;
let x_axis = DVec2::new(max.x - min.x, 0.);
DAffine2 {
matrix2: glam::DMat2::from_cols(x_axis, x_axis.perp()),
translation: DVec2::new(min.x, (min.y + max.y) / 2.),
}
}
@@ -699,27 +575,3 @@ impl core_types::bounds::BoundingBox for GradientStops {
core_types::bounds::RenderBoundingBox::Rectangle([start.min(end), start.max(end)])
}
}
#[cfg(test)]
mod tests {
use super::*;
use glam::DVec2;
fn linear_gradient(start: DVec2, end: DVec2) -> Gradient {
Gradient { start, end, ..Default::default() }
}
#[test]
fn to_transform_roundtrip() {
let cases = [(DVec2::ZERO, DVec2::X), (DVec2::new(10., 20.), DVec2::new(50., 30.)), (DVec2::new(-5., -5.), DVec2::new(5., 3.))];
for (start, end) in cases {
let transform = linear_gradient(start, end).to_transform();
let recovered_start = transform.transform_point2(DVec2::ZERO);
let recovered_end = transform.transform_point2(DVec2::X);
assert!((recovered_start - start).length() < 1e-10);
assert!((recovered_end - end).length() < 1e-10);
}
}
}
@@ -8,7 +8,6 @@ mod vector_modification;
mod vector_types;
pub use reference_point::*;
pub use style::PathStyle;
pub use vector_attributes::*;
pub use vector_modification::*;
pub use vector_types::*;
@@ -1,174 +1,16 @@
//! Contains stylistic options for SVG elements.
pub use crate::gradient::*;
use core_types::color::{Alpha, SRGBA8};
use core_types::list::List;
use core_types::Color;
use core_types::color::SRGBA8;
use core_types::transform::Transform;
use core_types::{ATTR_GRADIENT_TYPE, ATTR_OPACITY, ATTR_SPREAD_METHOD, ATTR_TRANSFORM, Color};
use dyn_any::DynAny;
use glam::DAffine2;
use glam::DVec2;
use std::f64::consts::{PI, TAU};
/// Describes the fill of a layer.
/// Describes an editable fill choice, storing color or gradient stops without gradient placement metadata.
///
/// Can be None, a solid [Color], or a linear/radial [Gradient].
///
/// In the future we'll probably also add a pattern fill. This will probably be named "Paint" in the future.
#[repr(C)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Default, Debug, Clone, PartialEq, graphene_hash::CacheHash, DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Fill {
#[default]
None,
Solid(Color),
Gradient(Gradient),
}
impl std::fmt::Display for Fill {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::None => write!(f, "None"),
Self::Solid(color) => write!(f, "#{} (Alpha: {}%)", SRGBA8::from(*color).to_rgb_hex(), color.a() * 100.),
Self::Gradient(gradient) => write!(f, "{gradient}"),
}
}
}
impl Fill {
/// Construct a new [Fill::Solid] from a [Color].
pub fn solid(color: Color) -> Self {
Self::Solid(color)
}
/// Construct a new [Fill::Solid] or [Fill::None] from an optional [Color].
pub fn solid_or_none(color: Option<Color>) -> Self {
match color {
Some(color) => Self::Solid(color),
None => Self::None,
}
}
/// Evaluate the color at some point on the fill. Doesn't currently work for Gradient.
pub fn color(&self) -> Color {
match self {
Self::None => Color::BLACK,
Self::Solid(color) => *color,
// TODO: Should correctly sample the gradient the equation here: https://svgwg.org/svg2-draft/pservers.html#Gradients
Self::Gradient(Gradient { stops, .. }) => {
if stops.is_empty() {
Color::BLACK
} else {
stops.color[0]
}
}
}
}
pub fn lerp(&self, other: &Self, time: f64) -> Self {
let transparent = Self::solid(Color::TRANSPARENT);
let a = if *self == Self::None && *other != Self::None { &transparent } else { self };
let b = if *other == Self::None && *self != Self::None { &transparent } else { other };
match (a, b) {
(Self::Solid(a), Self::Solid(b)) => Self::Solid(a.lerp(b, time as f32)),
(Self::Solid(a), Self::Gradient(b)) => {
let mut solid_to_gradient = b.clone();
solid_to_gradient.stops.color.iter_mut().for_each(|color| *color = *a);
let a = &solid_to_gradient;
Self::Gradient(a.lerp(b, time))
}
(Self::Gradient(a), Self::Solid(b)) => {
let mut gradient_to_solid = a.clone();
gradient_to_solid.stops.color.iter_mut().for_each(|color| *color = *b);
let b = &gradient_to_solid;
Self::Gradient(a.lerp(b, time))
}
(Self::Gradient(a), Self::Gradient(b)) => Self::Gradient(a.lerp(b, time)),
(Self::None, _) | (_, Self::None) => Self::None,
}
}
/// Extract a gradient from the fill
pub fn as_gradient(&self) -> Option<&Gradient> {
match self {
Self::Gradient(gradient) => Some(gradient),
_ => None,
}
}
/// Extract a solid color from the fill
pub fn as_solid(&self) -> Option<Color> {
match self {
Self::Solid(color) => Some(*color),
_ => None,
}
}
/// Find if fill can be represented with only opaque colors
pub fn is_opaque(&self) -> bool {
match self {
Fill::Solid(color) => color.is_opaque(),
Fill::Gradient(gradient) => gradient.stops.color.iter().all(|color| color.is_opaque()),
Fill::None => true,
}
}
/// Returns if fill is none
pub fn is_none(&self) -> bool {
*self == Self::None
}
}
impl From<Color> for Fill {
fn from(color: Color) -> Fill {
Fill::Solid(color)
}
}
impl From<Option<Color>> for Fill {
fn from(color: Option<Color>) -> Fill {
Fill::solid_or_none(color)
}
}
impl From<List<Color>> for Fill {
fn from(color: List<Color>) -> Fill {
let alpha: f64 = color.attribute_cloned_or(ATTR_OPACITY, 0, 1.);
let color = color.element(0).copied();
Fill::solid_or_none(color.map(|c| c.with_alpha(c.alpha() * alpha as f32)))
}
}
impl From<List<GradientStops>> for Fill {
fn from(gradient: List<GradientStops>) -> Fill {
let gradient_type = gradient.attribute_cloned_or_default::<GradientType>(ATTR_GRADIENT_TYPE, 0);
let spread_method = gradient.attribute_cloned_or_default::<GradientSpreadMethod>(ATTR_SPREAD_METHOD, 0);
let transform = gradient.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, 0);
Fill::Gradient(Gradient {
stops: gradient.element(0).cloned().unwrap_or_default(),
gradient_type,
spread_method,
start: transform.transform_point2(DVec2::ZERO),
end: transform.transform_point2(DVec2::X),
// TODO: Eventually remove this document upgrade code
absolute: true,
transform: DAffine2::IDENTITY,
})
}
}
impl From<Gradient> for Fill {
fn from(gradient: Gradient) -> Fill {
Fill::Gradient(gradient)
}
}
/// Describes the fill of a layer, but unlike [`Fill`], this doesn't store a [`Gradient`] directly but just its [`GradientStops`].
///
/// Can be None, a solid [Color], or a linear/radial [Gradient].
/// Can be None, a solid [Color], or a linear/radial [GradientStops].
///
/// In the future we'll probably also add a pattern fill.
///
@@ -262,30 +104,6 @@ impl FillChoice {
Self::Gradient(stops) => Some(stops.to_css_linear_gradient()),
}
}
/// Convert this [`FillChoice`] to a [`Fill`] using the provided [`Gradient`] as a base for the positional information of the gradient.
/// If a gradient isn't provided, default gradient positional information is used in cases where the [`FillChoice`] is a [`Gradient`].
pub fn to_fill(&self, existing_gradient: Option<&Gradient>) -> Fill {
match self {
Self::None => Fill::None,
Self::Solid(color) => Fill::Solid(*color),
Self::Gradient(stops) => {
let mut fill = existing_gradient.cloned().unwrap_or_default();
fill.stops = stops.clone();
Fill::Gradient(fill)
}
}
}
}
impl From<Fill> for FillChoice {
fn from(fill: Fill) -> Self {
match fill {
Fill::None => FillChoice::None,
Fill::Solid(color) => FillChoice::Solid(color),
Fill::Gradient(gradient) => FillChoice::Gradient(gradient.stops),
}
}
}
/// The stroke (outline) style of an SVG element.
@@ -389,8 +207,6 @@ fn daffine2_identity() -> DAffine2 {
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct Stroke {
/// Stroke color
pub color: Option<Color>,
/// Line thickness
pub weight: f64,
pub dash_lengths: Vec<f64>,
@@ -410,9 +226,8 @@ pub struct Stroke {
}
impl Stroke {
pub const fn new(color: Option<Color>, weight: f64) -> Self {
pub const fn new(weight: f64) -> Self {
Self {
color,
weight,
dash_lengths: Vec::new(),
dash_offset: 0.,
@@ -427,7 +242,6 @@ impl Stroke {
pub fn lerp(&self, other: &Self, time: f64) -> Self {
Self {
color: self.color.map(|color| color.lerp(&other.color.unwrap_or(color), time as f32)),
weight: self.weight + (other.weight - self.weight) * time,
dash_lengths: self.dash_lengths.iter().zip(other.dash_lengths.iter()).map(|(a, b)| a + (b - a) * time).collect(),
dash_offset: self.dash_offset + (other.dash_offset - self.dash_offset) * time,
@@ -463,11 +277,6 @@ impl Stroke {
}
}
/// Get the current stroke color.
pub fn color(&self) -> Option<Color> {
self.color
}
/// Get the current stroke weight.
pub fn weight(&self) -> f64 {
self.weight
@@ -533,12 +342,6 @@ impl Stroke {
self.join_miter_limit as f32
}
pub fn with_color(mut self, color: &Option<Color>) -> Option<Self> {
self.color = *color;
Some(self)
}
pub fn with_weight(mut self, weight: f64) -> Self {
self.weight = weight;
self
@@ -587,12 +390,10 @@ impl Stroke {
}
}
// Having an alpha of 1 to start with leads to a better experience with the properties panel
impl Default for Stroke {
fn default() -> Self {
Self {
weight: 0.,
color: Some(Color::BLACK),
dash_lengths: Vec::new(),
dash_offset: 0.,
cap: StrokeCap::Butt,
@@ -605,172 +406,6 @@ impl Default for Stroke {
}
}
#[repr(C)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Debug, Clone, PartialEq, Default, graphene_hash::CacheHash, DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PathStyle {
pub stroke: Option<Stroke>,
pub fill: Fill,
}
impl std::fmt::Display for PathStyle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let fill = &self.fill;
let stroke = match &self.stroke {
Some(stroke) => format!("#{} (Weight: {} px)", stroke.color.map_or("None".to_string(), |c| SRGBA8::from(c).to_rgba_hex()), stroke.weight),
None => "None".to_string(),
};
write!(f, "Fill: {fill}\nStroke: {stroke}")
}
}
impl PathStyle {
pub const fn new(stroke: Option<Stroke>, fill: Fill) -> Self {
Self { stroke, fill }
}
pub fn lerp(&self, other: &Self, time: f64) -> Self {
Self {
fill: self.fill.lerp(&other.fill, time),
stroke: match (self.stroke.as_ref(), other.stroke.as_ref()) {
(Some(a), Some(b)) => Some(a.lerp(b, time)),
(Some(a), None) => {
if time < 0.5 {
Some(a.clone())
} else {
None
}
}
(None, Some(b)) => {
if time < 0.5 {
Some(b.clone())
} else {
None
}
}
(None, None) => None,
},
}
}
/// Get the current path's [Fill].
///
/// # Example
/// ```
/// # use vector_types::vector::style::{Fill, PathStyle};
/// # use core_types::Color;
/// let fill = Fill::solid(Color::RED);
/// let style = PathStyle::new(None, fill.clone());
///
/// assert_eq!(*style.fill(), fill);
/// ```
pub fn fill(&self) -> &Fill {
&self.fill
}
pub fn fill_mut(&mut self) -> &mut Fill {
&mut self.fill
}
/// Get the current path's [Stroke].
///
/// # Example
/// ```
/// # use vector_types::vector::style::{Fill, Stroke, PathStyle};
/// # use core_types::Color;
/// let stroke = Stroke::new(Some(Color::GREEN), 42.);
/// let style = PathStyle::new(Some(stroke.clone()), Fill::None);
///
/// assert_eq!(style.stroke(), Some(stroke));
/// ```
pub fn stroke(&self) -> Option<Stroke> {
self.stroke.clone()
}
/// Replace the path's [Fill] with a provided one.
///
/// # Example
/// ```
/// # use vector_types::vector::style::{Fill, PathStyle};
/// # use core_types::Color;
/// let mut style = PathStyle::default();
///
/// assert_eq!(*style.fill(), Fill::None);
///
/// let fill = Fill::solid(Color::RED);
/// style.set_fill(fill.clone());
///
/// assert_eq!(*style.fill(), fill);
/// ```
pub fn set_fill(&mut self, fill: Fill) {
self.fill = fill;
}
pub fn set_stroke_transform(&mut self, transform: DAffine2) {
if let Some(stroke) = &mut self.stroke {
stroke.transform = transform;
}
}
/// Replace the path's [Stroke] with a provided one.
///
/// # Example
/// ```
/// # use vector_types::vector::style::{Stroke, PathStyle};
/// # use core_types::Color;
/// let mut style = PathStyle::default();
///
/// assert_eq!(style.stroke(), None);
///
/// let stroke = Stroke::new(Some(Color::GREEN), 42.);
/// style.set_stroke(stroke.clone());
///
/// assert_eq!(style.stroke(), Some(stroke));
/// ```
pub fn set_stroke(&mut self, stroke: Stroke) {
self.stroke = Some(stroke);
}
/// Set the path's fill to None.
///
/// # Example
/// ```
/// # use vector_types::vector::style::{Fill, PathStyle};
/// # use core_types::Color;
/// let mut style = PathStyle::new(None, Fill::Solid(Color::RED));
///
/// assert_ne!(*style.fill(), Fill::None);
///
/// style.clear_fill();
///
/// assert_eq!(*style.fill(), Fill::None);
/// ```
pub fn clear_fill(&mut self) {
self.fill = Fill::None;
}
/// Set the path's stroke to None.
///
/// # Example
/// ```
/// # use vector_types::vector::style::{Fill, Stroke, PathStyle};
/// # use core_types::Color;
/// let mut style = PathStyle::new(Some(Stroke::new(Some(Color::GREEN), 42.)), Fill::None);
///
/// assert!(style.stroke().is_some());
///
/// style.clear_stroke();
///
/// assert!(!style.stroke().is_some());
/// ```
pub fn clear_stroke(&mut self) {
self.stroke = None;
}
}
/// Ways the user can choose to view the artwork in the viewport.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, graphene_hash::CacheHash, DynAny)]
@@ -786,39 +421,3 @@ pub enum RenderMode {
/// Render a preview of how the object would be exported as an SVG.
SvgPreview,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fill_from_gradient_list_preserves_attributes() {
let mut list = List::new_from_element(GradientStops::default());
list.set_attribute(ATTR_GRADIENT_TYPE, 0, GradientType::Radial);
list.set_attribute(ATTR_SPREAD_METHOD, 0, GradientSpreadMethod::Reflect);
list.set_attribute(ATTR_TRANSFORM, 0, DAffine2::from_translation(DVec2::new(5., 7.)));
let Fill::Gradient(gradient) = Fill::from(list) else {
panic!("expected Fill::Gradient");
};
assert_eq!(gradient.gradient_type, GradientType::Radial);
assert_eq!(gradient.spread_method, GradientSpreadMethod::Reflect);
assert_eq!(gradient.start, DVec2::new(5., 7.));
assert_eq!(gradient.end, DVec2::new(6., 7.));
}
#[test]
fn fill_from_empty_gradient_list_uses_defaults() {
let list = List::new_from_element(GradientStops::default());
let Fill::Gradient(gradient) = Fill::from(list) else {
panic!("expected Fill::Gradient");
};
assert_eq!(gradient.gradient_type, GradientType::default());
assert_eq!(gradient.spread_method, GradientSpreadMethod::default());
assert_eq!(gradient.start, DVec2::ZERO);
assert_eq!(gradient.end, DVec2::X);
}
}
@@ -1,12 +1,11 @@
use super::misc::dvec2_to_point;
use super::style::{PathStyle, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use super::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin};
pub use super::vector_attributes::*;
use crate::subpath::{BezierHandles, ManipulatorGroup, Subpath};
use crate::vector::click_target::{ClickTargetType, FreePoint};
use crate::vector::misc::{HandleId, ManipulatorPointId};
use crate::vector::vector_modification::VectorExt;
use core::borrow::Borrow;
use core_types::Color;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::render_complexity::RenderComplexity;
use core_types::transform::Transform;
@@ -19,7 +18,7 @@ use std::collections::HashMap;
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Vector {
pub style: PathStyle,
pub stroke: Option<Stroke>,
/// A list of all manipulator groups (referenced in `subpaths`) that have colinear handles (where they're locked at 180° angles from one another).
/// This gets read in `graph_operation_message_handler.rs` by calling `inputs.as_mut_slice()` (search for the string `"Shape does not have both `subpath` and `colinear_manipulators` inputs"` to find it).
@@ -36,7 +35,7 @@ unsafe impl StaticType for Vector {
impl Default for Vector {
fn default() -> Self {
Self {
style: PathStyle::new(Some(Stroke::new(Some(Color::BLACK), 0.)), super::style::Fill::None),
stroke: Some(Stroke::new(0.)),
colinear_manipulators: Vec::new(),
point_domain: PointDomain::new(),
segment_domain: SegmentDomain::new(),
@@ -50,7 +49,7 @@ impl graphene_hash::CacheHash for Vector {
self.point_domain.cache_hash(state);
self.segment_domain.cache_hash(state);
self.region_domain.cache_hash(state);
self.style.cache_hash(state);
self.stroke.cache_hash(state);
self.colinear_manipulators.cache_hash(state);
}
}
@@ -243,7 +242,7 @@ impl Vector {
pub fn stroke_inclusive_bounding_box_with_transform(&self, transform: DAffine2) -> Option<[DVec2; 2]> {
let path_bounds = self.bounding_box_with_transform(transform);
let Some(stroke) = self.style.stroke() else { return path_bounds };
let Some(stroke) = self.stroke.as_ref() else { return path_bounds };
// Stroke alignment is only honored by the renderer when every subpath is closed; open paths fall
// back to drawing a Center-aligned `weight`-wide stroke. Match that behavior to keep bounds in sync.
let aligned_renders = stroke.align != StrokeAlign::Center && self.stroke_bezier_paths().all(|p| p.closed());
@@ -532,10 +531,16 @@ impl Vector {
self.region_domain.concat(&additional.region_domain, transform_of_additional, &id_map);
// TODO: properly deal with fills such as gradients
self.style = additional.style.clone();
self.stroke = additional.stroke.clone();
self.colinear_manipulators.extend(additional.colinear_manipulators.iter().copied());
}
pub fn set_stroke_transform(&mut self, transform: DAffine2) {
if let Some(stroke) = &mut self.stroke {
stroke.transform = transform;
}
}
}
impl BoundingBox for Vector {
@@ -549,8 +554,9 @@ impl BoundingBox for Vector {
}
// Include stroke by adding offset based on stroke width
let stroke_width = self.style.stroke().map(|s| s.weight()).unwrap_or_default();
let miter_limit = self.style.stroke().map(|s| s.join_miter_limit).unwrap_or(1.);
let stroke = self.stroke.clone();
let stroke_width = stroke.as_ref().map(|s| s.weight()).unwrap_or_default();
let miter_limit = stroke.as_ref().map(|s| s.join_miter_limit).unwrap_or(1.);
let scale = transform.scale_magnitudes();
// Use the full line width to account for different styles of stroke caps
@@ -75,7 +75,6 @@ impl TextureCache {
}
if Arc::strong_count(texture) == 1 {
free_bytes -= texture.memory_size_estimate();
texture.destroy();
false
} else {
true
+19 -29
View File
@@ -196,36 +196,24 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
})
.collect();
let number_min_values: Vec<_> = regular_fields
.iter()
.map(|field| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { number_soft_min, number_hard_min, .. }) => match (number_soft_min, number_hard_min) {
(Some(soft_min), _) => quote!(Some(#soft_min)),
(None, Some(hard_min)) => quote!(Some(#hard_min)),
(None, None) => quote!(None),
},
_ => quote!(None),
})
.collect();
let number_max_values: Vec<_> = regular_fields
.iter()
.map(|field| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { number_soft_max, number_hard_max, .. }) => match (number_soft_max, number_hard_max) {
(Some(soft_max), _) => quote!(Some(#soft_max)),
(None, Some(hard_max)) => quote!(Some(#hard_max)),
(None, None) => quote!(None),
},
_ => quote!(None),
})
.collect();
let bound_values = |select: fn(&RegularParsedField) -> &Option<NumberBound>| -> Vec<_> {
regular_fields
.iter()
.map(|field| match &field.ty {
ParsedFieldType::Regular(regular) => select(regular).as_ref().map_or(quote!(None), |bound| quote!(Some(#bound))),
_ => quote!(None),
})
.collect()
};
let number_soft_min_values = bound_values(|field| &field.number_soft_min);
let number_soft_max_values = bound_values(|field| &field.number_soft_max);
let number_hard_min_values = bound_values(|field| &field.number_hard_min);
let number_hard_max_values = bound_values(|field| &field.number_hard_max);
let number_mode_range_values: Vec<_> = regular_fields
.iter()
.map(|field| match &field.ty {
ParsedFieldType::Regular(RegularParsedField {
number_mode_range: Some(number_mode_range),
..
}) => quote!(Some(#number_mode_range)),
_ => quote!(None),
ParsedFieldType::Regular(RegularParsedField { number_mode_range, .. }) => quote!(#number_mode_range),
_ => quote!(false),
})
.collect();
let number_display_decimal_places: Vec<_> = regular_fields
@@ -518,8 +506,10 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
exposed: #exposed,
value_source: #value_sources,
default_type: #default_types,
number_min: #number_min_values,
number_max: #number_max_values,
number_soft_min: #number_soft_min_values,
number_soft_max: #number_soft_max_values,
number_hard_min: #number_hard_min_values,
number_hard_max: #number_hard_max_values,
number_mode_range: #number_mode_range_values,
number_display_decimal_places: #number_display_decimal_places,
number_step: #number_step,
+100 -58
View File
@@ -7,8 +7,8 @@ use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::token::{Comma, RArrow};
use syn::{
AttrStyle, Attribute, Error, Expr, ExprTuple, FnArg, GenericParam, Ident, ItemFn, Lit, LitFloat, LitInt, LitStr, Meta, Pat, PatIdent, PatType, Path, ReturnType, TraitBound, Type, TypeImplTrait,
TypeParam, TypeParamBound, Visibility, WhereClause, parse_quote,
AttrStyle, Attribute, Error, Expr, FnArg, GenericParam, Ident, ItemFn, Lit, LitFloat, LitInt, LitStr, Meta, Pat, PatIdent, PatType, Path, ReturnType, TraitBound, Type, TypeImplTrait, TypeParam,
TypeParamBound, Visibility, WhereClause, parse_quote,
};
use crate::codegen::generate_node_code;
@@ -126,7 +126,7 @@ pub enum ParsedFieldType {
Node(NodeParsedField),
}
/// A numeric bound value accepted by attributes like `#[soft_min]`, `#[hard_min]`, `#[soft_max]`, and `#[hard_max]`.
/// A single numeric endpoint within a `#[soft(..)]` or `#[hard(..)]` bounds range.
/// Accepts both integer literals (e.g. `1`, `-1`) and float literals (e.g. `1.`, `-500.`).
#[derive(Clone, Debug)]
pub struct NumberBound {
@@ -180,6 +180,52 @@ impl ToTokens for NumberBound {
}
}
/// A pair of numeric bounds parsed from the `#[soft(a..b)]` and `#[hard(a..b)]` attributes.
/// Either endpoint may be omitted for an open-ended bound (`a..` or `..b`), and each endpoint
/// independently accepts an integer or float literal (each cast to `f64`), so a mixed range like
/// `0..3.14159` is valid.
///
/// The operator is always the bare `..`; both endpoints are treated as inclusive (clamping reaches them).
/// Unlike a Rust range there is no `..=` form, `..` is purely this attribute DSL's bounds operator.
#[derive(Clone, Debug)]
pub struct NumberRange {
start: Option<NumberBound>,
end: Option<NumberBound>,
}
impl Parse for NumberRange {
fn parse(input: ParseStream) -> syn::Result<Self> {
if input.is_empty() {
return Err(input.error("expected a range like `0..100`, `..100`, or `0..`"));
}
// A leading endpoint is present unless the range opens directly into the `..` operator.
let start = if input.peek(syn::Token![..=]) || input.peek(syn::Token![..]) {
None
} else {
Some(input.parse::<NumberBound>()?)
};
// Only the bare `..` is accepted. `..=` is rejected even though both endpoints are inclusive here:
// this DSL treats `..` as its own bounds operator, deliberately diverging from Rust's range semantics.
if input.peek(syn::Token![..=]) {
return Err(input.error("use `..` rather than `..=` for number bounds; both endpoints are always inclusive (e.g. `0..100`)"));
}
if !input.peek(syn::Token![..]) {
return Err(input.error("expected a range like `0..100`, `..100`, or `0..`"));
}
input.parse::<syn::Token![..]>()?;
let end = if input.is_empty() { None } else { Some(input.parse::<NumberBound>()?) };
if start.is_none() && end.is_none() {
return Err(input.error("a bounds range must specify at least a lower or upper bound"));
}
Ok(NumberRange { start, end })
}
}
/// a param of any kind, either a concrete type or a generic type with a set of possible types specified via
/// `#[implementation(type)]`
#[derive(Clone, Debug)]
@@ -191,7 +237,8 @@ pub struct RegularParsedField {
pub number_soft_max: Option<NumberBound>,
pub number_hard_min: Option<NumberBound>,
pub number_hard_max: Option<NumberBound>,
pub number_mode_range: Option<ExprTuple>,
/// Whether the number input renders as a draggable slider (the `#[range]` attribute) rather than the default increment field.
pub number_mode_range: bool,
pub implementations: Punctuated<Type, Comma>,
pub gpu_image: bool,
}
@@ -680,47 +727,27 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
_ => ParsedValueSource::None,
};
let number_soft_min = extract_attribute(attrs, "soft_min")
// The slider's interactive extent (`#[soft(a..b)]`) and the enforced clamp (`#[hard(a..b)]`), each an
// optionally open-ended range. They decompose into the four bound values used by codegen and the UI.
let number_soft_bounds = extract_attribute(attrs, "soft")
.map(|attr| {
attr.parse_args()
.map_err(|e| Error::new_spanned(attr, format!("Invalid numerical `soft_min` value for argument '{ident}': {e}")))
attr.parse_args::<NumberRange>()
.map_err(|e| Error::new_spanned(attr, format!("Invalid `soft` bounds for argument '{ident}': {e}\nUSAGE EXAMPLE: #[soft(0..100)]")))
})
.transpose()?;
let number_soft_max = extract_attribute(attrs, "soft_max")
let number_hard_bounds = extract_attribute(attrs, "hard")
.map(|attr| {
attr.parse_args()
.map_err(|e| Error::new_spanned(attr, format!("Invalid numerical `soft_max` value for argument '{ident}': {e}")))
attr.parse_args::<NumberRange>()
.map_err(|e| Error::new_spanned(attr, format!("Invalid `hard` bounds for argument '{ident}': {e}\nUSAGE EXAMPLE: #[hard(0..100)]")))
})
.transpose()?;
let number_soft_min = number_soft_bounds.as_ref().and_then(|range| range.start.clone());
let number_soft_max = number_soft_bounds.as_ref().and_then(|range| range.end.clone());
let number_hard_min = number_hard_bounds.as_ref().and_then(|range| range.start.clone());
let number_hard_max = number_hard_bounds.as_ref().and_then(|range| range.end.clone());
let number_hard_min = extract_attribute(attrs, "hard_min")
.map(|attr| {
attr.parse_args()
.map_err(|e| Error::new_spanned(attr, format!("Invalid numerical `hard_min` value for argument '{ident}': {e}")))
})
.transpose()?;
let number_hard_max = extract_attribute(attrs, "hard_max")
.map(|attr| {
attr.parse_args()
.map_err(|e| Error::new_spanned(attr, format!("Invalid numerical `hard_max` value for argument '{ident}': {e}")))
})
.transpose()?;
let number_mode_range = extract_attribute(attrs, "range")
.map(|attr| {
attr.parse_args::<ExprTuple>().map_err(|e| {
Error::new_spanned(
attr,
format!("Invalid `range` tuple of min and max range slider values for argument '{ident}': {e}\nUSAGE EXAMPLE: #[range((0., 100.))]"),
)
})
})
.transpose()?;
if let Some(range) = &number_mode_range
&& range.elems.len() != 2
{
return Err(Error::new_spanned(range, "Expected a tuple of two values for `range` for the min and max, respectively"));
}
// The `#[range]` marker selects the slider widget; its extent is derived from the soft (then hard) bounds.
let number_mode_range = extract_attribute(attrs, "range").is_some();
let unit = extract_attribute(attrs, "unit")
.map(|attr| attr.parse_args::<LitStr>().map_err(|_e| Error::new_spanned(attr, "Expected a unit type as string".to_string())))
@@ -810,15 +837,15 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
.transpose()?
.unwrap_or_default();
// Error if a float literal is given for a bound attribute on an integer-typed field
// Error if a float literal is given for a bound on an integer-typed field
if is_integer_type(&ty) {
let bound_attrs = [
(&number_soft_min, "soft_min"),
(&number_hard_min, "hard_min"),
(&number_soft_max, "soft_max"),
(&number_hard_max, "hard_max"),
(&number_soft_min, "soft", "lower"),
(&number_soft_max, "soft", "upper"),
(&number_hard_min, "hard", "lower"),
(&number_hard_max, "hard", "upper"),
];
for (bound, attr_name) in bound_attrs {
for (bound, attr_name, end) in bound_attrs {
if let Some(NumberBound {
literal: NumberBoundLiteral::Float(_),
..
@@ -826,7 +853,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
{
return Err(Error::new_spanned(
&pat_ident,
format!("Attribute `#[{attr_name}]` on `{ident}` has a float literal, but `{ident}` is an integer type. Use an integer literal without a decimal point."),
format!("The {end} `#[{attr_name}]` bound on `{ident}` is a float literal, but `{ident}` is an integer type. Use an integer literal without a decimal point."),
));
}
}
@@ -1082,7 +1109,7 @@ mod tests {
number_soft_max: None,
number_hard_min: None,
number_hard_max: None,
number_mode_range: None,
number_mode_range: false,
implementations: Punctuated::new(),
gpu_image: false,
}),
@@ -1168,7 +1195,7 @@ mod tests {
number_soft_max: None,
number_hard_min: None,
number_hard_max: None,
number_mode_range: None,
number_mode_range: false,
implementations: Punctuated::new(),
gpu_image: false,
}),
@@ -1236,7 +1263,7 @@ mod tests {
number_soft_max: None,
number_hard_min: None,
number_hard_max: None,
number_mode_range: None,
number_mode_range: false,
implementations: Punctuated::new(),
gpu_image: false,
}),
@@ -1302,7 +1329,7 @@ mod tests {
number_soft_max: None,
number_hard_min: None,
number_hard_max: None,
number_mode_range: None,
number_mode_range: false,
implementations: {
let mut p = Punctuated::new();
p.push(parse_quote!(f32));
@@ -1330,9 +1357,9 @@ mod tests {
fn add(
a: f64,
/// b
#[range((0., 100.))]
#[soft_min(-500.)]
#[soft_max(500.)]
#[range]
#[soft(0..100)]
#[hard(-500..500)]
b: f64,
) -> f64 {
a + b
@@ -1376,11 +1403,11 @@ mod tests {
ty: parse_quote!(f64),
exposed: false,
value_source: ParsedValueSource::None,
number_soft_min: Some(parse_quote!(-500.)),
number_soft_max: Some(parse_quote!(500.)),
number_hard_min: None,
number_hard_max: None,
number_mode_range: Some(parse_quote!((0., 100.))),
number_soft_min: Some(parse_quote!(0)),
number_soft_max: Some(parse_quote!(100)),
number_hard_min: Some(parse_quote!(-500)),
number_hard_max: Some(parse_quote!(500)),
number_mode_range: true,
implementations: Punctuated::new(),
gpu_image: false,
}),
@@ -1396,6 +1423,21 @@ mod tests {
assert_parsed_node_fn(&parsed, &expected);
}
#[test]
fn test_empty_bounds_range() {
let attr = quote!(category("Math: Arithmetic"));
let input = quote!(
fn add(a: f64, #[soft()] b: f64) -> f64 {
a + b
}
);
let result = parse_node_fn(attr, input);
assert!(result.is_err());
let error_message = result.unwrap_err().to_string();
assert!(error_message.contains("expected a range like `0..100`, `..100`, or `0..`"));
}
#[test]
fn test_async_node() {
let attr = quote!(category("IO"));
@@ -1446,7 +1488,7 @@ mod tests {
number_soft_max: None,
number_hard_min: None,
number_hard_max: None,
number_mode_range: None,
number_mode_range: false,
implementations: Punctuated::new(),
gpu_image: false,
}),
@@ -238,7 +238,7 @@ impl PerPixelAdjustCodegen<'_> {
number_soft_max: None,
number_hard_min: None,
number_hard_max: None,
number_mode_range: None,
number_mode_range: false,
implementations: Default::default(),
gpu_image: false,
}),
+52 -13
View File
@@ -10,6 +10,7 @@ pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
validate_implementations_for_generics,
validate_primary_input_expose,
validate_min_max,
validate_range_slider_bounds,
];
for validator in validators {
@@ -39,18 +40,18 @@ fn validate_min_max(parsed: &ParsedNodeFn) {
if soft_min_value == hard_min_value {
emit_error!(
pat_ident.span(),
"Unnecessary #[soft_min] attribute on `{}`, as #[hard_min] has the same value.",
"Redundant lower bound on `{}`: the #[soft] and #[hard] lower bounds are equal.",
pat_ident.ident;
help = "You can safely remove the #[soft_min] attribute from this field.";
note = "#[soft_min] is redundant when it equals #[hard_min].",
help = "Drop the lower bound from #[soft] and let the slider fall back to #[hard].";
note = "A soft bound only matters when it sits inside the corresponding hard bound.",
);
} else if soft_min_value < hard_min_value {
emit_error!(
pat_ident.span(),
"The #[soft_min] attribute on `{}` is incorrectly greater than #[hard_min].",
"The #[soft] lower bound on `{}` is below the #[hard] lower bound.",
pat_ident.ident;
help = "You probably meant to reverse the two attribute values.";
note = "Allowing the possible slider range to preceed #[hard_min] doesn't make sense.",
help = "The soft (slider) range must stay within the hard (clamped) range.";
note = "Letting the slider range precede #[hard]'s lower bound doesn't make sense.",
);
}
}
@@ -61,18 +62,18 @@ fn validate_min_max(parsed: &ParsedNodeFn) {
if soft_max_value == hard_max_value {
emit_error!(
pat_ident.span(),
"Unnecessary #[soft_max] attribute on `{}`, as #[hard_max] has the same value.",
"Redundant upper bound on `{}`: the #[soft] and #[hard] upper bounds are equal.",
pat_ident.ident;
help = "You can safely remove the #[soft_max] attribute from this field.";
note = "#[soft_max] is redundant when it equals #[hard_max].",
help = "Drop the upper bound from #[soft] and let the slider fall back to #[hard].";
note = "A soft bound only matters when it sits inside the corresponding hard bound.",
);
} else if soft_max_value < hard_max_value {
} else if soft_max_value > hard_max_value {
emit_error!(
pat_ident.span(),
"The #[soft_max] attribute on `{}` is incorrectly greater than #[hard_max].",
"The #[soft] upper bound on `{}` is above the #[hard] upper bound.",
pat_ident.ident;
help = "You probably meant to reverse the two attribute values.";
note = "Allowing the possible slider range to exceed #[hard_max] doesn't make sense.",
help = "The soft (slider) range must stay within the hard (clamped) range.";
note = "Letting the slider range exceed #[hard]'s upper bound doesn't make sense.",
);
}
}
@@ -80,6 +81,44 @@ fn validate_min_max(parsed: &ParsedNodeFn) {
}
}
/// A `#[range]` slider needs a defined extent on both ends. The extent comes from `#[soft]` when present,
/// otherwise it falls back to `#[hard]`, so each end must be covered by at least one of the two attributes.
fn validate_range_slider_bounds(parsed: &ParsedNodeFn) {
for field in &parsed.fields {
if let ParsedField {
ty: ParsedFieldType::Regular(RegularParsedField {
number_mode_range: true,
number_soft_min,
number_soft_max,
number_hard_min,
number_hard_max,
..
}),
pat_ident,
..
} = field
{
let min_bounded = number_soft_min.is_some() || number_hard_min.is_some();
let max_bounded = number_soft_max.is_some() || number_hard_max.is_some();
let missing = match (min_bounded, max_bounded) {
(true, true) => continue,
(false, false) => "lower and upper bounds",
(false, true) => "a lower bound",
(true, false) => "an upper bound",
};
emit_error!(
pat_ident.span(),
"The #[range] slider on `{}` is missing {}.",
pat_ident.ident, missing;
help = "A slider needs both ends defined; add the missing bound via #[soft(..)] or #[hard(..)], e.g. #[soft(0..100)].";
note = "The slider's extent comes from #[soft] if present, otherwise #[hard].",
);
}
}
}
fn validate_primary_input_expose(parsed: &ParsedNodeFn) {
if let Some(ParsedField {
ty: ParsedFieldType::Regular(RegularParsedField { exposed: true, .. }),
+1 -1
View File
@@ -9,7 +9,7 @@ use vector_types::GradientStops;
/// Constructs a single-element `Artboard[]` with the given content and metadata stored as row attributes.
#[node_macro::node(category(""))]
pub async fn create_artboard<T: IntoGraphicList + 'n>(
pub async fn create_artboard<T: IntoGraphicList>(
ctx: impl ExtractAll + CloneVarArgs + Ctx,
/// Graphics to include within the artboard.
#[implementations(
+9 -7
View File
@@ -156,7 +156,9 @@ async fn mirror<T: 'n + Send + Clone>(
content: List<T>,
#[default(ReferencePoint::Center)] relative_to_bounds: ReferencePoint,
#[unit(" px")] offset: f64,
#[range((-90., 90.))] angle: Angle,
#[range]
#[soft(-90..90)]
angle: Angle,
#[default(true)] keep_original: bool,
) -> List<T>
where
@@ -563,7 +565,7 @@ pub async fn wrap_graphic<T: Into<Graphic> + 'n>(
/// Converts a list of graphical content into a `Graphic[]` by placing it into an element of a new wrapper `Graphic[]`.
/// If it is already a `Graphic[]`, it is not wrapped again. Use the 'Wrap Graphic' node if wrapping is always desired.
#[node_macro::node(category("General"))]
pub async fn to_graphic<T: IntoGraphicList + 'n>(
pub async fn to_graphic<T: IntoGraphicList>(
_: impl Ctx,
#[implementations(
List<Graphic>,
@@ -618,7 +620,7 @@ pub async fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten:
/// Converts a `Graphic[]` into a `Vector[]` by deeply flattening any vector content it contains, and discarding any non-vector content.
#[node_macro::node(category("Vector"))]
pub async fn flatten_vector<T: IntoGraphicList + 'n + Send + Clone>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> {
pub async fn flatten_vector<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> {
let graphic_list = content.into_graphic_list();
let mut output: List<Vector> = graphic_list.clone().into_flattened_list();
@@ -651,25 +653,25 @@ pub async fn flatten_vector<T: IntoGraphicList + 'n + Send + Clone>(_: impl Ctx,
/// Converts a `Graphic[]` into a `Raster[]` by deeply flattening any raster content it contains, and discarding any non-raster content.
#[node_macro::node(category("Raster"))]
pub async fn flatten_raster<T: IntoGraphicList + 'n + Send + Clone>(_: impl Ctx, #[implementations(List<Graphic>, List<Raster<CPU>>)] content: T) -> List<Raster<CPU>> {
pub async fn flatten_raster<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Raster<CPU>>)] content: T) -> List<Raster<CPU>> {
content.into_flattened_list()
}
/// Converts a `Graphic[]` into a `Color[]` by deeply flattening any color content it contains, and discarding any non-color content.
#[node_macro::node(category("General"))]
pub async fn flatten_color<T: IntoGraphicList + 'n + Send + Clone>(_: impl Ctx, #[implementations(List<Graphic>, List<Color>)] content: T) -> List<Color> {
pub async fn flatten_color<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Color>)] content: T) -> List<Color> {
content.into_flattened_list()
}
/// Converts a `Graphic[]` into a `GradientStops[]` by deeply flattening any gradient content it contains, and discarding any non-gradient content.
#[node_macro::node(category("General"))]
pub async fn flatten_gradient<T: IntoGraphicList + 'n + Send + Clone>(_: impl Ctx, #[implementations(List<Graphic>, List<GradientStops>)] content: T) -> List<GradientStops> {
pub async fn flatten_gradient<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<GradientStops>)] content: T) -> List<GradientStops> {
content.into_flattened_list()
}
/// Constructs a gradient from a `Color[]`, where the colors are evenly distributed as gradient stops across the range from 0 to 1.
#[node_macro::node(category("Color"))]
fn colors_to_gradient<T: IntoGraphicList + 'n + Send + Clone>(_: impl Ctx, #[implementations(List<Graphic>, List<Color>)] colors: T) -> List<GradientStops> {
fn colors_to_gradient<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Color>)] colors: T) -> List<GradientStops> {
let colors = colors.into_flattened_list::<Color>();
let total_colors = colors.len();
+5 -6
View File
@@ -22,13 +22,13 @@ fn text(
/// The font size used to draw the text.
#[unit(" px")]
#[default(24.)]
#[hard_min(1.)]
#[hard(1..)]
size: f64,
/// The line height ratio, relative to the font size. Each line is drawn lower than its previous line by the distance of *Size* × *Line Height*.
///
/// 0 means all lines overlap. 1 means all lines are spaced by just the font size. 1.2 is a common default for readable text. 2 means double-spaced text.
#[unit("x")]
#[hard_min(0.)]
#[hard(0..)]
#[step(0.1)]
#[default(1.2)]
line_height: f64,
@@ -38,15 +38,14 @@ fn text(
letter_spacing: f64,
/// The angle of faux italic slant applied to each glyph.
#[unit("°")]
#[hard_min(-85.)]
#[hard_max(85.)]
#[hard(-85..85)]
letter_tilt: f64,
/// Enables the maximum width constraint so lines can wrap.
#[widget(ParsedWidgetOverride::Hidden)]
has_max_width: bool,
/// The maximum width that the text block can occupy before wrapping to a new line. Otherwise, lines do not wrap.
#[unit(" px")]
#[hard_min(1.)]
#[hard(1..)]
#[widget(ParsedWidgetOverride::Custom = "optional_f64")]
max_width: f64,
/// Whether the *Max Height* property is enabled so that lines beyond it are not drawn.
@@ -54,7 +53,7 @@ fn text(
has_max_height: bool,
/// The maximum height that the text block can occupy. Excess lines are not drawn.
#[unit(" px")]
#[hard_min(1.)]
#[hard(1..)]
#[widget(ParsedWidgetOverride::Custom = "optional_f64")]
max_height: f64,
/// The horizontal alignment of each line of text within its surrounding box. To have an effect on a single line of text, *Max Width* must be set.
+39 -37
View File
@@ -1,15 +1,15 @@
use core_types::list::{Item, List};
use core_types::list::{ATTR_FILL, Item, List};
use core_types::uuid::NodeId;
use core_types::{
ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_GRADIENT_TYPE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_SPREAD_METHOD, ATTR_TRANSFORM, BlendMode, Color,
Ctx,
};
use glam::{DAffine2, DVec2};
use graphic_types::vector_types::gradient::{Gradient, GradientSpreadMethod, GradientType};
use graphic_types::graphic::{bake_paint_transforms, set_paint_attribute};
use graphic_types::vector_types::gradient::{GradientSpreadMethod, GradientType};
use graphic_types::vector_types::subpath::{ManipulatorGroup, Subpath};
use graphic_types::vector_types::vector::PointId;
use graphic_types::vector_types::vector::algorithms::merge_by_distance::MergeByDistanceExt;
use graphic_types::vector_types::vector::style::Fill;
use graphic_types::{Graphic, Vector};
use linesweeper::topology::Topology;
use linesweeper::{BinaryOp, FillRule, binary_op};
@@ -23,7 +23,7 @@ pub use vector_types::vector::misc::BooleanOperation;
/// Combines the geometric forms of one or more closed paths into a new vector path that results from cutting or joining the paths by the chosen method.
#[node_macro::node(category("Vector: Modifier"), memoize)]
async fn boolean_operation<I: graphic_types::IntoGraphicList + 'n + Send + Clone>(
async fn boolean_operation<I: graphic_types::IntoGraphicList>(
_: impl Ctx,
/// The `List` of vector paths to perform the boolean operation on. Nested `List`s are automatically flattened.
#[implementations(List<Graphic>, List<Vector>)]
@@ -49,7 +49,7 @@ async fn boolean_operation<I: graphic_types::IntoGraphicList + 'n + Send + Clone
let result_vector = result_vector_list.element_mut(0).unwrap();
Vector::transform(result_vector, transform);
result_vector.style.set_stroke_transform(DAffine2::IDENTITY);
result_vector.set_stroke_transform(DAffine2::IDENTITY);
// Snapshot the input layers as the `editor:merged_layers` attribute so the renderer can recurse into them
// for editor click-target preservation.
@@ -143,17 +143,14 @@ fn boolean_operation_on_vector_list(vector: &List<Vector>, boolean_operation: Bo
let copy_from_transform: DAffine2 = vector.attribute_cloned_or_default(ATTR_TRANSFORM, index);
// The boolean op bakes input transforms into the output geometry, so the result item carries no transform of its own
attributes.insert(ATTR_TRANSFORM, DAffine2::IDENTITY);
bake_paint_transforms(&mut attributes, copy_from_transform);
let copy_from = vector.element(index).unwrap();
let mut element = Vector {
style: copy_from.style.clone(),
let element = Vector {
stroke: copy_from.stroke.clone(),
..Default::default()
};
// An absolute gradient lives in the geometry's space, so bake the same transform into it to track the baked points
if let Fill::Gradient(gradient) = element.style.fill_mut()
&& gradient.absolute
{
gradient.transform = copy_from_transform * gradient.transform;
}
Item::from_parts(element, attributes)
} else {
Item::<Vector>::default()
@@ -204,15 +201,16 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> List<Vector> {
let mut subpath = Subpath::new_rectangle(DVec2::ZERO, DVec2::ONE);
subpath.apply_transform(transform);
let mut element = Vector::from_subpath(subpath);
element.style.set_fill(Fill::Solid(Color::BLACK));
let element = Vector::from_subpath(subpath);
Item::new_from_element(element)
let mut item = Item::new_from_element(element)
.with_attribute(ATTR_BLEND_MODE, blend_mode)
.with_attribute(ATTR_OPACITY, opacity)
.with_attribute(ATTR_OPACITY_FILL, fill)
.with_attribute(ATTR_CLIPPING_MASK, clip)
.with_attribute(ATTR_EDITOR_LAYER_PATH, layer)
.with_attribute(ATTR_EDITOR_LAYER_PATH, layer);
set_paint_attribute(item.attributes_mut(), ATTR_FILL, List::new_from_element(Color::BLACK));
item
};
// Apply the parent graphic's transform to each raster element, preserving each item's layer
@@ -236,15 +234,16 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> List<Vector> {
let mut subpath = Subpath::new_rectangle(DVec2::ZERO, DVec2::ONE);
subpath.apply_transform(transform);
let mut element = Vector::from_subpath(subpath);
element.style.set_fill(Fill::Solid(Color::BLACK));
let element = Vector::from_subpath(subpath);
Item::new_from_element(element)
let mut item = Item::new_from_element(element)
.with_attribute(ATTR_BLEND_MODE, blend_mode)
.with_attribute(ATTR_OPACITY, opacity)
.with_attribute(ATTR_OPACITY_FILL, fill)
.with_attribute(ATTR_CLIPPING_MASK, clip)
.with_attribute(ATTR_EDITOR_LAYER_PATH, layer)
.with_attribute(ATTR_EDITOR_LAYER_PATH, layer);
set_paint_attribute(item.attributes_mut(), ATTR_FILL, List::new_from_element(Color::BLACK));
item
};
// Apply the parent graphic's transform to each raster element, preserving each item's layer
@@ -278,10 +277,11 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> List<Vector> {
Graphic::Color(color) => color
.into_iter()
.map(|row| {
let (color, attributes) = row.into_parts();
let (color, mut attributes) = row.into_parts();
set_paint_attribute(&mut attributes, ATTR_FILL, List::new_from_element(color));
let mut element = Vector::default();
element.style.set_fill(Fill::Solid(color));
element.style.set_stroke_transform(DAffine2::IDENTITY);
element.set_stroke_transform(DAffine2::IDENTITY);
Item::from_parts(element, attributes)
})
@@ -289,20 +289,22 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> List<Vector> {
Graphic::Gradient(gradient) => gradient
.into_iter()
.map(|row| {
let (stops, attributes) = row.into_parts();
let (stops, mut attributes) = row.into_parts();
let mut gradient_paint = List::new_from_element(stops);
if let Some(transform) = attributes.remove::<DAffine2>(ATTR_TRANSFORM) {
gradient_paint.set_attribute(ATTR_TRANSFORM, 0, transform);
}
if let Some(gradient_type) = attributes.remove::<GradientType>(ATTR_GRADIENT_TYPE) {
gradient_paint.set_attribute(ATTR_GRADIENT_TYPE, 0, gradient_type);
}
if let Some(spread_method) = attributes.remove::<GradientSpreadMethod>(ATTR_SPREAD_METHOD) {
gradient_paint.set_attribute(ATTR_SPREAD_METHOD, 0, spread_method);
}
set_paint_attribute(&mut attributes, ATTR_FILL, gradient_paint);
let mut element = Vector::default();
// Convert the gradient's transform to absolute endpoints, matching `From<List<GradientStops>> for Fill`
let transform = attributes.get::<DAffine2>(ATTR_TRANSFORM).cloned().unwrap_or_default();
element.style.set_fill(Fill::Gradient(Gradient {
stops,
gradient_type: attributes.get::<GradientType>(ATTR_GRADIENT_TYPE).cloned().unwrap_or_default(),
spread_method: attributes.get::<GradientSpreadMethod>(ATTR_SPREAD_METHOD).cloned().unwrap_or_default(),
start: transform.transform_point2(DVec2::ZERO),
end: transform.transform_point2(DVec2::X),
absolute: true,
transform: DAffine2::IDENTITY,
}));
element.style.set_stroke_transform(DAffine2::IDENTITY);
element.set_stroke_transform(DAffine2::IDENTITY);
Item::from_parts(element, attributes)
})
+20 -13
View File
@@ -85,8 +85,9 @@ fn gamma_correction<T: Adjust<Color>>(
#[gpu_image]
mut input: T,
#[default(2.2)]
#[range((0.01, 10.))]
#[hard_min(0.0001)]
#[range]
#[hard(0.0001..)]
#[soft(0.01..10)]
gamma: f32,
inverse: bool,
) -> T {
@@ -344,22 +345,28 @@ fn black_and_white<T: Adjust<Color>>(
mut image: T,
#[default(Color::BLACK)] tint: Color,
#[default(40.)]
#[range((-200., 300.))]
#[range]
#[soft(-200..300)]
reds: PercentageF32,
#[default(60.)]
#[range((-200., 300.))]
#[range]
#[soft(-200..300)]
yellows: PercentageF32,
#[default(40.)]
#[range((-200., 300.))]
#[range]
#[soft(-200..300)]
greens: PercentageF32,
#[default(60.)]
#[range((-200., 300.))]
#[range]
#[soft(-200..300)]
cyans: PercentageF32,
#[default(20.)]
#[range((-200., 300.))]
#[range]
#[soft(-200..300)]
blues: PercentageF32,
#[default(80.)]
#[range((-200., 300.))]
#[range]
#[soft(-200..300)]
magentas: PercentageF32,
) -> T {
image.adjust(|color| {
@@ -997,12 +1004,11 @@ fn posterize<T: Adjust<Color>>(
#[gpu_image]
mut input: T,
#[default(4)]
#[hard_min(2)]
#[hard(2..)]
levels: u32,
) -> T {
let levels = levels as f32;
input.adjust(|color| {
// `hard_min(2)` constrains the widget but doesn't bind the data-flow input (a saved doc or upstream node could still feed 0 or 1, producing inf/NaN below).
let levels = (levels as f32).max(2.);
let number_of_areas = levels.recip();
let size_of_areas = (levels - 1.).recip();
color.map_gamma_rgb(|c| (c / number_of_areas).floor() * size_of_areas)
@@ -1029,8 +1035,9 @@ fn exposure<T: Adjust<Color>>(
exposure: f32,
offset: f32,
#[default(1.)]
#[range((0.01, 10.))]
#[hard_min(0.0001)]
#[range]
#[hard(0.0001..)]
#[soft(0.01..10)]
gamma_correction: f32,
) -> T {
input.adjust(|color| {
+6 -4
View File
@@ -92,8 +92,9 @@ async fn blur(
/// The image to be blurred.
image_frame: List<Raster<CPU>>,
/// The radius of the blur kernel.
#[range((0., 100.))]
#[hard_min(0.)]
#[range]
#[hard(0..)]
#[soft(..100)]
radius: PixelLength,
/// Use a lower-quality box kernel instead of a circular Gaussian kernel. This is faster but produces boxy artifacts.
box_blur: bool,
@@ -128,8 +129,9 @@ async fn median_filter(
/// The image to be filtered.
image_frame: List<Raster<CPU>>,
/// The radius of the filter kernel. Larger values remove more noise but may blur fine details.
#[range((0., 50.))]
#[hard_min(0.)]
#[range]
#[hard(0..)]
#[soft(..50)]
radius: PixelLength,
) -> List<Raster<CPU>> {
image_frame
@@ -8,7 +8,7 @@ async fn image_color_palette(
_: impl Ctx,
image: List<Raster<CPU>>,
#[default(4)]
#[hard_min(1)]
#[hard(1..)]
count: u32,
) -> List<Color> {
const GRID: f32 = 3.;
+26 -8
View File
@@ -20,13 +20,13 @@ async fn repeat<T: Into<Graphic> + Default + Send + Clone + 'static>(
)]
content: impl Node<'n, Context<'static>, Output = List<T>>,
#[default(1)]
#[hard_min(1)]
#[hard(1..)]
count: u32,
reverse: bool,
) -> List<T> {
// Someday this node can have the option to generate infinitely instead of a fixed count (basically `std::iter::repeat`).
let count = count.max(1) as usize;
let count = count as usize;
let mut result_list = List::new();
@@ -60,12 +60,12 @@ pub async fn repeat_array<T: Into<Graphic> + Default + Send + Clone + 'static>(
direction: PixelSize,
angle: Angle,
#[default(5)]
#[hard_min(1)]
#[hard(1..)]
count: u32,
) -> List<T> {
let angle = angle.to_radians();
let count = count.max(1);
let total = (count - 1) as f64;
// A single copy has no steps between copies, so the denominator is kept at 1 to avoid `0. / 0.` producing a NaN transform
let total = (count - 1).max(1) as f64;
let mut result_list = List::new();
@@ -108,11 +108,9 @@ async fn repeat_radial<T: Into<Graphic> + Default + Send + Clone + 'static>(
#[default(5)]
radius: f64,
#[default(5)]
#[hard_min(1)]
#[hard(1..)]
count: u32,
) -> List<T> {
let count = count.max(1);
let mut result_list = List::new();
for index in 0..count {
@@ -265,6 +263,26 @@ mod test {
}
}
#[tokio::test]
async fn repeat_single_copy() {
let context = OwnedContextImpl::default().into_context();
let repeated = super::repeat_array(
context,
&FutureWrapperNode(vector_node_from_bezpath(Rect::new(0., 0., 1., 1.).to_path(DEFAULT_ACCURACY))),
DVec2::new(12., 10.),
45.,
1,
)
.await;
let vector_list = vector_nodes::flatten_path(Footprint::default(), repeated).await;
let vector = vector_list.element(0).unwrap();
assert_eq!(vector.region_manipulator_groups().count(), 1);
let (_, manipulator_groups) = vector.region_manipulator_groups().next().unwrap();
let anchor = manipulator_groups[0].anchor;
assert!(anchor.length() < 1e-5, "Expected the single copy to be untransformed, found anchor {anchor}");
}
#[tokio::test]
async fn repeat_transform_position() {
let direction = DVec2::new(12., 10.);
+2 -2
View File
@@ -424,7 +424,7 @@ fn string_repeat(
string: String,
/// The number of times the string should appear in the output.
#[default(2)]
#[hard_min(1)]
#[hard(1..)]
count: u32,
/// The string placed between each repetition.
#[default("\\n")]
@@ -436,7 +436,7 @@ fn string_repeat(
) -> String {
let separator = if separator_escaping { unescape_string(separator) } else { separator };
let count = count.max(1) as usize;
let count = count as usize;
let mut result = String::with_capacity((string.len() + separator.len()) * count);
for i in 0..count {
@@ -77,7 +77,8 @@ fn arc(
radius: f64,
start_angle: Angle,
#[default(270.)]
#[range((0., 360.))]
#[range]
#[soft(0..360)]
sweep_angle: Angle,
arc_type: ArcType,
) -> List<Vector> {
@@ -167,7 +168,7 @@ fn regular_polygon<T: AsU64>(
_: impl Ctx,
_primary: (),
#[default(6)]
#[hard_min(3.)]
#[hard(3..)]
#[implementations(u32, u64, f64)]
sides: T,
#[unit(" px")]
@@ -185,7 +186,7 @@ fn star<T: AsU64>(
_: impl Ctx,
_primary: (),
#[default(5)]
#[hard_min(2.)]
#[hard(2..)]
#[implementations(u32, u64, f64)]
sides: T,
#[unit(" px")]
@@ -228,7 +229,7 @@ fn qr_code(
text: String,
#[widget(ParsedWidgetOverride::Hidden)] has_size: bool,
#[unit(" px")]
#[hard_min(1.)]
#[hard(1..)]
#[widget(ParsedWidgetOverride::Custom = "optional_f64")]
size: f64,
error_correction: QRCodeErrorCorrectionLevel,
@@ -267,7 +268,7 @@ fn qr_code(
};
if has_size {
vector.transform(glam::DAffine2::from_scale(DVec2::splat(size.max(1.) / qr_code.size() as f64)));
vector.transform(glam::DAffine2::from_scale(DVec2::splat(size / qr_code.size() as f64)));
}
List::new_from_element(vector)
@@ -312,7 +313,7 @@ fn grid<T: GridSpacing>(
_primary: (),
grid_type: GridType,
#[unit(" px")]
#[hard_min(0.)]
#[hard(0..)]
#[default(10)]
#[implementations(f64, DVec2)]
spacing: T,
+377 -125
View File
@@ -3,22 +3,24 @@ use core::f64::consts::{PI, TAU};
use core::hash::{Hash, Hasher};
use core_types::blending::BlendMode;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::list::{ATTR_FILL, ATTR_STROKE, Item, List, ListDyn};
use core_types::list::{ATTR_FILL, ATTR_STROKE, Item, ItemAttributeValues, List, ListDyn};
use core_types::registry::types::{Angle, Length, Multiplier, Percentage, PixelLength, Progression, SeedValue};
use core_types::transform::{Footprint, Transform};
use core_types::uuid::NodeId;
use core_types::{
ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, CloneVarArgs, Color, Context, Ctx, ExtractAll,
OwnedContextImpl,
ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_GRADIENT_TYPE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_SPREAD_METHOD, ATTR_TRANSFORM, CloneVarArgs,
Color, Context, Ctx, ExtractAll, OwnedContextImpl,
};
use glam::{DAffine2, DMat2, DVec2};
use graphic_types::Vector;
use graphic_types::graphic::{bake_paint_transforms, graphic_list_at, has_paint_at, is_paint_present, set_paint_attribute_at};
use graphic_types::raster_types::{CPU, GPU, Raster};
use graphic_types::{Graphic, IntoGraphicList};
use kurbo::simplify::{SimplifyOptions, simplify_bezpath};
use kurbo::{Affine, BezPath, DEFAULT_ACCURACY, Line, ParamCurve, ParamCurveArclen, PathEl, PathSeg, Shape};
use rand::{Rng, SeedableRng};
use std::collections::hash_map::DefaultHasher;
use vector_types::gradient::{build_transform_with_y_preservation, initial_gradient_transform_for_bounding_box};
use vector_types::subpath::{BezierHandles, ManipulatorGroup};
use vector_types::vector::PointDomain;
use vector_types::vector::algorithms::bezpath_algorithms::{self, TValue, eval_pathseg_euclidean, evaluate_bezpath, split_bezpath, tangent_on_bezpath};
@@ -29,14 +31,17 @@ use vector_types::vector::misc::{
CentroidType, ExtrudeJoiningAlgorithm, HandleId, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, bezpath_from_manipulator_groups,
bezpath_to_manipulator_groups, handles_to_segment, is_linear, point_to_dvec2, segment_to_handles,
};
use vector_types::vector::style::{Fill, Gradient, GradientStops, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use vector_types::vector::style::{GradientStops, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use vector_types::vector::{FillId, PointId, RegionId, SegmentDomain, SegmentId, StrokeId, VectorExt};
use vector_types::{GradientSpreadMethod, GradientType};
/// Implemented for types that contain vector items reachable via mutable access.
/// Used for the fill and stroke nodes so they can apply to either `List<Graphic>` or `List<Vector>`.
trait VectorListIterMut {
fn for_each_vector_mut(&mut self, f: impl FnMut(&mut Vector, DAffine2));
fn for_each_vector_list_mut(&mut self, f: impl FnMut(&mut List<Vector>));
fn vector_count(&self) -> usize;
}
@@ -51,6 +56,14 @@ impl VectorListIterMut for List<Graphic> {
}
}
fn for_each_vector_list_mut(&mut self, mut f: impl FnMut(&mut List<Vector>)) {
for graphic in self.iter_element_values_mut() {
if let Some(vector_list) = graphic.as_vector_mut() {
f(vector_list);
};
}
}
fn vector_count(&self) -> usize {
self.iter_element_values().filter_map(|element| element.as_vector()).map(|list| list.len()).sum()
}
@@ -64,6 +77,10 @@ impl VectorListIterMut for List<Vector> {
}
}
fn for_each_vector_list_mut(&mut self, mut f: impl FnMut(&mut List<Vector>)) {
f(self);
}
fn vector_count(&self) -> usize {
self.len()
}
@@ -109,26 +126,29 @@ where
let mut rng = rand::rngs::StdRng::seed_from_u64(seed.into());
let mut i: usize = 0;
content.for_each_vector_mut(|vector, _transform| {
let factor = match randomize {
true => rng.random::<f64>(),
false => match repeat_every {
0 => i as f64 / (length - 1).max(1) as f64,
1 => 0.,
_ => i as f64 % repeat_every as f64 / (repeat_every - 1) as f64,
},
};
content.for_each_vector_list_mut(|vector_list| {
for index in 0..vector_list.len() {
let factor = match randomize {
true => rng.random::<f64>(),
false => match repeat_every {
0 => i as f64 / (length - 1).max(1) as f64,
1 => 0.,
_ => i as f64 % repeat_every as f64 / (repeat_every - 1) as f64,
},
};
let color = gradient.evaluate(factor);
let color = gradient.evaluate(factor);
let paint = List::new_from_element(color).into_graphic_list();
if fill {
vector.style.set_fill(Fill::Solid(color));
if fill {
set_paint_attribute_at(vector_list, index, ATTR_FILL, paint.clone());
}
if stroke && vector_list.element(index).is_some_and(|vector| vector.stroke.is_some()) {
set_paint_attribute_at(vector_list, index, ATTR_STROKE, paint.clone());
}
i += 1;
}
if stroke && let Some(stroke) = vector.style.stroke().and_then(|stroke| stroke.with_color(&Some(color))) {
vector.style.set_stroke(stroke);
}
i += 1;
});
content
@@ -136,41 +156,77 @@ where
/// Applies a fill style to the vector content, giving an appearance to the area within the interior of the geometry.
#[node_macro::node(category("Vector: Style"), path(graphene_core::vector), properties("fill_properties"))]
async fn fill<F: Into<Fill> + 'n + Send, V: VectorListIterMut + 'n + Send>(
async fn fill<V: VectorListIterMut + 'n + Send, F: IntoGraphicList + 'n + Send + 'static>(
_: impl Ctx,
/// The content with vector paths to apply the fill style to.
#[implementations(
List<Vector>,
List<Vector>,
List<Vector>,
List<Vector>,
List<Graphic>,
List<Graphic>,
List<Graphic>,
List<Graphic>,
List<Vector>, List<Vector>, List<Vector>, List<Vector>, List<Vector>, List<Vector>,
List<Graphic>, List<Graphic>, List<Graphic>, List<Graphic>, List<Graphic>, List<Graphic>,
)]
mut content: V,
/// The fill to paint the path with.
#[default(Color::BLACK)]
#[implementations(
Fill,
List<Color>,
List<GradientStops>,
Gradient,
Fill,
List<Color>,
List<GradientStops>,
Gradient,
List<Graphic>, List<Vector>, List<Color>, List<GradientStops>, List<Raster<CPU>>, List<Raster<GPU>>,
List<Graphic>, List<Vector>, List<Color>, List<GradientStops>, List<Raster<CPU>>, List<Raster<GPU>>,
)]
fill: F,
mut fill: F,
_backup_color: List<Color>,
_backup_gradient: Gradient,
_backup_gradient: List<GradientStops>,
_gradient_type: GradientType,
_spread_method: GradientSpreadMethod,
_transform: Option<DAffine2>,
) -> V {
let fill: Fill = fill.into();
content.for_each_vector_mut(|vector, _transform| {
vector.style.set_fill(fill.clone());
});
if let Some(gradient) = (&mut fill as &mut dyn std::any::Any).downcast_mut::<List<GradientStops>>() {
if gradient.iter_attribute_values::<GradientType>(ATTR_GRADIENT_TYPE).is_none() {
for value in gradient.iter_attribute_values_mut_or_default::<GradientType>(ATTR_GRADIENT_TYPE) {
*value = _gradient_type;
}
}
if gradient.iter_attribute_values::<GradientSpreadMethod>(ATTR_SPREAD_METHOD).is_none() {
for value in gradient.iter_attribute_values_mut_or_default::<GradientSpreadMethod>(ATTR_SPREAD_METHOD) {
*value = _spread_method;
}
}
if gradient.iter_attribute_values::<DAffine2>(ATTR_TRANSFORM).is_none() {
let transform = _transform.unwrap_or_else(|| {
// Construct a transform that covers the bounding box of the paint target
let mut bounds: Option<[DVec2; 2]> = None;
content.for_each_vector_mut(|vector, _| {
if let Some([min, max]) = vector.bounding_box() {
bounds = Some(match bounds {
Some([bmin, bmax]) => [bmin.min(min), bmax.max(max)],
None => [min, max],
});
}
});
// Nudge a degenerate axis so the gradient transform stays invertible, matching the editor's `nonzero_bounding_box`
let [min, mut max] = bounds.unwrap_or([DVec2::ZERO, DVec2::ONE]);
if max.x - min.x < 1e-10 {
max.x = min.x + 1.;
}
if max.y - min.y < 1e-10 {
max.y = min.y + 1.;
}
initial_gradient_transform_for_bounding_box([min, max])
});
for value in gradient.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
*value = transform;
}
}
}
let fill = fill.into_graphic_list();
content.for_each_vector_list_mut(|vector_list| {
// Broadcast the same paint to every item, scanning the attribute column once instead of per index
for slot in vector_list.iter_attribute_values_mut_or_default::<List<Graphic>>(ATTR_FILL) {
*slot = fill.clone();
}
});
content
}
@@ -195,14 +251,41 @@ impl IntoF64Vec for String {
/// Applies a stroke style to the vector content, giving an appearance to the area within the outline of the geometry.
#[node_macro::node(category("Vector: Style"), path(graphene_core::vector), properties("stroke_properties"))]
async fn stroke<V, L: IntoF64Vec>(
async fn stroke<V, L: IntoF64Vec, P: IntoGraphicList + 'n + Send + 'static>(
_: impl Ctx,
/// The content with vector paths to apply the stroke style to.
#[implementations(List<Vector>, List<Vector>, List<Vector>, List<Graphic>, List<Graphic>, List<Graphic>)]
#[implementations(
List<Vector>, List<Vector>, List<Vector>,
List<Vector>, List<Vector>, List<Vector>,
List<Vector>, List<Vector>, List<Vector>,
List<Vector>, List<Vector>, List<Vector>,
List<Vector>, List<Vector>, List<Vector>,
List<Vector>, List<Vector>, List<Vector>,
List<Graphic>, List<Graphic>, List<Graphic>,
List<Graphic>, List<Graphic>, List<Graphic>,
List<Graphic>, List<Graphic>, List<Graphic>,
List<Graphic>, List<Graphic>, List<Graphic>,
List<Graphic>, List<Graphic>, List<Graphic>,
List<Graphic>, List<Graphic>, List<Graphic>,
)]
mut content: List<V>,
/// The stroke color.
/// The stroke paint.
#[default(Color::BLACK)]
color: List<Color>,
#[implementations(
List<Graphic>, List<Graphic>, List<Graphic>,
List<Vector>, List<Vector>, List<Vector>,
List<Color>, List<Color>, List<Color>,
List<GradientStops>, List<GradientStops>, List<GradientStops>,
List<Raster<CPU>>, List<Raster<CPU>>, List<Raster<CPU>>,
List<Raster<GPU>>, List<Raster<GPU>>, List<Raster<GPU>>,
List<Graphic>, List<Graphic>, List<Graphic>,
List<Vector>, List<Vector>, List<Vector>,
List<Color>, List<Color>, List<Color>,
List<GradientStops>, List<GradientStops>, List<GradientStops>,
List<Raster<CPU>>, List<Raster<CPU>>, List<Raster<CPU>>,
List<Raster<GPU>>, List<Raster<GPU>>, List<Raster<GPU>>,
)]
paint: P,
/// The stroke thickness.
#[unit(" px")]
#[default(2.)]
@@ -220,7 +303,20 @@ async fn stroke<V, L: IntoF64Vec>(
/// The order to paint the stroke on top of the fill, or the fill on top of the stroke.
paint_order: PaintOrder,
/// The stroke dash lengths. Each length forms a distance in a pattern where the first length is a dash, the second is a gap, and so on. If the list is an odd length, the pattern repeats with solid-gap roles reversed.
#[implementations(List<f64>, f64, String, List<f64>, f64, String)]
#[implementations(
List<f64>, f64, String,
List<f64>, f64, String,
List<f64>, f64, String,
List<f64>, f64, String,
List<f64>, f64, String,
List<f64>, f64, String,
List<f64>, f64, String,
List<f64>, f64, String,
List<f64>, f64, String,
List<f64>, f64, String,
List<f64>, f64, String,
List<f64>, f64, String,
)]
dash_lengths: L,
/// The phase offset distance from the starting point of the dash pattern.
#[unit(" px")]
@@ -232,7 +328,6 @@ where
let dash_lengths = dash_lengths.into_vec().into_iter().map(|length| length.max(0.)).collect();
let stroke = Stroke {
color: color.element(0).copied(),
weight,
dash_lengths,
dash_offset,
@@ -247,9 +342,16 @@ where
content.for_each_vector_mut(|vector, transform| {
let mut stroke = stroke.clone();
stroke.transform *= transform;
vector.style.set_stroke(stroke);
vector.stroke = Some(stroke);
});
let paint = paint.into_graphic_list();
content.for_each_vector_list_mut(|vector_list| {
// Broadcast the same paint to every item, scanning the attribute column once instead of per index
for slot in vector_list.iter_attribute_values_mut_or_default::<List<Graphic>>(ATTR_STROKE) {
*slot = paint.clone();
}
});
content
}
@@ -263,21 +365,25 @@ async fn copy_to_points<I: 'n + Send + Clone>(
content: List<I>,
/// Minimum range of randomized sizes given to each placed copy.
#[default(1)]
#[range((0., 2.))]
#[range]
#[soft(0..2)]
#[unit("x")]
random_scale_min: Multiplier,
/// Maximum range of randomized sizes given to each placed copy.
#[default(1)]
#[range((0., 2.))]
#[range]
#[soft(0..2)]
#[unit("x")]
random_scale_max: Multiplier,
/// Bias for the probability distribution of randomized sizes (0 is uniform, negatives favor more of small sizes, positives favor more of large sizes).
#[range((-50., 50.))]
#[range]
#[soft(-50..50)]
random_scale_bias: f64,
/// Seed to determine unique variations on all the randomized copy sizes.
random_scale_seed: SeedValue,
/// Range of randomized angles given to each placed copy, in degrees ranging from furthest clockwise to counterclockwise.
#[range((0., 360.))]
#[range]
#[soft(0..360)]
random_rotation: Angle,
/// Seed to determine unique variations on all the randomized copy angles.
random_rotation_seed: SeedValue,
@@ -337,18 +443,16 @@ async fn copy_to_points<I: 'n + Send + Clone>(
async fn round_corners(
_: impl Ctx,
source: List<Vector>,
#[hard_min(0.)]
#[hard(0..)]
#[default(10.)]
radius: PixelLength,
#[range((0., 1.))]
#[hard_min(0.)]
#[hard_max(1.)]
#[range]
#[hard(0..1)]
#[default(0.5)]
roundness: f64,
#[default(100.)] edge_length_limit: Percentage,
#[range((0., 180.))]
#[hard_min(0.)]
#[hard_max(180.)]
#[range]
#[hard(0..180)]
#[default(5.)]
min_angle_threshold: Angle,
) -> List<Vector> {
@@ -365,7 +469,7 @@ async fn round_corners(
let edge_length_limit = edge_length_limit * 0.005;
let mut result = Vector {
style: source.style.clone(),
stroke: source.stroke.clone(),
..Default::default()
};
@@ -452,7 +556,7 @@ pub fn merge_by_distance(
_: impl Ctx,
content: List<Vector>,
#[default(0.1)]
#[hard_min(0.0001)]
#[hard(0.0001..)]
distance: PixelLength,
algorithm: MergeByDistanceAlgorithm,
) -> List<Vector> {
@@ -744,7 +848,7 @@ async fn box_warp(_: impl Ctx, content: List<Vector>, #[expose] rectangle: List<
});
}
result.style.set_stroke_transform(DAffine2::IDENTITY);
result.set_stroke_transform(DAffine2::IDENTITY);
// Add this to the `List` and reset the transform since we've applied it directly to the points
*row.element_mut() = result;
@@ -892,8 +996,8 @@ async fn auto_tangents(
source: List<Vector>,
/// The amount of spread for the auto-tangents, from 0 (sharp corner) to 1 (full spread).
#[default(0.5)]
// TODO: Make this a soft range to allow any value to be typed in outside the slider range of 0 to 1
#[range((0., 1.))]
#[range]
#[soft(0..1)]
spread: f64,
/// If active, existing non-zero handles won't be affected.
#[default(true)]
@@ -906,7 +1010,7 @@ async fn auto_tangents(
let source = source.element(index).unwrap();
let mut result = Vector {
style: source.style.clone(),
stroke: source.stroke.clone(),
..Default::default()
};
@@ -1056,8 +1160,8 @@ async fn bounding_box(_: impl Ctx, content: List<Vector>) -> List<Vector> {
})
.unwrap_or_default();
result.style = vector.style.clone();
result.style.set_stroke_transform(DAffine2::IDENTITY);
result.stroke = vector.stroke.clone();
result.set_stroke_transform(DAffine2::IDENTITY);
*row.element_mut() = result;
row
@@ -1120,10 +1224,10 @@ async fn offset_path(_: impl Ctx, content: List<Vector>, distance: f64, join: St
let bezpaths = vector.stroke_bezpath_iter();
let mut result = Vector {
style: vector.style.clone(),
stroke: vector.stroke.clone(),
..Default::default()
};
result.style.set_stroke_transform(DAffine2::IDENTITY);
result.set_stroke_transform(DAffine2::IDENTITY);
// Perform operation on all subpaths in this shape.
for mut bezpath in bezpaths {
@@ -1154,18 +1258,22 @@ async fn offset_path(_: impl Ctx, content: List<Vector>, distance: f64, join: St
}
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
async fn solidify_stroke<T: IntoGraphicList + 'n + Send + Clone>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> {
async fn solidify_stroke<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> {
// TODO: Make this node support stroke align, which it currently ignores
let graphic_list = content.into_graphic_list();
let flattened: List<Vector> = graphic_list.clone().into_flattened_list();
// A fill exists when the canonical attribute carries paint
let has_fills: Vec<bool> = (0..flattened.len()).map(|index| has_paint_at(&flattened, index, ATTR_FILL)).collect();
let mut output: List<Vector> = flattened
.into_iter()
.flat_map(|row| {
.zip(has_fills)
.flat_map(|(row, has_fill)| {
let (mut vector, attributes) = row.into_parts();
let stroke = vector.style.stroke().clone().unwrap_or_default();
let stroke = vector.stroke.clone().unwrap_or_default();
let bezpaths = vector.stroke_bezpath_iter();
let mut solidified_stroke = Vector::default();
@@ -1195,7 +1303,7 @@ async fn solidify_stroke<T: IntoGraphicList + 'n + Send + Clone>(_: impl Ctx, #[
let stroke_options_default = kurbo::StrokeOpts::default();
let stroke_options_stable = kurbo::StrokeOpts::default().stable_dash_order(true);
// 0.25 is balanced between performace and accuracy of the curve.
// 0.25 is balanced between performance and accuracy of the curve.
const STROKE_TOLERANCE: f64 = 0.25;
for mut path in bezpaths {
@@ -1212,16 +1320,9 @@ async fn solidify_stroke<T: IntoGraphicList + 'n + Send + Clone>(_: impl Ctx, #[
solidified_stroke.append_bezpath(solidified);
}
// We set the solidified stroke's fill to the stroke's color and without a stroke.
if let Some(stroke) = vector.style.stroke() {
solidified_stroke.style.set_fill(Fill::solid_or_none(stroke.color));
}
// If the original vector has a fill, preserve it as a separate item with the stroke cleared.
let has_attr_fill = attributes.keys().any(|k| k == ATTR_FILL);
let has_fill = has_attr_fill || !vector.style.fill().is_none();
let fill_row = has_fill.then(|| {
vector.style.clear_stroke();
vector.stroke = None;
let mut fill_attributes = attributes.clone();
// No stroke remains on the fill row
fill_attributes.remove::<List<Graphic>>(ATTR_STROKE);
@@ -1277,7 +1378,7 @@ async fn separate_subpaths(_: impl Ctx, content: List<Vector>) -> List<Vector> {
return vec![row];
}
let style = row.element().style.clone();
let stroke = row.element().stroke.clone();
let (_, attributes) = row.into_parts();
bezpaths
@@ -1285,7 +1386,7 @@ async fn separate_subpaths(_: impl Ctx, content: List<Vector>) -> List<Vector> {
.map(|bezpath| {
let mut vector = Vector::default();
vector.append_bezpath(bezpath);
vector.style = style.clone();
vector.stroke = stroke.clone();
Item::from_parts(vector, attributes.clone())
})
@@ -1329,12 +1430,14 @@ async fn map_points(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: List<Vec
// TODO: Rename to "Combine Paths" and make this happen per-element instead of flattening every element into a single path. The migration for this should then become a Flatten Vector -> Combine Paths pair of nodes.
#[node_macro::node(category("Vector"), path(graphene_core::vector))]
pub async fn flatten_path<T: IntoGraphicList + 'n + Send>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> {
pub async fn flatten_path<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> {
let graphic_list = content.into_graphic_list();
let flattened = graphic_list.clone().into_flattened_list::<Vector>();
// Create a `List` with one empty `Vector` element, then get a mutable reference to it which we append flattened subpaths to
let mut output_list = List::new_from_element(Vector::default());
let mut primary_source = None;
let output = output_list.element_mut(0).unwrap();
// Concatenate every vector element's subpaths into the single output compound path
@@ -1347,11 +1450,30 @@ pub async fn flatten_path<T: IntoGraphicList + 'n + Send>(_: impl Ctx, #[impleme
(index, node_id).hash(&mut hasher);
let collision_hash_seed = hasher.finish();
output.concat(element, flattened.attribute_cloned_or_default(ATTR_TRANSFORM, index), collision_hash_seed);
let source_transform = flattened.attribute_cloned_or_default(ATTR_TRANSFORM, index);
output.concat(element, source_transform, collision_hash_seed);
// TODO: Make this instead use the first encountered style
// Use the last encountered style as the output style
output.style = element.style.clone();
// TODO: Make this instead use the first encountered stroke
// Use the last encountered stroke as the output stroke
output.stroke = element.stroke.clone();
primary_source = Some((index, source_transform));
}
if let Some((primary, source_transform)) = primary_source {
let source_attributes = flattened.clone_item_attributes(primary);
let mut attributes = ItemAttributeValues::new();
attributes.insert_cloned_from(&source_attributes, ATTR_FILL);
attributes.insert_cloned_from(&source_attributes, ATTR_STROKE);
bake_paint_transforms(&mut attributes, source_transform);
let output = std::mem::take(output_list.element_mut(0).unwrap());
output_list = List::new_from_item(Item::from_parts(output, attributes));
// Adopt the last input item's layer so the editor can also bucket clicks under a contributing child layer
let layer_path: List<NodeId> = flattened.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, primary);
output_list.set_attribute(ATTR_EDITOR_LAYER_PATH, 0, layer_path);
}
// Preserve a reference to the original upstream `List<Graphic>` so the renderer can recurse into it
@@ -1359,13 +1481,6 @@ pub async fn flatten_path<T: IntoGraphicList + 'n + Send>(_: impl Ctx, #[impleme
// This is the same mechanism Boolean Operation uses to keep its inputs editable after the merge.
output_list.set_attribute(ATTR_EDITOR_MERGED_LAYERS, 0, graphic_list);
// Adopt the last input item's layer so the editor can also bucket clicks under a contributing child layer
if !flattened.is_empty() {
let primary = flattened.len() - 1;
let layer_path: List<NodeId> = flattened.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, primary);
output_list.set_attribute(ATTR_EDITOR_LAYER_PATH, 0, layer_path);
}
output_list
}
@@ -1376,16 +1491,16 @@ async fn sample_polyline(
content: List<Vector>,
spacing: PointSpacingType,
#[default(100.)]
#[hard_min(0.)]
#[hard(0..)]
#[unit(" px")]
separation: f64,
#[default(100)]
#[hard_min(2)]
#[hard(2..)]
quantity: u32,
#[hard_min(0.)]
#[hard(0..)]
#[unit(" px")]
start_offset: f64,
#[hard_min(0.)]
#[hard(0..)]
#[unit(" px")]
stop_offset: f64,
adaptive_spacing: bool,
@@ -1406,10 +1521,10 @@ async fn sample_polyline(
segment_domain: Default::default(),
region_domain: Default::default(),
colinear_manipulators: Default::default(),
style: std::mem::take(&mut row.element_mut().style),
stroke: std::mem::take(&mut row.element_mut().stroke),
};
// Transfer the stroke transform from the input vector content to the result.
result.style.set_stroke_transform(row.attribute_cloned_or_default(ATTR_TRANSFORM));
result.set_stroke_transform(row.attribute_cloned_or_default(ATTR_TRANSFORM));
for local_bezpath in row.element().stroke_bezpath_iter() {
// Apply the transform to compute sample locations in world space (for correct distance-based spacing)
@@ -1480,7 +1595,7 @@ async fn simplify(
let inverse_transform = transform.inverse();
let mut result = Vector {
style: std::mem::take(&mut row.element_mut().style),
stroke: std::mem::take(&mut row.element_mut().stroke),
..Default::default()
};
@@ -1576,7 +1691,7 @@ async fn decimate(
let inverse_transform = transform.inverse();
let mut result = Vector {
style: std::mem::take(&mut row.element_mut().style),
stroke: std::mem::take(&mut row.element_mut().stroke),
..Default::default()
};
@@ -1655,7 +1770,7 @@ async fn cut_path(
if let Some((row_index, bezpath)) = bezpaths.get(index).cloned() {
let mut result_vector = Vector {
style: content.element(row_index).unwrap().style.clone(),
stroke: content.element(row_index).unwrap().stroke.clone(),
..Default::default()
};
@@ -1830,8 +1945,9 @@ async fn scatter_points(
content: List<Vector>,
#[unit(" px")]
#[default(10.)]
#[hard_min(0.01)]
#[range((1., 100.))]
#[range]
#[hard(0.01..)]
#[soft(1..100)]
separation: f64,
seed: SeedValue,
) -> List<Vector> {
@@ -1864,8 +1980,8 @@ async fn scatter_points(
}
// Transfer the style from the input vector content to the result.
result.style = row.element().style.clone();
result.style.set_stroke_transform(DAffine2::IDENTITY);
result.stroke = row.element().stroke.clone();
result.set_stroke_transform(DAffine2::IDENTITY);
*row.element_mut() = result;
row
@@ -2061,7 +2177,7 @@ async fn offset_points(
///
/// *Progression* morphs through all objects. Interpolation is linear unless *Path* geometry is provided to control the trajectory between key objects. The **Origins to Polyline** node may be used to create a path with anchor points corresponding to each object. Other nodes can modify its path segments.
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
async fn morph<I: IntoGraphicList + 'n + Send + Clone>(
async fn morph<I: IntoGraphicList>(
_: impl Ctx,
/// The vector objects to interpolate between. Mixed graphic content is deeply flattened to keep only vector elements.
#[implementations(List<Graphic>, List<Vector>)]
@@ -2174,6 +2290,79 @@ async fn morph<I: IntoGraphicList + 'n + Send + Clone>(
}
}
fn lerp_gradient_transform(gradient_list_a: &List<GradientStops>, gradient_list_b: &List<GradientStops>, time: f64) -> DAffine2 {
let transform_a = gradient_list_a.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, 0);
let transform_b = gradient_list_b.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, 0);
let start_a = transform_a.translation;
let end_a = transform_a.translation + transform_a.matrix2.x_axis;
let start_b = transform_b.translation;
let end_b = transform_b.translation + transform_b.matrix2.x_axis;
let start = start_a.lerp(start_b, time);
let end = end_a.lerp(end_b, time);
let metadata_source_transform = if time < 0.5 { transform_a } else { transform_b };
build_transform_with_y_preservation(metadata_source_transform, start, end)
}
// Lerp between two graphics. Solid color and gradient pairings interpolate; all other pairings step at the midpoint.
fn lerp_graphic(a: Option<&List<Graphic>>, b: Option<&List<Graphic>>, time: f64) -> Option<List<Graphic>> {
let transparent = List::new_from_element(Color::TRANSPARENT).into_graphic_list();
let a = a.filter(|graphic_list| is_paint_present(graphic_list));
let b = b.filter(|graphic_list| is_paint_present(graphic_list));
let (a, b) = match (a, b) {
(None, None) => return None,
(Some(a), None) => (a, &transparent),
(None, Some(b)) => (&transparent, b),
(Some(a), Some(b)) => (a, b),
};
// This keeps the gradient metadata attributes
let gradient_with_stops = |mut gradient_list: List<GradientStops>, stops: GradientStops| -> Graphic {
if let Some(target) = gradient_list.element_mut(0) {
*target = stops;
} else {
gradient_list.push(Item::new_from_element(stops));
}
Graphic::Gradient(gradient_list)
};
let graphic = match (a.element(0), b.element(0)) {
(Some(Graphic::Color(color_list_a)), Some(Graphic::Color(color_list_b))) => color_list_a
.element(0)
.zip(color_list_b.element(0))
.map(|(color_a, color_b)| Graphic::from(color_a.lerp(color_b, time as f32))),
(Some(Graphic::Color(color_list_a)), Some(Graphic::Gradient(gradient_list_b))) => color_list_a.element(0).zip(gradient_list_b.element(0)).map(|(color_a, stops_b)| {
let mut solid_to_gradient = stops_b.clone();
solid_to_gradient.color.iter_mut().for_each(|color| *color = *color_a);
let stops = solid_to_gradient.lerp(stops_b, time);
gradient_with_stops(gradient_list_b.clone(), stops)
}),
(Some(Graphic::Gradient(gradient_list_a)), Some(Graphic::Color(color_list_b))) => gradient_list_a.element(0).zip(color_list_b.element(0)).map(|(stops_a, color_b)| {
let mut gradient_to_solid = stops_a.clone();
gradient_to_solid.color.iter_mut().for_each(|color| *color = *color_b);
let stops = stops_a.lerp(&gradient_to_solid, time);
gradient_with_stops(gradient_list_a.clone(), stops)
}),
(Some(Graphic::Gradient(gradient_list_a)), Some(Graphic::Gradient(gradient_list_b))) => gradient_list_a.element(0).zip(gradient_list_b.element(0)).map(|(stops_a, stops_b)| {
let stops = stops_a.lerp(stops_b, time);
let metadata_source = if time < 0.5 { gradient_list_a } else { gradient_list_b };
let mut gradient_list = metadata_source.clone();
gradient_list.set_attribute(ATTR_TRANSFORM, 0, lerp_gradient_transform(gradient_list_a, gradient_list_b, time));
gradient_with_stops(gradient_list, stops)
}),
// Pairings beyond solid colors and gradients (raster, vector, or mixed) can't be interpolated, so step at the midpoint
_ => return Some(if time < 0.5 { a.clone() } else { b.clone() }),
};
graphic.map(List::new_from_element)
}
// Preserve original `List<Graphic>` as upstream data so this group layer's nested layers can be edited by the tools.
let mut graphic_list_content = content.clone().into_graphic_list();
@@ -2432,9 +2621,35 @@ async fn morph<I: IntoGraphicList + 'n + Send + Clone>(
return List::new_from_item(Item::from_parts(endpoint_element.clone(), attributes));
}
let mut vector = Vector {
style: source_element.style.lerp(&target_element.style, time),
..Default::default()
let stroke = match (source_element.stroke.as_ref(), target_element.stroke.as_ref()) {
(Some(a), Some(b)) => Some(a.lerp(b, time)),
(Some(a), None) => {
if time < 0.5 {
Some(a.clone())
} else {
None
}
}
(None, Some(b)) => {
if time < 0.5 {
None
} else {
Some(b.clone())
}
}
(None, None) => None,
};
let mut vector = Vector { stroke, ..Default::default() };
let fill_paint = {
let source = graphic_list_at(&content, source_index, ATTR_FILL);
let target = graphic_list_at(&content, target_index, ATTR_FILL);
lerp_graphic(source.as_deref(), target.as_deref(), time)
};
let stroke_paint = {
let source = graphic_list_at(&content, source_index, ATTR_STROKE);
let target = graphic_list_at(&content, target_index, ATTR_STROKE);
lerp_graphic(source.as_deref(), target.as_deref(), time)
};
// Work directly with manipulator groups, bypassing the BezPath intermediate representation.
@@ -2585,16 +2800,23 @@ async fn morph<I: IntoGraphicList + 'n + Send + Clone>(
let primary_index = if time < 0.5 { source_index } else { target_index };
let layer_path: List<NodeId> = content.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, primary_index);
List::new_from_item(
Item::new_from_element(vector)
.with_attribute(ATTR_TRANSFORM, lerped_transform)
.with_attribute(ATTR_BLEND_MODE, lerped_blend_mode)
.with_attribute(ATTR_OPACITY, lerped_opacity)
.with_attribute(ATTR_OPACITY_FILL, lerped_fill)
.with_attribute(ATTR_CLIPPING_MASK, lerped_clip)
.with_attribute(ATTR_EDITOR_LAYER_PATH, layer_path)
.with_attribute(ATTR_EDITOR_MERGED_LAYERS, graphic_list_content),
)
let mut item = Item::new_from_element(vector)
.with_attribute(ATTR_TRANSFORM, lerped_transform)
.with_attribute(ATTR_BLEND_MODE, lerped_blend_mode)
.with_attribute(ATTR_OPACITY, lerped_opacity)
.with_attribute(ATTR_OPACITY_FILL, lerped_fill)
.with_attribute(ATTR_CLIPPING_MASK, lerped_clip)
.with_attribute(ATTR_EDITOR_LAYER_PATH, layer_path)
.with_attribute(ATTR_EDITOR_MERGED_LAYERS, graphic_list_content);
if let Some(fill) = fill_paint {
item.set_attribute(ATTR_FILL, fill);
}
if let Some(stroke) = stroke_paint {
item.set_attribute(ATTR_STROKE, stroke);
}
List::new_from_item(item)
}
fn bevel_algorithm(mut vector: Vector, transform: DAffine2, distance: f64) -> Vector {
@@ -3204,6 +3426,36 @@ mod test {
assert!((morphed.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, 0).translation - DVec2::new(-50., -50.)).length() < 1e-3);
}
#[tokio::test]
async fn morph_interpolates_fill() {
let rect = || {
let mut v = Vector::default();
v.append_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY));
v
};
let item_a = Item::new_from_element(rect())
.with_attribute(ATTR_TRANSFORM, DAffine2::IDENTITY)
.with_attribute(ATTR_FILL, List::new_from_element(Color::RED).into_graphic_list());
let item_b = Item::new_from_element(rect())
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation((-100., -100.).into()))
.with_attribute(ATTR_FILL, List::new_from_element(Color::BLUE).into_graphic_list());
let mut content = List::new_from_item(item_a);
content.push(item_b);
let morphed = super::morph(Footprint::default(), content, 0.5, false, InterpolationDistribution::default(), List::default()).await;
let fill = graphic_list_at(&morphed, 0, ATTR_FILL).expect("Morph should keep the fill paint at the midpoint");
// Interpolated color between red and blue should have >0 value on both R and B
let Some(Graphic::Color(colors)) = fill.element(0) else {
panic!("Expected a solid color fill, got {:?}", fill.element(0));
};
let color = *colors.element(0).expect("Color present");
assert!(color.r() > 0. && color.b() > 0., "Fill should be a red-to-blue blend, got {color:?}");
}
#[track_caller]
fn contains_segment(vector: Vector, target: PathSeg) {
let segments = vector.segment_iter().map(|x| x.1);
+3 -1
View File
@@ -70,7 +70,9 @@ pub fn build_wasm_steps(release: bool, native: bool) -> Vec<Expression> {
if release {
let wasm_file = pkg_dir.join(format!("{OUT_NAME}_bg.wasm"));
steps.push(cmd!("wasm-opt", "-Os", "-g", &wasm_file, "-o", &wasm_file));
// `-Oz` (size over speed) keeps us under Cloudflare Pages' 25 MiB single-file cap.
// `-g` preserves the name section, which the panic hook reads at runtime to spot node-graph panics (see wrapper `lib.rs`).
steps.push(cmd!("wasm-opt", "-Oz", "-g", &wasm_file, "-o", &wasm_file));
}
steps