mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
34
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5fd2f4075f | ||
|
|
9bb2bace2f | ||
|
|
af8ef1ce2c | ||
|
|
e3bd661f54 | ||
|
|
6e018d17d2 | ||
|
|
b5e603b784 | ||
|
|
7477cd2fab | ||
|
|
d9f045aaec | ||
|
|
c099b7e76b | ||
|
|
a024a8102f | ||
|
|
8f087a395b | ||
|
|
b345ca3fd2 | ||
|
|
baf2403d7e | ||
|
|
377ba8f00c | ||
|
|
f8f3ca5a53 | ||
|
|
a2f8a5dd6a | ||
|
|
4c3fabbaa5 | ||
|
|
e391d10831 | ||
|
|
45f0d21f25 | ||
|
|
24746da590 | ||
|
|
8ef7432e33 | ||
|
|
e4bcb13b2a | ||
|
|
275d3d0af9 | ||
|
|
02a60ce521 | ||
|
|
d033921124 | ||
|
|
4e4dc189f2 | ||
|
|
59aa4510d0 | ||
|
|
e38fab2245 | ||
|
|
7ec230b71a | ||
|
|
8f323f09bc | ||
|
|
38e4036230 | ||
|
|
658f03704f | ||
|
|
34eedcc3ac | ||
|
|
bb7c1a2073 |
No files matched your search
@@ -1,2 +1,2 @@
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/6687dc6d3d8552948458d00d35e2bee3a40ab66b.tar.gz
|
||||
7663b4a35f377a5d3363430a725a1d5f634fbdc56adca5e43167786b8fe1b253
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/ca7dd793caba8999ec33fde99bb721a69c3d221f.tar.gz
|
||||
77e8a6b68d67a8d5fcfd6268a6b7938ac9322d877378c6563e933a57df6da821
|
||||
@@ -7,9 +7,15 @@ on:
|
||||
- master
|
||||
paths:
|
||||
- website/**
|
||||
- frontend/eslint.config.js
|
||||
- frontend/eslint-require-data-selectors.js
|
||||
- frontend/package-lock.json
|
||||
pull_request:
|
||||
paths:
|
||||
- website/**
|
||||
- frontend/eslint.config.js
|
||||
- frontend/eslint-require-data-selectors.js
|
||||
- frontend/package-lock.json
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
INDEX_HTML_HEAD_INCLUSION: <script defer data-domain="graphite.art" data-api="/visit/event" src="/visit/script.hash.js"></script>
|
||||
@@ -30,6 +36,10 @@ jobs:
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
cache-dependency-path: |
|
||||
frontend/package-lock.json
|
||||
website/package-lock.json
|
||||
|
||||
- name: 🕸 Install Zola
|
||||
uses: taiki-e/install-action@v2
|
||||
@@ -55,9 +65,12 @@ jobs:
|
||||
cargo run -p crate-hierarchy-viz -- website/generated
|
||||
cargo run -p editor-message-tree -- website/generated
|
||||
|
||||
- name: 🔧 Install website npm dependencies
|
||||
- name: 🔧 Install website and frontend npm dependencies
|
||||
run: |
|
||||
cd website
|
||||
# The website is linted by the frontend's ESLint config and the tools it installs
|
||||
cd frontend
|
||||
npm ci
|
||||
cd ../website
|
||||
npm ci
|
||||
|
||||
- name: 📃 Generate node catalog documentation
|
||||
|
||||
+22
-2
@@ -61,7 +61,9 @@ in
|
||||
graphite-bundle = (lib.call ./pkgs/graphite-bundle.nix) { };
|
||||
graphite-bundle-dev = (lib.call ./pkgs/graphite-bundle.nix) { graphite = graphite-dev; };
|
||||
graphite-flatpak-manifest = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { };
|
||||
graphite-flatpak-manifest-dev = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { graphite-bundle = graphite-bundle-dev; };
|
||||
graphite-flatpak-manifest-dev = (lib.call ./pkgs/graphite-flatpak-manifest.nix) {
|
||||
graphite-bundle = graphite-bundle-dev;
|
||||
};
|
||||
graphite-cef = lib.call ./pkgs/graphite-cef.nix;
|
||||
|
||||
# TODO: graphene-cli = lib.call ./pkgs/graphene-cli.nix;
|
||||
@@ -70,8 +72,26 @@ in
|
||||
|
||||
devShells = withArgs (
|
||||
{ lib, ... }:
|
||||
let
|
||||
shell = lib.makeOverridable (lib.call ./dev.nix);
|
||||
in
|
||||
{
|
||||
default = lib.call ./dev.nix;
|
||||
default = shell {
|
||||
desktop = true;
|
||||
};
|
||||
full = shell {
|
||||
desktop = true;
|
||||
x11 = true;
|
||||
playwright = true;
|
||||
};
|
||||
minimal = shell { };
|
||||
x11 = shell {
|
||||
desktop = true;
|
||||
x11 = true;
|
||||
};
|
||||
playwright = shell {
|
||||
playwright = true;
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
+80
-52
@@ -3,62 +3,90 @@
|
||||
deps,
|
||||
self,
|
||||
system,
|
||||
lib,
|
||||
...
|
||||
}:
|
||||
|
||||
{
|
||||
desktop ? false,
|
||||
x11 ? false,
|
||||
playwright ? false,
|
||||
}:
|
||||
|
||||
let
|
||||
libs = [
|
||||
pkgs.wayland
|
||||
pkgs.vulkan-loader
|
||||
pkgs.libGL
|
||||
pkgs.openssl
|
||||
pkgs.libraw
|
||||
features = [
|
||||
{
|
||||
packages = [
|
||||
pkgs.pkg-config
|
||||
|
||||
# X11 Support
|
||||
pkgs.libxkbcommon
|
||||
pkgs.libXcursor
|
||||
pkgs.libxcb
|
||||
pkgs.libX11
|
||||
pkgs.lld
|
||||
pkgs.nodejs
|
||||
pkgs.binaryen
|
||||
pkgs.wasm-bindgen-cli_0_2_121
|
||||
pkgs.cargo-about
|
||||
|
||||
pkgs.rustc
|
||||
pkgs.cargo
|
||||
pkgs.rust-analyzer
|
||||
pkgs.clippy
|
||||
pkgs.rustfmt
|
||||
|
||||
pkgs.git
|
||||
|
||||
pkgs.cargo-nextest
|
||||
pkgs.cargo-expand
|
||||
|
||||
# Linker
|
||||
pkgs.mold
|
||||
|
||||
# Profiling tools
|
||||
pkgs.gnuplot
|
||||
pkgs.samply
|
||||
pkgs.cargo-flamegraph
|
||||
|
||||
# Plotting tools
|
||||
pkgs.graphviz
|
||||
];
|
||||
}
|
||||
deps.rustGPU
|
||||
(lib.optionalAttrs desktop (
|
||||
{
|
||||
libs = [
|
||||
pkgs.wayland
|
||||
pkgs.vulkan-loader
|
||||
pkgs.libGL
|
||||
pkgs.libxkbcommon
|
||||
self.packages.${system}.graphite-cef
|
||||
];
|
||||
env = {
|
||||
CEF_PATH = "${self.packages.${system}.graphite-cef}/lib";
|
||||
XDG_DATA_DIRS = "${pkgs.gsettings-desktop-schemas}/share/gsettings-schemas/${pkgs.gsettings-desktop-schemas.name}:${pkgs.gtk3}/share/gsettings-schemas/${pkgs.gtk3.name}:$XDG_DATA_DIRS";
|
||||
};
|
||||
}
|
||||
))
|
||||
(lib.optionalAttrs x11 {
|
||||
libs = [
|
||||
pkgs.libXcursor
|
||||
pkgs.libxcb
|
||||
pkgs.libX11
|
||||
];
|
||||
})
|
||||
(lib.optionalAttrs playwright (
|
||||
assert pkgs.playwright-driver.version == (lib.importJSON ../tools/web-editor-driver/playwright/package-lock.json).packages."node_modules/playwright-core".version;
|
||||
{
|
||||
env = {
|
||||
PLAYWRIGHT_BROWSERS_PATH = pkgs.playwright-driver.browsers-chromium;
|
||||
PLAYWRIGHT_SKIP_VALIDATE_HOST_REQUIREMENTS = "true";
|
||||
};
|
||||
}
|
||||
))
|
||||
];
|
||||
|
||||
libs = lib.concatMap (feature: feature.libs or [ ]) features;
|
||||
in
|
||||
pkgs.mkShell (
|
||||
{
|
||||
packages = libs ++ [
|
||||
pkgs.pkg-config
|
||||
|
||||
pkgs.lld
|
||||
pkgs.nodejs
|
||||
pkgs.binaryen
|
||||
pkgs.wasm-bindgen-cli_0_2_121
|
||||
pkgs.cargo-about
|
||||
|
||||
pkgs.rustc
|
||||
pkgs.cargo
|
||||
pkgs.rust-analyzer
|
||||
pkgs.clippy
|
||||
pkgs.rustfmt
|
||||
|
||||
pkgs.git
|
||||
|
||||
pkgs.cargo-nextest
|
||||
pkgs.cargo-expand
|
||||
|
||||
# Linker
|
||||
pkgs.mold
|
||||
|
||||
# Profiling tools
|
||||
pkgs.gnuplot
|
||||
pkgs.samply
|
||||
pkgs.cargo-flamegraph
|
||||
|
||||
# Plotting tools
|
||||
pkgs.graphviz
|
||||
];
|
||||
|
||||
CEF_PATH = self.packages.${system}.graphite-cef;
|
||||
LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libs}:${self.packages.${system}.graphite-cef}";
|
||||
XDG_DATA_DIRS = "${pkgs.gsettings-desktop-schemas}/share/gsettings-schemas/${pkgs.gsettings-desktop-schemas.name}:${pkgs.gtk3}/share/gsettings-schemas/${pkgs.gtk3.name}:$XDG_DATA_DIRS";
|
||||
|
||||
}
|
||||
// deps.rustGPU.env
|
||||
)
|
||||
pkgs.mkShell {
|
||||
packages = libs ++ lib.concatMap (feature: feature.packages or [ ]) features;
|
||||
env = lib.mergeAttrsList (map (feature: feature.env or { }) features) // {
|
||||
LD_LIBRARY_PATH = lib.makeLibraryPath libs;
|
||||
};
|
||||
}
|
||||
@@ -30,12 +30,13 @@ pkgs.cef-binary.overrideAttrs {
|
||||
postInstall = ''
|
||||
rm -r $out/* $out/.* || true
|
||||
strip ./Release/*.so*
|
||||
mv ./Release/* $out/
|
||||
mkdir $out/lib
|
||||
mv ./Release/* $out/lib/
|
||||
find "./Resources/locales" -maxdepth 1 -type f ! -name 'en-US.pak' -delete
|
||||
mv ./Resources/* $out/
|
||||
mv ./include $out/
|
||||
mv ./Resources/* $out/lib/
|
||||
mv ./include $out/lib/
|
||||
|
||||
cat ./CREDITS.html | ${pkgs.xz}/bin/xz -9 -e -c > $out/CREDITS.html.xz
|
||||
cat ./CREDITS.html | ${pkgs.xz}/bin/xz -9 -e -c > $out/lib/CREDITS.html.xz
|
||||
|
||||
echo '${
|
||||
builtins.toJSON {
|
||||
@@ -43,6 +44,6 @@ pkgs.cef-binary.overrideAttrs {
|
||||
name = builtins.baseNameOf url;
|
||||
sha1 = "";
|
||||
}
|
||||
}' > $out/archive.json
|
||||
}' > $out/lib/archive.json
|
||||
'';
|
||||
}
|
||||
@@ -20,6 +20,7 @@ let
|
||||
pkgs.libGL
|
||||
pkgs.openssl
|
||||
pkgs.libraw
|
||||
self.packages.${system}.graphite-cef
|
||||
# X11 Support
|
||||
pkgs.libxkbcommon
|
||||
pkgs.libXcursor
|
||||
@@ -50,7 +51,7 @@ let
|
||||
pkgs.pkg-config
|
||||
pkgs.lld
|
||||
];
|
||||
env.CEF_PATH = self.packages.${system}.graphite-cef;
|
||||
env.CEF_PATH = "${self.packages.${system}.graphite-cef}/lib";
|
||||
buildPhase =
|
||||
let
|
||||
profile = if dev then "dev" else "release";
|
||||
@@ -99,7 +100,7 @@ deps.crane.lib.buildPackage (
|
||||
RASTER_NODES_SHADER_PATH = self.packages.${system}.graphite-raster-nodes-shaders;
|
||||
GRAPHITE_GIT_COMMIT_HASH = self.rev or "unknown";
|
||||
GRAPHITE_GIT_COMMIT_DATE = self.lastModified or "unknown";
|
||||
CEF_PATH = self.packages.${system}.graphite-cef;
|
||||
CEF_PATH = "${self.packages.${system}.graphite-cef}/lib";
|
||||
};
|
||||
|
||||
postPatch = ''
|
||||
@@ -148,7 +149,7 @@ deps.crane.lib.buildPackage (
|
||||
remove-references-to -t "${common.cargoVendorDir}" $out/bin/graphite
|
||||
|
||||
patchelf \
|
||||
--set-rpath "${pkgs.lib.makeLibraryPath libs}:${self.packages.${system}.graphite-cef}" \
|
||||
--set-rpath "${pkgs.lib.makeLibraryPath libs}" \
|
||||
--add-needed libGL.so \
|
||||
--add-needed libEGL.so \
|
||||
$out/bin/graphite
|
||||
|
||||
Generated
+50
-2
@@ -831,9 +831,9 @@ checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
|
||||
|
||||
[[package]]
|
||||
name = "convert_case"
|
||||
version = "0.8.0"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "baaaa0ecca5b51987b9423ccdc971514dd8b0bb7b4060b983d3664dad3f1f89f"
|
||||
checksum = "1af709f1f33454bf52eadfc8c78b3b9ef9cb26fb54d16dc9cd9a7299f899fd1b"
|
||||
dependencies = [
|
||||
"unicode-segmentation",
|
||||
]
|
||||
@@ -2040,6 +2040,7 @@ dependencies = [
|
||||
"dyn-any",
|
||||
"glam 0.33.10",
|
||||
"graph-craft",
|
||||
"graphene-animation",
|
||||
"graphene-application-io",
|
||||
"graphene-core",
|
||||
"graphene-hash",
|
||||
@@ -2066,6 +2067,17 @@ dependencies = [
|
||||
"wgpu-executor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "graphene-animation"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"dyn-any",
|
||||
"glam 0.33.10",
|
||||
"graphene-hash",
|
||||
"kurbo",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "graphene-application-io"
|
||||
version = "0.0.0"
|
||||
@@ -2129,6 +2141,7 @@ dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam 0.33.10",
|
||||
"graphene-animation",
|
||||
"graphene-hash",
|
||||
"graphic-types",
|
||||
"log",
|
||||
@@ -2413,6 +2426,15 @@ dependencies = [
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "graphite-editor-control-protocol"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"glam 0.33.10",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "graphite-proc-macros"
|
||||
version = "0.0.0"
|
||||
@@ -2990,6 +3012,7 @@ dependencies = [
|
||||
"futures",
|
||||
"glam 0.33.10",
|
||||
"graph-craft",
|
||||
"graphene-animation",
|
||||
"graphene-core",
|
||||
"graphene-std",
|
||||
"gungraun",
|
||||
@@ -3427,7 +3450,9 @@ name = "math-nodes"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam 0.33.10",
|
||||
"graphene-core",
|
||||
"graphic-types",
|
||||
"log",
|
||||
"math-parser",
|
||||
@@ -4397,10 +4422,15 @@ checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
|
||||
name = "preprocessor"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"futures",
|
||||
"glam 0.33.10",
|
||||
"graph-craft",
|
||||
"graphene-std",
|
||||
"interpreted-executor",
|
||||
"log",
|
||||
"node-macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4612,11 +4642,13 @@ name = "raster-nodes"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"color",
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"fastnoise-lite",
|
||||
"futures",
|
||||
"glam 0.33.10",
|
||||
"graphene-core",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"image",
|
||||
@@ -6873,6 +6905,22 @@ dependencies = [
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "web-editor-driver"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"clap",
|
||||
"getrandom 0.3.3",
|
||||
"glam 0.33.10",
|
||||
"graphite-editor-control-protocol",
|
||||
"image",
|
||||
"interprocess",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "web-sys"
|
||||
version = "0.3.98"
|
||||
|
||||
+5
-1
@@ -12,6 +12,7 @@ members = [
|
||||
"document/graph-storage",
|
||||
"document/container",
|
||||
"editor",
|
||||
"editor/control-protocol",
|
||||
"frontend/wrapper",
|
||||
"libraries/dyn-any",
|
||||
"libraries/math-parser",
|
||||
@@ -35,6 +36,7 @@ members = [
|
||||
"tools/third-party-licenses",
|
||||
"tools/editor-message-tree",
|
||||
"tools/node-docs",
|
||||
"tools/web-editor-driver",
|
||||
]
|
||||
default-members = [
|
||||
"editor",
|
||||
@@ -77,6 +79,7 @@ preprocessor = { path = "node-graph/preprocessor" }
|
||||
math-parser = { path = "libraries/math-parser" }
|
||||
graphene-application-io = { path = "node-graph/libraries/application-io" }
|
||||
graphene-resource = { path = "node-graph/libraries/resources" }
|
||||
graphene-animation = { path = "node-graph/libraries/animation" }
|
||||
core-types = { path = "node-graph/libraries/core-types" }
|
||||
no-std-types = { path = "node-graph/libraries/no-std-types" }
|
||||
raster-types = { path = "node-graph/libraries/raster-types" }
|
||||
@@ -106,6 +109,7 @@ wgpu-executor = { path = "node-graph/libraries/wgpu-executor" }
|
||||
wgpu-sync = { path = "libraries/wgpu-sync" }
|
||||
graphite-proc-macros = { path = "proc-macros" }
|
||||
graphite-editor = { path = "editor" }
|
||||
graphite-editor-control-protocol = { path = "editor/control-protocol" }
|
||||
graphene-canvas-utils = { path = "node-graph/libraries/canvas-utils" }
|
||||
ipsum = { path = "libraries/ipsum" }
|
||||
|
||||
@@ -123,7 +127,7 @@ env_logger = "0.11"
|
||||
log = "0.4"
|
||||
bitflags = { version = "2.4", features = ["serde"] }
|
||||
ctor = "0.2"
|
||||
convert_case = "0.8"
|
||||
convert_case = "0.12"
|
||||
titlecase = "3.6"
|
||||
fancy-regex = "0.18.0"
|
||||
unicode-segmentation = "1.13.2"
|
||||
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":fLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"Number":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"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_deduplicationLine truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[194878846429432339,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3Line truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[194878846429432339,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3]Line truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"I64":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"I64":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_vaLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Number":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":{"Integer":0},"exposed":false}},{"Value":{"tagged_value":{"Number":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"Number":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"Integer":3},"exposed":false}},{"Value":{"tagged_value":{"Number":2.0},"exposed":false}},{"Value":{"tagged_value":{"Number":0.5},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"Number":2.0},"exposed"Line truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<allocLine truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"outLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Number":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"Number":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":{"Number":4000.0},"exposed":false}},{"Value":{"tagged_value":{"Number":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":1415828794531Line truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":Line truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":Line truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpLine truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_Line truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_Line truncated
|
||||
@@ -134,6 +134,10 @@ pub(crate) mod menu {
|
||||
// Return None for shortcuts that include mouse motion because we can't show them in native menu
|
||||
return None;
|
||||
};
|
||||
// Native menu shortcuts allow only one non-modifier key, so a shortcut with more (like a double tap) would otherwise trigger on a single press of its last key
|
||||
if key.is_some() && !matches!(labeled_key.key(), Key::Shift | Key::Control | Key::Alt | Key::Meta | Key::Command | Key::Accel) {
|
||||
return None;
|
||||
}
|
||||
match labeled_key.key() {
|
||||
Key::Shift => modifiers |= Modifiers::SHIFT,
|
||||
Key::Control => modifiers |= Modifiers::CONTROL,
|
||||
|
||||
@@ -146,6 +146,7 @@ impl<L: Layout> Gdd<L> {
|
||||
// Carry the per-peer cursor + view settings so a `.gdd` reopened elsewhere restores the viewport.
|
||||
let session_state = SessionState {
|
||||
peer_id: self.session.peer(),
|
||||
user_id: self.session.user(),
|
||||
head_rev: self.session.head_rev(),
|
||||
last_broadcast_rev: self.session.last_broadcast_rev(),
|
||||
redo_stack: self.session.redo_stack().to_vec(),
|
||||
@@ -194,8 +195,15 @@ impl<L: Layout> Gdd<L> {
|
||||
if options.include_registry {
|
||||
// With history, the persisted snapshot is the retired registry and the hot log layers on top
|
||||
// (mirrors `Session::load`); without history it must be the full working registry, since
|
||||
// `bootstrap_from_registry` reconstructs the whole document from it alone.
|
||||
let snapshot = if options.include_history { export_session.retired_registry() } else { export_session.registry() };
|
||||
// `bootstrap_from_registry` reconstructs the whole document from it alone. That document starts a history of
|
||||
// its own, so the tombstones go.
|
||||
let live;
|
||||
let snapshot = if options.include_history {
|
||||
export_session.retired_registry()
|
||||
} else {
|
||||
live = export_session.registry().without_tombstones();
|
||||
&live
|
||||
};
|
||||
sink.write_entry(&io::path_for(self.layout.registry_basename(), codecs.registry), &codecs.registry.write_single(snapshot)?)?;
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ use document_container::backends::folder::FolderBackend;
|
||||
use document_container::{AnyContainer, AsyncContainer, ByteHolder};
|
||||
#[cfg(feature = "conversion")]
|
||||
use document_graph_storage::{CommitError, NodeMetadataSource};
|
||||
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session};
|
||||
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session, UserId};
|
||||
#[cfg(feature = "conversion")]
|
||||
use graphene_resource::LoadResource;
|
||||
use graphene_resource::ResourceHash;
|
||||
@@ -141,18 +141,19 @@ impl<L: Layout> Gdd<L> {
|
||||
let has_history = io::exists(&working, layout.history_basename(), codecs.history).await;
|
||||
|
||||
let peer = session_state.peer_id;
|
||||
let user = session_state.user_id;
|
||||
let mut session = match (has_registry, has_history) {
|
||||
(true, true) => {
|
||||
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
|
||||
let history = load_history(&working, &layout, codecs.history).await?;
|
||||
Session::load(peer, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
|
||||
Session::load(peer, user, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
|
||||
}
|
||||
(true, false) => {
|
||||
// Registry-only export: synthesize a history that reproduces this state.
|
||||
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
|
||||
Session::bootstrap_from_registry(peer, registry)?
|
||||
Session::bootstrap_from_registry(peer, user, registry)?
|
||||
}
|
||||
(false, _) => Session::replay_from_history(peer, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
|
||||
(false, _) => Session::replay_from_history(peer, user, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
|
||||
};
|
||||
|
||||
// Restore the published frontier (silent/published undo boundary) regardless of which load arm ran.
|
||||
@@ -178,7 +179,11 @@ impl<L: Layout> Gdd<L> {
|
||||
let manifest = Manifest::new(document_uuid, editor_version, stdlib_version);
|
||||
let codecs = manifest.codecs;
|
||||
io::write_single(&working, layout.manifest_basename(), MANIFEST_CODEC, &manifest)?;
|
||||
let session_state = SessionState { peer_id: peer, ..Default::default() };
|
||||
let session_state = SessionState {
|
||||
peer_id: peer,
|
||||
user_id: UserId(peer.0),
|
||||
..Default::default()
|
||||
};
|
||||
io::write_single(&working, layout.session_basename(), codecs.session, &session_state)?;
|
||||
|
||||
let session = Session::with_peer(peer);
|
||||
|
||||
@@ -134,7 +134,7 @@ impl<L: Layout> Gdd<L> {
|
||||
/// advanced past what the working copy reflects, so the caller should treat the document as needing
|
||||
/// re-persist (mirrors [`stage_runtime_snapshot`](Self::stage_runtime_snapshot)).
|
||||
pub fn apply_hot_op(&mut self, op: HotOp) -> Result<(), Error> {
|
||||
self.session.apply_hot_op(op.clone())?;
|
||||
self.session.replay_hot_op(op.clone())?;
|
||||
self.append_hot_frame(&op)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -194,6 +194,7 @@ impl<L: Layout> Gdd<L> {
|
||||
fn persist_session_state(&mut self) -> Result<(), Error> {
|
||||
let state = SessionState {
|
||||
peer_id: self.session.peer(),
|
||||
user_id: self.session.user(),
|
||||
head_rev: self.session.head_rev(),
|
||||
last_broadcast_rev: self.session.last_broadcast_rev(),
|
||||
redo_stack: self.session.redo_stack().to_vec(),
|
||||
@@ -205,12 +206,10 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Re-snapshot the materialized working registry to `registry.bin`. `Session::load` trusts the stored
|
||||
/// registry to match the persisted `head`, so any cursor move (undo/redo) that rewinds the working
|
||||
/// registry without retiring must re-persist it or a reopen would read a registry inconsistent with
|
||||
/// `head`. Synchronous and hot-path-safe (`write_non_blocking`).
|
||||
/// Re-snapshot the retired registry to `registry.bin`. `Session::load` trusts it to match the persisted `head`
|
||||
/// and replays the hot log on top, so it must hold no hot op, and any cursor move must re-persist it.
|
||||
fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
|
||||
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.registry())?;
|
||||
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.retired_registry())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//!
|
||||
//! Lives in `session.json`. Rewritten on retirement.
|
||||
|
||||
use document_graph_storage::{NetworkId, PeerId, Rev, Value};
|
||||
use document_graph_storage::{NetworkId, PeerId, Rev, UserId, Value};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
@@ -15,6 +15,9 @@ pub struct SessionState {
|
||||
/// tiebreaking and minting peer-scoped IDs.
|
||||
#[serde(default)]
|
||||
pub peer_id: PeerId,
|
||||
/// The person using this device, registered in the CRDT so undo and authorship follow them across peer ids.
|
||||
#[serde(default)]
|
||||
pub user_id: UserId,
|
||||
/// Local-chain cursor. Points at the most recently applied retired delta, or `None` on an empty
|
||||
/// document (no commits yet).
|
||||
#[serde(default)]
|
||||
|
||||
@@ -596,11 +596,19 @@ fn first_commit_registers_peer_and_survives_reopen() {
|
||||
|
||||
gdd.commit_from_runtime(&network, &NoMetadata, &ResourceRegistry::new(), &HashMapResourceStorage::new())
|
||||
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
|
||||
assert_eq!(gdd.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "first commit registers the peer");
|
||||
assert_eq!(
|
||||
gdd.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
|
||||
Some(UserId(21)),
|
||||
"first commit registers the peer"
|
||||
);
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
|
||||
assert_eq!(reopened.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "registration survives reopen");
|
||||
assert_eq!(
|
||||
reopened.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
|
||||
Some(UserId(21)),
|
||||
"registration survives reopen"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -682,3 +690,33 @@ fn declarations_round_trip_through_byte_store() {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(feature = "conversion")]
|
||||
#[test]
|
||||
fn an_export_without_history_drops_tombstones() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
use document_graph_storage::{Network, NetworkId, RegistryDelta};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xAC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let id = NetworkId(7);
|
||||
gdd.stage_constructed_ops(vec![RegistryDelta::AddNetwork { id, network: Network::default() }], &Default::default(), &empty_byte_store())
|
||||
.unwrap();
|
||||
gdd.stage_constructed_ops(vec![RegistryDelta::RemoveNetwork { id, snapshot: Network::default() }], &Default::default(), &empty_byte_store())
|
||||
.unwrap();
|
||||
assert!(gdd.registry().removed_networks.contains_key(&id));
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("flat");
|
||||
let options = ExportOptions {
|
||||
include_history: false,
|
||||
..ExportOptions::default()
|
||||
};
|
||||
gdd.export(&dest, ExportFormat::Folder, options, &empty_byte_store(), None)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
|
||||
|
||||
let reopened = GddV1::open(&dest).await.unwrap_or_else(|error| panic!("open failed: {error:?}"));
|
||||
assert!(reopened.registry().removed_networks.is_empty(), "a document without history starts without tombstones");
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// Staging a whole document after a recorded batch, and what a reopen must carry over.
|
||||
#![cfg(feature = "conversion")]
|
||||
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::{NoMetadata, PeerId, Registry};
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
|
||||
use graph_craft::{ProtoNodeIdentifier, concrete};
|
||||
use graphene_resource::ResourceRegistry;
|
||||
|
||||
fn network_with_one_node() -> NodeNetwork {
|
||||
let node = DocumentNode {
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
|
||||
call_argument: concrete!(()),
|
||||
..Default::default()
|
||||
};
|
||||
NodeNetwork {
|
||||
nodes: [(NodeId(1), node)].into_iter().collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A whole-document stage after a recorded batch stages nothing new: restating the batch would fail on the node it added.
|
||||
#[test]
|
||||
fn restaging_the_whole_document_after_a_batch_stages_nothing() {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(21), 1, "ed".into(), "std".into()).unwrap();
|
||||
let store = HashMapResourceStorage::new();
|
||||
let resources = ResourceRegistry::new();
|
||||
gdd.stage_runtime_snapshot(&NodeNetwork::default(), &NoMetadata, &resources, &store)
|
||||
.expect("first whole-document stage");
|
||||
|
||||
let target = Registry::convert_from_runtime(&network_with_one_node(), &NoMetadata, &resources, PeerId(21)).unwrap();
|
||||
let ops = document_graph_storage::delta::compute_deltas(gdd.registry(), &target.registry);
|
||||
gdd.stage_constructed_ops(ops, &target.declaration_bytes, &store).expect("recorded batch");
|
||||
let hot_before = gdd.session().hot_log().len();
|
||||
|
||||
gdd.stage_runtime_snapshot(&network_with_one_node(), &NoMetadata, &resources, &store)
|
||||
.expect("the runtime already matches what was staged");
|
||||
assert_eq!(gdd.session().hot_log().len(), hot_before, "nothing new to stage");
|
||||
}
|
||||
|
||||
/// `registry.bin` is the retired snapshot the hot log replays onto, so an op still hot at save time must stay out of it.
|
||||
#[test]
|
||||
fn a_reopen_keeps_unretired_hot_ops_out_of_the_retired_snapshot() {
|
||||
use document_graph_storage::{AttributeDelta, HotOp, RegistryDelta, TimeStamp, Value};
|
||||
let set = |value: u32, counter: u64| HotOp {
|
||||
op: RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: AttributeDelta {
|
||||
key: "k".into(),
|
||||
value: Some(Value::from(serde_json::json!(value))),
|
||||
},
|
||||
},
|
||||
timestamp: TimeStamp { counter, peer: PeerId(22) },
|
||||
};
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(22), 1, "ed".into(), "std".into()).unwrap();
|
||||
gdd.apply_hot_op(set(1, 1)).unwrap();
|
||||
gdd.apply_hot_op(set(2, 2)).unwrap();
|
||||
gdd.retire(TimeStamp { counter: 1, peer: PeerId(22) }).unwrap();
|
||||
|
||||
let retired = gdd.session().retired_registry().clone();
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.unwrap();
|
||||
assert!(reopened.session().retired_registry().value_equal(&retired), "the hot op leaked into the retired snapshot");
|
||||
assert_eq!(reopened.session().hot_log().len(), 1);
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{TimeStamp, Value, ValueError, from_value, to_value};
|
||||
use crate::{AttributeDelta, TimeStamp, Value, ValueError, from_value, to_value};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, btree_map};
|
||||
|
||||
/// Attribute keys. Glob-import (`use crate::attr::*`) at conversion sites.
|
||||
///
|
||||
@@ -8,64 +8,214 @@ use std::collections::BTreeMap;
|
||||
/// keys live on `Node.inputs_attributes[i]`; per-network keys live on `Network.attributes`.
|
||||
pub mod attr;
|
||||
|
||||
/// A type-erased attribute value paired with the timestamp at which it was last set.
|
||||
/// An attribute value and when it was last set. A deleted key stays as a stamped tombstone, which readers see as absent.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AttributeValue {
|
||||
pub value: Value,
|
||||
pub timestamp: TimeStamp,
|
||||
// No skipping: the registry is positional on disk.
|
||||
#[serde(default)]
|
||||
pub deleted: bool,
|
||||
}
|
||||
|
||||
impl AttributeValue {
|
||||
pub fn new(value: Value, timestamp: TimeStamp) -> Self {
|
||||
Self { value, timestamp }
|
||||
Self { value, timestamp, deleted: false }
|
||||
}
|
||||
|
||||
/// The tombstone of a key deleted at `timestamp`.
|
||||
pub fn deleted(timestamp: TimeStamp) -> Self {
|
||||
Self {
|
||||
value: Value::None,
|
||||
timestamp,
|
||||
deleted: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type Attributes = BTreeMap<String, AttributeValue>;
|
||||
/// Attribute keys and their values, each last-writer-wins on its own timestamp. A key the map lacks is deleted as of
|
||||
/// its floor, when the map was last written whole.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Attributes {
|
||||
entries: BTreeMap<String, AttributeValue>,
|
||||
#[serde(default)]
|
||||
floor: TimeStamp,
|
||||
}
|
||||
|
||||
impl Attributes {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// An empty map written whole at `floor`, which deletes every key older than it.
|
||||
pub fn empty_at(floor: TimeStamp) -> Self {
|
||||
Self { entries: BTreeMap::new(), floor }
|
||||
}
|
||||
|
||||
/// When the map was last written whole.
|
||||
pub fn floor(&self) -> TimeStamp {
|
||||
self.floor
|
||||
}
|
||||
|
||||
/// Carries `floor` with the entries, so they land as the map they were taken from rather than as a new write.
|
||||
pub fn set_floor(&mut self, floor: TimeStamp) {
|
||||
self.floor = floor;
|
||||
}
|
||||
|
||||
pub fn get(&self, key: &str) -> Option<&AttributeValue> {
|
||||
self.entries.get(key)
|
||||
}
|
||||
|
||||
pub fn contains_key(&self, key: &str) -> bool {
|
||||
self.entries.contains_key(key)
|
||||
}
|
||||
|
||||
/// Every entry, tombstones included.
|
||||
pub fn iter(&self) -> btree_map::Iter<'_, String, AttributeValue> {
|
||||
self.entries.iter()
|
||||
}
|
||||
|
||||
pub fn keys(&self) -> btree_map::Keys<'_, String, AttributeValue> {
|
||||
self.entries.keys()
|
||||
}
|
||||
|
||||
/// The live entries: every key that is not a tombstone.
|
||||
pub fn live(&self) -> impl Iterator<Item = (&String, &AttributeValue)> {
|
||||
self.entries.iter().filter(|(_, value)| !value.deleted)
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.entries.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.entries.is_empty()
|
||||
}
|
||||
|
||||
pub fn insert(&mut self, key: String, value: AttributeValue) -> Option<AttributeValue> {
|
||||
self.entries.insert(key, value)
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, key: &str) -> Option<AttributeValue> {
|
||||
self.entries.remove(key)
|
||||
}
|
||||
|
||||
/// Lands a single-key write if it is newer than the key's value, or than the floor for a key the map lacks. A
|
||||
/// deletion leaves a tombstone.
|
||||
pub(crate) fn apply_delta(&mut self, delta: AttributeDelta, timestamp: TimeStamp, force: bool) {
|
||||
let AttributeDelta { key, value } = delta;
|
||||
let decided = self.get(&key).map_or(self.floor, |existing| existing.timestamp);
|
||||
if !force && timestamp <= decided {
|
||||
return;
|
||||
}
|
||||
let entry = match value {
|
||||
Some(value) => AttributeValue::new(value, timestamp),
|
||||
None => AttributeValue::deleted(timestamp),
|
||||
};
|
||||
self.insert(key, entry);
|
||||
}
|
||||
|
||||
/// Write helpers for `Attributes`.
|
||||
pub trait AttributesWrite {
|
||||
/// Inserts `value` under `key`.
|
||||
fn set(&mut self, key: &str, value: Value, timestamp: TimeStamp);
|
||||
pub fn set(&mut self, key: &str, value: Value, timestamp: TimeStamp) {
|
||||
self.insert(key.to_string(), AttributeValue::new(value, timestamp));
|
||||
}
|
||||
|
||||
/// Serializes `value` and inserts it under `key`.
|
||||
fn set_serialized<T: serde::Serialize>(&mut self, key: &str, value: &T, timestamp: TimeStamp) -> Result<(), ValueError> {
|
||||
pub fn set_serialized<T: serde::Serialize>(&mut self, key: &str, value: &T, timestamp: TimeStamp) -> Result<(), ValueError> {
|
||||
self.set(key, to_value(value)?, timestamp);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Inserts only when `value != default`, so the read side falls back to the same default.
|
||||
fn set_if_not_default<T: serde::Serialize + PartialEq>(&mut self, key: &str, value: &T, default: &T, timestamp: TimeStamp) -> Result<(), ValueError> {
|
||||
pub fn set_if_not_default<T: serde::Serialize + PartialEq>(&mut self, key: &str, value: &T, default: &T, timestamp: TimeStamp) -> Result<(), ValueError> {
|
||||
if value != default {
|
||||
self.set_serialized(key, value, timestamp)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl AttributesWrite for Attributes {
|
||||
fn set(&mut self, key: &str, value: Value, timestamp: TimeStamp) {
|
||||
self.insert(key.to_string(), AttributeValue { value, timestamp });
|
||||
/// Deserializes the value under `key`, or `None` if missing, deleted or undecodable.
|
||||
pub fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
|
||||
self.get(key).filter(|v| !v.deleted).and_then(|v| from_value(&v.value).ok())
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed read helpers for `Attributes`.
|
||||
pub trait AttributesRead {
|
||||
/// Deserializes the value under `key`, or `None` if missing or undecodable.
|
||||
fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T>;
|
||||
|
||||
/// Same as `get_typed`, falling back to `default`.
|
||||
fn get_or<T: serde::de::DeserializeOwned>(&self, key: &str, default: T) -> T {
|
||||
pub fn get_or<T: serde::de::DeserializeOwned>(&self, key: &str, default: T) -> T {
|
||||
self.get_typed(key).unwrap_or(default)
|
||||
}
|
||||
|
||||
/// Same as `get_typed`, falling back to `T::default()`.
|
||||
fn get_or_default<T: serde::de::DeserializeOwned + Default>(&self, key: &str) -> T {
|
||||
pub fn get_or_default<T: serde::de::DeserializeOwned + Default>(&self, key: &str) -> T {
|
||||
self.get_typed(key).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Writes the map whole at `timestamp`: the floor deletes every other key without a tombstone per key.
|
||||
pub(crate) fn stamp(&mut self, timestamp: TimeStamp) {
|
||||
self.entries.retain(|_, value| !value.deleted);
|
||||
self.entries.values_mut().for_each(|value| value.timestamp = timestamp);
|
||||
self.floor = timestamp;
|
||||
}
|
||||
|
||||
/// Stamps what arrives unstamped: the whole map if it carries no floor, else only the entries at the origin.
|
||||
pub(crate) fn stamp_unstamped(&mut self, timestamp: TimeStamp) {
|
||||
if self.floor == TimeStamp::ORIGIN {
|
||||
return self.stamp(timestamp);
|
||||
}
|
||||
self.entries
|
||||
.values_mut()
|
||||
.filter(|value| value.timestamp == TimeStamp::ORIGIN)
|
||||
.for_each(|value| value.timestamp = timestamp);
|
||||
}
|
||||
|
||||
/// Folds `other` in key by key: the newer entry wins, and a key only one map holds dies if the other map's floor is
|
||||
/// newer, as that map was written whole after it.
|
||||
pub(crate) fn merge(&mut self, other: Attributes) {
|
||||
self.entries.retain(|_, value| value.timestamp >= other.floor);
|
||||
for (key, value) in other.entries {
|
||||
match self.entries.entry(key) {
|
||||
btree_map::Entry::Occupied(entry) if value.timestamp > entry.get().timestamp => *entry.into_mut() = value,
|
||||
btree_map::Entry::Vacant(entry) if value.timestamp >= self.floor => {
|
||||
entry.insert(value);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
self.floor = self.floor.max(other.floor);
|
||||
}
|
||||
|
||||
/// The newest stamp the map carries, its floor included.
|
||||
pub(crate) fn newest(&self) -> TimeStamp {
|
||||
self.entries.values().map(|value| value.timestamp).fold(self.floor, TimeStamp::max)
|
||||
}
|
||||
}
|
||||
|
||||
impl AttributesRead for Attributes {
|
||||
fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
|
||||
self.get(key).and_then(|v| from_value(&v.value).ok())
|
||||
impl FromIterator<(String, AttributeValue)> for Attributes {
|
||||
fn from_iter<I: IntoIterator<Item = (String, AttributeValue)>>(iter: I) -> Self {
|
||||
Self {
|
||||
entries: iter.into_iter().collect(),
|
||||
floor: TimeStamp::ORIGIN,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Extend<(String, AttributeValue)> for Attributes {
|
||||
fn extend<I: IntoIterator<Item = (String, AttributeValue)>>(&mut self, iter: I) {
|
||||
self.entries.extend(iter);
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoIterator for Attributes {
|
||||
type Item = (String, AttributeValue);
|
||||
type IntoIter = btree_map::IntoIter<String, AttributeValue>;
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.entries.into_iter()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoIterator for &'a Attributes {
|
||||
type Item = (&'a String, &'a AttributeValue);
|
||||
type IntoIter = btree_map::Iter<'a, String, AttributeValue>;
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.entries.iter()
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,10 @@
|
||||
use crate::{
|
||||
AttributeValue, Attributes, AttributesWrite, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value,
|
||||
attr, compute_rev,
|
||||
};
|
||||
use crate::{Attributes, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev};
|
||||
use graphene_resource::ResourceHash;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Content-addressed delta: `id` is `blake3_128(parents, author, timestamp, delta_type)`.
|
||||
///
|
||||
/// `reverse` is state-dependent undo bookkeeping (it captures pre-state at the moment the forward
|
||||
/// op was applied), so it's serialized for storage but excluded from the identity hash — two peers
|
||||
/// observing the same forward delta against different local states would otherwise compute
|
||||
/// different Revs for the same logical op.
|
||||
/// `reverse` is undo bookkeeping that depends on local state, so it is stored but left out of the identity hash.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Delta {
|
||||
pub id: Rev,
|
||||
@@ -25,6 +19,10 @@ pub struct Delta {
|
||||
/// identity, and two peers annotating the same op differently must still dedup to one `Rev`.
|
||||
#[serde(default)]
|
||||
pub attributes: Attributes,
|
||||
/// When the delta entered history, in Unix milliseconds by the retiring peer's clock; display only and outside the rev.
|
||||
/// Zero means unrecorded, saving the tag byte of an `Option`. Last, since the history codec is positional.
|
||||
#[serde(default)]
|
||||
pub(crate) retired_at_ms: u64,
|
||||
}
|
||||
|
||||
impl Delta {
|
||||
@@ -38,6 +36,7 @@ impl Delta {
|
||||
kind,
|
||||
reverse,
|
||||
attributes: Attributes::default(),
|
||||
retired_at_ms: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,6 +57,7 @@ impl Delta {
|
||||
reverse: kind.clone(),
|
||||
kind,
|
||||
attributes: Attributes::default(),
|
||||
retired_at_ms: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,6 +79,11 @@ impl Delta {
|
||||
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == Value::Bool(true))
|
||||
}
|
||||
|
||||
/// When the delta entered history in wall-clock milliseconds, if the peer that retired it recorded it.
|
||||
pub fn retired_at(&self) -> Option<u64> {
|
||||
(self.retired_at_ms != 0).then_some(self.retired_at_ms)
|
||||
}
|
||||
|
||||
/// The content-addressed `Rev` this delta's identity fields hash to. Equals `id` for a delta built
|
||||
/// via `new`/`merge`; differs only if `id` was tampered with or the hash derivation changed.
|
||||
pub fn recomputed_id(&self) -> Rev {
|
||||
@@ -101,8 +106,7 @@ pub enum RegistryDelta {
|
||||
id: NodeId,
|
||||
node: Node,
|
||||
},
|
||||
/// `snapshot` lets the reverse `AddNode` rebuild without reading the (already-removed) node from
|
||||
/// the registry, mirroring `RemoveNetwork`.
|
||||
/// `snapshot` is the node as removed, which folds in like any write so a removal of a node never seen still lands.
|
||||
RemoveNode {
|
||||
id: NodeId,
|
||||
snapshot: Node,
|
||||
@@ -155,13 +159,12 @@ pub enum RegistryDelta {
|
||||
id: NetworkId,
|
||||
network: Network,
|
||||
},
|
||||
/// `snapshot` lets the reverse delta rebuild without re-walking history.
|
||||
/// `snapshot` is the network as removed; see [`RemoveNode`](Self::RemoveNode).
|
||||
RemoveNetwork {
|
||||
id: NetworkId,
|
||||
snapshot: Network,
|
||||
},
|
||||
/// Register a whole resource entry at once. Overwrites any existing entry for `id`; the reverse
|
||||
/// of `RemoveResource`, the way `AddNetwork` pairs with `RemoveNetwork`.
|
||||
/// Register a whole resource entry at once, the way `AddNetwork` pairs with `RemoveNetwork`.
|
||||
AddResource {
|
||||
id: ResourceId,
|
||||
entry: ResourceEntry,
|
||||
@@ -190,9 +193,7 @@ pub enum RegistryDelta {
|
||||
id: ResourceId,
|
||||
key: SourceKey,
|
||||
},
|
||||
/// Append-only registration of a device's `PeerId` against its owning `UserId`.
|
||||
/// First write wins; conflicting re-registration errors. Duplicate identical registration
|
||||
/// is a no-op. Not LWW — the mapping is forever.
|
||||
/// Registers a device's `PeerId` to the `UserId` behind it; the newest registration wins.
|
||||
RegisterPeer {
|
||||
peer: PeerId,
|
||||
user: UserId,
|
||||
@@ -221,28 +222,34 @@ pub struct AttributeDelta {
|
||||
pub(crate) fn reverse_attribute_delta(delta: &AttributeDelta, attributes: &Attributes) -> AttributeDelta {
|
||||
AttributeDelta {
|
||||
key: delta.key.clone(),
|
||||
value: attributes.get(&delta.key).map(|previous| previous.value.clone()),
|
||||
value: attributes.get(&delta.key).filter(|previous| !previous.deleted).map(|previous| previous.value.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn apply_attribute_delta(delta: AttributeDelta, timestamp: TimeStamp, force: bool, attributes: &mut Attributes) {
|
||||
let AttributeDelta { key, value } = delta;
|
||||
match value {
|
||||
Some(value) => match attributes.entry(key) {
|
||||
std::collections::btree_map::Entry::Occupied(mut entry) => {
|
||||
if force || timestamp > entry.get().timestamp {
|
||||
entry.insert(AttributeValue { value, timestamp });
|
||||
}
|
||||
}
|
||||
std::collections::btree_map::Entry::Vacant(entry) => {
|
||||
entry.insert(AttributeValue { value, timestamp });
|
||||
}
|
||||
},
|
||||
None => {
|
||||
let should_remove = force || attributes.get(&key).is_none_or(|existing| timestamp > existing.timestamp);
|
||||
if should_remove {
|
||||
attributes.remove(&key);
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn unrecorded_retired_at_costs_one_byte_and_round_trips() {
|
||||
let base = Delta::new(
|
||||
None,
|
||||
PeerId(1),
|
||||
TimeStamp { counter: 1, peer: PeerId(1) },
|
||||
RegistryDelta::Other(Value::None),
|
||||
RegistryDelta::Other(Value::None),
|
||||
);
|
||||
let mut stamped = base.clone();
|
||||
stamped.retired_at_ms = 1_790_000_000_000;
|
||||
|
||||
let bare_base = postcard::to_allocvec(&base).expect("encode");
|
||||
let bare_stamped = postcard::to_allocvec(&stamped).expect("encode");
|
||||
// Only the integer's varint differs: one byte for zero, six for today's milliseconds, no tag byte in either.
|
||||
assert_eq!(bare_stamped.len() - bare_base.len(), postcard::to_allocvec(&1_790_000_000_000u64).unwrap().len() - 1);
|
||||
|
||||
let decoded: Delta = postcard::from_bytes(&bare_stamped).expect("decode");
|
||||
assert_eq!(decoded.retired_at(), Some(1_790_000_000_000));
|
||||
let decoded: Delta = postcard::from_bytes(&bare_base).expect("decode");
|
||||
assert_eq!(decoded.retired_at(), None);
|
||||
}
|
||||
}
|
||||
@@ -166,14 +166,14 @@ fn diff_resource_entry(id: ResourceId, from: &ResourceEntry, to: &ResourceEntry,
|
||||
deltas.push(RegistryDelta::SetResourceHash { id, hash: to.hash });
|
||||
}
|
||||
|
||||
for (key, _) in &from.sources {
|
||||
for (key, _) in from.live_sources() {
|
||||
if to.source(key).is_none() {
|
||||
deltas.push(RegistryDelta::RemoveSource { id, key: *key });
|
||||
}
|
||||
}
|
||||
|
||||
// Compare source bodies only; the per-source timestamp is derived from the diff, not part of it.
|
||||
for (key, to_source) in &to.sources {
|
||||
for (key, to_source) in to.live_sources() {
|
||||
if from.source(key).is_none_or(|from_source| from_source.source != to_source.source) {
|
||||
deltas.push(RegistryDelta::AddSource {
|
||||
id,
|
||||
@@ -196,15 +196,15 @@ fn nodes_have_same_implementation(a: &Node, b: &Node) -> bool {
|
||||
fn compute_attribute_deltas(from: &crate::Attributes, to: &crate::Attributes) -> Vec<AttributeDelta> {
|
||||
let mut deltas = Vec::new();
|
||||
|
||||
for key in from.keys() {
|
||||
if !to.contains_key(key) {
|
||||
for (key, _) in from.live() {
|
||||
if to.get(key).is_none_or(|value| value.deleted) {
|
||||
deltas.push(AttributeDelta { key: key.clone(), value: None });
|
||||
}
|
||||
}
|
||||
|
||||
// Compare by `value` only; the per-entry `timestamp` is derived from the diff, not part of it.
|
||||
for (key, to_value) in to {
|
||||
if from.get(key).is_none_or(|from_value| from_value.value != to_value.value) {
|
||||
for (key, to_value) in to.live() {
|
||||
if from.get(key).is_none_or(|from_value| from_value.deleted || from_value.value != to_value.value) {
|
||||
deltas.push(AttributeDelta {
|
||||
key: key.clone(),
|
||||
value: Some(to_value.value.clone()),
|
||||
@@ -298,7 +298,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_compute_deltas_change_network_attribute() {
|
||||
use crate::{AttributesWrite, TimeStamp};
|
||||
use crate::TimeStamp;
|
||||
|
||||
let mut from = Registry::default();
|
||||
from.networks.insert(NetworkId(0), Network::default());
|
||||
@@ -340,6 +340,7 @@ mod tests {
|
||||
crate::AttributeValue {
|
||||
value: Value::Str("old".into()),
|
||||
timestamp: stamp(0),
|
||||
deleted: false,
|
||||
},
|
||||
);
|
||||
from.node_instances.insert(NodeId(42), node);
|
||||
@@ -350,6 +351,7 @@ mod tests {
|
||||
crate::AttributeValue {
|
||||
value: Value::Str("new".into()),
|
||||
timestamp: stamp(1),
|
||||
deleted: false,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -375,6 +377,7 @@ mod tests {
|
||||
crate::AttributeValue {
|
||||
value: Value::Str("value".into()),
|
||||
timestamp: stamp(1),
|
||||
deleted: false,
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -1,23 +1,24 @@
|
||||
use std::collections::HashMap;
|
||||
use std::hash::Hash;
|
||||
|
||||
use crate::{
|
||||
CrdtError, Delta, ExportSlot, History, HotOp, LamportClock, MAX_EXPORT_SLOTS, NetworkId, NodeId, NodeInput, PeerId, Registry, RegistryDelta, ResourceEntry, Rev, SourceValue, TimeStamp, Value,
|
||||
apply_attribute_delta, reverse_attribute_delta,
|
||||
Attributes, CrdtError, Delta, ExportSlot, History, HotOp, Implementation, InputSlot, LamportClock, MAX_EXPORT_SLOTS, MAX_INPUT_SLOTS, Network, NetworkId, Node, NodeId, NodeInput, PeerId,
|
||||
PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, Rev, SourceValue, TimeStamp, Tombstone, UserId, Value, reverse_attribute_delta,
|
||||
};
|
||||
use std::borrow::Cow;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Document {
|
||||
/// Working registry: retired state with the current hot ops applied on top. This is what live
|
||||
/// reads and `registry()` observe, and what undo/redo force-apply against.
|
||||
/// reads and `registry()` observe.
|
||||
pub(crate) working_registry: Registry,
|
||||
/// Live broadcast stream, applied to the `working_registry` on receive, GC'd at retirement.
|
||||
/// Persisted for crash recovery so in-flight unretired work survives editor restarts.
|
||||
pub(crate) hot_log: Vec<HotOp>,
|
||||
/// The registry as of the last retirement, with no un-retired hot ops applied. Retirement computes
|
||||
/// each delta's `reverse` against this (so LWW reverses capture the true pre-op value, not the
|
||||
/// hot-polluted working state) and advances it, stamping fields at the fresh `T_retire`. Kept equal
|
||||
/// to `registry` *by value* whenever the hot log is empty (undo/redo resync it after moving the
|
||||
/// cursor), but field timestamps can differ: retirement bumps the snapshot's to `T_retire` while the
|
||||
/// working registry keeps the staging-time timestamps. Benign while the local monotonic clock makes
|
||||
/// new edits win
|
||||
/// hot-polluted working state) and advances it. It equals the working registry whenever the hot log is
|
||||
/// empty.
|
||||
pub(crate) retired_snapshot: Registry,
|
||||
/// User's cursor in their local history chain. `None` on an empty document (no commits yet).
|
||||
pub(crate) head: Option<Rev>,
|
||||
@@ -28,9 +29,8 @@ pub struct Document {
|
||||
pub(crate) redo_stack: Vec<Rev>,
|
||||
pub(crate) clock: LamportClock,
|
||||
pub(crate) peer: PeerId,
|
||||
/// Latest retired commit on the local chain that has been broadcast to at least one peer.
|
||||
/// Commits after this can be rewritten silently; commits at or before this are published
|
||||
/// and require forward reverse-delta ops to undo. `None` means nothing broadcast yet.
|
||||
pub(crate) user: UserId,
|
||||
/// The latest retired commit a peer holds: commits after it undo silently, commits up to it stay.
|
||||
pub(crate) last_broadcast_rev: Option<Rev>,
|
||||
/// Shared-monotonic counter feeding `next_node_id`. Bumped on every mint regardless of which
|
||||
/// peer is calling; collision avoidance comes from hashing `(self.peer, counter)`, so two peers
|
||||
@@ -39,6 +39,22 @@ pub struct Document {
|
||||
}
|
||||
|
||||
impl Document {
|
||||
pub(crate) fn empty(peer: PeerId, user: UserId) -> Self {
|
||||
Self {
|
||||
working_registry: Registry::default(),
|
||||
retired_snapshot: Registry::default(),
|
||||
history: History::new(),
|
||||
hot_log: Vec::new(),
|
||||
head: None,
|
||||
redo_stack: Vec::new(),
|
||||
clock: LamportClock::new(peer),
|
||||
peer,
|
||||
user,
|
||||
last_broadcast_rev: None,
|
||||
next_node_counter: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Mint a fresh `NodeId` scoped to this document's peer. The 64-bit ID is `blake3(peer, counter)`
|
||||
/// truncated; the counter is shared across peers and persisted with the document.
|
||||
pub fn next_node_id(&mut self) -> NodeId {
|
||||
@@ -51,42 +67,6 @@ impl Document {
|
||||
NodeId(u64::from_le_bytes(truncated))
|
||||
}
|
||||
|
||||
pub(crate) fn restore_node_from_history(&mut self, target: RegistryTarget, node_id: NodeId) -> Result<(), CrdtError> {
|
||||
let delta = self
|
||||
.find_in_ancestry(|d| matches!(d.reverse, RegistryDelta::AddNode { id, .. } if id == node_id))
|
||||
.ok_or(CrdtError::NodeNotInHistory(node_id))?;
|
||||
self.revert_delta(target, delta)
|
||||
}
|
||||
|
||||
pub(crate) fn restore_network_from_history(&mut self, target: RegistryTarget, network_id: NetworkId) -> Result<(), CrdtError> {
|
||||
// Find the Delta whose forward op removed this network. Its `reverse` is `AddNetwork`,
|
||||
// which is what we want to re-apply.
|
||||
let delta = self
|
||||
.find_in_ancestry(|d| matches!(d.reverse, RegistryDelta::AddNetwork { id, .. } if id == network_id))
|
||||
.ok_or(CrdtError::NetworkNotInHistory(network_id))?;
|
||||
self.revert_delta(target, delta)
|
||||
}
|
||||
|
||||
/// Search every delta reachable from `head` (following all parents, including a merge's
|
||||
/// `extra_parents`) for the first matching `predicate`, breadth-first. Resurrection needs full
|
||||
/// ancestry reachability, so a node added only on a merged-in branch is still found.
|
||||
fn find_in_ancestry(&self, predicate: impl Fn(&Delta) -> bool) -> Option<Delta> {
|
||||
let mut queue: std::collections::VecDeque<Rev> = self.head.into_iter().collect();
|
||||
let mut seen: std::collections::HashSet<Rev> = self.head.into_iter().collect();
|
||||
while let Some(rev) = queue.pop_front() {
|
||||
let Some(delta) = self.history.get(rev) else { continue };
|
||||
if predicate(delta) {
|
||||
return Some(delta.clone());
|
||||
}
|
||||
for parent in delta.all_parents() {
|
||||
if seen.insert(parent) {
|
||||
queue.push_back(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Apply a delta's `reverse` as the new forward op (silent-zone undo). Force-applied: structural
|
||||
/// ops are idempotent, and LWW arms assign the reverse value unconditionally even though it carries
|
||||
/// the same timestamp as the forward op it undoes.
|
||||
@@ -100,26 +80,21 @@ impl Document {
|
||||
self.apply_op_with(target, delta.kind, delta.timestamp, ApplyMode::Force)
|
||||
}
|
||||
|
||||
/// Apply a live broadcast op. Updates the registry via LWW and appends to the hot log.
|
||||
/// Doesn't touch history or `head` — hot ops are transient.
|
||||
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
|
||||
self.apply_op(hot_op.op.clone(), hot_op.timestamp)?;
|
||||
/// Stage a local op onto the working registry and the hot log.
|
||||
pub(crate) fn stage_hot_op(&mut self, hot_op: HotOp, mode: ApplyMode) -> Result<(), CrdtError> {
|
||||
self.apply_op_with(RegistryTarget::Working, hot_op.op.clone(), hot_op.timestamp, mode)?;
|
||||
self.hot_log.push(hot_op);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Replay a hot op recovered from persisted state. Idempotent on structural ops so that
|
||||
/// re-applying an op whose effect is already reflected in the registry is a no-op rather
|
||||
/// than an error.
|
||||
/// Replay a persisted or received hot op. One already reflected in the registry changes nothing.
|
||||
pub fn replay_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
|
||||
self.apply_op_idempotent(hot_op.op.clone(), hot_op.timestamp)?;
|
||||
self.hot_log.push(hot_op);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Apply a retired commit. Idempotent on structural ops (AddNode/AddNetwork on existing
|
||||
/// targets, Remove on missing ones) since hot ops already produced the structural state.
|
||||
/// The point is to bump field timestamps to T_retire via the LWW arms.
|
||||
/// Apply a retired commit and record it in history.
|
||||
pub fn apply_delta(&mut self, delta: Delta) -> Result<(), CrdtError> {
|
||||
for parent in delta.all_parents() {
|
||||
if !self.history.contains(parent) {
|
||||
@@ -135,26 +110,24 @@ impl Document {
|
||||
fn registry_mut(&mut self, target: RegistryTarget) -> &mut Registry {
|
||||
match target {
|
||||
RegistryTarget::Working => &mut self.working_registry,
|
||||
RegistryTarget::Snapshot => &mut self.retired_snapshot,
|
||||
RegistryTarget::Retired => &mut self.retired_snapshot,
|
||||
}
|
||||
}
|
||||
|
||||
fn registry_ref(&self, target: RegistryTarget) -> &Registry {
|
||||
pub(crate) fn registry_ref(&self, target: RegistryTarget) -> &Registry {
|
||||
match target {
|
||||
RegistryTarget::Working => &self.working_registry,
|
||||
RegistryTarget::Snapshot => &self.retired_snapshot,
|
||||
RegistryTarget::Retired => &self.retired_snapshot,
|
||||
}
|
||||
}
|
||||
|
||||
/// New local/remote op against the working registry: add ops error on duplicate targets and
|
||||
/// `Change*` ops error on a missing target, while remove ops no-op when the target is already
|
||||
/// absent; LWW arms keep the newer-timestamp value (strict `>`). The common entry point for edits.
|
||||
/// A fresh local edit against the working registry; see [`ApplyMode::Strict`].
|
||||
#[cfg(test)]
|
||||
pub(crate) fn apply_op(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
|
||||
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Live)
|
||||
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Strict)
|
||||
}
|
||||
|
||||
/// Replay/retire against the working registry: structural ops skip duplicate/missing targets (the
|
||||
/// state is already present from hot ops or a prior snapshot); LWW arms still gate on strict `>`.
|
||||
/// An op from a peer or from persisted state, against the working registry.
|
||||
pub(crate) fn apply_op_idempotent(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
|
||||
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Idempotent)
|
||||
}
|
||||
@@ -166,146 +139,180 @@ impl Document {
|
||||
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Force)
|
||||
}
|
||||
|
||||
/// Applies one op. Every field, existence included, is last-writer-wins on a timestamp, so ops fold alike in any order:
|
||||
/// an addition writes every field, a removal keeps the content as a tombstone, a newer write or reference revives an
|
||||
/// older removal, and a write to an entity never seen lands on a placeholder until its addition arrives.
|
||||
pub(crate) fn apply_op_with(&mut self, target: RegistryTarget, op: RegistryDelta, timestamp: TimeStamp, mode: ApplyMode) -> Result<(), CrdtError> {
|
||||
// Advance the local clock past every observed op, including ones that subsequently no-op or
|
||||
// error. Observation is about causality knowledge, not about whether the op took effect.
|
||||
self.clock.observe(timestamp);
|
||||
|
||||
// Structural ops skip (rather than error) on duplicate/missing targets when not a fresh edit;
|
||||
// LWW arms assign unconditionally only under `Force`.
|
||||
let idempotent = mode != ApplyMode::Live;
|
||||
let strict = mode == ApplyMode::Strict;
|
||||
let force = mode == ApplyMode::Force;
|
||||
|
||||
// Resurrect any concurrently-removed targets the op references before binding the registry
|
||||
// (resurrection re-borrows `self` via history), so the mutation below holds one `registry` ref.
|
||||
self.ensure_referenced_exist(target, &op)?;
|
||||
|
||||
let registry = self.registry_mut(target);
|
||||
match op {
|
||||
RegistryDelta::AddNode { id, node } => {
|
||||
if registry.node_instances.contains_key(&id) {
|
||||
if idempotent {
|
||||
// Hot ops already created this node; skip rather than error.
|
||||
return Ok(());
|
||||
}
|
||||
if strict && registry.node_instances.contains_key(&id) {
|
||||
return Err(CrdtError::NodeAlreadyExists(id));
|
||||
}
|
||||
registry.node_instances.insert(id, node);
|
||||
write_network(registry, node.network, timestamp, mode, |_| Ok(()))?;
|
||||
add_entity(&mut registry.node_instances, &mut registry.removed_nodes, id, node, timestamp, force);
|
||||
}
|
||||
RegistryDelta::RemoveNode { id, .. } => {
|
||||
registry.node_instances.remove(&id);
|
||||
RegistryDelta::RemoveNode { id, snapshot } => {
|
||||
remove_entity(&mut registry.node_instances, &mut registry.removed_nodes, id, snapshot, timestamp, force);
|
||||
}
|
||||
RegistryDelta::SetNodeInputs { id, inputs } => {
|
||||
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
// The list is one value rather than independently mergeable slots, so the newest slot stands in
|
||||
// for a timestamp the list itself does not carry, and an older write is dropped whole.
|
||||
let newest = node.inputs.iter().map(|slot| slot.timestamp).max().unwrap_or(TimeStamp::ORIGIN);
|
||||
if force || timestamp > newest {
|
||||
// The slots arrive carrying the placeholder timestamp they were built with, so they take this
|
||||
// op's instead. Leaving the placeholder would reset every slot to the origin and make each
|
||||
// later per-slot gate vacuously true, letting a stale write win.
|
||||
node.inputs = inputs.into_iter().map(|slot| crate::InputSlot { timestamp, ..slot }).collect();
|
||||
RegistryDelta::SetNodeInputs { id, mut inputs } => {
|
||||
inputs.iter_mut().for_each(|slot| stamp_listed_slot(slot, timestamp));
|
||||
let referenced: Vec<NodeId> = inputs
|
||||
.iter()
|
||||
.filter_map(|slot| match slot.input {
|
||||
NodeInput::Node { id, .. } => Some(id),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
ensure_seen(registry, &referenced, mode)?;
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
if force {
|
||||
node.inputs = inputs;
|
||||
node.inputs_timestamp = timestamp;
|
||||
} else {
|
||||
merge_inputs(node, inputs, timestamp);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
for referenced in referenced {
|
||||
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
|
||||
}
|
||||
}
|
||||
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
|
||||
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
let input = node.inputs.get_mut(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
|
||||
if force || timestamp > input.timestamp {
|
||||
input.input = new_input;
|
||||
input.timestamp = timestamp;
|
||||
let referenced = match new_input {
|
||||
NodeInput::Node { id, .. } => Some(id),
|
||||
_ => None,
|
||||
};
|
||||
ensure_seen(registry, referenced.as_slice(), mode)?;
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
let Some(input) = slot_for_write(node, index as usize, timestamp, mode)? else { return Ok(()) };
|
||||
if force || timestamp > input.timestamp {
|
||||
input.input = new_input;
|
||||
input.timestamp = timestamp;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
if let Some(referenced) = referenced {
|
||||
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
|
||||
}
|
||||
}
|
||||
RegistryDelta::SetNodeImplementation { id, implementation } => {
|
||||
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
if force || timestamp > node.implementation_timestamp {
|
||||
node.implementation = implementation;
|
||||
node.implementation_timestamp = timestamp;
|
||||
ensure_seen(registry, &[id], mode)?;
|
||||
if let Implementation::Network(network) = implementation {
|
||||
write_network(registry, network, timestamp, mode, |_| Ok(()))?;
|
||||
}
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
if force || timestamp > node.implementation_timestamp {
|
||||
node.implementation = implementation;
|
||||
node.implementation_timestamp = timestamp;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
RegistryDelta::ChangeNodeAttribute { id, delta } => {
|
||||
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
apply_attribute_delta(delta, timestamp, force, &mut node.attributes);
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
node.attributes.apply_delta(delta, timestamp, force);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => {
|
||||
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
let input = node.inputs.get_mut(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
|
||||
apply_attribute_delta(delta, timestamp, force, &mut input.attributes);
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
let Some(input) = slot_for_write(node, index as usize, timestamp, mode)? else { return Ok(()) };
|
||||
input.attributes.apply_delta(delta, timestamp, force);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
RegistryDelta::SetNetworkExport { id, index, export } => {
|
||||
let net = registry.networks.get_mut(&id).ok_or(CrdtError::NetworkDoesNotExist(id))?;
|
||||
let slot_idx = index as usize;
|
||||
|
||||
if slot_idx >= net.exports.len() {
|
||||
if slot_idx >= MAX_EXPORT_SLOTS {
|
||||
return Err(CrdtError::ExportSlotOutOfBounds(index));
|
||||
let referenced = match export {
|
||||
Some(NodeInput::Node { id, .. }) => Some(id),
|
||||
_ => None,
|
||||
};
|
||||
ensure_seen(registry, referenced.as_slice(), mode)?;
|
||||
write_network(registry, id, timestamp, mode, |net| {
|
||||
let slot_idx = index as usize;
|
||||
if slot_idx >= net.exports.len() {
|
||||
if slot_idx >= MAX_EXPORT_SLOTS {
|
||||
return Err(CrdtError::ExportSlotOutOfBounds(index));
|
||||
}
|
||||
// Past the end of a newer list the slot is gone, as with input slots.
|
||||
if !force && timestamp <= net.exports_timestamp {
|
||||
return Ok(());
|
||||
}
|
||||
let shape = net.exports_timestamp;
|
||||
net.exports.resize_with(slot_idx + 1, || ExportSlot { target: None, timestamp: shape });
|
||||
}
|
||||
net.exports.resize(
|
||||
slot_idx + 1,
|
||||
ExportSlot {
|
||||
target: None,
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let existing = &mut net.exports[slot_idx];
|
||||
if force || timestamp > existing.timestamp {
|
||||
existing.target = export;
|
||||
existing.timestamp = timestamp;
|
||||
let existing = &mut net.exports[slot_idx];
|
||||
if force || timestamp > existing.timestamp {
|
||||
existing.target = export;
|
||||
existing.timestamp = timestamp;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
if let Some(referenced) = referenced {
|
||||
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
|
||||
}
|
||||
}
|
||||
RegistryDelta::AddNetwork { id, network: contents } => {
|
||||
if registry.networks.contains_key(&id) {
|
||||
if idempotent {
|
||||
return Ok(());
|
||||
}
|
||||
RegistryDelta::AddNetwork { id, network } => {
|
||||
if strict && registry.networks.contains_key(&id) {
|
||||
return Err(CrdtError::NetworkAlreadyExists(id));
|
||||
}
|
||||
registry.networks.insert(id, contents);
|
||||
add_entity(&mut registry.networks, &mut registry.removed_networks, id, network, timestamp, force);
|
||||
}
|
||||
RegistryDelta::RemoveNetwork { id, .. } => {
|
||||
registry.networks.remove(&id);
|
||||
RegistryDelta::RemoveNetwork { id, snapshot } => {
|
||||
remove_entity(&mut registry.networks, &mut registry.removed_networks, id, snapshot, timestamp, force);
|
||||
}
|
||||
RegistryDelta::ChangeNetworkAttribute { id, delta } => {
|
||||
let net = registry.networks.get_mut(&id).ok_or(CrdtError::NetworkDoesNotExist(id))?;
|
||||
apply_attribute_delta(delta, timestamp, force, &mut net.attributes);
|
||||
write_network(registry, id, timestamp, mode, |net| {
|
||||
net.attributes.apply_delta(delta, timestamp, force);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
RegistryDelta::SetResourceHash { id, hash } => {
|
||||
let entry = registry.resources.entry(id).or_default();
|
||||
if force || timestamp > entry.hash_timestamp {
|
||||
entry.hash = hash;
|
||||
entry.hash_timestamp = timestamp;
|
||||
}
|
||||
upsert_resource(registry, id, timestamp, |entry| {
|
||||
if force || timestamp > entry.hash_timestamp {
|
||||
entry.hash = hash;
|
||||
entry.hash_timestamp = timestamp;
|
||||
}
|
||||
});
|
||||
}
|
||||
RegistryDelta::AddSource { id, key, source } => {
|
||||
let entry = registry.resources.entry(id).or_default();
|
||||
let value = SourceValue { source, timestamp };
|
||||
if force { entry.force_set_source(key, value) } else { entry.set_source(key, value) }
|
||||
upsert_resource(registry, id, timestamp, |entry| {
|
||||
let value = SourceValue { source, timestamp, deleted: false };
|
||||
if force { entry.force_set_source(key, value) } else { entry.set_source(key, value) }
|
||||
});
|
||||
}
|
||||
RegistryDelta::RemoveSource { id, key } => {
|
||||
if let Some(entry) = registry.resources.get_mut(&id) {
|
||||
// An upsert, so a removal for an entry never seen leaves a tombstone its addition loses to.
|
||||
upsert_resource(registry, id, timestamp, |entry| {
|
||||
if force {
|
||||
entry.force_remove_source(&key);
|
||||
} else {
|
||||
entry.remove_source(&key, timestamp);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
RegistryDelta::AddResource { id, entry } => {
|
||||
registry.resources.insert(id, entry);
|
||||
add_entity(&mut registry.resources, &mut registry.removed_resources, id, entry, timestamp, force);
|
||||
}
|
||||
RegistryDelta::RemoveResource { id, .. } => {
|
||||
registry.resources.remove(&id);
|
||||
RegistryDelta::RemoveResource { id, snapshot } => {
|
||||
remove_entity(&mut registry.resources, &mut registry.removed_resources, id, snapshot, timestamp, force);
|
||||
}
|
||||
RegistryDelta::RegisterPeer { peer, user } => match registry.peer_users.get(&peer) {
|
||||
Some(existing) if *existing != user => return Err(CrdtError::PeerRegistrationConflict(peer)),
|
||||
Some(_) => {}
|
||||
None => {
|
||||
registry.peer_users.insert(peer, user);
|
||||
RegistryDelta::RegisterPeer { peer, user } => {
|
||||
// The newest registration of a device wins, whatever order they land in.
|
||||
if registry.peer_users.get(&peer).is_none_or(|existing| timestamp > existing.timestamp) {
|
||||
registry.peer_users.insert(peer, PeerRegistration { user, timestamp });
|
||||
}
|
||||
},
|
||||
}
|
||||
RegistryDelta::ChangeDocumentAttribute { delta } => {
|
||||
apply_attribute_delta(delta, timestamp, force, &mut registry.attributes);
|
||||
registry.attributes.apply_delta(delta, timestamp, force);
|
||||
}
|
||||
// Merge is a structural sync point only; it mutates no registry state.
|
||||
RegistryDelta::Merge { .. } | RegistryDelta::Other(_) => {}
|
||||
@@ -313,99 +320,42 @@ impl Document {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resurrect (from history) any nodes/networks an op references that were concurrently removed, so
|
||||
/// the op applies against a consistent registry. Cascading: a node's owning network is restored
|
||||
/// before the node. No-op for ops that reference nothing absent.
|
||||
fn ensure_referenced_exist(&mut self, target: RegistryTarget, op: &RegistryDelta) -> Result<(), CrdtError> {
|
||||
match op {
|
||||
RegistryDelta::AddNode { node, .. } => self.ensure_network_exists(target, node.network())?,
|
||||
RegistryDelta::ChangeNodeInput { id, new_input, .. } => {
|
||||
if let NodeInput::Node { id: referenced, .. } = new_input {
|
||||
self.ensure_node_exists(target, *referenced)?;
|
||||
}
|
||||
self.ensure_node_exists(target, *id)?;
|
||||
}
|
||||
RegistryDelta::SetNodeInputs { id, inputs } => {
|
||||
for slot in inputs {
|
||||
if let NodeInput::Node { id: referenced, .. } = slot.input {
|
||||
self.ensure_node_exists(target, referenced)?;
|
||||
}
|
||||
}
|
||||
self.ensure_node_exists(target, *id)?;
|
||||
}
|
||||
RegistryDelta::SetNodeImplementation { id, implementation } => {
|
||||
if let crate::Implementation::Network(network) = implementation {
|
||||
self.ensure_network_exists(target, *network)?;
|
||||
}
|
||||
self.ensure_node_exists(target, *id)?;
|
||||
}
|
||||
RegistryDelta::ChangeNodeAttribute { id, .. } | RegistryDelta::ChangeNodeInputAttribute { id, .. } => self.ensure_node_exists(target, *id)?,
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: network, export: export_target, ..
|
||||
} => {
|
||||
if let Some(NodeInput::Node { id: referenced, .. }) = export_target {
|
||||
self.ensure_node_exists(target, *referenced)?;
|
||||
}
|
||||
self.ensure_network_exists(target, *network)?;
|
||||
}
|
||||
RegistryDelta::ChangeNetworkAttribute { id: network, .. } => self.ensure_network_exists(target, *network)?,
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_node_exists(&mut self, target: RegistryTarget, node_id: NodeId) -> Result<(), CrdtError> {
|
||||
if !self.registry_ref(target).node_instances.contains_key(&node_id) {
|
||||
self.restore_node_from_history(target, node_id)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_network_exists(&mut self, target: RegistryTarget, network_id: NetworkId) -> Result<(), CrdtError> {
|
||||
if !self.registry_ref(target).networks.contains_key(&network_id) {
|
||||
self.restore_network_from_history(target, network_id)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Compute the inverse of `delta` against the registry named by `target`. Retirement passes
|
||||
/// [`RegistryTarget::Snapshot`] so LWW reverses (export target, inputs, attributes, resource hash)
|
||||
/// [`RegistryTarget::Retired`] so LWW reverses (export target, inputs, attributes, resource hash)
|
||||
/// capture the true pre-op value rather than the hot-polluted working state.
|
||||
///
|
||||
/// A write reads its pre-op value from wherever it lands: the live entity, its tombstone, or for an
|
||||
/// entity never seen, a placeholder.
|
||||
pub(crate) fn compute_reverse_delta(&self, target: RegistryTarget, delta: &RegistryDelta) -> Result<RegistryDelta, CrdtError> {
|
||||
let registry = self.registry_ref(target);
|
||||
let node = |id: NodeId| registry.node_or_removed(id).map_or_else(|| Cow::Owned(Node::placeholder()), Cow::Borrowed);
|
||||
let unset = InputSlot::unset(TimeStamp::ORIGIN);
|
||||
let network = |id: NetworkId| registry.network_or_removed(id);
|
||||
let resource = |id: ResourceId| registry.resources.get(&id).or_else(|| registry.removed_resources.get(&id).map(|mark| &mark.content));
|
||||
Ok(match delta {
|
||||
RegistryDelta::AddNode { id, node } => RegistryDelta::RemoveNode { id: *id, snapshot: node.clone() },
|
||||
RegistryDelta::RemoveNode { id, snapshot } => RegistryDelta::AddNode { id: *id, node: snapshot.clone() },
|
||||
&RegistryDelta::SetNodeInputs { id, .. } => {
|
||||
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
RegistryDelta::SetNodeInputs { id, inputs: node.inputs.clone() }
|
||||
}
|
||||
&RegistryDelta::SetNodeImplementation { id, .. } => {
|
||||
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
RegistryDelta::SetNodeImplementation {
|
||||
id,
|
||||
implementation: node.implementation.clone(),
|
||||
}
|
||||
}
|
||||
&RegistryDelta::SetNodeInputs { id, .. } => RegistryDelta::SetNodeInputs { id, inputs: node(id).inputs.clone() },
|
||||
&RegistryDelta::SetNodeImplementation { id, .. } => RegistryDelta::SetNodeImplementation {
|
||||
id,
|
||||
implementation: node(id).implementation.clone(),
|
||||
},
|
||||
&RegistryDelta::ChangeNodeInput { id, index: input_idx, .. } => {
|
||||
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
let slot = node.inputs().get(input_idx as usize).ok_or(CrdtError::InputIndexOutOfBounds(input_idx as usize))?;
|
||||
let node = node(id);
|
||||
let slot = node.inputs().get(input_idx as usize).unwrap_or(&unset);
|
||||
RegistryDelta::ChangeNodeInput {
|
||||
id,
|
||||
index: input_idx,
|
||||
new_input: slot.input.clone(),
|
||||
}
|
||||
}
|
||||
&RegistryDelta::ChangeNodeAttribute { id, ref delta } => {
|
||||
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
RegistryDelta::ChangeNodeAttribute {
|
||||
id,
|
||||
delta: reverse_attribute_delta(delta, node.attributes()),
|
||||
}
|
||||
}
|
||||
&RegistryDelta::ChangeNodeAttribute { id, ref delta } => RegistryDelta::ChangeNodeAttribute {
|
||||
id,
|
||||
delta: reverse_attribute_delta(delta, node(id).attributes()),
|
||||
},
|
||||
&RegistryDelta::ChangeNodeInputAttribute { id, index, ref delta } => {
|
||||
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
let input = node.inputs().get(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
|
||||
let node = node(id);
|
||||
let input = node.inputs().get(index as usize).unwrap_or(&unset);
|
||||
RegistryDelta::ChangeNodeInputAttribute {
|
||||
id,
|
||||
index,
|
||||
@@ -413,15 +363,15 @@ impl Document {
|
||||
}
|
||||
}
|
||||
&RegistryDelta::SetNetworkExport { id, index, .. } => {
|
||||
// If the network is absent the forward op will resurrect it; the reverse is "set the export to None"
|
||||
// since pre-forward there was no export to point at.
|
||||
let export_target = registry.networks.get(&id).and_then(|net| net.exports.get(index as usize)).and_then(|s| s.target.clone());
|
||||
// Absent network or slot: pre-op there was no export to point at.
|
||||
let export_target = network(id).and_then(|net| net.exports.get(index as usize)).and_then(|s| s.target.clone());
|
||||
RegistryDelta::SetNetworkExport { id, index, export: export_target }
|
||||
}
|
||||
RegistryDelta::AddNetwork { id, network } => RegistryDelta::RemoveNetwork { id: *id, snapshot: network.clone() },
|
||||
&RegistryDelta::RemoveNetwork { id, ref snapshot } => RegistryDelta::AddNetwork { id, network: snapshot.clone() },
|
||||
&RegistryDelta::ChangeNetworkAttribute { id, ref delta } => {
|
||||
let current = registry.networks.get(&id).map(|net| &net.attributes).ok_or(CrdtError::NetworkDoesNotExist(id))?;
|
||||
let empty = Attributes::new();
|
||||
let current = network(id).map_or(&empty, |net| &net.attributes);
|
||||
RegistryDelta::ChangeNetworkAttribute {
|
||||
id,
|
||||
delta: reverse_attribute_delta(delta, current),
|
||||
@@ -435,9 +385,9 @@ impl Document {
|
||||
&RegistryDelta::RegisterPeer { peer, user } => RegistryDelta::RegisterPeer { peer, user },
|
||||
&RegistryDelta::SetResourceHash { id, .. } => RegistryDelta::SetResourceHash {
|
||||
id,
|
||||
hash: registry.resources.get(&id).and_then(|entry| entry.hash),
|
||||
hash: resource(id).and_then(|entry| entry.hash),
|
||||
},
|
||||
&RegistryDelta::AddSource { id, key, .. } => match registry.resources.get(&id).and_then(|entry| entry.source(&key)) {
|
||||
&RegistryDelta::AddSource { id, key, .. } => match resource(id).and_then(|entry| entry.source(&key)) {
|
||||
// The slot already held a source: undo restores it.
|
||||
Some(existing) => RegistryDelta::AddSource {
|
||||
id,
|
||||
@@ -447,7 +397,7 @@ impl Document {
|
||||
// The slot was empty: undo removes what this op added.
|
||||
None => RegistryDelta::RemoveSource { id, key },
|
||||
},
|
||||
&RegistryDelta::RemoveSource { id, key } => match registry.resources.get(&id).and_then(|entry| entry.source(&key)) {
|
||||
&RegistryDelta::RemoveSource { id, key } => match resource(id).and_then(|entry| entry.source(&key)) {
|
||||
Some(existing) => RegistryDelta::AddSource {
|
||||
id,
|
||||
key,
|
||||
@@ -475,22 +425,341 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// An entity whose existence and every field are last-writer-wins on a timestamp.
|
||||
pub(crate) trait Entity: Sized {
|
||||
/// The newest stamp of an addition or a write: the latest evidence the entity exists.
|
||||
fn presence(&self) -> TimeStamp;
|
||||
fn set_presence(&mut self, timestamp: TimeStamp);
|
||||
/// Stamps every field at `timestamp`, the way an addition writes all of them.
|
||||
fn stamp_all(&mut self, timestamp: TimeStamp);
|
||||
/// Folds `other` in, keeping whichever value of each field is newer.
|
||||
fn merge(&mut self, other: Self);
|
||||
/// Content for writes to land on before the addition, every field at the origin so the addition's win.
|
||||
fn placeholder() -> Self;
|
||||
}
|
||||
|
||||
impl Entity for Node {
|
||||
fn presence(&self) -> TimeStamp {
|
||||
self.presence
|
||||
}
|
||||
fn set_presence(&mut self, timestamp: TimeStamp) {
|
||||
self.presence = timestamp;
|
||||
}
|
||||
fn placeholder() -> Self {
|
||||
Node::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(0)), 0)
|
||||
}
|
||||
fn stamp_all(&mut self, timestamp: TimeStamp) {
|
||||
self.presence = timestamp;
|
||||
self.network_timestamp = timestamp;
|
||||
self.inputs_timestamp = timestamp;
|
||||
self.implementation_timestamp = timestamp;
|
||||
self.inputs.iter_mut().for_each(|slot| stamp_slot(slot, timestamp));
|
||||
self.attributes.stamp(timestamp);
|
||||
}
|
||||
fn merge(&mut self, other: Self) {
|
||||
if other.network_timestamp > self.network_timestamp {
|
||||
self.network = other.network;
|
||||
self.network_timestamp = other.network_timestamp;
|
||||
}
|
||||
if other.implementation_timestamp > self.implementation_timestamp {
|
||||
self.implementation = other.implementation;
|
||||
self.implementation_timestamp = other.implementation_timestamp;
|
||||
}
|
||||
merge_inputs(self, other.inputs, other.inputs_timestamp);
|
||||
self.attributes.merge(other.attributes);
|
||||
self.presence = self.presence.max(other.presence);
|
||||
}
|
||||
}
|
||||
|
||||
impl Entity for Network {
|
||||
fn presence(&self) -> TimeStamp {
|
||||
self.presence
|
||||
}
|
||||
fn set_presence(&mut self, timestamp: TimeStamp) {
|
||||
self.presence = timestamp;
|
||||
}
|
||||
fn placeholder() -> Self {
|
||||
Network::default()
|
||||
}
|
||||
fn stamp_all(&mut self, timestamp: TimeStamp) {
|
||||
self.presence = timestamp;
|
||||
self.exports_timestamp = timestamp;
|
||||
self.exports.iter_mut().for_each(|slot| slot.timestamp = timestamp);
|
||||
self.attributes.stamp(timestamp);
|
||||
}
|
||||
fn merge(&mut self, other: Self) {
|
||||
// As `merge_inputs`: the newer list decides the slot count, and a slot written after that shape survives past it.
|
||||
let (mut newer, shape, older) = if other.exports_timestamp > self.exports_timestamp {
|
||||
(other.exports, other.exports_timestamp, std::mem::take(&mut self.exports))
|
||||
} else {
|
||||
(std::mem::take(&mut self.exports), self.exports_timestamp, other.exports)
|
||||
};
|
||||
for (index, incoming) in older.into_iter().enumerate() {
|
||||
if index >= newer.len() {
|
||||
if incoming.timestamp <= shape {
|
||||
continue;
|
||||
}
|
||||
newer.resize_with(index + 1, || ExportSlot { target: None, timestamp: shape });
|
||||
}
|
||||
if incoming.timestamp > newer[index].timestamp {
|
||||
newer[index] = incoming;
|
||||
}
|
||||
}
|
||||
self.exports = newer;
|
||||
self.exports_timestamp = shape;
|
||||
self.attributes.merge(other.attributes);
|
||||
self.presence = self.presence.max(other.presence);
|
||||
}
|
||||
}
|
||||
|
||||
impl Entity for ResourceEntry {
|
||||
fn presence(&self) -> TimeStamp {
|
||||
self.presence
|
||||
}
|
||||
fn set_presence(&mut self, timestamp: TimeStamp) {
|
||||
self.presence = timestamp;
|
||||
}
|
||||
fn placeholder() -> Self {
|
||||
ResourceEntry::default()
|
||||
}
|
||||
fn stamp_all(&mut self, timestamp: TimeStamp) {
|
||||
self.presence = timestamp;
|
||||
self.hash_timestamp = timestamp;
|
||||
self.stamp_sources(timestamp);
|
||||
}
|
||||
fn merge(&mut self, other: Self) {
|
||||
if other.hash_timestamp > self.hash_timestamp {
|
||||
self.hash = other.hash;
|
||||
self.hash_timestamp = other.hash_timestamp;
|
||||
}
|
||||
self.merge_sources(other.sources, other.sources_timestamp);
|
||||
self.presence = self.presence.max(other.presence);
|
||||
}
|
||||
}
|
||||
|
||||
fn stamp_slot(slot: &mut InputSlot, timestamp: TimeStamp) {
|
||||
slot.timestamp = timestamp;
|
||||
slot.attributes.stamp(timestamp);
|
||||
}
|
||||
|
||||
/// Stamps a slot of a written input list. Attributes carried over with their own stamps keep them, and a floor carried
|
||||
/// with them, so they only win where they already did; what arrives unstamped is written at `timestamp`.
|
||||
fn stamp_listed_slot(slot: &mut InputSlot, timestamp: TimeStamp) {
|
||||
slot.timestamp = timestamp;
|
||||
slot.attributes.stamp_unstamped(timestamp);
|
||||
}
|
||||
|
||||
/// Folds an input list stamped `timestamp` into the node's: the newer list decides the slot count, a slot written after that
|
||||
/// shape survives past it, and a slot both hold keeps its newer value, so list and slot writes land alike in any order.
|
||||
fn merge_inputs(node: &mut Node, other: Vec<InputSlot>, timestamp: TimeStamp) {
|
||||
let (mut newer, shape, older) = if timestamp > node.inputs_timestamp {
|
||||
(other, timestamp, std::mem::take(&mut node.inputs))
|
||||
} else {
|
||||
(std::mem::take(&mut node.inputs), node.inputs_timestamp, other)
|
||||
};
|
||||
// A slot the older list lacks was absent as of that list's shape, as a write past its end would find it.
|
||||
let older_shape = if shape == timestamp { node.inputs_timestamp } else { timestamp };
|
||||
for slot in newer.iter_mut().skip(older.len()) {
|
||||
slot.attributes.merge(Attributes::empty_at(older_shape));
|
||||
}
|
||||
for (index, incoming) in older.into_iter().enumerate() {
|
||||
if index >= newer.len() {
|
||||
if slot_newest(&incoming) <= shape {
|
||||
continue;
|
||||
}
|
||||
newer.resize_with(index + 1, || InputSlot::unset(shape));
|
||||
}
|
||||
let slot = &mut newer[index];
|
||||
if incoming.timestamp > slot.timestamp {
|
||||
slot.input = incoming.input;
|
||||
slot.timestamp = incoming.timestamp;
|
||||
}
|
||||
slot.attributes.merge(incoming.attributes);
|
||||
}
|
||||
node.inputs = newer;
|
||||
node.inputs_timestamp = shape;
|
||||
}
|
||||
|
||||
/// The newest write the slot carries, its attributes included.
|
||||
fn slot_newest(slot: &InputSlot) -> TimeStamp {
|
||||
slot.timestamp.max(slot.attributes.newest())
|
||||
}
|
||||
|
||||
/// The slot at `index` for a write at `timestamp`; past the end it exists only if the write is newer than the list's shape.
|
||||
fn slot_for_write(node: &mut Node, index: usize, timestamp: TimeStamp, mode: ApplyMode) -> Result<Option<&mut InputSlot>, CrdtError> {
|
||||
if index >= node.inputs.len() {
|
||||
if index >= MAX_INPUT_SLOTS || mode == ApplyMode::Strict {
|
||||
return Err(CrdtError::InputIndexOutOfBounds(index));
|
||||
}
|
||||
if mode != ApplyMode::Force && timestamp <= node.inputs_timestamp {
|
||||
return Ok(None);
|
||||
}
|
||||
let shape = node.inputs_timestamp;
|
||||
node.inputs.resize_with(index + 1, || InputSlot::unset(shape));
|
||||
}
|
||||
Ok(node.inputs.get_mut(index))
|
||||
}
|
||||
|
||||
/// The entity's content wherever it sits: live, or held by its tombstone.
|
||||
fn content_mut<'a, K: Hash + Eq + Copy, T>(live: &'a mut HashMap<K, T>, dead: &'a mut HashMap<K, Tombstone<T>>, id: K) -> Option<&'a mut T> {
|
||||
live.get_mut(&id).or_else(|| dead.get_mut(&id).map(|mark| &mut mark.content))
|
||||
}
|
||||
|
||||
/// Revives a removed entity whose presence has grown past its removal. A placeholder stays dead.
|
||||
fn revive_if_newer<K: Hash + Eq + Copy, T: Entity>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K) {
|
||||
if dead.get(&id).is_some_and(|mark| !mark.placeholder && mark.content.presence() > mark.timestamp) {
|
||||
let mark = dead.remove(&id).expect("checked above");
|
||||
live.insert(id, mark.content);
|
||||
}
|
||||
}
|
||||
|
||||
/// Folds an addition's or removal's content into what is held under `id`. It proves the entity was added, so a placeholder
|
||||
/// holding it stops being one.
|
||||
fn merge_entity<K: Hash + Eq + Copy, T: Entity>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, content: T) {
|
||||
if let Some(mark) = dead.get_mut(&id).filter(|mark| mark.placeholder) {
|
||||
// The placeholder holds only early writes: they land on the real content as if the addition came first.
|
||||
let early = std::mem::replace(&mut mark.content, content);
|
||||
mark.content.merge(early);
|
||||
mark.placeholder = false;
|
||||
} else if let Some(existing) = content_mut(live, dead, id) {
|
||||
existing.merge(content);
|
||||
} else {
|
||||
live.insert(id, content);
|
||||
}
|
||||
revive_if_newer(live, dead, id);
|
||||
}
|
||||
|
||||
/// An addition at `timestamp`: every field written at `timestamp`, live unless a newer removal holds it dead.
|
||||
fn add_entity<K: Hash + Eq + Copy, T: Entity>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, mut content: T, timestamp: TimeStamp, force: bool) {
|
||||
if force {
|
||||
dead.remove(&id);
|
||||
live.insert(id, content);
|
||||
return;
|
||||
}
|
||||
content.stamp_all(timestamp);
|
||||
merge_entity(live, dead, id, content);
|
||||
}
|
||||
|
||||
/// A removal at `timestamp`: dead unless a newer addition or write holds it live. The snapshot folds in first, so a removal of an
|
||||
/// entity never seen still lands.
|
||||
fn remove_entity<K: Hash + Eq + Copy, T: Entity>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, snapshot: T, timestamp: TimeStamp, force: bool) {
|
||||
merge_entity(live, dead, id, snapshot);
|
||||
if let Some(mark) = dead.get_mut(&id) {
|
||||
mark.timestamp = if force { timestamp } else { mark.timestamp.max(timestamp) };
|
||||
} else if live.get(&id).is_some_and(|content| force || timestamp > content.presence()) {
|
||||
let content = live.remove(&id).expect("checked above");
|
||||
dead.insert(
|
||||
id,
|
||||
Tombstone {
|
||||
content,
|
||||
timestamp,
|
||||
placeholder: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A write at `timestamp` to the entity under `id`, wherever its content sits: it revives an older removal, and lands on a
|
||||
/// placeholder for an entity never seen. A fresh local edit on one gets `missing()` instead.
|
||||
fn write_entity<K: Hash + Eq + Copy, T: Entity>(
|
||||
live: &mut HashMap<K, T>,
|
||||
dead: &mut HashMap<K, Tombstone<T>>,
|
||||
id: K,
|
||||
timestamp: TimeStamp,
|
||||
mode: ApplyMode,
|
||||
missing: impl FnOnce() -> CrdtError,
|
||||
f: impl FnOnce(&mut T) -> Result<(), CrdtError>,
|
||||
) -> Result<(), CrdtError> {
|
||||
let force = mode == ApplyMode::Force;
|
||||
let unseen = !live.contains_key(&id) && !dead.contains_key(&id);
|
||||
if unseen {
|
||||
if mode == ApplyMode::Strict {
|
||||
return Err(missing());
|
||||
}
|
||||
dead.insert(
|
||||
id,
|
||||
Tombstone {
|
||||
content: T::placeholder(),
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
placeholder: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
let content = content_mut(live, dead, id).expect("held above");
|
||||
if let Err(error) = f(content) {
|
||||
// A rejected op changes nothing, so the placeholder made for it goes too.
|
||||
if unseen {
|
||||
dead.remove(&id);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
content.set_presence(content.presence().max(timestamp));
|
||||
if force && let Some(mark) = dead.remove(&id) {
|
||||
live.insert(id, mark.content);
|
||||
}
|
||||
revive_if_newer(live, dead, id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A fresh local edit cannot name a node never seen. Checked before an op's first write, so a refused op changes nothing.
|
||||
fn ensure_seen(registry: &Registry, ids: &[NodeId], mode: ApplyMode) -> Result<(), CrdtError> {
|
||||
let unseen = |id: &&NodeId| !registry.node_instances.contains_key(id) && !registry.removed_nodes.contains_key(id);
|
||||
match ids.iter().find(unseen) {
|
||||
Some(&id) if mode == ApplyMode::Strict => Err(CrdtError::TargetNodeDoesNotExist(id)),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`write_entity()`] to a node; with a no-op `f`, records a reference to it.
|
||||
fn write_node(registry: &mut Registry, id: NodeId, timestamp: TimeStamp, mode: ApplyMode, f: impl FnOnce(&mut Node) -> Result<(), CrdtError>) -> Result<(), CrdtError> {
|
||||
write_entity(
|
||||
&mut registry.node_instances,
|
||||
&mut registry.removed_nodes,
|
||||
id,
|
||||
timestamp,
|
||||
mode,
|
||||
|| CrdtError::TargetNodeDoesNotExist(id),
|
||||
f,
|
||||
)
|
||||
}
|
||||
|
||||
fn write_network(registry: &mut Registry, id: NetworkId, timestamp: TimeStamp, mode: ApplyMode, f: impl FnOnce(&mut Network) -> Result<(), CrdtError>) -> Result<(), CrdtError> {
|
||||
write_entity(&mut registry.networks, &mut registry.removed_networks, id, timestamp, mode, || CrdtError::NetworkDoesNotExist(id), f)
|
||||
}
|
||||
|
||||
/// [`write_entity()`] for a resource, creating an entry never seen first, since single-field resource ops are upserts.
|
||||
fn upsert_resource(registry: &mut Registry, id: ResourceId, timestamp: TimeStamp, f: impl FnOnce(&mut ResourceEntry)) {
|
||||
if !registry.resources.contains_key(&id) && !registry.removed_resources.contains_key(&id) {
|
||||
registry.resources.insert(
|
||||
id,
|
||||
ResourceEntry {
|
||||
presence: timestamp,
|
||||
..ResourceEntry::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
let entry = content_mut(&mut registry.resources, &mut registry.removed_resources, id).expect("held above");
|
||||
f(entry);
|
||||
entry.set_presence(entry.presence().max(timestamp));
|
||||
revive_if_newer(&mut registry.resources, &mut registry.removed_resources, id);
|
||||
}
|
||||
|
||||
/// Which of a [`Document`]'s two registries an apply targets: the working copy (retired state plus
|
||||
/// live hot ops) or the retired snapshot (retired deltas only). Retirement targets the snapshot so
|
||||
/// reverses capture pre-op values; the hot path and undo/redo target the working copy.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum RegistryTarget {
|
||||
Working,
|
||||
Snapshot,
|
||||
Retired,
|
||||
}
|
||||
|
||||
/// How [`Document::apply_op_with`] resolves structural collisions and LWW timestamp ties.
|
||||
/// How [`Document::apply_op_with`] treats what it finds.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum ApplyMode {
|
||||
/// Fresh local/remote edit: structural ops error on duplicate/missing targets; LWW uses strict `>`.
|
||||
Live,
|
||||
/// Replay/retire: structural ops skip duplicate/missing targets; LWW still uses strict `>`.
|
||||
/// A fresh local edit: adding what exists or writing to what was never seen is an error.
|
||||
Strict,
|
||||
/// An op from a peer or from persisted state: every arm is a timestamp comparison.
|
||||
Idempotent,
|
||||
/// Silent-zone undo/redo rewind: structural ops are idempotent and LWW arms assign unconditionally.
|
||||
/// Silent-zone undo/redo rewind: every write lands, whatever its timestamp.
|
||||
Force,
|
||||
}
|
||||
@@ -11,8 +11,8 @@ use serde::Serialize;
|
||||
use crate::attr::*;
|
||||
use crate::metadata_source::{NoMetadata, NodeMetadataSource};
|
||||
use crate::{
|
||||
AttributesWrite, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ProtoNode, ROOT_NETWORK, Registry, ResourceHash, ResourceId, TimeStamp, Value,
|
||||
ValueError, from_value, to_value,
|
||||
ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ProtoNode, ROOT_NETWORK, Registry, ResourceHash, ResourceId, TimeStamp, Value, ValueError, from_value,
|
||||
to_value,
|
||||
};
|
||||
|
||||
fn map_serialization_error(key: &str) -> impl FnOnce(ValueError) -> ConversionError + '_ {
|
||||
@@ -221,11 +221,13 @@ pub fn convert_resource_entry(resources: &graphene_resource::ResourceRegistry, i
|
||||
peer,
|
||||
};
|
||||
let body = to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
|
||||
entry.set_source(
|
||||
// Built rather than written: the chain is put in place as converted, floor and all at the origin.
|
||||
entry.force_set_source(
|
||||
key,
|
||||
crate::SourceValue {
|
||||
source: body,
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
deleted: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -339,7 +341,15 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
|
||||
write_ui_network_attributes(&mut attributes, node_network, metadata_path, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
|
||||
write_scope_injections(&mut attributes, node_network, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
|
||||
|
||||
registry.networks.insert(network_id, Network { exports, attributes });
|
||||
registry.networks.insert(
|
||||
network_id,
|
||||
Network {
|
||||
presence: TimeStamp::ORIGIN,
|
||||
exports,
|
||||
exports_timestamp: TimeStamp::ORIGIN,
|
||||
attributes,
|
||||
},
|
||||
);
|
||||
ctx.network_ids.insert(metadata_path.to_vec(), network_id);
|
||||
|
||||
Ok(())
|
||||
@@ -411,6 +421,7 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
|
||||
let mut inputs = Vec::with_capacity(doc_node.inputs.len());
|
||||
for (input_index, input) in doc_node.inputs.iter().enumerate() {
|
||||
let mut input_attrs = convert_input_attributes(input)?;
|
||||
input_attrs.set_floor(timestamp);
|
||||
write_ui_input_attributes(&mut input_attrs, ctx.metadata, metadata_path, runtime_node_id, input_index, timestamp)?;
|
||||
|
||||
inputs.push(InputSlot {
|
||||
@@ -432,7 +443,7 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
|
||||
let implementation = convert_implementation(&doc_node.implementation, &node_path, child_metadata_path, registry, ctx, recurse)?;
|
||||
|
||||
// Defaults match `DocumentNode::default()`; `to_runtime` rehydrates absent keys from the same defaults.
|
||||
let mut attributes = crate::Attributes::new();
|
||||
let mut attributes = crate::Attributes::empty_at(timestamp);
|
||||
attributes
|
||||
.set_if_not_default(node::CALL_ARGUMENT, &doc_node.call_argument, &concrete!(Context), timestamp)
|
||||
.map_err(map_serialization_error(node::CALL_ARGUMENT))?;
|
||||
@@ -449,6 +460,9 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
|
||||
write_ui_attributes(&mut attributes, ctx.metadata, metadata_path, runtime_node_id, timestamp)?;
|
||||
|
||||
Ok(Node {
|
||||
presence: timestamp,
|
||||
network_timestamp: timestamp,
|
||||
inputs_timestamp: timestamp,
|
||||
implementation,
|
||||
implementation_timestamp: timestamp,
|
||||
inputs,
|
||||
@@ -812,7 +826,15 @@ impl<'m> ScopedConversion<'m> {
|
||||
write_ui_network_attributes(&mut attributes, node_network, local_path, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
|
||||
write_scope_injections(&mut attributes, node_network, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
|
||||
|
||||
registry.networks.insert(network_id, Network { exports, attributes });
|
||||
registry.networks.insert(
|
||||
network_id,
|
||||
Network {
|
||||
presence: TimeStamp::ORIGIN,
|
||||
exports,
|
||||
exports_timestamp: TimeStamp::ORIGIN,
|
||||
attributes,
|
||||
},
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -3,21 +3,26 @@
|
||||
//! [`History`] owns the deltas in topological order (every parent precedes its children) plus an
|
||||
//! index from [`Rev`] to position for O(1) lookup. The order is a valid replay order, so it is what
|
||||
//! gets serialized to the on-disk history file and what [`crate::Session::replay_from_history`]
|
||||
//! consumes. Retired commits have a single writer in every regime (solo editing, or leader-ordered
|
||||
//! collaboration where the leader serializes retired commits), so appending preserves the order by
|
||||
//! construction. The only operation that introduces out-of-order deltas is [`merge`](History::merge),
|
||||
//! which re-sorts the combined set into the canonical order to restore the invariant.
|
||||
//! consumes. Appending a commit keeps the order; deltas arriving out of it are put back by
|
||||
//! a canonical sort.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use crate::{AttributesWrite, CrdtError, Delta, Rev, TimeStamp, Value};
|
||||
use crate::{CrdtError, Delta, RegistryDelta, ResourceHash, Rev, TimeStamp, Value};
|
||||
|
||||
/// Every mutator maintains the indexes, so the tips and named hashes are probes, not scans of a growing history.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct History {
|
||||
/// Deltas in topological order. Mutated only via [`push`](Self::push).
|
||||
deltas: Vec<Delta>,
|
||||
/// `Rev` to its position in `deltas`. Kept in sync with `deltas` by every mutator.
|
||||
index: HashMap<Rev, usize>,
|
||||
/// Every rev some delta names as a parent.
|
||||
referenced: HashSet<Rev>,
|
||||
/// Deltas no other delta names as a parent.
|
||||
tips: HashSet<Rev>,
|
||||
/// Content hashes the deltas name, from resource additions and removals.
|
||||
resource_hashes: HashSet<ResourceHash>,
|
||||
}
|
||||
|
||||
impl History {
|
||||
@@ -27,8 +32,9 @@ impl History {
|
||||
|
||||
/// Build from deltas already in topological order (the on-disk load path), indexing them in place.
|
||||
pub fn from_ordered(deltas: Vec<Delta>) -> Self {
|
||||
let index = deltas.iter().enumerate().map(|(position, delta)| (delta.id, position)).collect();
|
||||
Self { deltas, index }
|
||||
let mut history = Self::default();
|
||||
deltas.into_iter().for_each(|delta| history.push(delta));
|
||||
history
|
||||
}
|
||||
|
||||
pub fn get(&self, rev: Rev) -> Option<&Delta> {
|
||||
@@ -39,6 +45,11 @@ impl History {
|
||||
self.index.contains_key(&rev)
|
||||
}
|
||||
|
||||
/// The content hashes named by any resource addition or removal in history.
|
||||
pub fn resource_hashes(&self) -> &HashSet<ResourceHash> {
|
||||
&self.resource_hashes
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.deltas.len()
|
||||
}
|
||||
@@ -51,10 +62,25 @@ impl History {
|
||||
/// (idempotent re-apply) overwrites the existing entry in place rather than appending, so the
|
||||
/// order and index are unchanged.
|
||||
pub fn push(&mut self, delta: Delta) {
|
||||
match &delta.kind {
|
||||
RegistryDelta::AddResource { entry, .. } => self.resource_hashes.extend(entry.hash),
|
||||
RegistryDelta::RemoveResource { snapshot, .. } => self.resource_hashes.extend(snapshot.hash),
|
||||
RegistryDelta::SetResourceHash { hash: Some(hash), .. } => {
|
||||
self.resource_hashes.insert(*hash);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if let Some(&position) = self.index.get(&delta.id) {
|
||||
self.deltas[position] = delta;
|
||||
return;
|
||||
}
|
||||
for parent in delta.all_parents() {
|
||||
self.referenced.insert(parent);
|
||||
self.tips.remove(&parent);
|
||||
}
|
||||
if !self.referenced.contains(&delta.id) {
|
||||
self.tips.insert(delta.id);
|
||||
}
|
||||
self.index.insert(delta.id, self.deltas.len());
|
||||
self.deltas.push(delta);
|
||||
}
|
||||
@@ -119,11 +145,24 @@ impl History {
|
||||
}
|
||||
}
|
||||
|
||||
/// `roots` and everything reachable from them through all parent links. Unknown roots are skipped.
|
||||
pub(crate) fn ancestors(&self, roots: impl IntoIterator<Item = Rev>) -> HashSet<Rev> {
|
||||
let mut seen = HashSet::new();
|
||||
let mut stack: Vec<Rev> = roots.into_iter().filter(|rev| self.contains(*rev)).collect();
|
||||
while let Some(rev) = stack.pop() {
|
||||
if seen.insert(rev)
|
||||
&& let Some(delta) = self.get(rev)
|
||||
{
|
||||
stack.extend(delta.all_parents());
|
||||
}
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
/// The current tips: revs that no other delta lists as a parent (the divergent heads). A linear
|
||||
/// history has exactly one tip; concurrent branches have several. Sorted ascending for determinism.
|
||||
pub fn tips(&self) -> Vec<Rev> {
|
||||
let referenced: std::collections::HashSet<Rev> = self.deltas.iter().flat_map(|delta| delta.all_parents()).collect();
|
||||
let mut tips: Vec<Rev> = self.deltas.iter().map(|delta| delta.id).filter(|rev| !referenced.contains(rev)).collect();
|
||||
let mut tips: Vec<Rev> = self.tips.iter().copied().collect();
|
||||
tips.sort_unstable();
|
||||
tips
|
||||
}
|
||||
|
||||
@@ -56,6 +56,8 @@ pub const ROOT_NETWORK: NetworkId = NetworkId(0);
|
||||
/// Upper bound on a network's export slot count, guarding `SetExport` against a malicious or corrupted
|
||||
/// slot index forcing an unbounded `exports` allocation.
|
||||
pub(crate) const MAX_EXPORT_SLOTS: usize = 1 << 16;
|
||||
/// A per-slot write can bring a slot past the end of the list into being, so it is capped the same way.
|
||||
pub(crate) const MAX_INPUT_SLOTS: usize = 1 << 16;
|
||||
|
||||
/// Per-device identity. Stable per `(device, document)`. Used for CRDT tiebreaking and `NodeId`
|
||||
/// scoping. Globally unique across all peers ever in a document.
|
||||
|
||||
@@ -42,6 +42,7 @@ pub use to_runtime::Declarations;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
mod bookkeeping;
|
||||
mod crdt;
|
||||
mod round_trip;
|
||||
}
|
||||
@@ -4,14 +4,23 @@ use std::borrow::Cow;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Node {
|
||||
/// The latest addition or write, so a concurrent removal resolves by stamp; see [`Registry::removed_nodes`](crate::Registry::removed_nodes).
|
||||
#[serde(default)]
|
||||
pub(crate) presence: TimeStamp,
|
||||
pub(crate) network: NetworkId,
|
||||
/// When the node was last added, which decides its network between concurrent additions of one id.
|
||||
#[serde(default)]
|
||||
pub(crate) network_timestamp: TimeStamp,
|
||||
pub(crate) implementation: Implementation,
|
||||
/// When the implementation was last written, so a swap resolves by last-writer-wins rather than by
|
||||
/// the order ops happen to arrive in. Absent from documents written before swaps were expressible.
|
||||
#[serde(default)]
|
||||
pub(crate) implementation_timestamp: TimeStamp,
|
||||
pub(crate) inputs: Vec<InputSlot>,
|
||||
/// When the input list last changed shape, so list and slot writes resolve alike in either order.
|
||||
#[serde(default)]
|
||||
pub(crate) inputs_timestamp: TimeStamp,
|
||||
pub(crate) attributes: Attributes,
|
||||
pub(crate) network: NetworkId,
|
||||
}
|
||||
|
||||
impl Node {
|
||||
@@ -47,15 +56,25 @@ impl Node {
|
||||
attributes_value_equal(&self.attributes, &other.attributes)
|
||||
}
|
||||
|
||||
/// A node in `network` whose `inputs` slots are unset, for a caller that fills them in with
|
||||
/// `ChangeNodeInput`. The slot count is fixed at creation, since changing an input addresses a
|
||||
/// slot by position.
|
||||
pub fn new(network: NetworkId, implementation: Implementation, inputs: usize) -> Self {
|
||||
Self {
|
||||
presence: TimeStamp::ORIGIN,
|
||||
network_timestamp: TimeStamp::ORIGIN,
|
||||
inputs_timestamp: TimeStamp::ORIGIN,
|
||||
implementation,
|
||||
implementation_timestamp: TimeStamp::ORIGIN,
|
||||
inputs: vec![InputSlot::unset(TimeStamp::ORIGIN); inputs],
|
||||
attributes: Attributes::new(),
|
||||
network,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn dummy() -> Self {
|
||||
Self {
|
||||
implementation: Implementation::ProtoNode(ResourceId::new()),
|
||||
implementation_timestamp: TimeStamp::default(),
|
||||
inputs: vec![],
|
||||
attributes: Attributes::new(),
|
||||
network: crate::ROOT_NETWORK,
|
||||
}
|
||||
Self::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::new()), 0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,6 +87,22 @@ pub struct InputSlot {
|
||||
pub attributes: Attributes,
|
||||
}
|
||||
|
||||
impl InputSlot {
|
||||
/// A slot holding nothing, stamped `timestamp`.
|
||||
pub fn unset(timestamp: TimeStamp) -> Self {
|
||||
// `to_runtime` reads this back as a `TaggedValue`, whose unit `None` variant encodes as this string.
|
||||
// Pinned by `unset_input_slot_deserializes_as_tagged_value_none`.
|
||||
Self {
|
||||
input: NodeInput::Value {
|
||||
value: Value::Str("None".to_string()),
|
||||
exposed: false,
|
||||
},
|
||||
timestamp,
|
||||
attributes: Attributes::empty_at(timestamp),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum NodeInput {
|
||||
Node {
|
||||
@@ -97,7 +132,13 @@ pub enum Implementation {
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Network {
|
||||
/// The latest addition or write; see [`Node::presence`](crate::Node).
|
||||
#[serde(default)]
|
||||
pub(crate) presence: TimeStamp,
|
||||
pub exports: Vec<ExportSlot>,
|
||||
/// When the export list last changed shape; see [`Node::inputs_timestamp`](crate::Node).
|
||||
#[serde(default)]
|
||||
pub(crate) exports_timestamp: TimeStamp,
|
||||
/// Per-network `ui::*` state (navigation, previewing). Separate from `Node.attributes` so
|
||||
/// view-state edits LWW independently.
|
||||
pub attributes: Attributes,
|
||||
@@ -125,7 +166,7 @@ impl Network {
|
||||
|
||||
/// One positional export slot. `target == None` marks an empty/removed slot. Timestamp drives LWW
|
||||
/// on concurrent `SetExport` ops.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ExportSlot {
|
||||
pub target: Option<NodeInput>,
|
||||
pub timestamp: TimeStamp,
|
||||
@@ -159,6 +200,19 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// `to_runtime` has to read back what `Node::new` writes into an unset slot, so its literal must stay
|
||||
/// in step with how `TaggedValue::None` serializes.
|
||||
#[test]
|
||||
fn unset_input_slot_deserializes_as_tagged_value_none() {
|
||||
let node = Node::new(crate::ROOT_NETWORK, Implementation::Network(crate::ROOT_NETWORK), 1);
|
||||
let NodeInput::Value { value, .. } = &node.inputs()[0].input else {
|
||||
panic!("a fresh slot holds a value input");
|
||||
};
|
||||
|
||||
let tagged: graph_craft::document::value::TaggedValue = crate::from_value(value).expect("the unset slot value must deserialize");
|
||||
assert_eq!(tagged, graph_craft::document::value::TaggedValue::None);
|
||||
}
|
||||
|
||||
/// A `SetExport(None)` truncation leaves a trailing empty slot. Such a network is value-equal to
|
||||
/// the same network without that slot, so the soak oracle doesn't false-report drift.
|
||||
#[test]
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
|
||||
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceEntry, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// The live document. Every field, existence included, is last-writer-wins on a timestamp, so the registry depends on the
|
||||
/// set of ops applied and not their order. A removed entity keeps a tombstone: an older op lands on it, a newer one
|
||||
/// revives the entity.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Registry {
|
||||
pub node_instances: HashMap<NodeId, Node>,
|
||||
@@ -9,13 +12,58 @@ pub struct Registry {
|
||||
/// Content-addressable resources (images, fonts, eventually proto-node declarations) referenced
|
||||
/// by `ResourceId`. See [`ResourceStore`].
|
||||
pub resources: ResourceStore,
|
||||
/// Append-only mapping from per-device `PeerId` to per-human `UserId`.
|
||||
/// Registered by each device's first contribution via `RegistryDelta::RegisterPeer`.
|
||||
pub peer_users: HashMap<PeerId, UserId>,
|
||||
/// Which person each device is, from `RegistryDelta::RegisterPeer`, so undo and authorship scope by person.
|
||||
pub peer_users: HashMap<PeerId, PeerRegistration>,
|
||||
pub attributes: Attributes,
|
||||
/// Tombstones of removed nodes, so an op on one is ordered against its removal whichever arrives first.
|
||||
#[serde(default)]
|
||||
pub removed_nodes: HashMap<NodeId, Tombstone<Node>>,
|
||||
/// Tombstones of removed networks; see [`removed_nodes`](Self::removed_nodes).
|
||||
#[serde(default)]
|
||||
pub removed_networks: HashMap<NetworkId, Tombstone<Network>>,
|
||||
/// Tombstones of removed resources; see [`removed_nodes`](Self::removed_nodes).
|
||||
#[serde(default)]
|
||||
pub removed_resources: HashMap<ResourceId, Tombstone<ResourceEntry>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PeerRegistration {
|
||||
pub user: UserId,
|
||||
pub timestamp: TimeStamp,
|
||||
}
|
||||
|
||||
/// A removed entity's content, for reviving it, and its removal stamp.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Tombstone<T> {
|
||||
pub content: T,
|
||||
pub timestamp: TimeStamp,
|
||||
/// Nothing has added the entity yet: it stays dead until an addition folds in, the content holding writes that came first.
|
||||
#[serde(default)]
|
||||
pub placeholder: bool,
|
||||
}
|
||||
|
||||
impl Registry {
|
||||
/// The node under `id`, live or as removed, for a reference to a node the runtime cannot hold.
|
||||
pub(crate) fn node_or_removed(&self, id: NodeId) -> Option<&Node> {
|
||||
self.node_instances.get(&id).or_else(|| self.removed_nodes.get(&id).map(|mark| &mark.content))
|
||||
}
|
||||
|
||||
/// The network under `id`, live or as it was when removed.
|
||||
pub(crate) fn network_or_removed(&self, id: NetworkId) -> Option<&Network> {
|
||||
self.networks.get(&id).or_else(|| self.removed_networks.get(&id).map(|mark| &mark.content))
|
||||
}
|
||||
|
||||
/// The live entities alone, for a document starting a history of its own: tombstones only order removals against ops
|
||||
/// that share this one.
|
||||
pub fn without_tombstones(&self) -> Registry {
|
||||
Registry {
|
||||
removed_nodes: HashMap::new(),
|
||||
removed_networks: HashMap::new(),
|
||||
removed_resources: HashMap::new(),
|
||||
..self.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// True if both registries agree on every value-bearing field, ignoring per-slot and
|
||||
/// per-attribute timestamps. Mirrors `compute_deltas`'s value-only semantics, so unchanged
|
||||
/// state at a stamped slot doesn't count as drift. `peer_users` is excluded: it isn't diffed by
|
||||
@@ -85,10 +133,10 @@ impl Registry {
|
||||
}
|
||||
|
||||
pub(crate) fn attributes_value_equal(a: &Attributes, b: &Attributes) -> bool {
|
||||
if a.len() != b.len() {
|
||||
if a.live().count() != b.live().count() {
|
||||
return false;
|
||||
}
|
||||
a.iter().all(|(key, value)| b.get(key).is_some_and(|other| value.value == other.value))
|
||||
a.live().all(|(key, value)| b.get(key).is_some_and(|other| !other.deleted && value.value == other.value))
|
||||
}
|
||||
|
||||
/// Value-level resource comparison: same resolved hashes and same source chains (keyed by
|
||||
@@ -100,54 +148,92 @@ pub(crate) fn resources_value_equal(a: &ResourceStore, b: &ResourceStore) -> boo
|
||||
a.iter().all(|(id, entry)| {
|
||||
b.get(id).is_some_and(|other| {
|
||||
entry.hash == other.hash
|
||||
&& entry.sources.len() == other.sources.len()
|
||||
&& entry.sources.iter().all(|(key, value)| other.source(key).is_some_and(|other_value| value.source == other_value.source))
|
||||
&& entry.live_sources().count() == other.live_sources().count()
|
||||
&& entry.live_sources().all(|(key, value)| other.source(key).is_some_and(|other_value| value.source == other_value.source))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Stable identity for any timestamped slot in a `Registry`. Used by `order_consistent`.
|
||||
/// Stable identity for any timestamp in a `Registry`, tombstoned content and existence stamps included. Used by
|
||||
/// `order_consistent`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
enum TimestampKey {
|
||||
/// A whole-entity stamp under its field name: presence, a shape or floor, a removal.
|
||||
Node(NodeId, &'static str),
|
||||
NodeInput(NodeId, usize),
|
||||
NodeInputFloor(NodeId, usize),
|
||||
NodeInputAttribute(NodeId, usize, String),
|
||||
NodeAttribute(NodeId, String),
|
||||
Network(NetworkId, &'static str),
|
||||
NetworkExport(NetworkId, usize),
|
||||
NetworkAttribute(NetworkId, String),
|
||||
DocumentAttribute(String),
|
||||
ResourceHash(ResourceId),
|
||||
Resource(ResourceId, &'static str),
|
||||
ResourceSource(ResourceId, SourceKey),
|
||||
Document(&'static str),
|
||||
PeerRegistration(PeerId),
|
||||
}
|
||||
|
||||
fn collect_timestamps(registry: &Registry) -> HashMap<TimestampKey, TimeStamp> {
|
||||
let mut out = HashMap::new();
|
||||
for (node_id, node) in ®istry.node_instances {
|
||||
let nodes = registry.node_instances.iter().chain(registry.removed_nodes.iter().map(|(id, mark)| (id, &mark.content)));
|
||||
for (&id, node) in nodes {
|
||||
for (field, timestamp) in [
|
||||
("presence", node.presence),
|
||||
("network", node.network_timestamp),
|
||||
("inputs", node.inputs_timestamp),
|
||||
("implementation", node.implementation_timestamp),
|
||||
("attributes", node.attributes.floor()),
|
||||
] {
|
||||
out.insert(TimestampKey::Node(id, field), timestamp);
|
||||
}
|
||||
for (i, slot) in node.inputs.iter().enumerate() {
|
||||
out.insert(TimestampKey::NodeInput(*node_id, i), slot.timestamp);
|
||||
out.insert(TimestampKey::NodeInput(id, i), slot.timestamp);
|
||||
out.insert(TimestampKey::NodeInputFloor(id, i), slot.attributes.floor());
|
||||
for (key, value) in &slot.attributes {
|
||||
out.insert(TimestampKey::NodeInputAttribute(*node_id, i, key.clone()), value.timestamp);
|
||||
out.insert(TimestampKey::NodeInputAttribute(id, i, key.clone()), value.timestamp);
|
||||
}
|
||||
}
|
||||
for (key, value) in &node.attributes {
|
||||
out.insert(TimestampKey::NodeAttribute(*node_id, key.clone()), value.timestamp);
|
||||
out.insert(TimestampKey::NodeAttribute(id, key.clone()), value.timestamp);
|
||||
}
|
||||
}
|
||||
for (network_id, network) in ®istry.networks {
|
||||
let networks = registry.networks.iter().chain(registry.removed_networks.iter().map(|(id, mark)| (id, &mark.content)));
|
||||
for (&id, network) in networks {
|
||||
for (field, timestamp) in [("presence", network.presence), ("exports", network.exports_timestamp), ("attributes", network.attributes.floor())] {
|
||||
out.insert(TimestampKey::Network(id, field), timestamp);
|
||||
}
|
||||
for (i, slot) in network.exports.iter().enumerate() {
|
||||
out.insert(TimestampKey::NetworkExport(*network_id, i), slot.timestamp);
|
||||
out.insert(TimestampKey::NetworkExport(id, i), slot.timestamp);
|
||||
}
|
||||
for (key, value) in &network.attributes {
|
||||
out.insert(TimestampKey::NetworkAttribute(*network_id, key.clone()), value.timestamp);
|
||||
out.insert(TimestampKey::NetworkAttribute(id, key.clone()), value.timestamp);
|
||||
}
|
||||
}
|
||||
out.insert(TimestampKey::Document("attributes"), registry.attributes.floor());
|
||||
for (key, value) in ®istry.attributes {
|
||||
out.insert(TimestampKey::DocumentAttribute(key.clone()), value.timestamp);
|
||||
}
|
||||
for (id, entry) in ®istry.resources {
|
||||
out.insert(TimestampKey::ResourceHash(*id), entry.hash_timestamp);
|
||||
for (source_key, source_value) in &entry.sources {
|
||||
out.insert(TimestampKey::ResourceSource(*id, *source_key), source_value.timestamp);
|
||||
let resources = registry.resources.iter().chain(registry.removed_resources.iter().map(|(id, mark)| (id, &mark.content)));
|
||||
for (&id, entry) in resources {
|
||||
for (field, timestamp) in [("presence", entry.presence), ("hash", entry.hash_timestamp), ("sources", entry.sources_timestamp)] {
|
||||
out.insert(TimestampKey::Resource(id, field), timestamp);
|
||||
}
|
||||
for (source_key, source_value) in &entry.sources {
|
||||
out.insert(TimestampKey::ResourceSource(id, *source_key), source_value.timestamp);
|
||||
}
|
||||
}
|
||||
for (&id, mark) in ®istry.removed_nodes {
|
||||
out.insert(TimestampKey::Node(id, "removed"), mark.timestamp);
|
||||
}
|
||||
for (&id, mark) in ®istry.removed_networks {
|
||||
out.insert(TimestampKey::Network(id, "removed"), mark.timestamp);
|
||||
}
|
||||
for (&id, mark) in ®istry.removed_resources {
|
||||
out.insert(TimestampKey::Resource(id, "removed"), mark.timestamp);
|
||||
}
|
||||
for (&peer, registration) in ®istry.peer_users {
|
||||
out.insert(TimestampKey::PeerRegistration(peer), registration.timestamp);
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -18,6 +18,20 @@ pub struct SourceKey {
|
||||
pub struct SourceValue {
|
||||
pub source: Value,
|
||||
pub timestamp: TimeStamp,
|
||||
/// A removed source stays as a stamped tombstone, which readers see as absent.
|
||||
#[serde(default)]
|
||||
pub deleted: bool,
|
||||
}
|
||||
|
||||
impl SourceValue {
|
||||
/// The tombstone of a source removed at `timestamp`.
|
||||
pub fn deleted(timestamp: TimeStamp) -> Self {
|
||||
Self {
|
||||
source: Value::None,
|
||||
timestamp,
|
||||
deleted: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A single content-addressable resource: an ordered, conflict-mergeable chain of fallback sources
|
||||
@@ -26,8 +40,12 @@ pub struct SourceValue {
|
||||
/// resource agree by construction, since the hash is content-derived).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
|
||||
pub struct ResourceEntry {
|
||||
/// The latest addition or write; see [`Node::presence`](crate::Node).
|
||||
pub(crate) presence: TimeStamp,
|
||||
/// Fallback chain kept sorted by `SourceKey`, so iteration yields highest-priority first.
|
||||
pub sources: Vec<(SourceKey, SourceValue)>,
|
||||
/// When `sources` was last written whole, by an addition; a key the chain lacks is deleted as of then.
|
||||
pub sources_timestamp: TimeStamp,
|
||||
pub hash: Option<ResourceHash>,
|
||||
pub hash_timestamp: TimeStamp,
|
||||
}
|
||||
@@ -39,12 +57,22 @@ impl<'de> Deserialize<'de> for ResourceEntry {
|
||||
// collapse any duplicate keys, keeping the higher-timestamp value (LWW).
|
||||
#[derive(Deserialize)]
|
||||
struct Raw {
|
||||
#[serde(default)]
|
||||
presence: TimeStamp,
|
||||
sources: Vec<(SourceKey, SourceValue)>,
|
||||
#[serde(default)]
|
||||
sources_timestamp: TimeStamp,
|
||||
hash: Option<ResourceHash>,
|
||||
hash_timestamp: TimeStamp,
|
||||
}
|
||||
|
||||
let Raw { mut sources, hash, hash_timestamp } = Raw::deserialize(deserializer)?;
|
||||
let Raw {
|
||||
presence,
|
||||
mut sources,
|
||||
sources_timestamp,
|
||||
hash,
|
||||
hash_timestamp,
|
||||
} = Raw::deserialize(deserializer)?;
|
||||
sources.sort_by_key(|(a, _)| *a);
|
||||
sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| {
|
||||
// `dedup_by` keeps the first of each run; sorting is stable, so resolve duplicates by LWW.
|
||||
@@ -57,7 +85,13 @@ impl<'de> Deserialize<'de> for ResourceEntry {
|
||||
true
|
||||
});
|
||||
|
||||
Ok(Self { sources, hash, hash_timestamp })
|
||||
Ok(Self {
|
||||
presence,
|
||||
sources,
|
||||
sources_timestamp,
|
||||
hash,
|
||||
hash_timestamp,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,52 +102,89 @@ impl ResourceEntry {
|
||||
pub fn embedded(hash: ResourceHash, peer: PeerId, timestamp: TimeStamp) -> Self {
|
||||
let embedded = to_value(&graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
|
||||
let priority = Priority::new(0.).expect("0. is finite");
|
||||
let sources = vec![(SourceKey { priority, peer }, SourceValue { source: embedded, timestamp })];
|
||||
let sources = vec![(
|
||||
SourceKey { priority, peer },
|
||||
SourceValue {
|
||||
source: embedded,
|
||||
timestamp,
|
||||
deleted: false,
|
||||
},
|
||||
)];
|
||||
|
||||
Self {
|
||||
presence: timestamp,
|
||||
sources,
|
||||
sources_timestamp: timestamp,
|
||||
hash: Some(hash),
|
||||
hash_timestamp: timestamp,
|
||||
}
|
||||
}
|
||||
|
||||
/// The source body and timestamp stored under `key`, if any.
|
||||
/// The live source stored under `key`, if any; a tombstone is absent.
|
||||
pub fn source(&self, key: &SourceKey) -> Option<&SourceValue> {
|
||||
self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)).ok().map(|index| &self.sources[index].1)
|
||||
self.find(key).ok().map(|index| &self.sources[index].1).filter(|value| !value.deleted)
|
||||
}
|
||||
|
||||
/// Insert or LWW-overwrite the entry at `key`. A re-set at an existing key wins only if `value`'s
|
||||
/// timestamp is strictly newer; a fresh key is inserted in sorted position.
|
||||
pub fn set_source(&mut self, key: SourceKey, value: SourceValue) {
|
||||
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
|
||||
Ok(index) => {
|
||||
if value.timestamp > self.sources[index].1.timestamp {
|
||||
self.sources[index].1 = value;
|
||||
}
|
||||
}
|
||||
Err(index) => self.sources.insert(index, (key, value)),
|
||||
}
|
||||
/// The live sources in precedence order, tombstones skipped.
|
||||
pub(crate) fn live_sources(&self) -> impl Iterator<Item = (&SourceKey, &SourceValue)> {
|
||||
self.sources.iter().filter(|(_, value)| !value.deleted).map(|(key, value)| (key, value))
|
||||
}
|
||||
|
||||
/// Like [`set_source`](Self::set_source) but assigns unconditionally (silent-zone rewind), where the
|
||||
/// precomputed reverse/forward value is authoritative even if its timestamp ties what it replaces.
|
||||
pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) {
|
||||
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
|
||||
fn find(&self, key: &SourceKey) -> Result<usize, usize> {
|
||||
self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key))
|
||||
}
|
||||
|
||||
/// The stamp that decides a write to `key`: its entry's, tombstone included, or the chain's floor.
|
||||
fn deciding_timestamp(&self, key: &SourceKey) -> TimeStamp {
|
||||
self.find(key).map_or(self.sources_timestamp, |index| self.sources[index].1.timestamp)
|
||||
}
|
||||
|
||||
fn put(&mut self, key: SourceKey, value: SourceValue) {
|
||||
match self.find(&key) {
|
||||
Ok(index) => self.sources[index].1 = value,
|
||||
Err(index) => self.sources.insert(index, (key, value)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove the entry at `key` if its timestamp is strictly older than `timestamp` (LWW). Returns
|
||||
/// whether anything was removed.
|
||||
pub fn remove_source(&mut self, key: &SourceKey, timestamp: TimeStamp) -> bool {
|
||||
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)) {
|
||||
Ok(index) if timestamp > self.sources[index].1.timestamp => {
|
||||
self.sources.remove(index);
|
||||
true
|
||||
/// Writes the chain whole at `timestamp`: the floor deletes every other key without a tombstone per key.
|
||||
pub(crate) fn stamp_sources(&mut self, timestamp: TimeStamp) {
|
||||
self.sources.retain(|(_, value)| !value.deleted);
|
||||
self.sources.iter_mut().for_each(|(_, value)| value.timestamp = timestamp);
|
||||
self.sources_timestamp = timestamp;
|
||||
}
|
||||
|
||||
/// Folds another chain in key by key, as attribute maps merge.
|
||||
pub(crate) fn merge_sources(&mut self, other: Vec<(SourceKey, SourceValue)>, other_floor: TimeStamp) {
|
||||
self.sources.retain(|(_, value)| value.timestamp >= other_floor);
|
||||
for (key, value) in other {
|
||||
match self.find(&key) {
|
||||
Ok(index) if value.timestamp > self.sources[index].1.timestamp => self.sources[index].1 = value,
|
||||
Err(index) if value.timestamp >= self.sources_timestamp => self.sources.insert(index, (key, value)),
|
||||
_ => {}
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
self.sources_timestamp = self.sources_timestamp.max(other_floor);
|
||||
}
|
||||
|
||||
/// Insert or LWW-overwrite the entry at `key`; a re-set wins only with a strictly newer stamp.
|
||||
pub fn set_source(&mut self, key: SourceKey, value: SourceValue) {
|
||||
if value.timestamp > self.deciding_timestamp(&key) {
|
||||
self.put(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
/// Like [`set_source`](Self::set_source) but assigns unconditionally (silent-zone rewind, or building an entry).
|
||||
pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) {
|
||||
self.put(key, value);
|
||||
}
|
||||
|
||||
/// Remove the source at `key` if `timestamp` is newer than what decides it, leaving a tombstone. Returns whether it landed.
|
||||
pub fn remove_source(&mut self, key: &SourceKey, timestamp: TimeStamp) -> bool {
|
||||
if timestamp <= self.deciding_timestamp(key) {
|
||||
return false;
|
||||
}
|
||||
self.put(*key, SourceValue::deleted(timestamp));
|
||||
true
|
||||
}
|
||||
|
||||
/// Like [`remove_source`](Self::remove_source) but removes unconditionally (silent-zone rewind).
|
||||
@@ -130,15 +201,14 @@ impl ResourceEntry {
|
||||
/// True if the chain already carries a `DataSource::Embedded` source. Decodes each source body into
|
||||
/// `DataSource` so a shape change in the serialized form can't slip an embedded source past detection.
|
||||
pub fn has_embedded_source(&self) -> bool {
|
||||
self.sources
|
||||
.iter()
|
||||
self.live_sources()
|
||||
.any(|(_, value)| matches!(from_value::<graphene_resource::DataSource>(&value.source), Ok(graphene_resource::DataSource::Embedded)))
|
||||
}
|
||||
|
||||
/// A `SourceKey` ordered strictly ahead of every current source, so an inserted entry becomes the
|
||||
/// highest-precedence fallback.
|
||||
pub fn highest_precedence_key(&self, peer: PeerId) -> SourceKey {
|
||||
let min_priority = self.sources.first().map(|(key, _)| key.priority.value()).unwrap_or(0.);
|
||||
let min_priority = self.live_sources().next().map(|(key, _)| key.priority.value()).unwrap_or(0.);
|
||||
SourceKey {
|
||||
priority: Priority::new(min_priority - 1.).expect("finite priority minus one is finite"),
|
||||
peer,
|
||||
@@ -247,12 +317,15 @@ mod tests {
|
||||
SourceValue {
|
||||
source: Value::Float(priority),
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
deleted: false,
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
// Build a deliberately unsorted chain as a literal (bypassing the sorted-insert API), then round-trip it through `Value`.
|
||||
let unsorted = ResourceEntry {
|
||||
presence: TimeStamp::ORIGIN,
|
||||
sources_timestamp: TimeStamp::ORIGIN,
|
||||
sources: vec![source(2.), source(0.), source(1.)],
|
||||
hash: None,
|
||||
hash_timestamp: TimeStamp::ORIGIN,
|
||||
@@ -277,11 +350,14 @@ mod tests {
|
||||
SourceValue {
|
||||
source: Value::Str(body.into()),
|
||||
timestamp: TimeStamp { counter, peer: PeerId(1) },
|
||||
deleted: false,
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
let with_duplicates = ResourceEntry {
|
||||
presence: TimeStamp::ORIGIN,
|
||||
sources_timestamp: TimeStamp::ORIGIN,
|
||||
sources: vec![entry(5, "newer"), entry(1, "older")],
|
||||
hash: None,
|
||||
hash_timestamp: TimeStamp::ORIGIN,
|
||||
|
||||
@@ -29,22 +29,15 @@ impl Session {
|
||||
Self::with_peer(PeerId(core_types::uuid::generate_uuid()))
|
||||
}
|
||||
|
||||
/// Construct a session bound to a specific `PeerId`. Used by tests; production code wants
|
||||
/// `Session::new`.
|
||||
/// A session for `peer` standing for itself as a person, for tests and tools without a stored identity.
|
||||
pub fn with_peer(peer: PeerId) -> Self {
|
||||
Self::with_identity(peer, UserId(peer.0))
|
||||
}
|
||||
|
||||
/// A session for device `peer` used by person `user`, whom its registration records.
|
||||
pub fn with_identity(peer: PeerId, user: UserId) -> Self {
|
||||
Self {
|
||||
document: Document {
|
||||
working_registry: Registry::default(),
|
||||
retired_snapshot: Registry::default(),
|
||||
history: History::new(),
|
||||
hot_log: Vec::new(),
|
||||
head: None,
|
||||
redo_stack: Vec::new(),
|
||||
clock: LamportClock::new(peer),
|
||||
peer,
|
||||
last_broadcast_rev: None,
|
||||
next_node_counter: 0,
|
||||
},
|
||||
document: Document::empty(peer, user),
|
||||
remote_tips: HashMap::new(),
|
||||
}
|
||||
}
|
||||
@@ -53,6 +46,15 @@ impl Session {
|
||||
self.document.peer
|
||||
}
|
||||
|
||||
pub fn user(&self) -> UserId {
|
||||
self.document.user
|
||||
}
|
||||
|
||||
pub fn user_of(&self, peer: PeerId) -> Option<UserId> {
|
||||
let registered = || self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user);
|
||||
(peer == self.document.peer).then_some(self.document.user).or_else(registered)
|
||||
}
|
||||
|
||||
pub fn registry(&self) -> &Registry {
|
||||
&self.document.working_registry
|
||||
}
|
||||
@@ -142,16 +144,16 @@ impl Session {
|
||||
///
|
||||
/// The peer's first contribution is preceded by a `RegisterPeer` op, so the device's
|
||||
/// `PeerId → UserId` mapping is established (and, under causal delivery, observed by other peers)
|
||||
/// before any of its edits. A no-op batch doesn't register — registration rides a real edit.
|
||||
fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
/// before any of its edits. A no-op batch doesn't register, since registration rides a real edit.
|
||||
pub(crate) fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
let mut pending: Vec<RegistryDelta> = ops.into_iter().collect();
|
||||
if pending.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
if !self.document.working_registry.peer_users.contains_key(&self.document.peer) {
|
||||
let user = UserId(self.document.peer.0);
|
||||
pending.insert(0, RegistryDelta::RegisterPeer { peer: self.document.peer, user });
|
||||
let (peer, user) = (self.document.peer, self.document.user);
|
||||
if self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user) != Some(user) {
|
||||
pending.insert(0, RegistryDelta::RegisterPeer { peer, user });
|
||||
}
|
||||
|
||||
let mut staged = Vec::with_capacity(pending.len());
|
||||
@@ -160,7 +162,7 @@ impl Session {
|
||||
op,
|
||||
timestamp: self.document.clock.tick(),
|
||||
};
|
||||
self.document.apply_hot_op(hot_op.clone())?;
|
||||
self.document.stage_hot_op(hot_op.clone(), ApplyMode::Strict)?;
|
||||
staged.push(hot_op);
|
||||
}
|
||||
Ok(staged)
|
||||
@@ -168,19 +170,23 @@ impl Session {
|
||||
|
||||
/// Wrap each op as a `Delta`, apply it, and chain it onto the local history. One tick per op.
|
||||
///
|
||||
/// Operates on the *retired snapshot*: reverses are computed against and forward ops applied to it,
|
||||
/// so each `reverse` captures the true pre-op value rather than the hot-polluted working state. The
|
||||
/// working registry already reflects these ops (they were staged as hot ops before retirement, or
|
||||
/// equal the snapshot when there are none), so it is left untouched.
|
||||
/// Operates on the retired snapshot, so each `reverse` holds the true pre-op state; the working registry already
|
||||
/// reflects the ops, staged before retirement or equal to the snapshot when nothing is hot.
|
||||
///
|
||||
/// `idempotent`: pass `true` when the snapshot already reflects the op (retirement of an already-
|
||||
/// applied hot op) so duplicate structural inserts no-op rather than error.
|
||||
fn commit_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>, idempotent: bool) -> Result<Vec<Rev>, CrdtError> {
|
||||
let target = RegistryTarget::Snapshot;
|
||||
self.commit_ops_authored_at(ops.into_iter().map(|op| (op, None)), idempotent)
|
||||
}
|
||||
|
||||
/// [`commit_ops`](Self::commit_ops) for ops paired with their authored stamp (`None` to mint one), which retirement keeps
|
||||
/// so LWW resolves as it did live.
|
||||
fn commit_ops_authored_at(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Option<TimeStamp>)>, idempotent: bool) -> Result<Vec<Rev>, CrdtError> {
|
||||
let target = RegistryTarget::Retired;
|
||||
let ops = ops.into_iter();
|
||||
let mut produced = Vec::with_capacity(ops.size_hint().0);
|
||||
|
||||
for op in ops {
|
||||
for (op, authored_at) in ops {
|
||||
// A new edit abandons any undone-forward branch: those revs stay in the DAG but are no
|
||||
// longer reachable via redo. (Mirrors the legacy editor clearing its redo history on
|
||||
// commit.) Done on the first real op so a no-op commit doesn't silently disable redo.
|
||||
@@ -189,9 +195,9 @@ impl Session {
|
||||
}
|
||||
|
||||
let reverse = self.document.compute_reverse_delta(target, &op)?;
|
||||
let timestamp = self.document.clock.tick();
|
||||
let timestamp = authored_at.unwrap_or_else(|| self.document.clock.tick());
|
||||
let parent = self.document.head;
|
||||
let author = self.document.peer;
|
||||
let author = timestamp.peer;
|
||||
|
||||
let delta = Delta::new(parent, author, timestamp, op, reverse);
|
||||
let rev = delta.id;
|
||||
@@ -202,7 +208,7 @@ impl Session {
|
||||
{
|
||||
return Err(CrdtError::NotFoundInHistory(parent));
|
||||
}
|
||||
let mode = if idempotent { ApplyMode::Idempotent } else { ApplyMode::Live };
|
||||
let mode = if idempotent { ApplyMode::Idempotent } else { ApplyMode::Strict };
|
||||
self.document.apply_op_with(target, delta.kind.clone(), delta.timestamp, mode)?;
|
||||
self.document.history.push(delta);
|
||||
self.document.head = Some(rev);
|
||||
@@ -215,7 +221,7 @@ impl Session {
|
||||
/// Wrap an already-materialized snapshot. Trusts `registry` to match `history`; advances the
|
||||
/// clock past every observed timestamp but does not re-apply ops. `history` is taken in on-disk
|
||||
/// (topological) order.
|
||||
pub fn load(peer: PeerId, registry: Registry, history: Vec<Delta>, head: Option<Rev>, redo_stack: Vec<Rev>, next_node_counter: u64) -> Self {
|
||||
pub fn load(peer: PeerId, user: UserId, registry: Registry, history: Vec<Delta>, head: Option<Rev>, redo_stack: Vec<Rev>, next_node_counter: u64) -> Self {
|
||||
let mut clock = LamportClock::new(peer);
|
||||
for delta in &history {
|
||||
clock.observe(delta.timestamp);
|
||||
@@ -228,13 +234,11 @@ impl Session {
|
||||
retired_snapshot: registry.clone(),
|
||||
working_registry: registry,
|
||||
history: History::from_ordered(history),
|
||||
hot_log: Vec::new(),
|
||||
head,
|
||||
redo_stack,
|
||||
clock,
|
||||
peer,
|
||||
last_broadcast_rev: None,
|
||||
next_node_counter,
|
||||
..Document::empty(peer, user)
|
||||
},
|
||||
remote_tips: HashMap::new(),
|
||||
}
|
||||
@@ -242,8 +246,8 @@ impl Session {
|
||||
|
||||
/// Rebuild the registry from scratch by applying every delta in causal order.
|
||||
/// `deltas` must be in causal order (every parent before its children).
|
||||
pub fn replay_from_history(peer: PeerId, deltas: impl IntoIterator<Item = Delta>, next_node_counter: u64) -> Result<Self, CrdtError> {
|
||||
let mut session = Self::with_peer(peer);
|
||||
pub fn replay_from_history(peer: PeerId, user: UserId, deltas: impl IntoIterator<Item = Delta>, next_node_counter: u64) -> Result<Self, CrdtError> {
|
||||
let mut session = Self::with_identity(peer, user);
|
||||
session.document.next_node_counter = next_node_counter;
|
||||
|
||||
for delta in deltas {
|
||||
@@ -258,11 +262,6 @@ impl Session {
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
/// Apply a hot op without going through the broadcast stream.
|
||||
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
|
||||
self.document.apply_hot_op(hot_op)
|
||||
}
|
||||
|
||||
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
|
||||
/// where the registry may already reflect the op's effect from a prior retired snapshot.
|
||||
pub fn replay_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
|
||||
@@ -301,25 +300,28 @@ impl Session {
|
||||
Ok(Some(merge_rev))
|
||||
}
|
||||
|
||||
/// Promote hot ops with timestamp `≤ up_to` into retired deltas, re-applied with fresh
|
||||
/// retirement timestamps so LWW arms bump field timestamps to `T_retire`.
|
||||
///
|
||||
/// Today: one retired delta per hot op. Coarsening is a future step.
|
||||
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, CrdtError> {
|
||||
let mut drained = Vec::new();
|
||||
let mut remaining = Vec::with_capacity(self.document.hot_log.len());
|
||||
for hot_op in self.document.hot_log.drain(..) {
|
||||
if hot_op.timestamp <= up_to {
|
||||
drained.push(hot_op);
|
||||
} else {
|
||||
remaining.push(hot_op);
|
||||
}
|
||||
/// The retired snapshot as history alone gives it: the fold of `head`'s ancestry, leaving out undone deltas kept for redo.
|
||||
pub fn snapshot_from_history(&self) -> Result<Registry, CrdtError> {
|
||||
let reachable = self.document.history.ancestors(self.document.head);
|
||||
let mut scratch = Document::empty(self.document.peer, self.document.user);
|
||||
for delta in self.document.history.iter().filter(|delta| reachable.contains(&delta.id)) {
|
||||
scratch.apply_op_with(RegistryTarget::Working, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
|
||||
}
|
||||
self.document.hot_log = remaining;
|
||||
|
||||
self.commit_ops(drained.into_iter().map(|hot_op| hot_op.op), true)
|
||||
Ok(scratch.working_registry)
|
||||
}
|
||||
|
||||
pub fn history_len(&self) -> usize {
|
||||
self.document.history.len()
|
||||
}
|
||||
|
||||
/// Promote every hot op stamped at or before `up_to` into retired deltas in hot-log order, each keeping its authored
|
||||
/// stamp.
|
||||
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, CrdtError> {
|
||||
let (drained, kept): (Vec<HotOp>, Vec<HotOp>) = self.document.hot_log.drain(..).partition(|hot_op| hot_op.timestamp <= up_to);
|
||||
self.document.hot_log = kept;
|
||||
let ops = drained.into_iter().map(|hot_op| (hot_op.op, Some(hot_op.timestamp)));
|
||||
self.commit_ops_authored_at(ops, true)
|
||||
}
|
||||
/// Mark a retired delta as the end of a user interaction, so the undo cursor treats it as a checkpoint.
|
||||
/// Called once per interaction by the editor-facing commit path (not by resource/internal commits).
|
||||
pub fn mark_interaction_end(&mut self, rev: Rev) {
|
||||
@@ -435,9 +437,9 @@ impl Session {
|
||||
|
||||
/// Build a synthetic linear history whose replay reproduces `registry`. Each op gets a
|
||||
/// freshly-ticked clock timestamp and chains to the previous op's `Rev`.
|
||||
pub fn bootstrap_from_registry(peer: PeerId, registry: Registry) -> Result<Self, CrdtError> {
|
||||
pub fn bootstrap_from_registry(peer: PeerId, user: UserId, registry: Registry) -> Result<Self, CrdtError> {
|
||||
let ops = crate::delta::compute_deltas(&Registry::default(), ®istry);
|
||||
let mut session = Self::with_peer(peer);
|
||||
let mut session = Self::with_identity(peer, user);
|
||||
session.commit_ops(ops, false)?;
|
||||
// No hot ops on this path, so the working registry must mirror the freshly-built snapshot.
|
||||
session.document.working_registry = session.document.retired_snapshot.clone();
|
||||
@@ -465,18 +467,10 @@ impl Session {
|
||||
/// interaction's `AddResource` from the working registry, so a redoable (or re-undoable) interaction's
|
||||
/// resources no longer appear in `registry().resources` even though redo still needs them. Resource GC
|
||||
/// must keep this whole set alive, not just the current head's, or undo then redo loses declaration
|
||||
/// bytes. Walks current resources plus each delta's `AddResource`/`RemoveResource` snapshot.
|
||||
/// bytes. Walks current resources plus each delta's `AddResource`/`RemoveResource` snapshot and `SetResourceHash`.
|
||||
pub fn all_referenced_resource_hashes(&self) -> HashSet<ResourceHash> {
|
||||
let mut hashes: HashSet<ResourceHash> = self.document.working_registry.resources.values().filter_map(|entry| entry.hash).collect();
|
||||
|
||||
for delta in self.document.history.iter() {
|
||||
match &delta.kind {
|
||||
RegistryDelta::AddResource { entry, .. } => hashes.extend(entry.hash),
|
||||
RegistryDelta::RemoveResource { snapshot, .. } => hashes.extend(snapshot.hash),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
hashes.extend(self.document.history.resource_hashes());
|
||||
hashes
|
||||
}
|
||||
|
||||
@@ -542,7 +536,7 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Test-only: commit a single op as a retired delta on the local chain, returning the result so a
|
||||
/// test can observe a resurrection failure (e.g. `NotFoundInHistory`).
|
||||
/// test can observe a failure (e.g. `NotFoundInHistory`).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn commit_op_for_test(&mut self, op: RegistryDelta) -> Result<(), CrdtError> {
|
||||
self.commit_ops(std::iter::once(op), false).map(|_| ())
|
||||
@@ -594,10 +588,6 @@ pub enum CrdtError {
|
||||
ExportSlotOutOfBounds(u32),
|
||||
#[error("Delta {0} not found in history")]
|
||||
NotFoundInHistory(Rev),
|
||||
#[error("No history entry resurrects node {0}")]
|
||||
NodeNotInHistory(NodeId),
|
||||
#[error("No history entry resurrects network {0}")]
|
||||
NetworkNotInHistory(NetworkId),
|
||||
#[error("Nothing to undo")]
|
||||
NothingToUndo,
|
||||
#[error("Nothing to redo")]
|
||||
@@ -606,9 +596,6 @@ pub enum CrdtError {
|
||||
NodeAlreadyExists(NodeId),
|
||||
#[error("Network {0} already exists")]
|
||||
NetworkAlreadyExists(NetworkId),
|
||||
/// PeerId is already registered to a different UserId.
|
||||
#[error("Peer {0:?} is already registered to a different user")]
|
||||
PeerRegistrationConflict(PeerId),
|
||||
#[error("Delta stored under {stored} hashes to {expected}")]
|
||||
RevMismatch { stored: Rev, expected: Rev },
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
use crate::{AttributeDelta, CrdtError, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, RegistryDelta, Session, UserId, Value};
|
||||
|
||||
fn set_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: AttributeDelta {
|
||||
key: key.to_string(),
|
||||
value: Some(Value::from(serde_json::json!(value))),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn add_network(id: u64) -> RegistryDelta {
|
||||
RegistryDelta::AddNetwork {
|
||||
id: NetworkId(id),
|
||||
network: Network::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every op commutes, so the snapshot folds to the working registry's values whatever the log order.
|
||||
#[test]
|
||||
fn retirement_takes_the_ops_under_the_cutoff_in_any_applied_order() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
// The log is in arrival order: a guest's later-stamped op sits ahead of an earlier one.
|
||||
let hot = |op, counter, peer| crate::HotOp {
|
||||
op,
|
||||
timestamp: crate::TimeStamp { counter, peer: PeerId(peer) },
|
||||
};
|
||||
let (late, own) = (hot(add_network(9), 50, 2), hot(set_attribute("x", 1), 20, 3));
|
||||
host.replay_hot_op(late.clone()).expect("the late-stamped op lands first");
|
||||
host.replay_hot_op(own.clone()).expect("the earlier-stamped op lands second");
|
||||
|
||||
host.retire(own.timestamp).expect("retire");
|
||||
assert_eq!(host.hot_log().len(), 1, "the later-stamped op stays hot");
|
||||
assert!(!host.retired_registry().networks.contains_key(&NetworkId(9)));
|
||||
assert!(host.registry().networks.contains_key(&NetworkId(9)));
|
||||
assert!(host.retired_registry().attributes.get("x").is_some_and(|value| !value.deleted));
|
||||
|
||||
host.retire(late.timestamp).expect("retire the rest");
|
||||
assert!(host.hot_log().is_empty());
|
||||
assert!(host.registry().value_equal(host.retired_registry()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newest_peer_registration_wins_in_any_order() {
|
||||
// Registration rides the staging path, so the steps go through the hot log and retire.
|
||||
fn stage_and_retire(session: &mut Session, op: RegistryDelta) {
|
||||
let hot = session.stage_ops([op]).expect("stage");
|
||||
session.retire(hot.last().expect("staged").timestamp).expect("retire");
|
||||
}
|
||||
let mut device = Session::with_identity(PeerId(1), UserId(10));
|
||||
stage_and_retire(&mut device, set_attribute("first", 1));
|
||||
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(10));
|
||||
|
||||
// The person at the device changes, so the next batch registers again.
|
||||
device.document.user = UserId(20);
|
||||
stage_and_retire(&mut device, set_attribute("second", 2));
|
||||
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(20));
|
||||
let registrations = device.history().filter(|delta| matches!(delta.kind, RegistryDelta::RegisterPeer { .. })).count();
|
||||
assert_eq!(registrations, 2, "one registration per person the device stood for");
|
||||
|
||||
let mut other = Session::with_peer(PeerId(2));
|
||||
for delta in device.cloned_deltas().into_iter().rev() {
|
||||
other.document.apply_op_idempotent(delta.kind, delta.timestamp).unwrap();
|
||||
}
|
||||
assert_eq!(other.user_of(PeerId(1)), Some(UserId(20)), "the newest registration wins in any order");
|
||||
assert_eq!(other.user_of(PeerId(3)), None, "a peer never registered has no user");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_local_op_leaves_the_working_registry_unchanged() {
|
||||
let mut s = Session::with_peer(PeerId(1));
|
||||
let node = Node::new(NetworkId(1), Implementation::Network(NetworkId(1)), 1);
|
||||
s.stage_ops([
|
||||
RegistryDelta::AddNetwork {
|
||||
id: NetworkId(1),
|
||||
network: Network::default(),
|
||||
},
|
||||
RegistryDelta::AddNode { id: NodeId(1), node },
|
||||
])
|
||||
.unwrap();
|
||||
let before = s.registry().clone();
|
||||
|
||||
let refused = s.stage_ops([RegistryDelta::ChangeNodeInput {
|
||||
id: NodeId(1),
|
||||
index: 0,
|
||||
new_input: NodeInput::Node { id: NodeId(404), index: 0 },
|
||||
}]);
|
||||
assert!(matches!(refused, Err(CrdtError::TargetNodeDoesNotExist(_))));
|
||||
assert_eq!(s.registry(), &before, "the refused op's write to node 1 stayed in the working registry");
|
||||
}
|
||||
@@ -42,7 +42,9 @@ fn apply_hot_op_advances_clock_past_observed_timestamp() {
|
||||
timestamp: observed,
|
||||
};
|
||||
|
||||
document.apply_hot_op(hot_op).expect("RemoveNode on absent node is a no-op, not an error");
|
||||
document
|
||||
.stage_hot_op(hot_op, crate::document::ApplyMode::Strict)
|
||||
.expect("RemoveNode on absent node is a no-op, not an error");
|
||||
|
||||
assert!(
|
||||
document.clock.counter >= observed.counter,
|
||||
@@ -263,7 +265,11 @@ fn first_contribution_registers_the_peer() {
|
||||
let registrations = first.iter().filter(|hot_op| matches!(hot_op.op, RegistryDelta::RegisterPeer { .. })).count();
|
||||
assert_eq!(registrations, 1, "exactly one RegisterPeer on first contribution");
|
||||
assert!(matches!(first[0].op, RegistryDelta::RegisterPeer { .. }), "RegisterPeer must precede the edit ops");
|
||||
assert_eq!(session.registry().peer_users.get(&PeerId(7)), Some(&crate::UserId(7)), "peer mapped to its UserId");
|
||||
assert_eq!(
|
||||
session.registry().peer_users.get(&PeerId(7)).map(|registration| registration.user),
|
||||
Some(crate::UserId(7)),
|
||||
"peer mapped to its UserId"
|
||||
);
|
||||
|
||||
// A second, distinct contribution must not re-register.
|
||||
let mut other_network = tiny_network();
|
||||
@@ -284,9 +290,9 @@ fn first_contribution_registers_the_peer() {
|
||||
assert_eq!(fresh.registry().peer_users, peers_before, "a no-op batch must not add a registration");
|
||||
}
|
||||
|
||||
/// A SetExport against a removed network must restore the network from history rather than error.
|
||||
/// A SetExport newer than a network's removal revives the network from its tombstone instead of erroring.
|
||||
#[test]
|
||||
fn set_export_resurrects_absent_network() {
|
||||
fn set_network_export_revives_a_removed_network() {
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
let network_id = NetworkId(7);
|
||||
|
||||
@@ -304,7 +310,7 @@ fn set_export_resurrects_absent_network() {
|
||||
snapshot: Network::default(),
|
||||
},
|
||||
);
|
||||
assert!(!document.working_registry.networks.contains_key(&network_id), "network should be removed before the resurrection test");
|
||||
assert!(!document.working_registry.networks.contains_key(&network_id), "network should be removed before the revival");
|
||||
|
||||
commit_op(
|
||||
&mut document,
|
||||
@@ -315,12 +321,12 @@ fn set_export_resurrects_absent_network() {
|
||||
},
|
||||
);
|
||||
|
||||
assert!(document.working_registry.networks.contains_key(&network_id), "SetExport should have resurrected the network");
|
||||
assert!(document.working_registry.networks.contains_key(&network_id), "SetExport should have revived the network");
|
||||
}
|
||||
|
||||
/// Cascading resurrection: bringing a node back must also restore its owning network when absent.
|
||||
/// An addition into a removed network is evidence the network exists, so it brings the network back.
|
||||
#[test]
|
||||
fn add_node_resurrects_owning_network() {
|
||||
fn add_node_revives_its_removed_network() {
|
||||
use crate::Node;
|
||||
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
@@ -345,18 +351,13 @@ fn add_node_resurrects_owning_network() {
|
||||
let node = Node { network: network_id, ..Node::dummy() };
|
||||
commit_op(&mut document, RegistryDelta::AddNode { id: node_id, node });
|
||||
|
||||
assert!(
|
||||
document.working_registry.networks.contains_key(&network_id),
|
||||
"AddNode should have cascaded a resurrection of the owning network"
|
||||
);
|
||||
assert!(document.working_registry.networks.contains_key(&network_id), "AddNode should have revived the owning network");
|
||||
assert!(document.working_registry.node_instances.contains_key(&node_id), "the node itself should also be present");
|
||||
}
|
||||
|
||||
/// Reverting the same removal twice (the moral equivalent of two peers concurrently resurrecting
|
||||
/// the same node) must not error on the second apply. Today the second revert hits
|
||||
/// `apply_op(AddNode, false)` against a present node and returns `NodeAlreadyExists`.
|
||||
/// Two peers reverting one removal: the second revival is not newer than the first, so it lands once.
|
||||
#[test]
|
||||
fn concurrent_resurrection_via_revert_is_idempotent() {
|
||||
fn the_same_revival_arriving_twice_lands_once() {
|
||||
use crate::Node;
|
||||
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
@@ -373,40 +374,19 @@ fn concurrent_resurrection_via_revert_is_idempotent() {
|
||||
let node = Node { network: network_id, ..Node::dummy() };
|
||||
commit_op(&mut document, RegistryDelta::AddNode { id: node_id, node: node.clone() });
|
||||
commit_op(&mut document, RegistryDelta::RemoveNode { id: node_id, snapshot: node });
|
||||
assert!(!document.working_registry.node_instances.contains_key(&node_id), "node should be removed before the resurrection test");
|
||||
assert!(!document.working_registry.node_instances.contains_key(&node_id), "node should be removed before the revival");
|
||||
|
||||
document.restore_node_from_history(RegistryTarget::Working, node_id).expect("first resurrection should succeed");
|
||||
assert!(document.working_registry.node_instances.contains_key(&node_id), "first resurrection should bring the node back");
|
||||
let revive = RegistryDelta::AddNode {
|
||||
id: node_id,
|
||||
node: Node { network: network_id, ..Node::dummy() },
|
||||
};
|
||||
let at = document.clock.tick();
|
||||
document.apply_op_idempotent(revive.clone(), at).expect("first revival");
|
||||
assert!(document.working_registry.node_instances.contains_key(&node_id), "the first revival brings the node back");
|
||||
|
||||
let second = document.restore_node_from_history(RegistryTarget::Working, node_id);
|
||||
assert!(second.is_ok(), "second resurrection of an already-present node should be a no-op, got {second:?}");
|
||||
}
|
||||
|
||||
/// History-based resurrection must work when the matching delta is the *root* commit. The history
|
||||
/// walk used to drop the root (its empty parent list short-circuited the iterator before yielding
|
||||
/// it), so a node removed by the very first commit could not be restored.
|
||||
#[test]
|
||||
fn restore_node_from_root_commit() {
|
||||
use crate::Node;
|
||||
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
let node_id = NodeId(42);
|
||||
|
||||
let node = Node::dummy();
|
||||
|
||||
// Seed the working state so the root commit can remove the node (its reverse is the `AddNode` the
|
||||
// resurrection looks for). This `RemoveNode` is the only commit, so the match sits at the root.
|
||||
document.working_registry.networks.insert(ROOT_NETWORK, Network::default());
|
||||
document.retired_snapshot.networks.insert(ROOT_NETWORK, Network::default());
|
||||
document.working_registry.node_instances.insert(node_id, node.clone());
|
||||
document.retired_snapshot.node_instances.insert(node_id, node.clone());
|
||||
commit_op(&mut document, RegistryDelta::RemoveNode { id: node_id, snapshot: node });
|
||||
assert!(!document.working_registry.node_instances.contains_key(&node_id), "node should be removed by the root commit");
|
||||
|
||||
document
|
||||
.restore_node_from_history(RegistryTarget::Working, node_id)
|
||||
.expect("resurrection from the root commit should succeed");
|
||||
assert!(document.working_registry.node_instances.contains_key(&node_id), "node must be restored from the root commit");
|
||||
let second = document.apply_op_idempotent(revive, at);
|
||||
assert!(second.is_ok(), "the same revival again is a no-op, got {second:?}");
|
||||
assert!(document.working_registry.node_instances.contains_key(&node_id));
|
||||
}
|
||||
|
||||
/// Erroring ops still bump the clock: we observed the timestamp on the wire, the fact that the
|
||||
@@ -563,7 +543,10 @@ fn remove_source_reverse_restores_prior() {
|
||||
}
|
||||
|
||||
document.apply_op(RD::RemoveSource { id, key }, ts(5, 1)).unwrap();
|
||||
assert!(document.working_registry.resources.get(&id).unwrap().sources.is_empty(), "source removed");
|
||||
assert!(
|
||||
document.working_registry.resources.get(&id).unwrap().live_sources().next().is_none(),
|
||||
"source removed, a tombstone left"
|
||||
);
|
||||
|
||||
// Applying the reverse restores the chain.
|
||||
document.apply_op(reverse, ts(6, 1)).unwrap();
|
||||
@@ -623,7 +606,16 @@ use crate::{ResourceEntry, ResourceStore, SourceValue};
|
||||
|
||||
fn entry_with_source(priority: f64, peer: u64, body: Value, hash: Option<ResourceHash>) -> ResourceEntry {
|
||||
ResourceEntry {
|
||||
sources: vec![(source_key(priority, peer), SourceValue { source: body, timestamp: ts(1, peer) })],
|
||||
presence: ts(1, peer),
|
||||
sources: vec![(
|
||||
source_key(priority, peer),
|
||||
SourceValue {
|
||||
source: body,
|
||||
timestamp: ts(1, peer),
|
||||
deleted: false,
|
||||
},
|
||||
)],
|
||||
sources_timestamp: TimeStamp::ORIGIN,
|
||||
hash,
|
||||
hash_timestamp: ts(1, peer),
|
||||
}
|
||||
@@ -674,6 +666,7 @@ fn compute_deltas_diffs_resources_and_round_trips() {
|
||||
SourceValue {
|
||||
source: Value::Str("url".into()),
|
||||
timestamp: ts(1, 1),
|
||||
deleted: false,
|
||||
},
|
||||
);
|
||||
to.insert(kept, kept_entry);
|
||||
@@ -699,6 +692,8 @@ fn compute_deltas_diffs_resources_and_round_trips() {
|
||||
// Apply the diff to a document seeded with `from`, then check it matches `to` by value.
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
document.working_registry = registry_with_resources(from);
|
||||
// A clock is past every stamp in the registry it edits, as a session's persisted clock is.
|
||||
document.clock.observe(ts(1, 1));
|
||||
for op in deltas {
|
||||
let timestamp = document.clock.tick();
|
||||
document.apply_op(op, timestamp).expect("apply resource delta");
|
||||
@@ -746,6 +741,15 @@ fn all_referenced_resource_hashes_survives_undo() {
|
||||
session.all_referenced_resource_hashes().contains(&hash),
|
||||
"the undone interaction's resource must still be reported so GC keeps its bytes for redo"
|
||||
);
|
||||
|
||||
// A later hash change, undone, keeps the new hash reported too: redo puts it back.
|
||||
session.redo().expect("redo");
|
||||
let changed = ResourceHash::from(&b"changed-bytes"[..]);
|
||||
let hot_ops = session.stage_ops([crate::RegistryDelta::SetResourceHash { id, hash: Some(changed) }]).expect("stage hash change");
|
||||
let revs = session.retire(hot_ops.last().expect("staged").timestamp).expect("retire");
|
||||
session.mark_interaction_end(*revs.last().expect("one retired delta"));
|
||||
session.undo().expect("undo the hash change");
|
||||
assert!(session.all_referenced_resource_hashes().contains(&changed), "the undone hash change keeps its bytes for redo");
|
||||
}
|
||||
|
||||
/// A commit that produces no deltas must not touch the redo stack. Redo is only abandoned by a real
|
||||
@@ -811,7 +815,7 @@ fn embed_resource_sources_preserves_unretired_hot_ops() {
|
||||
/// ordered (`BTreeMap`): a hash-randomized map would give the same logical delta different `Rev`s.
|
||||
#[test]
|
||||
fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
||||
use crate::{AttributeValue, AttributesWrite, Implementation};
|
||||
use crate::{AttributeValue, Implementation};
|
||||
|
||||
let keys = ["ui::position", "ui::display_name", "ui::locked", "ui::pinned", "call_argument", "context_features"];
|
||||
|
||||
@@ -836,6 +840,9 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
||||
}];
|
||||
|
||||
Node {
|
||||
presence: Default::default(),
|
||||
network_timestamp: Default::default(),
|
||||
inputs_timestamp: Default::default(),
|
||||
implementation: implementation.clone(),
|
||||
implementation_timestamp: Default::default(),
|
||||
inputs,
|
||||
@@ -880,3 +887,439 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
||||
|
||||
assert_eq!(delta_forward.id, delta_reversed.id, "Rev must not depend on attribute insertion order");
|
||||
}
|
||||
|
||||
fn add_network(id: u64) -> RegistryDelta {
|
||||
let network = Network::default();
|
||||
RegistryDelta::AddNetwork { id: NetworkId(id), network }
|
||||
}
|
||||
|
||||
fn change_node_attribute(id: NodeId, key: &str, value: serde_json::Value) -> RegistryDelta {
|
||||
let delta = crate::AttributeDelta {
|
||||
key: key.into(),
|
||||
value: Some(Value::from(value)),
|
||||
};
|
||||
RegistryDelta::ChangeNodeAttribute { id, delta }
|
||||
}
|
||||
|
||||
fn hot_op(op: RegistryDelta, counter: u64, peer: u64) -> HotOp {
|
||||
HotOp { op, timestamp: ts(counter, peer) }
|
||||
}
|
||||
|
||||
/// So the snapshot and a replay keep the LWW winner the live view did, whether the straggler retires with it or after.
|
||||
#[test]
|
||||
fn retirement_preserves_the_live_lww_winner() {
|
||||
for straggler_retires_alone in [false, true] {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
let winner = hot_op(set_document_attribute("k", 1), 10, 2);
|
||||
host.replay_hot_op(winner.clone()).expect("apply winner");
|
||||
if straggler_retires_alone {
|
||||
host.retire(winner.timestamp).expect("retire winner");
|
||||
}
|
||||
host.replay_hot_op(hot_op(set_document_attribute("k", 2), 5, 3)).expect("apply straggler");
|
||||
host.retire(winner.timestamp).expect("retire");
|
||||
|
||||
let value = |registry: &crate::Registry| registry.attributes.get("k").map(|attribute| attribute.value.clone());
|
||||
let replayed = host.snapshot_from_history().expect("refold");
|
||||
let values = [value(host.registry()), value(host.retired_registry()), value(&replayed)];
|
||||
assert_eq!(values, [(); 3].map(|_| Some(Value::from(serde_json::json!(1)))), "straggler retires alone: {straggler_retires_alone}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Random ops over a few colliding ids fold to one registry in any order. Removal snapshots are constant or, as a remover
|
||||
/// sends them, a fold of some earlier ops.
|
||||
#[test]
|
||||
fn a_set_of_ops_folds_to_one_registry_in_any_order() {
|
||||
use crate::{Implementation, Priority, ResourceEntry, SourceKey, SourceValue, UserId};
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
struct Lcg(u64);
|
||||
impl Lcg {
|
||||
fn below(&mut self, bound: u64) -> u64 {
|
||||
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
(self.0 >> 33) % bound
|
||||
}
|
||||
}
|
||||
|
||||
/// Folds the ops in order.
|
||||
fn fold(ops: &[(RegistryDelta, TimeStamp)]) -> crate::Registry {
|
||||
let mut document = fresh_document(PeerId(9));
|
||||
for (op, at) in ops {
|
||||
document.apply_op_idempotent(op.clone(), *at).unwrap_or_else(|error| panic!("{op:?} at {at:?}: {error}"));
|
||||
}
|
||||
document.working_registry
|
||||
}
|
||||
|
||||
fn random_op(rng: &mut Lcg, at: TimeStamp, seen: &[(RegistryDelta, TimeStamp)], real_snapshots: bool) -> RegistryDelta {
|
||||
let node_id = NodeId(1 + rng.below(4));
|
||||
let network_id = NetworkId(1 + rng.below(3));
|
||||
let resource_id = ResourceId::from(1 + rng.below(2));
|
||||
let input = |rng: &mut Lcg| match rng.below(3) {
|
||||
0 => crate::NodeInput::Node {
|
||||
id: NodeId(1 + rng.below(4)),
|
||||
index: 0,
|
||||
},
|
||||
_ => crate::NodeInput::Value {
|
||||
value: Value::from(serde_json::json!(rng.below(100))),
|
||||
exposed: false,
|
||||
},
|
||||
};
|
||||
// A write, or a deletion one time in four.
|
||||
let attribute = |rng: &mut Lcg, key: &str| crate::AttributeDelta {
|
||||
key: key.into(),
|
||||
value: (rng.below(4) > 0).then(|| Value::from(serde_json::json!(rng.below(100)))),
|
||||
};
|
||||
let key = |rng: &mut Lcg| SourceKey {
|
||||
priority: Priority::new(rng.below(2) as f64).expect("finite"),
|
||||
peer: PeerId(1 + rng.below(2).min(at.peer.0)),
|
||||
};
|
||||
// What a remover saw: some of the ops before it. Two snapshots agreeing on a stamp then agree on the value,
|
||||
// which a fabricated snapshot only does by being constant.
|
||||
let saw = |rng: &mut Lcg| fold(&seen.iter().filter(|_| rng.below(2) == 0).cloned().collect::<Vec<_>>());
|
||||
match rng.below(22) {
|
||||
0 => {
|
||||
// An export list of its own, so additions of different lengths meet.
|
||||
let exports = (0..rng.below(3))
|
||||
.map(|_| crate::ExportSlot {
|
||||
target: Some(input(rng)),
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
})
|
||||
.collect();
|
||||
RegistryDelta::AddNetwork {
|
||||
id: network_id,
|
||||
network: Network { exports, ..Default::default() },
|
||||
}
|
||||
}
|
||||
1 => {
|
||||
let snapshot = if real_snapshots { saw(rng).networks.get(&network_id).cloned() } else { Some(Network::default()) };
|
||||
snapshot.map_or(RegistryDelta::Other(Value::None), |snapshot| RegistryDelta::RemoveNetwork { id: network_id, snapshot })
|
||||
}
|
||||
2 | 3 => RegistryDelta::AddNode {
|
||||
id: node_id,
|
||||
node: Node::new(network_id, Implementation::ProtoNode(ResourceId::from(7)), 1 + rng.below(2) as usize),
|
||||
},
|
||||
4 => {
|
||||
let fabricated = || Node::new(NetworkId(1), Implementation::ProtoNode(ResourceId::from(7)), 2);
|
||||
let snapshot = if real_snapshots { saw(rng).node_instances.get(&node_id).cloned() } else { Some(fabricated()) };
|
||||
snapshot.map_or(RegistryDelta::Other(Value::None), |snapshot| RegistryDelta::RemoveNode { id: node_id, snapshot })
|
||||
}
|
||||
5 | 6 => RegistryDelta::ChangeNodeInput {
|
||||
id: node_id,
|
||||
index: rng.below(3) as u32,
|
||||
new_input: input(rng),
|
||||
},
|
||||
7 => RegistryDelta::SetNodeInputs {
|
||||
id: node_id,
|
||||
inputs: (0..1 + rng.below(3))
|
||||
.map(|_| {
|
||||
let mut slot = InputSlot {
|
||||
input: input(rng),
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
attributes: Default::default(),
|
||||
};
|
||||
// Half the time a slot carries attributes over with earlier stamps, as an implementation swap does.
|
||||
if rng.below(2) == 0 {
|
||||
let floor = TimeStamp {
|
||||
counter: 1 + rng.below(at.counter),
|
||||
peer: PeerId(1 + rng.below(3)),
|
||||
};
|
||||
let label = TimeStamp {
|
||||
counter: floor.counter + rng.below(at.counter - floor.counter + 1),
|
||||
..floor
|
||||
};
|
||||
slot.attributes
|
||||
.insert("label".into(), crate::AttributeValue::new(Value::from(serde_json::json!(rng.below(100))), label));
|
||||
slot.attributes.set_floor(floor);
|
||||
}
|
||||
slot
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
8 => {
|
||||
let key = ["name", "lock"][rng.below(2) as usize];
|
||||
RegistryDelta::ChangeNodeAttribute {
|
||||
id: node_id,
|
||||
delta: attribute(rng, key),
|
||||
}
|
||||
}
|
||||
9 => RegistryDelta::SetNodeImplementation {
|
||||
id: node_id,
|
||||
implementation: match rng.below(2) {
|
||||
0 => Implementation::Network(network_id),
|
||||
_ => Implementation::ProtoNode(ResourceId::from(rng.below(3))),
|
||||
},
|
||||
},
|
||||
10 => RegistryDelta::SetNetworkExport {
|
||||
id: network_id,
|
||||
index: rng.below(2) as u32,
|
||||
export: match rng.below(2) {
|
||||
0 => None,
|
||||
_ => Some(input(rng)),
|
||||
},
|
||||
},
|
||||
11 => RegistryDelta::AddResource {
|
||||
id: resource_id,
|
||||
entry: ResourceEntry::default(),
|
||||
},
|
||||
12 => {
|
||||
let snapshot = if real_snapshots {
|
||||
saw(rng).resources.get(&resource_id).cloned()
|
||||
} else {
|
||||
Some(ResourceEntry::default())
|
||||
};
|
||||
snapshot.map_or(RegistryDelta::Other(Value::None), |snapshot| RegistryDelta::RemoveResource { id: resource_id, snapshot })
|
||||
}
|
||||
13 => RegistryDelta::SetResourceHash {
|
||||
id: resource_id,
|
||||
hash: Some(ResourceHash::from([rng.below(2) as u8; 32])),
|
||||
},
|
||||
14 => RegistryDelta::AddSource {
|
||||
id: resource_id,
|
||||
key: key(rng),
|
||||
source: Value::from(serde_json::json!(rng.below(100))),
|
||||
},
|
||||
15 => RegistryDelta::ChangeNodeInputAttribute {
|
||||
id: node_id,
|
||||
index: rng.below(3) as u32,
|
||||
delta: attribute(rng, "label"),
|
||||
},
|
||||
16 => RegistryDelta::ChangeNetworkAttribute {
|
||||
id: network_id,
|
||||
delta: attribute(rng, "name"),
|
||||
},
|
||||
17 => RegistryDelta::RemoveSource { id: resource_id, key: key(rng) },
|
||||
18 => RegistryDelta::RegisterPeer {
|
||||
peer: PeerId(1 + rng.below(2)),
|
||||
user: UserId(rng.below(3)),
|
||||
},
|
||||
19 => RegistryDelta::ChangeDocumentAttribute { delta: attribute(rng, "doc") },
|
||||
_ => {
|
||||
// A resource added whole, with content.
|
||||
let mut entry = ResourceEntry {
|
||||
hash: Some(ResourceHash::from([rng.below(2) as u8; 32])),
|
||||
..Default::default()
|
||||
};
|
||||
let source = SourceValue {
|
||||
source: Value::from(serde_json::json!(rng.below(100))),
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
deleted: false,
|
||||
};
|
||||
entry.set_source(key(rng), source);
|
||||
RegistryDelta::AddResource { id: resource_id, entry }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for real_snapshots in [false, true] {
|
||||
for seed in 0..300u64 {
|
||||
let mut rng = Lcg(seed);
|
||||
let mut ops: Vec<(RegistryDelta, TimeStamp)> = Vec::new();
|
||||
for i in 0..8 + rng.below(24) {
|
||||
let at = TimeStamp {
|
||||
counter: 1 + i,
|
||||
peer: PeerId(1 + rng.below(3)),
|
||||
};
|
||||
let op = random_op(&mut rng, at, &ops, real_snapshots);
|
||||
ops.push((op, at));
|
||||
}
|
||||
|
||||
let reference = fold(&ops);
|
||||
for _ in 0..6 {
|
||||
let mut shuffled = ops.clone();
|
||||
for i in (1..shuffled.len()).rev() {
|
||||
shuffled.swap(i, rng.below(i as u64 + 1) as usize);
|
||||
}
|
||||
let order: Vec<u64> = shuffled.iter().map(|(_, at)| at.counter).collect();
|
||||
assert_eq!(fold(&shuffled), reference, "seed {seed}, real snapshots {real_snapshots}: folded differently in the order {order:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An entry stamped at its map's floor was written with it, so folding a removal's snapshot keeps it.
|
||||
#[test]
|
||||
fn a_removal_snapshot_keeps_the_attributes_the_addition_wrote() {
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
let id = NodeId(4);
|
||||
let mut node = Node::new(ROOT_NETWORK, crate::Implementation::ProtoNode(graphene_resource::ResourceId::from(7)), 1);
|
||||
node.attributes.set("ui::name", Value::from(serde_json::json!("Layer")), TimeStamp::ORIGIN);
|
||||
node.inputs[0].attributes.set("reflection_metadata", Value::from(serde_json::json!("meta")), TimeStamp::ORIGIN);
|
||||
commit_op(&mut document, add_network(ROOT_NETWORK.0));
|
||||
commit_op(&mut document, RegistryDelta::AddNode { id, node });
|
||||
|
||||
// A removal and a newer write, which revives the node from the tombstone.
|
||||
let removal = RegistryDelta::RemoveNode {
|
||||
id,
|
||||
snapshot: document.working_registry.node_instances[&id].clone(),
|
||||
};
|
||||
let removed_at = document.clock.tick();
|
||||
document.apply_op_idempotent(removal.clone(), removed_at).expect("removal");
|
||||
let written_at = document.clock.tick();
|
||||
document.apply_op_idempotent(change_node_attribute(id, "ui::lock", serde_json::json!(true)), written_at).expect("write");
|
||||
|
||||
let revived = &document.working_registry.node_instances[&id];
|
||||
assert_eq!(revived.attributes.get_typed::<String>("ui::name").as_deref(), Some("Layer"));
|
||||
assert_eq!(revived.inputs()[0].attributes.get_typed::<String>("reflection_metadata").as_deref(), Some("meta"));
|
||||
|
||||
// The same removal replayed into the live node is too old to land and changes nothing.
|
||||
let mut replayed = document.clone();
|
||||
replayed.apply_op_idempotent(removal, removed_at).expect("a replayed removal");
|
||||
assert_eq!(replayed.working_registry, document.working_registry);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_replayed_op_changes_nothing() {
|
||||
use crate::{Implementation, NodeInput};
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
let node = Node::new(NetworkId(1), Implementation::Network(NetworkId(1)), 1);
|
||||
for (op, counter) in [
|
||||
(add_network(1), 1),
|
||||
(RegistryDelta::AddNode { id: NodeId(1), node: node.clone() }, 2),
|
||||
(RegistryDelta::AddNode { id: NodeId(2), node: node.clone() }, 3),
|
||||
(RegistryDelta::RemoveNode { id: NodeId(2), snapshot: node }, 4),
|
||||
] {
|
||||
document.apply_op_idempotent(op, ts(counter, 5)).unwrap();
|
||||
}
|
||||
let before = document.working_registry.clone();
|
||||
|
||||
let out_of_bounds = RegistryDelta::ChangeNodeInput {
|
||||
id: NodeId(1),
|
||||
index: 1 << 20,
|
||||
new_input: NodeInput::Node { id: NodeId(2), index: 0 },
|
||||
};
|
||||
assert!(document.apply_op_idempotent(out_of_bounds, ts(5, 5)).is_err());
|
||||
assert_eq!(document.working_registry, before);
|
||||
}
|
||||
|
||||
/// An implementation swap carries a slot's `ui::*` attributes over as the editor held them; a concurrent rename and a
|
||||
/// concurrent first-time attribute on that slot both survive it, whichever lands first.
|
||||
#[test]
|
||||
fn an_implementation_swap_keeps_concurrent_slot_attribute_writes() {
|
||||
use crate::Implementation;
|
||||
use graphene_resource::ResourceId;
|
||||
let slot_attribute = |key: &str, value: &str| RegistryDelta::ChangeNodeInputAttribute {
|
||||
id: NodeId(1),
|
||||
index: 0,
|
||||
delta: crate::AttributeDelta {
|
||||
key: key.into(),
|
||||
value: Some(Value::from(serde_json::json!(value))),
|
||||
},
|
||||
};
|
||||
let mut base = fresh_document(PeerId(1));
|
||||
commit_op(&mut base, add_network(1));
|
||||
let node = Node::new(NetworkId(1), Implementation::ProtoNode(ResourceId::from(7)), 1);
|
||||
commit_op(&mut base, RegistryDelta::AddNode { id: NodeId(1), node });
|
||||
commit_op(&mut base, slot_attribute("ui::name", "a"));
|
||||
|
||||
// The swap as the editor builds it: the new slot with the held slot's `ui::*` attributes and floor carried over.
|
||||
let held = base.working_registry.node_instances[&NodeId(1)].inputs()[0].clone();
|
||||
let mut carried = InputSlot::unset(TimeStamp::ORIGIN);
|
||||
carried.attributes.set_floor(held.attributes.floor());
|
||||
carried.attributes.extend(held.attributes.into_iter().filter(|(key, value)| key.starts_with("ui::") && !value.deleted));
|
||||
let swap = (RegistryDelta::SetNodeInputs { id: NodeId(1), inputs: vec![carried] }, ts(20, 1));
|
||||
let rename = (slot_attribute("ui::name", "b"), ts(10, 2));
|
||||
let describe = (slot_attribute("ui::description", "d"), ts(11, 2));
|
||||
|
||||
for order in [[&swap, &rename, &describe], [&rename, &describe, &swap]] {
|
||||
let mut document = base.clone();
|
||||
for (op, at) in order {
|
||||
document.apply_op_idempotent(op.clone(), *at).expect("apply");
|
||||
}
|
||||
let slot = &document.working_registry.node_instances[&NodeId(1)].inputs()[0];
|
||||
assert_eq!(
|
||||
slot.attributes.get("ui::name").map(|value| value.value.clone()),
|
||||
Some(Value::from(serde_json::json!("b"))),
|
||||
"the rename survives"
|
||||
);
|
||||
assert!(slot.attributes.get("ui::description").is_some_and(|value| !value.deleted), "the first-time attribute survives");
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-adding a removed network with a shorter export list drops the slots past its end, whichever lands first.
|
||||
#[test]
|
||||
fn a_network_re_added_shorter_keeps_only_its_own_exports() {
|
||||
use crate::ExportSlot;
|
||||
let export = |node: u64| ExportSlot {
|
||||
target: Some(crate::NodeInput::Node { id: NodeId(node), index: 0 }),
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
};
|
||||
let network = |exports: Vec<ExportSlot>| Network { exports, ..Default::default() };
|
||||
let added = (
|
||||
RegistryDelta::AddNetwork {
|
||||
id: NetworkId(1),
|
||||
network: network(vec![export(1), export(2)]),
|
||||
},
|
||||
ts(1, 1),
|
||||
);
|
||||
let removed = (
|
||||
RegistryDelta::RemoveNetwork {
|
||||
id: NetworkId(1),
|
||||
snapshot: network(vec![export(1), export(2)]),
|
||||
},
|
||||
ts(2, 1),
|
||||
);
|
||||
let re_added = (
|
||||
RegistryDelta::AddNetwork {
|
||||
id: NetworkId(1),
|
||||
network: network(vec![export(3)]),
|
||||
},
|
||||
ts(3, 2),
|
||||
);
|
||||
for order in [[&added, &removed, &re_added], [&re_added, &removed, &added]] {
|
||||
let mut document = fresh_document(PeerId(9));
|
||||
for (op, at) in order {
|
||||
document.apply_op_idempotent(op.clone(), *at).expect("apply");
|
||||
}
|
||||
let exports = &document.working_registry.networks[&NetworkId(1)].exports;
|
||||
assert_eq!(exports.iter().map(|slot| slot.target.clone()).collect::<Vec<_>>(), vec![export(3).target]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Two registries ordering a removal differently against a write are not order-consistent, though their values agree.
|
||||
#[test]
|
||||
fn order_consistency_covers_removal_stamps() {
|
||||
let with_removal_at = |counter: u64| {
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
let node = Node::new(NetworkId(1), crate::Implementation::ProtoNode(graphene_resource::ResourceId::from(7)), 0);
|
||||
document.apply_op_idempotent(RegistryDelta::AddNode { id: NodeId(2), node: node.clone() }, ts(3, 1)).expect("add");
|
||||
document
|
||||
.apply_op_idempotent(RegistryDelta::RemoveNode { id: NodeId(1), snapshot: node }, ts(counter, 1))
|
||||
.expect("remove");
|
||||
document.working_registry
|
||||
};
|
||||
let (earlier, later) = (with_removal_at(2), with_removal_at(4));
|
||||
assert!(earlier.value_equal(&later));
|
||||
assert!(!earlier.order_consistent(&later));
|
||||
}
|
||||
|
||||
/// An input naming a node whose addition has not arrived renders as a dangling input, as one naming a removed node does,
|
||||
/// rather than failing the conversion: the placeholder knows nothing of the node's network.
|
||||
#[test]
|
||||
fn an_input_naming_a_node_not_yet_added_renders_dangling() {
|
||||
use crate::Implementation;
|
||||
let (nested, empty, owner, inner, unseen) = (NetworkId(5), NetworkId(6), NodeId(1), NodeId(2), NodeId(3));
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
let ops = [
|
||||
add_network(ROOT_NETWORK.0),
|
||||
add_network(nested.0),
|
||||
add_network(empty.0),
|
||||
RegistryDelta::AddNode {
|
||||
id: owner,
|
||||
node: Node::new(ROOT_NETWORK, Implementation::Network(nested), 0),
|
||||
},
|
||||
RegistryDelta::AddNode {
|
||||
id: inner,
|
||||
node: Node::new(nested, Implementation::Network(empty), 1),
|
||||
},
|
||||
RegistryDelta::ChangeNodeInput {
|
||||
id: inner,
|
||||
index: 0,
|
||||
new_input: crate::NodeInput::Node { id: unseen, index: 0 },
|
||||
},
|
||||
];
|
||||
for (counter, op) in (1..).zip(ops) {
|
||||
document.apply_op_idempotent(op, ts(counter, 2)).expect("apply");
|
||||
}
|
||||
assert!(document.working_registry.removed_nodes.get(&unseen).is_some_and(|mark| mark.placeholder));
|
||||
|
||||
document.working_registry.to_runtime_with_metadata(&crate::Declarations::new()).expect("converts with a dangling input");
|
||||
}
|
||||
@@ -650,7 +650,6 @@ fn node_input_f64_round_trips_bit_exact() {
|
||||
/// Conversion must reject this rather than silently collapse them and drop a node.
|
||||
#[test]
|
||||
fn duplicate_runtime_node_id_is_rejected() {
|
||||
use crate::AttributesWrite;
|
||||
use crate::TimeStamp;
|
||||
use crate::to_runtime::ConversionError;
|
||||
|
||||
@@ -717,7 +716,6 @@ fn scope_injections_round_trip() {
|
||||
/// network) must error rather than emit an injection pointing at a nonexistent runtime node.
|
||||
#[test]
|
||||
fn dangling_scope_injection_is_rejected() {
|
||||
use crate::AttributesWrite;
|
||||
use crate::TimeStamp;
|
||||
use crate::to_runtime::ConversionError;
|
||||
|
||||
@@ -757,6 +755,9 @@ fn cyclic_network_reference_is_rejected() {
|
||||
registry.node_instances.insert(
|
||||
crate::NodeId(0),
|
||||
Node {
|
||||
presence: Default::default(),
|
||||
network_timestamp: Default::default(),
|
||||
inputs_timestamp: Default::default(),
|
||||
implementation: Implementation::Network(child_network_id),
|
||||
implementation_timestamp: Default::default(),
|
||||
inputs: Vec::new(),
|
||||
@@ -767,6 +768,9 @@ fn cyclic_network_reference_is_rejected() {
|
||||
registry.node_instances.insert(
|
||||
crate::NodeId(1),
|
||||
Node {
|
||||
presence: Default::default(),
|
||||
network_timestamp: Default::default(),
|
||||
inputs_timestamp: Default::default(),
|
||||
implementation: Implementation::Network(crate::ROOT_NETWORK),
|
||||
implementation_timestamp: Default::default(),
|
||||
inputs: Vec::new(),
|
||||
|
||||
@@ -10,7 +10,7 @@ use rustc_hash::{FxHashMap, FxHashSet};
|
||||
|
||||
use crate::attr::*;
|
||||
use crate::metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry};
|
||||
use crate::{AttributesRead, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId, Value, from_value};
|
||||
use crate::{Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId, Value, from_value};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ConversionError {
|
||||
@@ -51,19 +51,7 @@ impl Registry {
|
||||
let mut node_metadata = Some(Vec::new());
|
||||
let mut network_metadata = Some(Vec::new());
|
||||
|
||||
// Group nodes by their owning network in one pass, so each `convert_network` call (one per
|
||||
// network, including nested ones) takes its node list by lookup instead of rescanning the whole
|
||||
// flat `node_instances` map, which would be quadratic on graphs with many networks.
|
||||
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
|
||||
for (&global_id, node) in &self.node_instances {
|
||||
nodes_by_network.entry(node.network).or_default().push((global_id, node));
|
||||
}
|
||||
|
||||
let context = ConversionContext {
|
||||
registry: self,
|
||||
declarations,
|
||||
nodes_by_network,
|
||||
};
|
||||
let context = ConversionContext::new(self, declarations);
|
||||
|
||||
// Reject cycles up front so the recursive conversion below can assume the network reference
|
||||
// graph is acyclic and never blow the stack on a self-referential `Implementation::Network`.
|
||||
@@ -82,7 +70,7 @@ impl Registry {
|
||||
let mut registry = graphene_resource::ResourceRegistry::new();
|
||||
|
||||
for (id, entry) in &self.resources {
|
||||
for (_, source) in &entry.sources {
|
||||
for (_, source) in entry.live_sources() {
|
||||
let decoded: graphene_resource::DataSource = from_value(&source.source).map_err(|error| ConversionError::DeserializationError(error.to_string()))?;
|
||||
registry.push_source_back(id, decoded);
|
||||
}
|
||||
@@ -104,6 +92,26 @@ struct ConversionContext<'a> {
|
||||
nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &'a Node)>>,
|
||||
}
|
||||
|
||||
impl<'a> ConversionContext<'a> {
|
||||
fn new(registry: &'a Registry, declarations: &'a Declarations) -> Self {
|
||||
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
|
||||
for (&global_id, node) in ®istry.node_instances {
|
||||
nodes_by_network.entry(node.network).or_default().push((global_id, node));
|
||||
}
|
||||
Self {
|
||||
registry,
|
||||
declarations,
|
||||
nodes_by_network,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The id the node had in the runtime it was converted from, kept as an attribute so a conversion back
|
||||
/// lands it under the id the editor's metadata is keyed by.
|
||||
fn runtime_node_id(global_id: NodeId, node: &Node) -> RuntimeNodeId {
|
||||
RuntimeNodeId(node.attributes.get_typed(node::ORIGINAL_NODE_ID).unwrap_or(global_id.0))
|
||||
}
|
||||
|
||||
/// Converts a single network. Recurses through `Implementation::Network` owning nodes.
|
||||
///
|
||||
/// **ID remapping:** Registry uses globally hashed IDs; runtime networks need local IDs. We pull
|
||||
@@ -166,7 +174,7 @@ fn convert_network(
|
||||
node_collector: &mut Option<Vec<NodeMetadataEntry>>,
|
||||
network_collector: &mut Option<Vec<NetworkMetadataEntry>>,
|
||||
) -> Result<NodeNetwork, ConversionError> {
|
||||
let network = context.registry.networks.get(&network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
|
||||
let network = context.registry.network_or_removed(network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
|
||||
|
||||
if let Some(collector) = network_collector.as_mut() {
|
||||
collector.push(extract_network_metadata(context.registry, &network.attributes, metadata_path, network_id));
|
||||
@@ -174,8 +182,8 @@ fn convert_network(
|
||||
|
||||
let mut nodes: FxHashMap<RuntimeNodeId, DocumentNode> = FxHashMap::default();
|
||||
for &(global_id, node) in context.nodes_by_network.get(&network_id).map(Vec::as_slice).unwrap_or_default() {
|
||||
let local_id = node.attributes.get_typed(node::ORIGINAL_NODE_ID).unwrap_or(global_id.0);
|
||||
let runtime_id = RuntimeNodeId(local_id);
|
||||
let runtime_id = runtime_node_id(global_id, node);
|
||||
let local_id = runtime_id.0;
|
||||
|
||||
if let Some(collector) = node_collector.as_mut() {
|
||||
collector.push(extract_ui_metadata(node, global_id, metadata_path, runtime_id));
|
||||
@@ -232,8 +240,7 @@ fn read_scope_injections(registry: &Registry, network_id: NetworkId, attributes:
|
||||
});
|
||||
};
|
||||
|
||||
let local_id = referenced.attributes.get_typed(node::ORIGINAL_NODE_ID).unwrap_or(storage_id.0);
|
||||
Ok((key, (RuntimeNodeId(local_id), ty)))
|
||||
Ok((key, (runtime_node_id(storage_id, referenced), ty)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -271,8 +278,7 @@ fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[R
|
||||
fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes, network_path: &[RuntimeNodeId], network_id: NetworkId) -> NetworkMetadataEntry {
|
||||
let to_runtime_id = |storage_id: NodeId| {
|
||||
let node = registry.node_instances.get(&storage_id).filter(|node| node.network == network_id)?;
|
||||
let local_id = node.attributes.get_typed(node::ORIGINAL_NODE_ID).unwrap_or(storage_id.0);
|
||||
Some(RuntimeNodeId(local_id))
|
||||
Some(runtime_node_id(storage_id, node))
|
||||
};
|
||||
|
||||
let pinned_order = attributes
|
||||
@@ -293,7 +299,7 @@ fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes,
|
||||
/// Reassembles `input_data` by scanning every attribute under `ui::input_data::` and stripping the prefix.
|
||||
fn extract_input_metadata(attributes: &crate::Attributes) -> InputMetadataEntry {
|
||||
let input_data: HashMap<String, Value> = attributes
|
||||
.iter()
|
||||
.live()
|
||||
.filter_map(|(key, value)| key.strip_prefix(node::input::ui::DATA_PREFIX).map(|sub_key| (sub_key.to_owned(), value.value.clone())))
|
||||
.collect();
|
||||
|
||||
@@ -335,20 +341,22 @@ fn convert_node(
|
||||
fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput, input_attributes: &crate::Attributes) -> Result<GraphCraftNodeInput, ConversionError> {
|
||||
Ok(match input {
|
||||
NodeInput::Node { id: node_id, index: output_index } => {
|
||||
let referenced = registry.node_instances.get(node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
|
||||
// A node removed concurrently keeps its id, as the editor holds a dangling input. So does one whose addition has not
|
||||
// arrived yet, though its placeholder knows nothing of its network.
|
||||
let referenced = registry.node_or_removed(*node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
|
||||
let placeholder = registry.removed_nodes.get(node_id).is_some_and(|mark| mark.placeholder);
|
||||
|
||||
// Runtime references are local to one network. A cross-network reference would remap to a
|
||||
// local ID that doesn't exist in the current runtime network, so reject it.
|
||||
if referenced.network != network_id {
|
||||
if !placeholder && referenced.network != network_id {
|
||||
return Err(ConversionError::CrossNetworkReference {
|
||||
network: network_id,
|
||||
referenced: *node_id,
|
||||
});
|
||||
}
|
||||
|
||||
let local_id = referenced.attributes.get_typed(node::ORIGINAL_NODE_ID).unwrap_or(node_id.0);
|
||||
GraphCraftNodeInput::Node {
|
||||
node_id: RuntimeNodeId(local_id),
|
||||
node_id: runtime_node_id(*node_id, referenced),
|
||||
output_index: *output_index as usize,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "graphite-editor-control-protocol"
|
||||
description = "The commands, results, and scenarios that scripts, QA, and agents use to operate the Graphite editor"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
# Workspace dependencies
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
glam = { workspace = true, features = ["serde"] }
|
||||
@@ -0,0 +1,354 @@
|
||||
//! The commands that scripts, QA, and agents send to operate the Graphite editor the way a person does, the results they get back,
|
||||
//! the scenario files that hold a sequence of commands, and the messages that carry them between a client and an editor host.
|
||||
//!
|
||||
//! Each message travels as one line of JSON.
|
||||
|
||||
use glam::{DVec2, UVec2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::num::NonZeroU32;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Increases whenever a change would break a client or host written against an earlier version.
|
||||
pub const PROTOCOL_VERSION: u32 = 1;
|
||||
|
||||
/// Which origin a point is measured from.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Space {
|
||||
/// The page's top left corner.
|
||||
#[default]
|
||||
Page,
|
||||
/// The document viewport's top left corner.
|
||||
Viewport,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MouseButton {
|
||||
#[default]
|
||||
Left,
|
||||
Middle,
|
||||
Right,
|
||||
}
|
||||
|
||||
/// An area of the page, in CSS pixels.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Rectangle {
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
pub width: f64,
|
||||
pub height: f64,
|
||||
}
|
||||
|
||||
/// Frames captured along a drag and laid out in one image, each marked with where the pointer was.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Filmstrip {
|
||||
/// Where the image is written, with a relative path landing in the host's output directory.
|
||||
pub path: PathBuf,
|
||||
/// How many frames to capture, spread evenly along the drag.
|
||||
pub frames: Option<NonZeroU32>,
|
||||
/// Limits each frame to the document viewport (`"viewport"`) or the first element matching a CSS selector.
|
||||
pub region: Option<String>,
|
||||
/// Limits each frame to an exact area of the page, overriding the region.
|
||||
pub clip: Option<Rectangle>,
|
||||
}
|
||||
|
||||
/// One step of operating the editor with the mouse and keyboard, or of observing the result.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase", deny_unknown_fields)]
|
||||
pub enum Command {
|
||||
/// Moves the pointer one small step per rendered frame, as a real pointer does, or in the given number of steps.
|
||||
Move { to: DVec2, space: Option<Space>, steps: Option<NonZeroU32> },
|
||||
|
||||
/// Presses a mouse button.
|
||||
Down { button: Option<MouseButton> },
|
||||
|
||||
/// Releases a mouse button.
|
||||
Up { button: Option<MouseButton> },
|
||||
|
||||
/// Moves the pointer to a point and clicks there, with the keys held from before the first press.
|
||||
Click {
|
||||
at: DVec2,
|
||||
space: Option<Space>,
|
||||
button: Option<MouseButton>,
|
||||
count: Option<NonZeroU32>,
|
||||
keys: Option<Vec<String>>,
|
||||
},
|
||||
|
||||
/// Drags between two points with the keys held from before the press.
|
||||
/// With `release` set to false, the button and keys stay held once the drag succeeds.
|
||||
Drag {
|
||||
from: DVec2,
|
||||
to: DVec2,
|
||||
space: Option<Space>,
|
||||
button: Option<MouseButton>,
|
||||
keys: Option<Vec<String>>,
|
||||
steps: Option<NonZeroU32>,
|
||||
release: Option<bool>,
|
||||
filmstrip: Option<Filmstrip>,
|
||||
},
|
||||
|
||||
/// Holds a key, named as in `KeyboardEvent.key` or `KeyboardEvent.code`, such as `Shift` or `KeyP`.
|
||||
KeyDown { key: String },
|
||||
|
||||
/// Releases a held key.
|
||||
KeyUp { key: String },
|
||||
|
||||
/// Taps a key, or a combination such as `Control+KeyZ`, where a final `+` is the plus key itself.
|
||||
Press { key: String },
|
||||
|
||||
/// Types text into the focused field.
|
||||
Type { text: String },
|
||||
|
||||
/// Turns the mouse wheel, in notches of up to 100 pixels, optionally after moving the pointer to a point.
|
||||
Scroll { delta: DVec2, at: Option<DVec2>, space: Option<Space> },
|
||||
|
||||
/// Pauses for a number of milliseconds.
|
||||
Wait { milliseconds: u64 },
|
||||
|
||||
/// Waits until the editor stops redrawing, giving up after the timeout in milliseconds.
|
||||
WaitIdle { timeout: Option<u64> },
|
||||
|
||||
/// Captures the page, or part of it, optionally marking the pointer with a crosshair.
|
||||
Screenshot {
|
||||
path: PathBuf,
|
||||
cursor: Option<bool>,
|
||||
region: Option<String>,
|
||||
clip: Option<Rectangle>,
|
||||
},
|
||||
|
||||
/// Finds elements by a `data-*` attribute name, the visible text they contain, or both.
|
||||
Locate { data: Option<String>, text: Option<String> },
|
||||
|
||||
/// Fails unless the page shows the expected elements, found as `locate` finds them and narrowed to those with a field holding `value`.
|
||||
/// With only a `value`, it looks among every field. It expects exactly `count` elements, or at least one without a count.
|
||||
Expect {
|
||||
data: Option<String>,
|
||||
text: Option<String>,
|
||||
value: Option<String>,
|
||||
count: Option<u32>,
|
||||
},
|
||||
|
||||
/// Changes the size of the page, in CSS pixels.
|
||||
Resize { size: UVec2 },
|
||||
|
||||
/// Reports the state of the session.
|
||||
Status {},
|
||||
}
|
||||
|
||||
impl Command {
|
||||
/// The name the command is given by its `type` field.
|
||||
pub fn name(&self) -> &'static str {
|
||||
match self {
|
||||
Command::Move { .. } => "move",
|
||||
Command::Down { .. } => "down",
|
||||
Command::Up { .. } => "up",
|
||||
Command::Click { .. } => "click",
|
||||
Command::Drag { .. } => "drag",
|
||||
Command::KeyDown { .. } => "keyDown",
|
||||
Command::KeyUp { .. } => "keyUp",
|
||||
Command::Press { .. } => "press",
|
||||
Command::Type { .. } => "type",
|
||||
Command::Scroll { .. } => "scroll",
|
||||
Command::Wait { .. } => "wait",
|
||||
Command::WaitIdle { .. } => "waitIdle",
|
||||
Command::Screenshot { .. } => "screenshot",
|
||||
Command::Locate { .. } => "locate",
|
||||
Command::Expect { .. } => "expect",
|
||||
Command::Resize { .. } => "resize",
|
||||
Command::Status {} => "status",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An element found by a `locate` command.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Located {
|
||||
#[serde(rename = "box")]
|
||||
pub bounds: Rectangle,
|
||||
pub center: DVec2,
|
||||
/// The start of the element's text, with its whitespace collapsed.
|
||||
pub text: String,
|
||||
/// What the element holds if it is a field, or else what the first field inside it holds.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub value: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SessionStatus {
|
||||
pub url: String,
|
||||
pub size: UVec2,
|
||||
pub pointer: DVec2,
|
||||
/// Where the document viewport is on the page, if one is open.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub viewport: Option<Rectangle>,
|
||||
pub held_keys: Vec<String>,
|
||||
pub held_buttons: Vec<MouseButton>,
|
||||
pub crashed: bool,
|
||||
}
|
||||
|
||||
/// What came of one command.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CommandResult {
|
||||
/// The `type` of the command this reports on.
|
||||
#[serde(rename = "type")]
|
||||
pub command: String,
|
||||
pub ok: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub error: Option<String>,
|
||||
/// Where a screenshot or filmstrip was written.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub path: Option<PathBuf>,
|
||||
/// The pointer's position on the page in each frame of a filmstrip, in the order the frames are laid out.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub frames: Option<Vec<DVec2>>,
|
||||
/// Whether the editor stopped redrawing before the timeout.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub stable: Option<bool>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub located: Option<Vec<Located>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub status: Option<SessionStatus>,
|
||||
/// The errors the page logged since the previous command, or for the first, since it loaded.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub console_errors: Vec<String>,
|
||||
}
|
||||
|
||||
impl CommandResult {
|
||||
pub fn succeeded(command: &Command) -> Self {
|
||||
Self {
|
||||
command: command.name().to_string(),
|
||||
ok: true,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn failed(command: &Command, error: String) -> Self {
|
||||
Self {
|
||||
command: command.name().to_string(),
|
||||
ok: false,
|
||||
error: Some(error),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the steps of a scenario file, which holds one command per line written as JSON, leaving out blank lines and `//` comments.
|
||||
pub fn parse_scenario(text: &str) -> Result<Vec<Command>, String> {
|
||||
text.lines()
|
||||
.enumerate()
|
||||
.filter(|(_, line)| {
|
||||
let line = line.trim();
|
||||
!line.is_empty() && !line.starts_with("//")
|
||||
})
|
||||
.map(|(index, line)| serde_json::from_str(line).map_err(|error| format!("Line {}: {error}", index + 1)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A message from a client to an editor host.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum ClientMessage {
|
||||
/// Attaches to the session, which the host refuses unless the protocol version matches and the token is the host's own.
|
||||
Attach { version: u32, token: String },
|
||||
|
||||
/// Performs commands in order, stopping at the first that fails, since the later ones were written assuming it succeeded.
|
||||
/// With `fail_on_console_errors`, a command also fails if the page has logged an error since the previous one.
|
||||
Perform {
|
||||
id: u64,
|
||||
commands: Vec<Command>,
|
||||
#[serde(default)]
|
||||
fail_on_console_errors: bool,
|
||||
},
|
||||
|
||||
/// Ends the session and closes the editor.
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
/// A message from an editor host to a client.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum HostMessage {
|
||||
/// Accepts a connection, naming the host's process so a client can tell it apart from one that has replaced it.
|
||||
Attached { version: u32, process_id: u32 },
|
||||
|
||||
/// Turns away a connection, after which the host closes it.
|
||||
Refused { reason: String },
|
||||
|
||||
/// Reports on each command performed, in order.
|
||||
Results { id: u64, results: Vec<CommandResult> },
|
||||
|
||||
/// Confirms a shutdown, after which the connection closes once the host has exited.
|
||||
ShuttingDown,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn scenario_steps_parse() {
|
||||
let steps = parse_scenario(
|
||||
r#"// Draw a rectangle
|
||||
{ "type": "resize", "size": [1600, 1000] }
|
||||
{ "type": "press", "key": "KeyM" }
|
||||
|
||||
// Drag out the rectangle
|
||||
{ "type": "drag", "from": [200, 150], "to": [500, 350], "space": "viewport", "filmstrip": { "path": "drag.png", "frames": 4 } }
|
||||
{ "type": "waitIdle" }
|
||||
{ "type": "screenshot", "path": "rectangle.png", "region": "viewport" }
|
||||
{ "type": "status" }
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(steps.len(), 6);
|
||||
assert_eq!(steps[0], Command::Resize { size: UVec2::new(1600, 1000) });
|
||||
assert!(
|
||||
matches!(&steps[2], Command::Drag { to, space: Some(Space::Viewport), filmstrip: Some(Filmstrip { frames: Some(frames), .. }), .. } if *to == DVec2::new(500., 350.) && frames.get() == 4)
|
||||
);
|
||||
assert_eq!(steps[5], Command::Status {});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scenario_mistakes_name_their_line() {
|
||||
let error = parse_scenario("// A mistake on the third line\n{ \"type\": \"status\" }\n{ \"type\": \"teleport\" }").unwrap_err();
|
||||
assert!(error.starts_with("Line 3:"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_fields_parse() {
|
||||
let steps = parse_scenario("{ \"type\": \"expect\", \"data\": \"layer\", \"count\": 0 }\n{ \"type\": \"expect\", \"value\": \"500.26\" }").unwrap();
|
||||
assert!(matches!(steps[0], Command::Expect { count: Some(0), .. }));
|
||||
assert!(matches!(&steps[1], Command::Expect { value: Some(value), count: None, .. } if value == "500.26"));
|
||||
|
||||
// Clients that predate the option leave it out
|
||||
let perform: ClientMessage = serde_json::from_str(r#"{ "type": "perform", "id": 1, "commands": [] }"#).unwrap();
|
||||
assert!(matches!(perform, ClientMessage::Perform { fail_on_console_errors: false, .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mistakes_are_refused() {
|
||||
// A misspelled field
|
||||
assert!(serde_json::from_str::<Command>(r#"{ "type": "move", "to": [1, 2], "stpes": 3 }"#).is_err());
|
||||
// A count that must be a positive integer
|
||||
assert!(serde_json::from_str::<Command>(r#"{ "type": "click", "at": [1, 2], "count": 0 }"#).is_err());
|
||||
// An unknown command
|
||||
assert!(serde_json::from_str::<Command>(r#"{ "type": "teleport", "to": [1, 2] }"#).is_err());
|
||||
// A field on a command that takes none
|
||||
assert!(serde_json::from_str::<Command>(r#"{ "type": "status", "milliseconds": 5 }"#).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_match_the_type_field() {
|
||||
let commands = [Command::KeyDown { key: "Shift".into() }, Command::WaitIdle { timeout: None }, Command::Status {}];
|
||||
|
||||
for command in commands {
|
||||
let json = serde_json::to_value(&command).unwrap();
|
||||
assert_eq!(json["type"], command.name());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,10 @@ pub const VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR: f64 = 0.95;
|
||||
|
||||
pub const DRAG_BEYOND_VIEWPORT_MAX_OVEREXTENSION_PIXELS: f64 = 50.;
|
||||
pub const DRAG_BEYOND_VIEWPORT_SPEED_FACTOR: f64 = 20.;
|
||||
/// How long a dragged wire must stay beyond the node graph's edge before auto-panning begins, so passing over to another panel doesn't pan.
|
||||
pub const WIRE_DRAG_AUTO_PAN_DELAY_MILLISECONDS: u64 = 400;
|
||||
/// How long a dragged wire must rest over a node before the node reveals its hidden inputs the wire could connect to.
|
||||
pub const WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS: u64 = 250;
|
||||
|
||||
// SNAPPING POINT
|
||||
pub const SNAP_POINT_TOLERANCE: f64 = 5.;
|
||||
@@ -187,6 +191,8 @@ pub const AUTO_SAVE_TIMEOUT_SECONDS: u64 = 1;
|
||||
|
||||
// INPUT
|
||||
pub const DOUBLE_CLICK_MILLISECONDS: u64 = 500;
|
||||
/// Maximum duration of the whole double-tap gesture, measured from the first tap's key-down to the second tap's key-up.
|
||||
pub const DOUBLE_TAP_MILLISECONDS: u64 = 1000;
|
||||
|
||||
// UI
|
||||
pub const UI_SCALE_DEFAULT: f64 = 1.;
|
||||
|
||||
@@ -2,6 +2,7 @@ use crate::messages::debug::utility_types::MessageLoggingVerbosity;
|
||||
use crate::messages::defer::DeferMessageContext;
|
||||
use crate::messages::dialog::DialogMessageContext;
|
||||
use crate::messages::layout::layout_message_handler::LayoutMessageContext;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::utility_types::PanelType;
|
||||
use crate::messages::preferences::preferences_message_handler::PreferencesMessageContext;
|
||||
use crate::messages::prelude::*;
|
||||
@@ -64,6 +65,9 @@ const SIDE_EFFECT_FREE_MESSAGES: &[MessageDiscriminant] = &[
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
|
||||
NodeGraphMessageDiscriminant::RunDocumentGraph,
|
||||
))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
|
||||
NodeGraphMessageDiscriminant::UpdateLayerPanel,
|
||||
))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::SubmitActiveGraphRender),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::SubmitEyedropperPreviewRender),
|
||||
MessageDiscriminant::Frontend(FrontendMessageDiscriminant::UpdateUIScale),
|
||||
@@ -258,6 +262,7 @@ impl Dispatcher {
|
||||
ipp: &self.message_handlers.input_preprocessor_message_handler,
|
||||
preferences: &self.message_handlers.preferences_message_handler,
|
||||
current_tool: &self.message_handlers.tool_message_handler.tool_state.tool_data.active_tool_type,
|
||||
tool_edit_target: &self.message_handlers.tool_message_handler.edit_target,
|
||||
reset_node_definitions_on_open: self.message_handlers.portfolio_message_handler.reset_node_definitions_on_open,
|
||||
timing_information: self.message_handlers.animation_message_handler.timing_information(),
|
||||
animation: &self.message_handlers.animation_message_handler,
|
||||
@@ -284,26 +289,45 @@ impl Dispatcher {
|
||||
.active_document_id
|
||||
.and_then(|document_id| self.message_handlers.portfolio_message_handler.documents.get_mut(&document_id))
|
||||
{
|
||||
let selected_nodes = document.network_interface.selected_nodes();
|
||||
let metadata = &document.network_interface.document_network_metadata().persistent_metadata;
|
||||
let selected_nodes = document.network_interface.selected_nodes_in_nested_network(document.selection_network_path()).unwrap_or_default();
|
||||
let network_interface = &document.network_interface;
|
||||
let layer_metadata = document.metadata();
|
||||
let metadata = &network_interface.document_network_metadata().persistent_metadata;
|
||||
|
||||
// Layers only exist in the document network, so a selection inside a subgraph has none
|
||||
let in_document_network = document.selection_network_path().is_empty();
|
||||
|
||||
menu_bar_message_handler.has_active_document = true;
|
||||
menu_bar_message_handler.canvas_tilted = document.document_ptz.tilt() != 0.;
|
||||
menu_bar_message_handler.canvas_flipped = document.document_ptz.flip;
|
||||
menu_bar_message_handler.rulers_visible = document.rulers_visible;
|
||||
menu_bar_message_handler.node_graph_open = document.is_graph_overlay_open();
|
||||
menu_bar_message_handler.has_artboards = LayerNodeIdentifier::ROOT_PARENT
|
||||
.children(layer_metadata)
|
||||
.any(|layer| network_interface.is_artboard(&layer.to_node(), &[]));
|
||||
menu_bar_message_handler.has_selected_nodes = selected_nodes.selected_nodes().next().is_some();
|
||||
menu_bar_message_handler.has_selected_layers = selected_nodes.selected_visible_layers(&document.network_interface).next().is_some();
|
||||
menu_bar_message_handler.has_selected_layers = in_document_network && selected_nodes.selected_layers(layer_metadata).next().is_some();
|
||||
menu_bar_message_handler.has_selected_visible_layers = in_document_network && selected_nodes.selected_visible_layers(network_interface).next().is_some();
|
||||
menu_bar_message_handler.has_selected_visible_and_unlocked_layers =
|
||||
in_document_network && selected_nodes.selected_visible_and_unlocked_layers(network_interface).next().is_some();
|
||||
menu_bar_message_handler.has_selected_groups = in_document_network
|
||||
&& selected_nodes
|
||||
.selected_layers(layer_metadata)
|
||||
.any(|layer| layer.has_children(layer_metadata) && !network_interface.is_artboard(&layer.to_node(), &[]));
|
||||
menu_bar_message_handler.has_selection_history = (!metadata.selection_undo_history.is_empty(), !metadata.selection_redo_history.is_empty());
|
||||
menu_bar_message_handler.make_path_editable_is_allowed = make_path_editable_is_allowed(&mut document.network_interface).is_some();
|
||||
menu_bar_message_handler.make_path_editable_is_allowed = in_document_network && make_path_editable_is_allowed(&mut document.network_interface).is_some();
|
||||
} else {
|
||||
menu_bar_message_handler.has_active_document = false;
|
||||
menu_bar_message_handler.canvas_tilted = false;
|
||||
menu_bar_message_handler.canvas_flipped = false;
|
||||
menu_bar_message_handler.rulers_visible = false;
|
||||
menu_bar_message_handler.node_graph_open = false;
|
||||
menu_bar_message_handler.has_artboards = false;
|
||||
menu_bar_message_handler.has_selected_nodes = false;
|
||||
menu_bar_message_handler.has_selected_layers = false;
|
||||
menu_bar_message_handler.has_selected_visible_layers = false;
|
||||
menu_bar_message_handler.has_selected_visible_and_unlocked_layers = false;
|
||||
menu_bar_message_handler.has_selected_groups = false;
|
||||
menu_bar_message_handler.has_selection_history = (false, false);
|
||||
menu_bar_message_handler.make_path_editable_is_allowed = false;
|
||||
}
|
||||
@@ -490,7 +514,7 @@ mod test {
|
||||
});
|
||||
|
||||
// Check if the graph renders
|
||||
if let Err(e) = editor.eval_graph().await {
|
||||
if let Err(e) = editor.eval_graph_until_finished().await {
|
||||
print_problem_to_terminal_on_failure(&format!("Failed to evaluate the graph for document '{document_name}':\n{e}"));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::consts::DEFAULT_STROKE_WIDTH;
|
||||
use crate::messages::clipboard::utility_types::{ClipboardContent, ClipboardContentRaw, ClipboardItem, ClipboardLayer, ClipboardResource, ResourceData};
|
||||
use crate::messages::portfolio::document::SelectionParts;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
@@ -79,23 +80,18 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
}
|
||||
|
||||
ClipboardMessage::CopyLayers => {
|
||||
if current_tool == &ToolType::Path {
|
||||
let Some(active_document) = portfolio.active_document() else { return };
|
||||
|
||||
// The Path tool copies the points it's editing in the viewport
|
||||
if current_tool == &ToolType::Path && !active_document.graph_view_overlay_open() {
|
||||
responses.add(PathToolMessage::Copy);
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(active_document) = portfolio.active_document_id.and_then(|id| portfolio.documents.get_mut(&id)) else {
|
||||
return;
|
||||
};
|
||||
let SelectionParts { layers, chain_nodes, other_nodes } = active_document.partition_selection();
|
||||
let mut items = Vec::new();
|
||||
|
||||
if active_document.graph_view_overlay_open() {
|
||||
responses.add(NodeGraphMessage::Copy);
|
||||
return;
|
||||
}
|
||||
|
||||
let mut buffer = Vec::new();
|
||||
|
||||
let mut ordered_last_elements = active_document.network_interface.shallowest_unique_layers(&[]).collect::<Vec<_>>();
|
||||
let mut ordered_last_elements = layers;
|
||||
ordered_last_elements.sort_by_key(|layer| {
|
||||
let Some(parent) = layer.parent(active_document.metadata()) else { return usize::MAX };
|
||||
DocumentMessageHandler::get_calculated_insert_index(active_document.metadata(), &SelectedNodes(vec![layer.to_node()]), parent)
|
||||
@@ -123,38 +119,69 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
.collect::<Vec<_>>();
|
||||
tree_path.reverse();
|
||||
|
||||
buffer.push(ClipboardLayer {
|
||||
items.push(ClipboardItem::Layer(ClipboardLayer {
|
||||
nodes: active_document.network_interface.copy_nodes(©_ids, &[]).collect(),
|
||||
visible: active_document.network_interface.selected_nodes().layer_visible(layer, &active_document.network_interface),
|
||||
locked: active_document.network_interface.selected_nodes().layer_locked(layer, &active_document.network_interface),
|
||||
collapsed: active_document.collapsed.0.contains(&tree_path),
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
responses.add(ClipboardMessage::WriteItems {
|
||||
items: buffer.into_iter().map(ClipboardItem::Layer).collect(),
|
||||
});
|
||||
let copies = chain_nodes
|
||||
.iter()
|
||||
.filter_map(|node_id| active_document.network_interface.copy_chain_node(node_id, &[]))
|
||||
.collect::<Vec<_>>();
|
||||
if !copies.is_empty() {
|
||||
items.push(ClipboardItem::ChainNodes(copies));
|
||||
}
|
||||
|
||||
// Other nodes are kept under their own IDs, so a paste can tell when it's over the same nodes
|
||||
if !other_nodes.is_empty() {
|
||||
let copy_ids = active_document.with_layer_content(&other_nodes).into_iter().map(|node_id| (node_id, node_id)).collect();
|
||||
let nodes = active_document.network_interface.copy_nodes(©_ids, active_document.selection_network_path()).collect();
|
||||
items.push(ClipboardItem::Nodes(nodes));
|
||||
}
|
||||
|
||||
responses.add(ClipboardMessage::WriteItems { items });
|
||||
}
|
||||
ClipboardMessage::CutLayers => {
|
||||
if current_tool == &ToolType::Path {
|
||||
let Some(active_document) = portfolio.active_document() else { return };
|
||||
|
||||
if current_tool == &ToolType::Path && !active_document.graph_view_overlay_open() {
|
||||
responses.add(PathToolMessage::Cut);
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(active_document) = portfolio.active_document()
|
||||
&& active_document.graph_view_overlay_open()
|
||||
{
|
||||
responses.add(NodeGraphMessage::Cut);
|
||||
let SelectionParts { layers, chain_nodes, other_nodes } = active_document.partition_selection();
|
||||
responses.add(ClipboardMessage::CopyLayers);
|
||||
|
||||
// Layers and other nodes go along with what only they use, while chain nodes go alone so pasting them can wire back to what fed them
|
||||
let deleted_with_children = layers.iter().map(|layer| layer.to_node()).chain(other_nodes).collect::<Vec<_>>();
|
||||
if deleted_with_children.is_empty() && chain_nodes.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
responses.add(ClipboardMessage::CopyLayers);
|
||||
responses.add(DocumentMessage::DeleteSelectedLayers);
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
if !deleted_with_children.is_empty() {
|
||||
responses.add(NodeGraphMessage::DeleteNodes {
|
||||
node_ids: deleted_with_children,
|
||||
delete_children: true,
|
||||
});
|
||||
}
|
||||
if !chain_nodes.is_empty() {
|
||||
responses.add(NodeGraphMessage::DeleteNodes {
|
||||
node_ids: chain_nodes,
|
||||
delete_children: false,
|
||||
});
|
||||
}
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SelectedNodesUpdated);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
ClipboardMessage::WriteItems { items } => {
|
||||
let has_content = items.iter().any(|item| match item {
|
||||
ClipboardItem::Layer(entry) => !entry.nodes.is_empty(),
|
||||
ClipboardItem::Nodes(nodes) => !nodes.is_empty(),
|
||||
ClipboardItem::ChainNodes(copies) => !copies.is_empty(),
|
||||
ClipboardItem::Vector(vector) => !vector.is_empty(),
|
||||
ClipboardItem::Resource(_) => true,
|
||||
});
|
||||
@@ -167,6 +194,7 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
match item {
|
||||
ClipboardItem::Layer(entry) => entry.nodes.iter().for_each(|(_, template)| network_interface::collect_template_resources(template, &mut resource_ids)),
|
||||
ClipboardItem::Nodes(nodes) => nodes.iter().for_each(|(_, template)| network_interface::collect_template_resources(template, &mut resource_ids)),
|
||||
ClipboardItem::ChainNodes(copies) => copies.iter().for_each(|copy| network_interface::collect_template_resources(©.template, &mut resource_ids)),
|
||||
ClipboardItem::Vector(_) | ClipboardItem::Resource(_) => {}
|
||||
}
|
||||
}
|
||||
@@ -227,6 +255,7 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
|
||||
let mut layers = Vec::new();
|
||||
let mut node_groups = Vec::new();
|
||||
let mut chain_node_groups = Vec::new();
|
||||
let mut vectors = Vec::new();
|
||||
let mut resources = Vec::new();
|
||||
for item in items {
|
||||
@@ -244,6 +273,12 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
}
|
||||
node_groups.push(nodes);
|
||||
}
|
||||
ClipboardItem::ChainNodes(mut copies) => {
|
||||
for copy in &mut copies {
|
||||
copy.template.normalize_stored_types();
|
||||
}
|
||||
chain_node_groups.push(copies);
|
||||
}
|
||||
ClipboardItem::Vector(vector) => vectors.push(vector),
|
||||
ClipboardItem::Resource(resource) => resources.push(resource),
|
||||
}
|
||||
@@ -279,7 +314,10 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
responses.add(ClipboardMessage::PasteLayers { entries: layers });
|
||||
}
|
||||
for nodes in node_groups {
|
||||
responses.add(NodeGraphMessage::InsertNodes { nodes });
|
||||
responses.add(DocumentMessage::PasteNodes { nodes });
|
||||
}
|
||||
for copies in chain_node_groups {
|
||||
responses.add(DocumentMessage::PasteChainNodes { copies });
|
||||
}
|
||||
for paths in vectors {
|
||||
responses.add(ClipboardMessage::PasteVectors { paths });
|
||||
@@ -302,7 +340,6 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
.collect::<Vec<_>>();
|
||||
parent_tree_path.reverse();
|
||||
|
||||
let mut all_new_ids = Vec::new();
|
||||
let mut layers = Vec::new();
|
||||
|
||||
let mut added_nodes = false;
|
||||
@@ -321,8 +358,6 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
added_nodes = true;
|
||||
}
|
||||
|
||||
all_new_ids.extend(new_ids.values().copied());
|
||||
|
||||
responses.add(NodeGraphMessage::AddNodes { nodes: entry.nodes, new_ids });
|
||||
responses.add(NodeGraphMessage::MoveLayerToStack { layer, parent, insert_index: 0 });
|
||||
|
||||
@@ -351,22 +386,24 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: all_new_ids });
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet {
|
||||
nodes: layers.iter().map(|layer| layer.to_node()).collect(),
|
||||
});
|
||||
responses.add(DeferMessage::AfterGraphRun {
|
||||
messages: vec![PortfolioMessage::CenterLayers { layers }.into()],
|
||||
});
|
||||
}
|
||||
}
|
||||
ClipboardMessage::PasteVectors { paths } => {
|
||||
// If using Path tool then send the operation to Path tool
|
||||
// The Path tool pastes points into the path it's editing in the viewport
|
||||
// TODO: Consider if this is actually the correct place to put this logic
|
||||
// TODO: Consider making paste in general go through the current tool, so that the tool can decide what to do
|
||||
if *current_tool == ToolType::Path {
|
||||
if *current_tool == ToolType::Path && portfolio.active_document().is_some_and(|document| !document.graph_view_overlay_open()) {
|
||||
responses.add(PathToolMessage::Paste { paths });
|
||||
return;
|
||||
}
|
||||
|
||||
// If not using Path tool, create new layers and add paths into those
|
||||
// Otherwise, create new layers and add paths into those
|
||||
if let Some(document) = portfolio.active_document() {
|
||||
let mut layers = Vec::new();
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{ChainNodeCopy, NodeTemplate};
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64;
|
||||
use glam::DAffine2;
|
||||
@@ -27,6 +27,8 @@ pub type ClipboardVectorEntry = (LayerNodeIdentifier, Vector, DAffine2);
|
||||
pub enum ClipboardItem {
|
||||
Layer(ClipboardLayer),
|
||||
Nodes(Vec<(NodeId, NodeTemplate)>),
|
||||
/// Nodes copied from layers' chains, ordered by their layer's place in the Layers panel, then from the layer outward.
|
||||
ChainNodes(Vec<ChainNodeCopy>),
|
||||
Vector(Vec<ClipboardVectorEntry>),
|
||||
Resource(ClipboardResource),
|
||||
}
|
||||
|
||||
@@ -107,7 +107,11 @@ impl MessageHandler<ColorPickerMessage, ()> for ColorPickerMessageHandler {
|
||||
self.gradient_cyclic = ramp.gradient_cyclic;
|
||||
self.gradient_hue_direction = ramp.gradient_hue_direction;
|
||||
self.gradient_interpolation = ramp.gradient_interpolation;
|
||||
let gradient = Gradient::from(ramp);
|
||||
let mut gradient = Gradient::from(ramp);
|
||||
// An empty gradient renders solid black, so it's edited as black to black, which looks the same but has stops to edit
|
||||
if gradient.is_empty() {
|
||||
gradient = Gradient::from(vec![Color::BLACK, Color::BLACK]);
|
||||
}
|
||||
let first_color = gradient.color(0).unwrap_or(Color::BLACK);
|
||||
self.gradient = Some(gradient);
|
||||
self.adopt_color(first_color);
|
||||
|
||||
+2
-18
@@ -1,6 +1,6 @@
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use glam::UVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
@@ -26,23 +26,7 @@ impl MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHa
|
||||
|
||||
if self.infinite {
|
||||
// Infinite canvas: add a locked white background layer
|
||||
let node_id = NodeId::new();
|
||||
responses.add(GraphOperationMessage::NewColorFillLayer {
|
||||
node_id,
|
||||
color: Color::WHITE,
|
||||
parent: LayerNodeIdentifier::ROOT_PARENT,
|
||||
insert_index: 0,
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetDisplayNameImpl {
|
||||
node_id,
|
||||
network_path: Vec::new(),
|
||||
alias: "Background".to_string(),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetLocked {
|
||||
node_id,
|
||||
network_path: Vec::new(),
|
||||
locked: true,
|
||||
});
|
||||
graph_modification_utils::new_background_layer(0, responses);
|
||||
} else if self.dimensions.x > 0 && self.dimensions.y > 0 {
|
||||
// Finite canvas: create an artboard with the specified dimensions
|
||||
responses.add(GraphOperationMessage::NewArtboard {
|
||||
|
||||
@@ -3,6 +3,7 @@ use super::utility_types::{MouseCursorIcon, PersistedState};
|
||||
use crate::messages::app_window::app_window_message_handler::AppWindowPlatform;
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage, FileDialogOptions, FileFilter, FileType, RasterizedImage};
|
||||
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
|
||||
use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{
|
||||
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, NodeGraphErrorDiagnostic,
|
||||
@@ -67,6 +68,8 @@ pub enum FrontendMessage {
|
||||
SendUIMetadata {
|
||||
#[serde(rename = "nodeDescriptions")]
|
||||
node_descriptions: Vec<(String, String)>,
|
||||
#[serde(rename = "nodeIcons")]
|
||||
node_icons: Vec<(String, IconName)>,
|
||||
#[serde(rename = "nodeTypes")]
|
||||
node_types: Vec<FrontendNodeType>,
|
||||
},
|
||||
@@ -207,6 +210,23 @@ pub enum FrontendMessage {
|
||||
layout_target: LayoutTarget,
|
||||
diff: Vec<WidgetDiff>, // TODO: Align this with what's generated
|
||||
},
|
||||
/// The tokens of what a math expression widget holds, for it to color and typeset once they arrive, and the names offered to
|
||||
/// finish the one at the caret, where they were asked for.
|
||||
UpdateMathExpressionAnalysis {
|
||||
#[serde(rename = "widgetId")]
|
||||
widget_id: WidgetId,
|
||||
source: String,
|
||||
tokens: Vec<MathExpressionToken>,
|
||||
tooltips: Vec<MathExpressionTooltip>,
|
||||
completions: Option<MathExpressionCompletions>,
|
||||
},
|
||||
/// The value of math typed in a math expression widget's number popover, written as a number, or `None` where it isn't a finite real number.
|
||||
UpdateMathExpressionEvaluation {
|
||||
#[serde(rename = "widgetId")]
|
||||
widget_id: WidgetId,
|
||||
source: String,
|
||||
result: Option<String>,
|
||||
},
|
||||
UpdateImportReorderIndex {
|
||||
#[serde(rename = "importIndex")]
|
||||
index: Option<usize>,
|
||||
|
||||
@@ -16,6 +16,8 @@ pub enum InputMapperMessage {
|
||||
KeyUpNoRepeat(Key),
|
||||
#[child]
|
||||
DoubleClick(MouseButton),
|
||||
#[child]
|
||||
DoubleTap(Key),
|
||||
|
||||
// Messages
|
||||
PointerMove,
|
||||
|
||||
@@ -40,6 +40,7 @@ impl InputMapperMessageHandler {
|
||||
.chain(self.mapping.key_up_no_repeat.iter())
|
||||
.chain(self.mapping.key_down_no_repeat.iter())
|
||||
.chain(self.mapping.double_click.iter())
|
||||
.chain(self.mapping.double_tap.iter())
|
||||
.chain(std::iter::once(&self.mapping.wheel_scroll))
|
||||
.chain(std::iter::once(&self.mapping.pointer_move));
|
||||
let all_mapping_entries = all_key_mapping_entries.flat_map(|entry| entry.0.iter());
|
||||
@@ -69,6 +70,7 @@ impl InputMapperMessageHandler {
|
||||
use InputMapperMessage as IMM;
|
||||
match entry.input {
|
||||
IMM::KeyDown(key) | IMM::KeyUp(key) | IMM::KeyDownNoRepeat(key) | IMM::KeyUpNoRepeat(key) => keys.push(key),
|
||||
IMM::DoubleTap(key) => keys.extend([key, key]),
|
||||
_ => (),
|
||||
}
|
||||
|
||||
|
||||
@@ -337,7 +337,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
entry!(KeyDown(Tab); action_dispatch=ToolMessage::ToggleSelectVsPath),
|
||||
//
|
||||
// DocumentMessage
|
||||
entry!(KeyDown(Space); modifiers=[Control], action_dispatch=DocumentMessage::GraphViewOverlayToggle),
|
||||
entry!(DoubleTap(Space); action_dispatch=DocumentMessage::GraphViewOverlayToggle),
|
||||
entry!(KeyDownNoRepeat(Escape); action_dispatch=DocumentMessage::Escape),
|
||||
entry!(KeyDown(Delete); action_dispatch=DocumentMessage::DeleteSelectedLayers),
|
||||
entry!(KeyDown(Backspace); action_dispatch=DocumentMessage::DeleteSelectedLayers),
|
||||
@@ -354,8 +354,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
entry!(KeyDown(KeyA); modifiers=[Alt], action_dispatch=DocumentMessage::DeselectAllLayers),
|
||||
entry!(KeyDown(KeyS); modifiers=[Accel], action_dispatch=DocumentMessage::SaveDocument),
|
||||
entry!(KeyDown(KeyS); modifiers=[Accel, Shift], action_dispatch=DocumentMessage::SaveDocumentAs),
|
||||
entry!(KeyDown(KeyD); modifiers=[Accel], canonical, action_dispatch=DocumentMessage::DuplicateSelectedLayers),
|
||||
entry!(KeyDown(KeyJ); modifiers=[Accel], action_dispatch=DocumentMessage::DuplicateSelectedLayers),
|
||||
entry!(KeyDown(KeyD); modifiers=[Accel], action_dispatch=DocumentMessage::DuplicateSelectedLayers),
|
||||
entry!(KeyDown(KeyB); modifiers=[Accel, Alt], action_dispatch=DocumentMessage::BlendSelectedLayers),
|
||||
entry!(KeyDown(KeyM); modifiers=[Accel, Alt], action_dispatch=DocumentMessage::MorphSelectedLayers), // Might get eaten by the GeForce Experience overlay for some Windows users
|
||||
entry!(KeyDown(KeyG); modifiers=[Accel], action_dispatch=DocumentMessage::GroupSelectedLayers { group_folder_type: GroupFolderType::Layer }),
|
||||
@@ -416,23 +415,32 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
// NavigationMessage
|
||||
entry!(KeyDown(MouseMiddle); modifiers=[Alt], action_dispatch=NavigationMessage::BeginCanvasTilt { was_dispatched_from_menu: false }),
|
||||
entry!(KeyDown(MouseLeft); modifiers=[Alt, Space], action_dispatch=NavigationMessage::BeginCanvasTilt { was_dispatched_from_menu: false }),
|
||||
entry!(KeyDown(MouseMiddle); modifiers=[Control], action_dispatch=NavigationMessage::BeginCanvasZoom),
|
||||
entry!(KeyDown(MouseLeft); modifiers=[Control, Space], action_dispatch=NavigationMessage::BeginCanvasZoom),
|
||||
entry!(KeyDown(MouseMiddle); action_dispatch=NavigationMessage::BeginCanvasPan),
|
||||
entry!(KeyDown(MouseLeft); modifiers=[Space], action_dispatch=NavigationMessage::BeginCanvasPan),
|
||||
entry!(KeyDown(MouseMiddle); modifiers=[Control, Alt], action_dispatch=NavigationMessage::BeginCanvasZoom { artwork_behind_graph: true }),
|
||||
entry!(KeyDown(MouseLeft); modifiers=[Control, Alt, Space], action_dispatch=NavigationMessage::BeginCanvasZoom { artwork_behind_graph: true }),
|
||||
entry!(KeyDown(MouseMiddle); modifiers=[Control], action_dispatch=NavigationMessage::BeginCanvasZoom { artwork_behind_graph: false }),
|
||||
entry!(KeyDown(MouseLeft); modifiers=[Control, Space], action_dispatch=NavigationMessage::BeginCanvasZoom { artwork_behind_graph: false }),
|
||||
entry!(KeyDown(MouseMiddle); action_dispatch=NavigationMessage::BeginCanvasPan { artwork_behind_graph: false }),
|
||||
entry!(KeyDown(MouseLeft); modifiers=[Space], action_dispatch=NavigationMessage::BeginCanvasPan { artwork_behind_graph: false }),
|
||||
entry!(KeyDown(NumpadAdd); modifiers=[Accel], action_dispatch=NavigationMessage::CanvasZoomIncrease { center_on_mouse: false }),
|
||||
// `FakeKeyPlus` is a nonfunctional key mapping that must be accompanied by its real `Equal` key counterpart. This is used only to set the canonical key label so it shows "+" instead of "=" in the UI.
|
||||
entry!(KeyDown(FakeKeyPlus); modifiers=[Accel], canonical, action_dispatch=NavigationMessage::CanvasZoomIncrease { center_on_mouse: false }),
|
||||
entry!(KeyDown(Equal); modifiers=[Accel], action_dispatch=NavigationMessage::CanvasZoomIncrease { center_on_mouse: false }),
|
||||
entry!(KeyDown(Minus); modifiers=[Accel], action_dispatch=NavigationMessage::CanvasZoomDecrease { center_on_mouse: false }),
|
||||
entry!(WheelScroll; modifiers=[Control], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel),
|
||||
entry!(WheelScroll; modifiers=[Command], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel),
|
||||
entry!(WheelScroll; modifiers=[Shift], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: true }),
|
||||
entry!(WheelScroll; disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: false }),
|
||||
entry!(WheelScroll; modifiers=[Control, Alt], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel { artwork_behind_graph: true }),
|
||||
entry!(WheelScroll; modifiers=[Command, Alt], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel { artwork_behind_graph: true }),
|
||||
entry!(WheelScroll; modifiers=[Control], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel { artwork_behind_graph: false }),
|
||||
entry!(WheelScroll; modifiers=[Command], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel { artwork_behind_graph: false }),
|
||||
entry!(WheelScroll; modifiers=[Shift, Alt], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: true, artwork_behind_graph: true }),
|
||||
entry!(WheelScroll; modifiers=[Alt], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: false, artwork_behind_graph: true }),
|
||||
entry!(WheelScroll; modifiers=[Shift], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: true, artwork_behind_graph: false }),
|
||||
entry!(WheelScroll; disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: false, artwork_behind_graph: false }),
|
||||
// On Mac, the OS already converts Shift+scroll into horizontal scrolling so we have to reverse the behavior from normal to produce the same outcome
|
||||
entry!(WheelScroll; modifiers=[Control], disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: is_mac }),
|
||||
entry!(WheelScroll; modifiers=[Shift], disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: !is_mac }),
|
||||
entry!(WheelScroll; disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel),
|
||||
entry!(WheelScroll; modifiers=[Control, Alt], disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: is_mac, artwork_behind_graph: true }),
|
||||
entry!(WheelScroll; modifiers=[Shift, Alt], disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: !is_mac, artwork_behind_graph: true }),
|
||||
entry!(WheelScroll; modifiers=[Alt], disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel { artwork_behind_graph: true }),
|
||||
entry!(WheelScroll; modifiers=[Control], disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: is_mac, artwork_behind_graph: false }),
|
||||
entry!(WheelScroll; modifiers=[Shift], disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: !is_mac, artwork_behind_graph: false }),
|
||||
entry!(WheelScroll; disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel { artwork_behind_graph: false }),
|
||||
entry!(KeyDown(PageUp); modifiers=[Shift], action_dispatch=NavigationMessage::CanvasPanByViewportFraction { delta: DVec2::new(1., 0.) }),
|
||||
entry!(KeyDown(PageDown); modifiers=[Shift], action_dispatch=NavigationMessage::CanvasPanByViewportFraction { delta: DVec2::new(-1., 0.) }),
|
||||
entry!(KeyDown(PageUp); action_dispatch=NavigationMessage::CanvasPanByViewportFraction { delta: DVec2::new(0., 1.) }),
|
||||
@@ -463,7 +471,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
entry!(KeyDown(Space); modifiers=[Shift], action_dispatch=AnimationMessage::ToggleLivePreview),
|
||||
entry!(KeyDown(Home); modifiers=[Shift], action_dispatch=AnimationMessage::RestartAnimation),
|
||||
];
|
||||
let (mut key_up, mut key_down, mut key_up_no_repeat, mut key_down_no_repeat, mut double_click, mut wheel_scroll, mut pointer_move, mut pointer_shake) = mappings;
|
||||
let (mut key_up, mut key_down, mut key_up_no_repeat, mut key_down_no_repeat, mut double_click, mut double_tap, mut wheel_scroll, mut pointer_move, mut pointer_shake) = mappings;
|
||||
|
||||
let sort = |list: &mut KeyMappingEntries| list.0.sort_by_key(|entry| std::cmp::Reverse(entry.modifiers.count_ones()));
|
||||
// Sort the sublists of `key_up`, `key_down`, `key_up_no_repeat`, and `key_down_no_repeat`
|
||||
@@ -476,6 +484,10 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
for sublist in &mut double_click {
|
||||
sort(sublist)
|
||||
}
|
||||
// Sort the sublists of `double_tap`
|
||||
for sublist in &mut double_tap {
|
||||
sort(sublist)
|
||||
}
|
||||
// Sort `wheel_scroll`
|
||||
sort(&mut wheel_scroll);
|
||||
// Sort `pointer_move`
|
||||
@@ -489,6 +501,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
key_up_no_repeat,
|
||||
key_down_no_repeat,
|
||||
double_click,
|
||||
double_tap,
|
||||
wheel_scroll,
|
||||
pointer_move,
|
||||
pointer_shake,
|
||||
|
||||
@@ -119,6 +119,7 @@ macro_rules! mapping {
|
||||
let mut key_up_no_repeat = KeyMappingEntries::key_array();
|
||||
let mut key_down_no_repeat = KeyMappingEntries::key_array();
|
||||
let mut double_click = KeyMappingEntries::mouse_buttons_arrays();
|
||||
let mut double_tap = KeyMappingEntries::key_array();
|
||||
let mut wheel_scroll = KeyMappingEntries::new();
|
||||
let mut pointer_move = KeyMappingEntries::new();
|
||||
let mut pointer_shake = KeyMappingEntries::new();
|
||||
@@ -138,6 +139,7 @@ macro_rules! mapping {
|
||||
InputMapperMessage::KeyDownNoRepeat(key) => &mut key_down_no_repeat[key as usize],
|
||||
InputMapperMessage::KeyUpNoRepeat(key) => &mut key_up_no_repeat[key as usize],
|
||||
InputMapperMessage::DoubleClick(key) => &mut double_click[key as usize],
|
||||
InputMapperMessage::DoubleTap(key) => &mut double_tap[key as usize],
|
||||
InputMapperMessage::WheelScroll => &mut wheel_scroll,
|
||||
InputMapperMessage::PointerMove => &mut pointer_move,
|
||||
InputMapperMessage::PointerShake => &mut pointer_shake,
|
||||
@@ -148,7 +150,7 @@ macro_rules! mapping {
|
||||
}
|
||||
)*
|
||||
|
||||
(key_up, key_down, key_up_no_repeat, key_down_no_repeat, double_click, wheel_scroll, pointer_move, pointer_shake)
|
||||
(key_up, key_down, key_up_no_repeat, key_down_no_repeat, double_click, double_tap, wheel_scroll, pointer_move, pointer_shake)
|
||||
}};
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ pub struct Mapping {
|
||||
pub key_up_no_repeat: [KeyMappingEntries; NUMBER_OF_KEYS],
|
||||
pub key_down_no_repeat: [KeyMappingEntries; NUMBER_OF_KEYS],
|
||||
pub double_click: [KeyMappingEntries; NUMBER_OF_MOUSE_BUTTONS],
|
||||
pub double_tap: [KeyMappingEntries; NUMBER_OF_KEYS],
|
||||
pub wheel_scroll: KeyMappingEntries,
|
||||
pub pointer_move: KeyMappingEntries,
|
||||
pub pointer_shake: KeyMappingEntries,
|
||||
@@ -36,6 +37,7 @@ impl Mapping {
|
||||
InputMapperMessage::KeyDownNoRepeat(key) => &self.key_down_no_repeat[*key as usize],
|
||||
InputMapperMessage::KeyUpNoRepeat(key) => &self.key_up_no_repeat[*key as usize],
|
||||
InputMapperMessage::DoubleClick(key) => &self.double_click[*key as usize],
|
||||
InputMapperMessage::DoubleTap(key) => &self.double_tap[*key as usize],
|
||||
InputMapperMessage::WheelScroll => &self.wheel_scroll,
|
||||
InputMapperMessage::PointerMove => &self.pointer_move,
|
||||
InputMapperMessage::PointerShake => &self.pointer_shake,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::application::Editor;
|
||||
use crate::consts::DOUBLE_TAP_MILLISECONDS;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, KeyStates, ModifierKeys};
|
||||
use crate::messages::input_mapper::utility_types::misc::FrameTimeInfo;
|
||||
use crate::messages::input_mapper::utility_types::pointer::{MouseButton, MouseKeys, PointerState};
|
||||
@@ -17,6 +18,18 @@ pub struct InputPreprocessorMessageHandler {
|
||||
pub keyboard: KeyStates,
|
||||
pub mouse: PointerState,
|
||||
pointer_down_time: f64,
|
||||
/// Double-tap detection state, timed as one gesture from the first tap's key-down.
|
||||
double_tap_state: DoubleTapState,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
enum DoubleTapState {
|
||||
#[default]
|
||||
Idle,
|
||||
/// The first press of the key, timed from its key-down.
|
||||
FirstTap { key: Key, start_time: u64 },
|
||||
/// The second press of the key is down, still timed from the first tap's key-down.
|
||||
SecondTap { key: Key, start_time: u64 },
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
@@ -26,6 +39,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
|
||||
match message {
|
||||
InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys } => {
|
||||
self.double_tap_state = DoubleTapState::Idle;
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
@@ -45,7 +59,22 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
InputPreprocessorMessage::KeyDown { key, key_repeat, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
self.keyboard.set(key as usize);
|
||||
|
||||
if !key_repeat {
|
||||
// A press that arrives with a mouse button or modifier held can neither open nor close a double tap,
|
||||
// and it breaks a first tap already waiting
|
||||
let interrupted = !self.mouse.mouse_keys.is_empty() || !modifier_keys.is_empty();
|
||||
|
||||
self.double_tap_state = match (interrupted, self.double_tap_state) {
|
||||
(true, _) => DoubleTapState::Idle,
|
||||
(false, DoubleTapState::FirstTap { key: first_key, start_time }) if first_key == key && self.time.saturating_sub(start_time) < DOUBLE_TAP_MILLISECONDS => {
|
||||
DoubleTapState::SecondTap { key, start_time }
|
||||
}
|
||||
// A late second press starts a new first tap instead of carrying a pair that can't succeed,
|
||||
// so a slow tap followed by a quick double tap still works
|
||||
(false, _) => DoubleTapState::FirstTap { key, start_time: self.time },
|
||||
};
|
||||
|
||||
responses.add(InputMapperMessage::KeyDownNoRepeat(key));
|
||||
}
|
||||
responses.add(InputMapperMessage::KeyDown(key));
|
||||
@@ -56,9 +85,22 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
if !key_repeat {
|
||||
responses.add(InputMapperMessage::KeyUpNoRepeat(key));
|
||||
}
|
||||
if let DoubleTapState::SecondTap { key: tapped_key, start_time } = self.double_tap_state
|
||||
&& tapped_key == key
|
||||
&& self.mouse.mouse_keys.is_empty()
|
||||
{
|
||||
self.double_tap_state = DoubleTapState::Idle;
|
||||
|
||||
// `self.time` only advances on animation-frame ticks, so while the editor is stalled both taps can
|
||||
// share a stale timestamp. That makes a double tap easier to trigger, not harder, so no correction is applied.
|
||||
if self.time.saturating_sub(start_time) < DOUBLE_TAP_MILLISECONDS {
|
||||
responses.add(InputMapperMessage::DoubleTap(key));
|
||||
}
|
||||
}
|
||||
responses.add(InputMapperMessage::KeyUp(key));
|
||||
}
|
||||
InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys } => {
|
||||
self.double_tap_state = DoubleTapState::Idle;
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
@@ -78,6 +120,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
self.translate_mouse_event(pointer_state, false, responses);
|
||||
}
|
||||
InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys } => {
|
||||
self.double_tap_state = DoubleTapState::Idle;
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
@@ -99,6 +142,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
self.frame_time.advance_timestamp(Duration::from_millis(timestamp));
|
||||
}
|
||||
InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys } => {
|
||||
self.double_tap_state = DoubleTapState::Idle;
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
@@ -193,8 +237,10 @@ impl InputPreprocessorMessageHandler {
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::DoubleTapState;
|
||||
use crate::consts::DOUBLE_TAP_MILLISECONDS;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
|
||||
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
|
||||
use crate::messages::input_mapper::utility_types::pointer::{EditorPointerState, MouseKeys};
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[test]
|
||||
@@ -299,4 +345,310 @@ mod test {
|
||||
assert!(responses.contains(&InputMapperMessage::KeyDown(Key::Control).into()));
|
||||
assert!(responses.contains(&InputMapperMessage::KeyDown(Key::Control).into()));
|
||||
}
|
||||
|
||||
fn key_down(input_preprocessor: &mut InputPreprocessorMessageHandler, key: Key, responses: &mut VecDeque<Message>) {
|
||||
process_input(
|
||||
input_preprocessor,
|
||||
InputPreprocessorMessage::KeyDown {
|
||||
key,
|
||||
key_repeat: false,
|
||||
modifier_keys: ModifierKeys::empty(),
|
||||
},
|
||||
responses,
|
||||
);
|
||||
}
|
||||
|
||||
fn key_up(input_preprocessor: &mut InputPreprocessorMessageHandler, key: Key, responses: &mut VecDeque<Message>) {
|
||||
process_input(
|
||||
input_preprocessor,
|
||||
InputPreprocessorMessage::KeyUp {
|
||||
key,
|
||||
key_repeat: false,
|
||||
modifier_keys: ModifierKeys::empty(),
|
||||
},
|
||||
responses,
|
||||
);
|
||||
}
|
||||
|
||||
fn tap(input_preprocessor: &mut InputPreprocessorMessageHandler, key: Key, time: u64, responses: &mut VecDeque<Message>) {
|
||||
input_preprocessor.time = time;
|
||||
key_down(input_preprocessor, key, responses);
|
||||
key_up(input_preprocessor, key, responses);
|
||||
}
|
||||
|
||||
fn process_input(input_preprocessor: &mut InputPreprocessorMessageHandler, message: InputPreprocessorMessage, responses: &mut VecDeque<Message>) {
|
||||
input_preprocessor.process_message(
|
||||
message,
|
||||
responses,
|
||||
InputPreprocessorMessageContext {
|
||||
viewport: &ViewportMessageHandler::default(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_double_tap_within_threshold() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
tap(&mut input_preprocessor, Key::Space, 0, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
input_preprocessor.time = 50;
|
||||
key_down(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
|
||||
assert!(!responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
// The stored time stays at the first tap's key-down, since the whole gesture is timed from there
|
||||
assert_eq!(input_preprocessor.double_tap_state, DoubleTapState::SecondTap { key: Key::Space, start_time: 0 });
|
||||
|
||||
responses.clear();
|
||||
key_up(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
|
||||
assert!(responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
assert_eq!(input_preprocessor.double_tap_state, DoubleTapState::Idle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_double_tap_outside_threshold() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
tap(&mut input_preprocessor, Key::Space, 0, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
// A second press that already arrives too late starts a new first tap instead of completing the pair
|
||||
input_preprocessor.time = DOUBLE_TAP_MILLISECONDS + 1;
|
||||
key_down(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
|
||||
assert!(!responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
assert_eq!(
|
||||
input_preprocessor.double_tap_state,
|
||||
DoubleTapState::FirstTap {
|
||||
key: Key::Space,
|
||||
start_time: DOUBLE_TAP_MILLISECONDS + 1
|
||||
}
|
||||
);
|
||||
|
||||
responses.clear();
|
||||
key_up(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
|
||||
assert!(!responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_double_tap_exceeding_total_duration_fails() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
tap(&mut input_preprocessor, Key::Space, 0, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
input_preprocessor.time = 50;
|
||||
key_down(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
// The second press alone is short, but the whole gesture from the first key-down to the second key-up exceeds the limit
|
||||
input_preprocessor.time = DOUBLE_TAP_MILLISECONDS;
|
||||
key_up(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
|
||||
assert!(!responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_slow_tap_then_quick_double_tap_still_works() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
tap(&mut input_preprocessor, Key::Space, 0, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
// Too slow to pair with the first tap, so this becomes a new first tap of its own
|
||||
tap(&mut input_preprocessor, Key::Space, DOUBLE_TAP_MILLISECONDS + 1, &mut responses);
|
||||
assert!(!responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
responses.clear();
|
||||
|
||||
// A quick pair after that still registers
|
||||
tap(&mut input_preprocessor, Key::Space, DOUBLE_TAP_MILLISECONDS + 51, &mut responses);
|
||||
assert!(responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_double_tap_interrupted_by_pointer_down() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
tap(&mut input_preprocessor, Key::Space, 0, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
input_preprocessor.time = 50;
|
||||
key_down(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
process_input(
|
||||
&mut input_preprocessor,
|
||||
InputPreprocessorMessage::PointerDown {
|
||||
editor_mouse_state: EditorPointerState::default(),
|
||||
modifier_keys: ModifierKeys::empty(),
|
||||
},
|
||||
&mut responses,
|
||||
);
|
||||
responses.clear();
|
||||
|
||||
key_up(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
|
||||
assert!(!responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_double_tap_not_interrupted_by_mouse_movement() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
tap(&mut input_preprocessor, Key::Space, 0, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
input_preprocessor.time = 50;
|
||||
key_down(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
process_input(
|
||||
&mut input_preprocessor,
|
||||
InputPreprocessorMessage::PointerMove {
|
||||
editor_mouse_state: EditorPointerState::default(),
|
||||
modifier_keys: ModifierKeys::empty(),
|
||||
},
|
||||
&mut responses,
|
||||
);
|
||||
responses.clear();
|
||||
|
||||
key_up(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
|
||||
assert!(responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_double_tap_blocked_by_mouse_button_held() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
input_preprocessor.mouse.mouse_keys = MouseKeys::LEFT;
|
||||
|
||||
tap(&mut input_preprocessor, Key::Space, 0, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
input_preprocessor.time = 50;
|
||||
key_down(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
|
||||
assert_eq!(input_preprocessor.double_tap_state, DoubleTapState::Idle);
|
||||
|
||||
responses.clear();
|
||||
key_up(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
|
||||
assert!(!responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_double_tap_modified_first_press_never_arms() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
// Press Shift+Space first, as for live preview, then a plain Space within the threshold
|
||||
process_input(
|
||||
&mut input_preprocessor,
|
||||
InputPreprocessorMessage::KeyDown {
|
||||
key: Key::Space,
|
||||
key_repeat: false,
|
||||
modifier_keys: ModifierKeys::SHIFT,
|
||||
},
|
||||
&mut responses,
|
||||
);
|
||||
assert_eq!(
|
||||
input_preprocessor.double_tap_state,
|
||||
DoubleTapState::Idle,
|
||||
"A modified first press should leave no double-tap state at all"
|
||||
);
|
||||
|
||||
tap(&mut input_preprocessor, Key::Space, 50, &mut responses);
|
||||
|
||||
assert!(!responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_double_tap_reset_by_a_different_key() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
tap(&mut input_preprocessor, Key::Space, 0, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
// A different key between the taps makes the next Space press start a fresh pair
|
||||
tap(&mut input_preprocessor, Key::KeyA, 50, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
input_preprocessor.time = 100;
|
||||
key_down(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
assert_eq!(
|
||||
input_preprocessor.double_tap_state,
|
||||
DoubleTapState::FirstTap { key: Key::Space, start_time: 100 },
|
||||
"The intervening key should have reset the detector"
|
||||
);
|
||||
|
||||
responses.clear();
|
||||
key_up(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
assert!(!responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_double_tap_blocked_by_a_modifier_key() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
tap(&mut input_preprocessor, Key::Space, 0, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
// Shift+Space is its own shortcut, so a modifier held on the second tap suppresses the double tap
|
||||
input_preprocessor.time = 50;
|
||||
process_input(
|
||||
&mut input_preprocessor,
|
||||
InputPreprocessorMessage::KeyDown {
|
||||
key: Key::Space,
|
||||
key_repeat: false,
|
||||
modifier_keys: ModifierKeys::SHIFT,
|
||||
},
|
||||
&mut responses,
|
||||
);
|
||||
|
||||
assert_eq!(input_preprocessor.double_tap_state, DoubleTapState::Idle);
|
||||
|
||||
responses.clear();
|
||||
key_up(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
assert!(!responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_double_tap_ignores_key_repeat() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
tap(&mut input_preprocessor, Key::Space, 0, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
// A held key's auto-repeat must not read as a second tap
|
||||
input_preprocessor.time = 50;
|
||||
process_input(
|
||||
&mut input_preprocessor,
|
||||
InputPreprocessorMessage::KeyDown {
|
||||
key: Key::Space,
|
||||
key_repeat: true,
|
||||
modifier_keys: ModifierKeys::empty(),
|
||||
},
|
||||
&mut responses,
|
||||
);
|
||||
|
||||
assert_eq!(input_preprocessor.double_tap_state, DoubleTapState::FirstTap { key: Key::Space, start_time: 0 });
|
||||
|
||||
responses.clear();
|
||||
key_up(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
assert!(!responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
}
|
||||
}
|
||||
@@ -35,4 +35,19 @@ pub enum LayoutMessage {
|
||||
widget_id: WidgetId,
|
||||
file: DroppedFile,
|
||||
},
|
||||
/// Tokenizes what a math expression widget holds as it is typed, replying with what the frontend colors and typesets, and with
|
||||
/// the names that finish the one at the caret, where the caret is given. Unless they're `asked` for, as by a shortcut, names are
|
||||
/// offered only once part of one is typed.
|
||||
AnalyzeMathExpression {
|
||||
layout_target: LayoutTarget,
|
||||
widget_id: WidgetId,
|
||||
source: String,
|
||||
caret: Option<u32>,
|
||||
asked: bool,
|
||||
},
|
||||
/// Evaluates math typed in a math expression widget's number popover, replying with its value written as the number to take its place.
|
||||
EvaluateMathExpression {
|
||||
widget_id: WidgetId,
|
||||
source: String,
|
||||
},
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
use crate::messages::input_mapper::utility_types::keyboard::KeysGroup;
|
||||
use crate::messages::layout::utility_types::math_expression::{
|
||||
MathExpressionTokens, math_expression_completions, math_expression_error, math_expression_error_ranges, math_expression_number, math_expression_tokens,
|
||||
};
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::prelude::*;
|
||||
@@ -91,6 +94,41 @@ impl MessageHandler<LayoutMessage, LayoutMessageContext<'_>> for LayoutMessageHa
|
||||
responses.add((dropdown_input.on_file_drop.callback)(&file));
|
||||
}
|
||||
}
|
||||
LayoutMessage::AnalyzeMathExpression {
|
||||
layout_target,
|
||||
widget_id,
|
||||
source,
|
||||
caret,
|
||||
asked,
|
||||
} => {
|
||||
let Some(layout) = self.layouts.get(layout_target as usize) else {
|
||||
warn!("AnalyzeMathExpression referenced an invalid layout. `widget_id: {widget_id}`, `layout_target: {layout_target:?}`");
|
||||
return;
|
||||
};
|
||||
let Some(widget_instance) = layout.iter().find(|widget| widget.widget_id == widget_id) else {
|
||||
warn!("AnalyzeMathExpression referenced an invalid widget ID. `widget_id: {widget_id}`, `layout_target: {layout_target:?}`");
|
||||
return;
|
||||
};
|
||||
let Widget::MathExpressionInput(input) = &*widget_instance.widget else {
|
||||
warn!("AnalyzeMathExpression referenced a widget other than a MathExpressionInput. `widget_id: {widget_id}`");
|
||||
return;
|
||||
};
|
||||
|
||||
// The reply carries the source it read, so the frontend can drop one that a later keystroke has outdated
|
||||
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(&source, input.accepts_reducers);
|
||||
let completions = caret.map(|caret| math_expression_completions(&source, caret, asked));
|
||||
responses.add(FrontendMessage::UpdateMathExpressionAnalysis {
|
||||
widget_id,
|
||||
source,
|
||||
tokens,
|
||||
tooltips,
|
||||
completions,
|
||||
});
|
||||
}
|
||||
LayoutMessage::EvaluateMathExpression { widget_id, source } => {
|
||||
let result = math_expression_number(&source);
|
||||
responses.add(FrontendMessage::UpdateMathExpressionEvaluation { widget_id, source, result });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -320,6 +358,29 @@ impl LayoutMessageHandler {
|
||||
responses.add(callback_message);
|
||||
}
|
||||
Widget::ImageLabel(_) => {}
|
||||
Widget::MathExpressionInput(math_expression_input) => {
|
||||
let callback_message = match action {
|
||||
WidgetValueAction::Commit => (math_expression_input.on_commit.callback)(&()),
|
||||
WidgetValueAction::Update => {
|
||||
let Some(update_value) = value.as_str() else {
|
||||
error!("MathExpressionInput update was not of type: string");
|
||||
return;
|
||||
};
|
||||
|
||||
// The widget is resent as stored, so its tokens and errors must be for its new value rather than its old one
|
||||
let accepts_reducers = math_expression_input.accepts_reducers;
|
||||
let error = math_expression_error(update_value, accepts_reducers);
|
||||
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(update_value, accepts_reducers);
|
||||
math_expression_input.tokens = tokens;
|
||||
math_expression_input.tooltips = tooltips;
|
||||
math_expression_input.errors = math_expression_error_ranges(update_value, error.as_ref());
|
||||
math_expression_input.value = update_value.into();
|
||||
(math_expression_input.on_update.callback)(math_expression_input)
|
||||
}
|
||||
};
|
||||
|
||||
responses.add(callback_message);
|
||||
}
|
||||
Widget::ShortcutLabel(_) => {}
|
||||
Widget::IconLabel(_) => {}
|
||||
Widget::NodeCatalog(node_type_input) => match action {
|
||||
|
||||
@@ -2,7 +2,9 @@ use super::widgets::button_widgets::*;
|
||||
use super::widgets::input_widgets::*;
|
||||
use super::widgets::label_widgets::*;
|
||||
use crate::application::generate_uuid;
|
||||
use crate::messages::frontend::IconName;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::KeysGroup;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
||||
use crate::messages::prelude::*;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
@@ -58,12 +60,12 @@ define_layout_target!(
|
||||
DialogColumn2,
|
||||
/// Contains the widgets located directly above the canvas to the right, for example the zoom in and out buttons.
|
||||
DocumentBar,
|
||||
/// Controls for adding, grouping, and deleting layers at the bottom of the Layers panel.
|
||||
LayersPanelBottomBar,
|
||||
/// Visibility and lock toggles for the selection at the bottom left of the Layers panel.
|
||||
LayersPanelBottomLeftBar,
|
||||
/// Controls for adding, grouping, and deleting layers at the bottom right of the Layers panel.
|
||||
LayersPanelBottomRightBar,
|
||||
/// Blending options at the top of the Layers panel.
|
||||
LayersPanelControlLeftBar,
|
||||
/// Selected layer status (locked/hidden) at the top of the Layers panel.
|
||||
LayersPanelControlRightBar,
|
||||
/// The dropdown menu at the very top of the application: File, Edit, etc.
|
||||
MenuBar,
|
||||
/// Bar at the top of the node graph containing the location and the "Preview" and "Hide" buttons.
|
||||
@@ -147,6 +149,23 @@ pub trait Diffable: Clone + PartialEq {
|
||||
fn replace_widget_ids(&mut self, layout_target: LayoutTarget, widget_path: &mut Vec<usize>, checkbox_map: &HashMap<CheckboxId, CheckboxId>);
|
||||
}
|
||||
|
||||
/// Hashes menu list entry sections, with each entry's children, for the frontend to cache a menu list by.
|
||||
pub fn hash_menu_list_entry_sections(entry_sections: &MenuListEntrySections) -> u64 {
|
||||
fn hash_into(hasher: &mut DefaultHasher, entry_sections: &MenuListEntrySections) {
|
||||
for (index, entries) in entry_sections.iter().enumerate() {
|
||||
index.hash(hasher);
|
||||
for entry in entries {
|
||||
entry.hash(hasher);
|
||||
hash_into(hasher, &entry.children);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut hasher = DefaultHasher::new();
|
||||
hash_into(&mut hasher, entry_sections);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
/// Computes a deterministic WidgetId based on layout target, path, and widget type.
|
||||
fn compute_widget_id(layout_target: LayoutTarget, widget_path: &[usize], widget: &Widget) -> WidgetId {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
@@ -371,12 +390,25 @@ pub struct WidgetTable {
|
||||
pub unstyled: bool,
|
||||
}
|
||||
|
||||
/// A wire drawn between Properties panel sections, styled like the graph's wire carrying the same data.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct SectionWire {
|
||||
#[serde(rename = "dataType")]
|
||||
pub data_type: FrontendGraphDataType,
|
||||
/// Whether the wire carries a list, drawn as two parallel lines.
|
||||
#[serde(rename = "isList")]
|
||||
pub is_list: bool,
|
||||
}
|
||||
|
||||
/// A collapsible Properties panel section for a single node: a header with its name and pin, delete, and visibility controls, above its input parameter widgets.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
|
||||
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct WidgetSection {
|
||||
/// The node's name shown in the section header: its given alias with the implementation name in parentheses, or just the implementation name.
|
||||
pub name: String,
|
||||
/// The node definition's icon, shown before the name in the section header (none when it has no icon).
|
||||
pub icon: Option<IconName>,
|
||||
/// The node definition's description, shown as the header's tooltip (empty when it has none).
|
||||
pub description: String,
|
||||
/// Whether the node is visible rather than hidden (shown as the eye icon).
|
||||
@@ -385,6 +417,12 @@ pub struct WidgetSection {
|
||||
pub pinned: bool,
|
||||
/// Whether this section can be dragged to reorder it within its layer's chain of nodes (true for a layer chain's nodes, but not its terminal layer node).
|
||||
pub draggable: bool,
|
||||
/// For a selected layer's own section, the wire drawn up into its chain input from its chain's sections below (none when it has no chain).
|
||||
#[serde(rename = "chainWire")]
|
||||
pub chain_wire: Option<SectionWire>,
|
||||
/// For a section in a selected layer's chain, the wire drawn up to the section above, which its node's output feeds.
|
||||
#[serde(rename = "outputWire")]
|
||||
pub output_wire: Option<SectionWire>,
|
||||
/// Whether this section is expanded to show its contents, as opposed to being collapsed down to just its header.
|
||||
pub expanded: bool,
|
||||
/// The ID of the node whose properties this section displays.
|
||||
@@ -424,13 +462,17 @@ impl LayoutGroup {
|
||||
Self::Table(WidgetTable { rows, unstyled })
|
||||
}
|
||||
|
||||
pub fn section(name: impl Into<String>, description: impl Into<String>, visible: bool, pinned: bool, expanded: bool, id: u64, layout: Layout) -> Self {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn section(name: impl Into<String>, icon: Option<IconName>, description: impl Into<String>, visible: bool, pinned: bool, expanded: bool, id: u64, layout: Layout) -> Self {
|
||||
Self::Section(WidgetSection {
|
||||
name: name.into(),
|
||||
icon,
|
||||
description: description.into(),
|
||||
visible,
|
||||
pinned,
|
||||
draggable: false,
|
||||
chain_wire: None,
|
||||
output_wire: None,
|
||||
expanded,
|
||||
id,
|
||||
layout,
|
||||
@@ -454,6 +496,7 @@ impl LayoutGroup {
|
||||
Widget::IconLabel(x) => &mut x.tooltip_description,
|
||||
Widget::ImageButton(x) => &mut x.tooltip_description,
|
||||
Widget::ImageLabel(x) => &mut x.tooltip_description,
|
||||
Widget::MathExpressionInput(x) => &mut x.tooltip_description,
|
||||
Widget::NumberInput(x) => &mut x.tooltip_description,
|
||||
Widget::PopoverButton(x) => &mut x.tooltip_description,
|
||||
Widget::TextAreaInput(x) => &mut x.tooltip_description,
|
||||
@@ -526,20 +569,26 @@ impl Diffable for LayoutGroup {
|
||||
(
|
||||
Self::Section(WidgetSection {
|
||||
name: current_name,
|
||||
icon: current_icon,
|
||||
description: current_description,
|
||||
visible: current_visible,
|
||||
pinned: current_pinned,
|
||||
draggable: current_draggable,
|
||||
chain_wire: current_chain_wire,
|
||||
output_wire: current_output_wire,
|
||||
expanded: current_expanded,
|
||||
id: current_id,
|
||||
layout: current_layout,
|
||||
}),
|
||||
Self::Section(WidgetSection {
|
||||
name: new_name,
|
||||
icon: new_icon,
|
||||
description: new_description,
|
||||
visible: new_visible,
|
||||
pinned: new_pinned,
|
||||
draggable: new_draggable,
|
||||
chain_wire: new_chain_wire,
|
||||
output_wire: new_output_wire,
|
||||
expanded: new_expanded,
|
||||
id: new_id,
|
||||
layout: new_layout,
|
||||
@@ -549,19 +598,25 @@ impl Diffable for LayoutGroup {
|
||||
// TODO: Diff insersion and deletion of items
|
||||
if current_layout.0.len() != new_layout.0.len()
|
||||
|| *current_name != new_name
|
||||
|| *current_icon != new_icon
|
||||
|| *current_description != new_description
|
||||
|| *current_visible != new_visible
|
||||
|| *current_pinned != new_pinned
|
||||
|| *current_draggable != new_draggable
|
||||
|| *current_chain_wire != new_chain_wire
|
||||
|| *current_output_wire != new_output_wire
|
||||
|| *current_expanded != new_expanded
|
||||
|| *current_id != new_id
|
||||
{
|
||||
// Update self to reflect new changes
|
||||
current_name.clone_from(&new_name);
|
||||
current_icon.clone_from(&new_icon);
|
||||
current_description.clone_from(&new_description);
|
||||
*current_visible = new_visible;
|
||||
*current_pinned = new_pinned;
|
||||
*current_draggable = new_draggable;
|
||||
*current_chain_wire = new_chain_wire;
|
||||
*current_output_wire = new_output_wire;
|
||||
*current_expanded = new_expanded;
|
||||
*current_id = new_id;
|
||||
current_layout.clone_from(&new_layout);
|
||||
@@ -569,10 +624,13 @@ impl Diffable for LayoutGroup {
|
||||
// Push an update layout group to the diff
|
||||
let new_value = Self::Section(WidgetSection {
|
||||
name: new_name,
|
||||
icon: new_icon,
|
||||
description: new_description,
|
||||
visible: new_visible,
|
||||
pinned: new_pinned,
|
||||
draggable: new_draggable,
|
||||
chain_wire: new_chain_wire,
|
||||
output_wire: new_output_wire,
|
||||
expanded: new_expanded,
|
||||
id: new_id,
|
||||
layout: new_layout,
|
||||
@@ -815,6 +873,7 @@ pub enum Widget {
|
||||
IconLabel(IconLabel),
|
||||
ImageButton(ImageButton),
|
||||
ImageLabel(ImageLabel),
|
||||
MathExpressionInput(MathExpressionInput),
|
||||
ShortcutLabel(ShortcutLabel),
|
||||
NodeCatalog(NodeCatalog),
|
||||
NumberInput(NumberInput),
|
||||
@@ -878,6 +937,7 @@ impl DiffUpdate {
|
||||
Widget::ShortcutLabel(widget) => widget.shortcut.as_mut(),
|
||||
Widget::IconLabel(_)
|
||||
| Widget::ImageLabel(_)
|
||||
| Widget::MathExpressionInput(_)
|
||||
| Widget::NodeCatalog(_)
|
||||
| Widget::ReferencePointInput(_)
|
||||
| Widget::RadioInput(_)
|
||||
@@ -924,28 +984,6 @@ impl DiffUpdate {
|
||||
}
|
||||
}
|
||||
|
||||
// Hash the menu list entry sections for caching purposes
|
||||
let hash_menu_list_entry_sections = |entry_sections: &MenuListEntrySections| {
|
||||
struct RecursiveHasher<'a> {
|
||||
hasher: DefaultHasher,
|
||||
hash_fn: &'a dyn Fn(&mut RecursiveHasher, &MenuListEntrySections),
|
||||
}
|
||||
let mut recursive_hasher = RecursiveHasher {
|
||||
hasher: DefaultHasher::new(),
|
||||
hash_fn: &|recursive_hasher, entry_sections| {
|
||||
for (index, entries) in entry_sections.iter().enumerate() {
|
||||
index.hash(&mut recursive_hasher.hasher);
|
||||
for entry in entries {
|
||||
entry.hash(&mut recursive_hasher.hasher);
|
||||
(recursive_hasher.hash_fn)(recursive_hasher, &entry.children);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
(recursive_hasher.hash_fn)(&mut recursive_hasher, entry_sections);
|
||||
recursive_hasher.hasher.finish()
|
||||
};
|
||||
|
||||
// Apply shortcut conversions to all widgets that have menu lists
|
||||
let convert_menu_lists = |widget_instance: &mut WidgetInstance| match &mut *widget_instance.widget {
|
||||
Widget::DropdownInput(dropdown_input) => {
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
//! What the math parser reads of an expression, converted for a math expression widget into the UTF-16 code units its frontend's strings use.
|
||||
|
||||
use crate::messages::layout::utility_types::layout_widget::hash_menu_list_entry_sections;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use math_parser::parser::{ErrorMessage, ParseError};
|
||||
|
||||
/// The source's UTF-16 length up to each byte, so the parser's byte offsets convert to the frontend's code units in one lookup.
|
||||
fn utf16_offsets(source: &str) -> Vec<u32> {
|
||||
let mut units = vec![0_u32; source.len() + 1];
|
||||
let mut count = 0;
|
||||
for (byte, character) in source.char_indices() {
|
||||
units[byte..byte + character.len_utf8()].fill(count);
|
||||
count += character.len_utf16() as u32;
|
||||
}
|
||||
units[source.len()] = count;
|
||||
units
|
||||
}
|
||||
|
||||
/// Why a math expression fails to parse, or `None` when it parses. Where the node applies a lone operator or function name like
|
||||
/// `+` or `min` across its items, that counts as valid too.
|
||||
pub fn math_expression_error(expression: &str, accepts_reducers: bool) -> Option<ParseError> {
|
||||
// A blank expression is unfinished rather than wrong, so it goes unflagged like any empty field
|
||||
if expression.trim().is_empty() || (accepts_reducers && math_parser::reducer::classify_reducer(expression, math_parser::context::NothingMap).is_some()) {
|
||||
return None;
|
||||
}
|
||||
math_parser::ast::Node::try_parse_from_str(expression).err()
|
||||
}
|
||||
|
||||
/// The stretches of a math expression its parse error points at, for the frontend to underline. An empty span, where something is
|
||||
/// missing like at the end of the input, has nothing to underline, so it widens to the character before it, past any whitespace.
|
||||
pub fn math_expression_error_ranges(source: &str, error: Option<&ParseError>) -> Vec<MathExpressionRange> {
|
||||
let units = utf16_offsets(source);
|
||||
|
||||
let spans = error.into_iter().flat_map(|error| error.messages().iter().filter_map(ErrorMessage::span));
|
||||
spans
|
||||
.filter_map(|span| {
|
||||
let before = source.get(..span.start)?.trim_end();
|
||||
let span = match before.chars().next_back() {
|
||||
Some(character) if span.is_empty() => before.len() - character.len_utf8()..before.len(),
|
||||
_ => span,
|
||||
};
|
||||
Some(MathExpressionRange {
|
||||
start: *units.get(span.start)?,
|
||||
end: *units.get(span.end)?,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The names offered to finish the one being typed in a math expression, in sections by kind, each entry's value being the text
|
||||
/// that replaces the stretch of code units from `start` to `end`, the name the caret is in or beside. A call's `()` takes the caret
|
||||
/// between them, except that a suffixed form's `_`, like `log_`'s, is selected instead, for its suffix to be typed over or after it.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct MathExpressionCompletions {
|
||||
pub start: u32,
|
||||
pub end: u32,
|
||||
pub entries: MenuListEntrySections,
|
||||
#[serde(rename = "entriesHash")]
|
||||
pub entries_hash: u64,
|
||||
/// The index among all the sections' entries of the one fitting what's typed best, which starts highlighted.
|
||||
pub best: u32,
|
||||
}
|
||||
|
||||
/// The names offered to finish the one the caret, given in code units, stands in or beside. Unless they're `asked` for, as by a
|
||||
/// shortcut rather than by typing, they're offered only once part of a name is typed before the caret.
|
||||
pub fn math_expression_completions(source: &str, caret: u32, asked: bool) -> MathExpressionCompletions {
|
||||
let units = utf16_offsets(source);
|
||||
// Each character's bytes share the offset of its first, so the first byte reaching the caret begins the character after it
|
||||
let byte = units.partition_point(|&unit| unit < caret).min(source.len());
|
||||
let completions = math_parser::completion::completions(source, byte, asked);
|
||||
let best = completions.best as u32;
|
||||
|
||||
// A function comes with the parentheses of its call, unless they're already there, spaced or not
|
||||
let parenthesized = source.get(completions.end..).unwrap_or_default().trim_start().starts_with('(');
|
||||
|
||||
let mut entries: MenuListEntrySections = Vec::new();
|
||||
let mut previous_kind = None;
|
||||
for offer in completions.offers {
|
||||
if previous_kind != Some(offer.kind) {
|
||||
entries.push(Vec::new());
|
||||
previous_kind = Some(offer.kind);
|
||||
}
|
||||
if let Some(section) = entries.last_mut() {
|
||||
let insertion = if offer.signature.is_some() && !parenthesized {
|
||||
format!("{}()", offer.name)
|
||||
} else {
|
||||
offer.name.to_string()
|
||||
};
|
||||
let label = offer.signature.unwrap_or_else(|| offer.name.to_string());
|
||||
|
||||
// A builtin is named at the row's end and hovers with the tooltip it has where it's written
|
||||
let entry = MenuListEntry::new(insertion).label(label);
|
||||
let entry = match offer.tooltip {
|
||||
Some(tooltip) => entry
|
||||
.annotation(tooltip.label.clone())
|
||||
.tooltip_label(tooltip.label)
|
||||
.tooltip_description(tooltip.description)
|
||||
.tooltip_code(tooltip.form.unwrap_or_default()),
|
||||
None => entry,
|
||||
};
|
||||
section.push(entry);
|
||||
}
|
||||
}
|
||||
|
||||
MathExpressionCompletions {
|
||||
start: units[completions.start],
|
||||
end: units[completions.end],
|
||||
entries_hash: hash_menu_list_entry_sections(&entries),
|
||||
entries,
|
||||
best,
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of math typed in place of a number, written as a number literal, or `None` where it isn't a finite real number.
|
||||
pub fn math_expression_number(source: &str) -> Option<String> {
|
||||
use math_parser::value::{Number, Value};
|
||||
|
||||
let Value::Number(number) = math_parser::evaluate(source).ok()?.ok()?.into_value()?;
|
||||
if let Number::Integer(integer) = number {
|
||||
return Some(integer.to_string());
|
||||
}
|
||||
|
||||
let real = graphene_std::math::float_noise::round_away_float_noise(number.as_real()?);
|
||||
if !real.is_finite() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// A magnitude far from 1 is written in scientific notation, which a literal can hold too
|
||||
let magnitude = real.abs();
|
||||
Some(if magnitude != 0. && !(1e-6..1e16).contains(&magnitude) {
|
||||
format!("{real:e}")
|
||||
} else {
|
||||
real.to_string()
|
||||
})
|
||||
}
|
||||
|
||||
/// A math expression's tokens for the frontend to color and typeset, each naming its tooltip by its index among the tooltips, which
|
||||
/// are listed once each however many tokens share one, like a matrix literal's brackets and separators.
|
||||
pub struct MathExpressionTokens {
|
||||
pub tokens: Vec<MathExpressionToken>,
|
||||
pub tooltips: Vec<MathExpressionTooltip>,
|
||||
}
|
||||
|
||||
/// The tokens of a math expression for the frontend to color and typeset, with the parser's byte offsets converted to code units.
|
||||
pub fn math_expression_tokens(source: &str, accepts_reducers: bool) -> MathExpressionTokens {
|
||||
let units = utf16_offsets(source);
|
||||
let mut tooltips: Vec<MathExpressionTooltip> = Vec::new();
|
||||
|
||||
let tokens = math_parser::highlight::highlight(source, accepts_reducers).into_iter().map(|token| {
|
||||
let tooltip = token.tooltip.map(|tooltip| MathExpressionTooltip {
|
||||
label: tooltip.label,
|
||||
form: tooltip.form,
|
||||
description: tooltip.description,
|
||||
signature: tooltip.signature.map(|signature| MathExpressionSignature {
|
||||
opening: signature.opening,
|
||||
parameters: signature.parameters.into_iter().map(str::to_string).collect(),
|
||||
separator: signature.separator.to_string(),
|
||||
closing: signature.closing.to_string(),
|
||||
range: signature.range.to_string(),
|
||||
pointers: signature
|
||||
.pointers
|
||||
.into_iter()
|
||||
.map(|pointer| MathExpressionPointer {
|
||||
line: pointer.line as u32,
|
||||
column: pointer.column as u32,
|
||||
arrow: pointer.arrow.to_string(),
|
||||
})
|
||||
.collect(),
|
||||
lines: signature.lines.into_iter().map(|line| line as u32).collect(),
|
||||
}),
|
||||
});
|
||||
let tooltip = tooltip.map(|tooltip| match tooltips.iter().position(|listed| *listed == tooltip) {
|
||||
Some(index) => index as u32,
|
||||
None => {
|
||||
tooltips.push(tooltip);
|
||||
(tooltips.len() - 1) as u32
|
||||
}
|
||||
});
|
||||
|
||||
MathExpressionToken {
|
||||
start: units[token.start],
|
||||
end: units[token.end],
|
||||
role: token.role.into(),
|
||||
superscript: token.superscript,
|
||||
subscript: token.subscript.map(|offset| units[token.start + offset] - units[token.start]),
|
||||
partner: token.partner.map(|partner| partner as u32),
|
||||
separates: token.separates.map(|opener| opener as u32),
|
||||
tooltip,
|
||||
literal: token.literal.map(|literal| MathExpressionLiteral {
|
||||
start: units[literal.start],
|
||||
after_operand: literal.after_operand,
|
||||
}),
|
||||
}
|
||||
});
|
||||
let tokens = tokens.collect();
|
||||
|
||||
MathExpressionTokens { tokens, tooltips }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn math_typed_for_a_number_is_written_as_its_value() {
|
||||
assert_eq!(math_expression_number("1/4").as_deref(), Some("0.25"));
|
||||
assert_eq!(math_expression_number("0.1 + 0.2").as_deref(), Some("0.3"), "float noise is rounded away");
|
||||
assert_eq!(math_expression_number("2^60").as_deref(), Some("1152921504606846976"), "an integer stays exact");
|
||||
assert_eq!(math_expression_number("-pi").as_deref(), Some("-3.14159265359"), "rounding away noise keeps 12 significant digits");
|
||||
assert_eq!(math_expression_number("10^-9 / 4").as_deref(), Some("2.5e-10"), "a tiny magnitude is written in scientific notation");
|
||||
|
||||
// Anything other than a finite real number has no number to write
|
||||
for source in ["1/0", "2i", "x + 1", "I", "2 +"] {
|
||||
assert_eq!(math_expression_number(source), None, "`{source}`");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn math_expression_completions_count_code_units_and_group_by_kind() {
|
||||
// `π` is one code unit and `𝑥` two, so the typed `ta` begins 6 units in, though 9 bytes in
|
||||
let completions = math_expression_completions("π𝑥 + ta", 8, false);
|
||||
assert_eq!((completions.start, completions.end), (6, 8));
|
||||
assert_eq!(
|
||||
math_expression_completions("x wh", 4, false).best,
|
||||
1,
|
||||
"`where` is highlighted after `within`, which only holds the letters"
|
||||
);
|
||||
|
||||
// A function shows its signature while its call is what's inserted
|
||||
let sections = |completions: MathExpressionCompletions| {
|
||||
let section = |section: &Vec<MenuListEntry>| section.iter().map(|entry| (entry.value.clone(), entry.label.clone())).collect::<Vec<_>>();
|
||||
completions.entries.iter().map(section).collect::<Vec<_>>()
|
||||
};
|
||||
let pair = |value: &str, label: &str| (value.to_string(), label.to_string());
|
||||
assert_eq!(
|
||||
sections(completions),
|
||||
[
|
||||
vec![pair("tan()", "tan(θ)"), pair("tanh()", "tanh(x)"), pair("translation()", "translation(A)")],
|
||||
vec![pair("τ", "τ"), pair("tau", "tau")]
|
||||
]
|
||||
);
|
||||
|
||||
// Parentheses already after the name, spaced or not, are the call's own
|
||||
assert_eq!(
|
||||
sections(math_expression_completions("ta (2)", 2, false)),
|
||||
[
|
||||
vec![pair("tan", "tan(θ)"), pair("tanh", "tanh(x)"), pair("translation", "translation(A)")],
|
||||
vec![pair("τ", "τ"), pair("tau", "tau")]
|
||||
]
|
||||
);
|
||||
|
||||
// A suffixed form comes with its call's parentheses like any function
|
||||
let completions = math_expression_completions("log", 3, false);
|
||||
assert_eq!(sections(completions), [vec![pair("log_()", "log_(x)"), pair("log()", "log(x, b?)")]]);
|
||||
|
||||
// An operator typed in ASCII offers its typeset alias in place of it
|
||||
let completions = math_expression_completions("!", 1, false);
|
||||
assert_eq!((completions.start, completions.end), (0, 1));
|
||||
assert_eq!(sections(completions), [vec![pair("¬", "¬")]]);
|
||||
|
||||
// Typing where no name is begun offers nothing, unless the names are asked for
|
||||
assert!(math_expression_completions("2 + ", 4, false).entries.is_empty());
|
||||
assert!(!math_expression_completions("2 + ", 4, true).entries.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod layout_widget;
|
||||
pub mod math_expression;
|
||||
pub mod tooltip_markdown;
|
||||
pub mod widgets;
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::WidgetCallback;
|
||||
use derivative::*;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
use graphite_proc_macros::WidgetBuilder;
|
||||
@@ -33,6 +34,10 @@ pub struct IconButton {
|
||||
#[serde(rename = "tooltipShortcut")]
|
||||
pub tooltip_shortcut: Option<ActionShortcut>,
|
||||
|
||||
// Drag and drop
|
||||
#[serde(rename = "dragDropKinds")]
|
||||
pub drag_drop_kinds: DragDropKinds,
|
||||
|
||||
// Callbacks
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
@@ -45,6 +50,19 @@ pub struct IconButton {
|
||||
pub on_drag_drop: WidgetCallback<IconButton>,
|
||||
}
|
||||
|
||||
/// What can be dragged in the Layers panel and dropped onto an icon button to perform its `on_drag_drop` action.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum DragDropKinds {
|
||||
/// Nothing, so the button isn't a drop target.
|
||||
#[default]
|
||||
None,
|
||||
/// Layers.
|
||||
Layers,
|
||||
/// Layers, or the nodes in a layer's chain.
|
||||
LayersAndChainNodes,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder)]
|
||||
#[derivative(Debug, PartialEq, Default)]
|
||||
@@ -95,6 +113,15 @@ pub struct ParameterExposeButton {
|
||||
pub exposed: bool,
|
||||
#[serde(rename = "dataType")]
|
||||
pub data_type: FrontendGraphDataType,
|
||||
/// The node whose input this connector represents, so it can be dragged to and from as a wire endpoint.
|
||||
#[serde(rename = "nodeId")]
|
||||
pub node_id: NodeId,
|
||||
/// A `u32` so it reaches the frontend as a number rather than a bigint.
|
||||
#[serde(rename = "inputIndex")]
|
||||
pub input_index: u32,
|
||||
/// Whether the wire currently being dragged in the graph can be dropped onto this connector.
|
||||
#[serde(rename = "wireDropTarget")]
|
||||
pub wire_drop_target: bool,
|
||||
|
||||
// Tooltips
|
||||
#[serde(rename = "tooltipLabel")]
|
||||
|
||||
@@ -138,6 +138,8 @@ pub struct MenuListEntry {
|
||||
pub label: String,
|
||||
#[widget_builder(string)]
|
||||
pub icon: Option<IconName>,
|
||||
/// Text at the row's right end, in the place of a shortcut, like the name of a completion.
|
||||
pub annotation: String,
|
||||
pub disabled: bool,
|
||||
|
||||
// Children
|
||||
@@ -156,6 +158,9 @@ pub struct MenuListEntry {
|
||||
pub tooltip_description: String,
|
||||
#[serde(rename = "tooltipShortcut")]
|
||||
pub tooltip_shortcut: Option<ActionShortcut>,
|
||||
/// Code at the right of the tooltip's header, like a completion's signature.
|
||||
#[serde(rename = "tooltipCode")]
|
||||
pub tooltip_code: String,
|
||||
|
||||
// Callbacks
|
||||
#[serde(skip)]
|
||||
@@ -171,6 +176,7 @@ impl std::hash::Hash for MenuListEntry {
|
||||
self.value.hash(state);
|
||||
self.label.hash(state);
|
||||
self.icon.hash(state);
|
||||
self.annotation.hash(state);
|
||||
self.disabled.hash(state);
|
||||
}
|
||||
}
|
||||
@@ -499,6 +505,153 @@ pub struct TextInput {
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
}
|
||||
|
||||
/// A math expression's text field, typeset with math italics and syntax highlighting as it is edited.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder)]
|
||||
#[derivative(Debug, PartialEq, Default)]
|
||||
pub struct MathExpressionInput {
|
||||
// Content
|
||||
#[widget_builder(constructor)]
|
||||
pub value: String,
|
||||
/// The value's tokens, which the frontend colors and typesets, as it does the tokens sent for each edit while typing.
|
||||
pub tokens: Vec<MathExpressionToken>,
|
||||
/// What hovering each token shows, listed once each however many tokens share one.
|
||||
pub tooltips: Vec<MathExpressionTooltip>,
|
||||
/// The stretches of the value its parse errors point at, which the frontend underlines.
|
||||
pub errors: Vec<MathExpressionRange>,
|
||||
/// Whether a lone operator or function name like `+` or `max` is an expression, applied across a list as by the Math node.
|
||||
#[serde(skip)]
|
||||
pub accepts_reducers: bool,
|
||||
pub disabled: bool,
|
||||
|
||||
// Tooltips
|
||||
#[serde(rename = "tooltipLabel")]
|
||||
pub tooltip_label: String,
|
||||
#[serde(rename = "tooltipDescription")]
|
||||
pub tooltip_description: String,
|
||||
#[serde(rename = "tooltipShortcut")]
|
||||
pub tooltip_shortcut: Option<ActionShortcut>,
|
||||
|
||||
// Callbacks
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_update: WidgetCallback<MathExpressionInput>,
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
}
|
||||
|
||||
/// A stretch of a math expression with the role its spelling gives it, in the UTF-16 code units the frontend's strings use.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct MathExpressionToken {
|
||||
pub start: u32,
|
||||
pub end: u32,
|
||||
pub role: MathExpressionRole,
|
||||
/// How many exponents deep it stands, 0 outside any.
|
||||
pub superscript: u8,
|
||||
/// Where a name's subscript begins, in code units from its start.
|
||||
pub subscript: Option<u32>,
|
||||
/// The index among the tokens of the delimiter pairing with this one.
|
||||
pub partner: Option<u32>,
|
||||
/// For a comma or semicolon, the index among the tokens of the opener of the group whose parts it separates.
|
||||
pub separates: Option<u32>,
|
||||
/// The index among the tooltips of what hovering the token shows: a builtin's, constant's, or operator's documentation, or the
|
||||
/// drawing of a matrix or range literal.
|
||||
pub tooltip: Option<u32>,
|
||||
/// For a finite number, the literal it's part of, which the frontend can adjust as one value.
|
||||
pub literal: Option<MathExpressionLiteral>,
|
||||
}
|
||||
|
||||
/// A number as the frontend may adjust it as one value, written from its start to the end of the number's token.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct MathExpressionLiteral {
|
||||
/// Where it begins, at any sign right before the number.
|
||||
pub start: u32,
|
||||
/// Whether it follows an operand it multiplies, where a sign written before it would subtract instead.
|
||||
#[serde(rename = "afterOperand")]
|
||||
pub after_operand: bool,
|
||||
}
|
||||
|
||||
/// A math expression token's hover text, in the tooltip Markdown subset.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct MathExpressionTooltip {
|
||||
pub label: String,
|
||||
/// How it's written, like `sin(θ)`, `a + b`, or `π`, which the frontend shows beside the label.
|
||||
pub form: Option<String>,
|
||||
pub description: String,
|
||||
/// The signature of a call or matrix literal, which its form shows, for the frontend to mark the argument or entry being typed in it.
|
||||
pub signature: Option<MathExpressionSignature>,
|
||||
}
|
||||
|
||||
/// A call's or matrix literal's parameters between its delimiters, like `sin(` and `)` or `[` and `]`.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct MathExpressionSignature {
|
||||
pub opening: String,
|
||||
pub parameters: Vec<String>,
|
||||
pub separator: String,
|
||||
pub closing: String,
|
||||
/// For a call, the range of its results, like `[0, ∞]`, written after an arrow.
|
||||
pub range: String,
|
||||
/// For a drawn matrix literal, the arrow pointing at each entry's row or column, for the frontend to draw at the one being typed.
|
||||
pub pointers: Vec<MathExpressionPointer>,
|
||||
/// For a call, the description line explaining each parameter, for the frontend to mark the one being typed.
|
||||
pub lines: Vec<u32>,
|
||||
}
|
||||
|
||||
/// An arrow to draw into a tooltip description's code block, at a character of one of its lines.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct MathExpressionPointer {
|
||||
pub line: u32,
|
||||
pub column: u32,
|
||||
pub arrow: String,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum MathExpressionRole {
|
||||
Number,
|
||||
Variable,
|
||||
Matrix,
|
||||
Basis,
|
||||
Function,
|
||||
Keyword,
|
||||
Operator,
|
||||
Bracket,
|
||||
MatrixLiteral,
|
||||
Error,
|
||||
}
|
||||
|
||||
impl From<math_parser::highlight::Role> for MathExpressionRole {
|
||||
fn from(role: math_parser::highlight::Role) -> Self {
|
||||
use math_parser::highlight::Role;
|
||||
match role {
|
||||
Role::Number => Self::Number,
|
||||
Role::Variable => Self::Variable,
|
||||
Role::Matrix => Self::Matrix,
|
||||
Role::Basis => Self::Basis,
|
||||
Role::Function => Self::Function,
|
||||
Role::Keyword => Self::Keyword,
|
||||
Role::Operator => Self::Operator,
|
||||
Role::Bracket => Self::Bracket,
|
||||
Role::MatrixLiteral => Self::MatrixLiteral,
|
||||
Role::Error => Self::Error,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A stretch of a math expression, in the UTF-16 code units the frontend's strings use.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct MathExpressionRange {
|
||||
pub start: u32,
|
||||
pub end: u32,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Default, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder)]
|
||||
#[derivative(Debug, PartialEq)]
|
||||
|
||||
@@ -12,8 +12,12 @@ pub struct MenuBarMessageHandler {
|
||||
pub canvas_flipped: bool,
|
||||
pub rulers_visible: bool,
|
||||
pub node_graph_open: bool,
|
||||
pub has_artboards: bool,
|
||||
pub has_selected_nodes: bool,
|
||||
pub has_selected_layers: bool,
|
||||
pub has_selected_visible_layers: bool,
|
||||
pub has_selected_visible_and_unlocked_layers: bool,
|
||||
pub has_selected_groups: bool,
|
||||
pub has_selection_history: (bool, bool),
|
||||
pub message_logging_verbosity: MessageLoggingVerbosity,
|
||||
pub reset_node_definitions_on_open: bool,
|
||||
@@ -44,8 +48,12 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
fn layout(&self) -> Layout {
|
||||
let no_active_document = !self.has_active_document;
|
||||
let node_graph_open = self.node_graph_open;
|
||||
let has_artboards = self.has_artboards;
|
||||
let has_selected_nodes = self.has_selected_nodes;
|
||||
let has_selected_layers = self.has_selected_layers;
|
||||
let has_selected_visible_layers = self.has_selected_visible_layers;
|
||||
let has_selected_visible_and_unlocked_layers = self.has_selected_visible_and_unlocked_layers;
|
||||
let has_selected_groups = self.has_selected_groups;
|
||||
let has_selection_history = self.has_selection_history;
|
||||
let message_logging_verbosity_off = self.message_logging_verbosity == MessageLoggingVerbosity::Off;
|
||||
let message_logging_verbosity_names = self.message_logging_verbosity == MessageLoggingVerbosity::Names;
|
||||
@@ -201,13 +209,13 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon("Cut")
|
||||
.tooltip_shortcut(action_shortcut!(ClipboardMessageDiscriminant::Cut))
|
||||
.on_commit(|_| ClipboardMessage::Cut.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_nodes),
|
||||
MenuListEntry::new("Copy")
|
||||
.label("Copy")
|
||||
.icon("Copy")
|
||||
.tooltip_shortcut(action_shortcut!(ClipboardMessageDiscriminant::Copy))
|
||||
.on_commit(|_| ClipboardMessage::Copy.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_nodes),
|
||||
MenuListEntry::new("Paste")
|
||||
.label("Paste")
|
||||
.icon("Paste")
|
||||
@@ -234,7 +242,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.label("Convert to Infinite Canvas")
|
||||
.icon("Artboard")
|
||||
.on_commit(|_| DocumentMessage::RemoveArtboards.into())
|
||||
.disabled(no_active_document),
|
||||
.disabled(no_active_document || !has_artboards),
|
||||
],
|
||||
])
|
||||
.widget_instance(),
|
||||
@@ -267,7 +275,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon("FolderOpen")
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::UngroupSelectedLayers))
|
||||
.on_commit(|_| DocumentMessage::UngroupSelectedLayers.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_groups),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Hide/Show")
|
||||
@@ -275,7 +283,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon("EyeHide")
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::ToggleSelectedVisibility))
|
||||
.on_commit(|_| DocumentMessage::ToggleSelectedVisibility.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_nodes),
|
||||
MenuListEntry::new("Lock/Unlock")
|
||||
.label("Lock/Unlock")
|
||||
.icon("PadlockLocked")
|
||||
@@ -289,19 +297,19 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon("TransformationGrab")
|
||||
.tooltip_shortcut(action_shortcut!(TransformLayerMessageDiscriminant::BeginGrab))
|
||||
.on_commit(|_| TransformLayerMessage::BeginGrab.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || node_graph_open || !has_selected_visible_and_unlocked_layers),
|
||||
MenuListEntry::new("Rotate")
|
||||
.label("Rotate")
|
||||
.icon("TransformationRotate")
|
||||
.tooltip_shortcut(action_shortcut!(TransformLayerMessageDiscriminant::BeginRotate))
|
||||
.on_commit(|_| TransformLayerMessage::BeginRotate.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || node_graph_open || !has_selected_visible_and_unlocked_layers),
|
||||
MenuListEntry::new("Scale")
|
||||
.label("Scale")
|
||||
.icon("TransformationScale")
|
||||
.tooltip_shortcut(action_shortcut!(TransformLayerMessageDiscriminant::BeginScale))
|
||||
.on_commit(|_| TransformLayerMessage::BeginScale.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || node_graph_open || !has_selected_visible_and_unlocked_layers),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Arrange")
|
||||
@@ -346,7 +354,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
MenuListEntry::new("Align")
|
||||
.label("Align")
|
||||
.icon("AlignVerticalCenter")
|
||||
.disabled(no_active_document || !has_selected_layers)
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers)
|
||||
.children(vec![
|
||||
vec![
|
||||
MenuListEntry::new("Align Left")
|
||||
@@ -359,7 +367,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
MenuListEntry::new("Align Horizontal Center")
|
||||
.label("Align Horizontal Center")
|
||||
.icon("AlignHorizontalCenter")
|
||||
@@ -370,7 +378,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
MenuListEntry::new("Align Right")
|
||||
.label("Align Right")
|
||||
.icon("AlignRight")
|
||||
@@ -381,7 +389,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Align Top")
|
||||
@@ -394,7 +402,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
MenuListEntry::new("Align Vertical Center")
|
||||
.label("Align Vertical Center")
|
||||
.icon("AlignVerticalCenter")
|
||||
@@ -405,7 +413,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
MenuListEntry::new("Align Bottom")
|
||||
.label("Align Bottom")
|
||||
.icon("AlignBottom")
|
||||
@@ -416,40 +424,40 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
],
|
||||
]),
|
||||
MenuListEntry::new("Flip")
|
||||
.label("Flip")
|
||||
.icon("FlipVertical")
|
||||
.disabled(no_active_document || !has_selected_layers)
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers)
|
||||
.children(vec![vec![
|
||||
MenuListEntry::new("Flip Horizontal")
|
||||
.label("Flip Horizontal")
|
||||
.icon("FlipHorizontal")
|
||||
.on_commit(|_| DocumentMessage::FlipSelectedLayers { flip_axis: FlipAxis::X }.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
MenuListEntry::new("Flip Vertical")
|
||||
.label("Flip Vertical")
|
||||
.icon("FlipVertical")
|
||||
.on_commit(|_| DocumentMessage::FlipSelectedLayers { flip_axis: FlipAxis::Y }.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
]]),
|
||||
MenuListEntry::new("Turn")
|
||||
.label("Turn")
|
||||
.icon("TurnPositive90")
|
||||
.disabled(no_active_document || !has_selected_layers)
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers)
|
||||
.children(vec![vec![
|
||||
MenuListEntry::new("Turn -90°")
|
||||
.label("Turn -90°")
|
||||
.icon("TurnNegative90")
|
||||
.on_commit(|_| DocumentMessage::RotateSelectedLayers { degrees: -90. }.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
MenuListEntry::new("Turn 90°")
|
||||
.label("Turn 90°")
|
||||
.icon("TurnPositive90")
|
||||
.on_commit(|_| DocumentMessage::RotateSelectedLayers { degrees: 90. }.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
]]),
|
||||
MenuListEntry::new("Boolean")
|
||||
.label("Boolean")
|
||||
@@ -513,7 +521,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
vec![
|
||||
MenuListEntry::new("Make Path Editable")
|
||||
.label("Make Path Editable")
|
||||
.icon("NodeShape")
|
||||
.icon("Path")
|
||||
.on_commit(|_| NodeGraphMessage::AddPathNode.into())
|
||||
.disabled(!make_path_editable_is_allowed),
|
||||
MenuListEntry::new("Expand Fill/Stroke")
|
||||
@@ -546,7 +554,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon("SelectParent")
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::SelectParentLayer))
|
||||
.on_commit(|_| DocumentMessage::SelectParentLayer.into())
|
||||
.disabled(no_active_document || !has_selected_nodes),
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Previous Selection")
|
||||
@@ -600,7 +608,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon("FrameSelected")
|
||||
.tooltip_shortcut(action_shortcut!(NavigationMessageDiscriminant::FitViewportToSelection))
|
||||
.on_commit(|_| NavigationMessage::FitViewportToSelection.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || if node_graph_open { !has_selected_nodes } else { !has_selected_visible_layers }),
|
||||
MenuListEntry::new("Zoom to Fit")
|
||||
.label("Zoom to Fit")
|
||||
.icon("FrameAll")
|
||||
|
||||
@@ -11,13 +11,12 @@ use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::blending::BlendMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::core_types::misc::format_f64;
|
||||
use graphene_std::extract_xy::XY;
|
||||
use graphene_std::gradient::Gradient;
|
||||
use graphene_std::list::{Item, List, NodeIdPath};
|
||||
use graphene_std::math::float_noise::round_away_float_noise;
|
||||
use graphene_std::memo::IORecord;
|
||||
use graphene_std::raster::{
|
||||
AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RedGreenBlueAlpha, RelativeAbsolute,
|
||||
AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RelativeAbsolute,
|
||||
SelectiveColorChoice, TonalRange,
|
||||
};
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
@@ -40,6 +39,7 @@ use std::sync::Arc;
|
||||
#[derive(ExtractField)]
|
||||
pub struct DataPanelMessageContext<'a> {
|
||||
pub network_interface: &'a mut NodeNetworkInterface,
|
||||
pub selection_network_path: &'a [NodeId],
|
||||
pub data_panel_open: bool,
|
||||
}
|
||||
|
||||
@@ -100,12 +100,17 @@ impl MessageHandler<DataPanelMessage, DataPanelMessageContext<'_>> for DataPanel
|
||||
|
||||
impl DataPanelMessageHandler {
|
||||
fn update_layout(&mut self, responses: &mut VecDeque<Message>, context: DataPanelMessageContext<'_>) {
|
||||
let DataPanelMessageContext { network_interface, .. } = context;
|
||||
let DataPanelMessageContext {
|
||||
network_interface,
|
||||
selection_network_path,
|
||||
..
|
||||
} = context;
|
||||
|
||||
let mut layout_data = LayoutData {
|
||||
current_depth: 0,
|
||||
desired_path: &mut self.element_path,
|
||||
network_interface: &*network_interface,
|
||||
selection_network_path,
|
||||
node_lookup_network_path: Vec::new(),
|
||||
gradient_settings: GradientSettings::default(),
|
||||
breadcrumbs: Vec::new(),
|
||||
@@ -176,6 +181,8 @@ struct LayoutData<'a> {
|
||||
current_depth: usize,
|
||||
desired_path: &'a mut Vec<PathStep>,
|
||||
network_interface: &'a NodeNetworkInterface,
|
||||
/// The network open in the graph, which is where selecting a node takes effect.
|
||||
selection_network_path: &'a [NodeId],
|
||||
/// The `network_path` to use when resolving a `NodeId` against the network interface.
|
||||
/// Defaults to root (`&[]`); `List<NodeId>` rendering temporarily sets it to the path's prefix so nested
|
||||
/// layers (e.g. inside a Ctrl+M-merged custom subgraph) resolve correctly.
|
||||
@@ -238,13 +245,11 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
|
||||
List<TextDenomination>,
|
||||
List<DesaturateMethod>,
|
||||
List<RedGreenBlue>,
|
||||
List<RedGreenBlueAlpha>,
|
||||
List<RelativeAbsolute>,
|
||||
List<SelectiveColorChoice>,
|
||||
List<TonalRange>,
|
||||
List<AdjustmentChannel>,
|
||||
List<HueSaturationRange>,
|
||||
List<XY>,
|
||||
List<ScaleType>,
|
||||
List<ReferencePoint>,
|
||||
List<CentroidType>,
|
||||
@@ -294,13 +299,11 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
|
||||
Item<TextDenomination>,
|
||||
Item<DesaturateMethod>,
|
||||
Item<RedGreenBlue>,
|
||||
Item<RedGreenBlueAlpha>,
|
||||
Item<RelativeAbsolute>,
|
||||
Item<SelectiveColorChoice>,
|
||||
Item<TonalRange>,
|
||||
Item<AdjustmentChannel>,
|
||||
Item<HueSaturationRange>,
|
||||
Item<XY>,
|
||||
Item<ScaleType>,
|
||||
Item<ReferencePoint>,
|
||||
Item<CentroidType>,
|
||||
@@ -1034,13 +1037,11 @@ impl_table_item_layout_for_choice_enum!(
|
||||
TextDenomination,
|
||||
DesaturateMethod,
|
||||
RedGreenBlue,
|
||||
RedGreenBlueAlpha,
|
||||
RelativeAbsolute,
|
||||
SelectiveColorChoice,
|
||||
TonalRange,
|
||||
AdjustmentChannel,
|
||||
HueSaturationRange,
|
||||
XY,
|
||||
ScaleType,
|
||||
CentroidType,
|
||||
BooleanOperation,
|
||||
@@ -1092,108 +1093,83 @@ impl TableItemLayout for NodeId {
|
||||
fn identifier(&self) -> String {
|
||||
format!("Node {self}")
|
||||
}
|
||||
// Override so the breadcrumb uses the same resolved display name as the value button, instead of the bare-ID fallback `identifier()` returns.
|
||||
// Override so the breadcrumb uses the node's resolved display name instead of the bare-ID fallback `identifier()` returns
|
||||
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
data.breadcrumbs.push(node_id_display_label(*self, data.network_interface, &data.node_lookup_network_path));
|
||||
self.value_page(data)
|
||||
}
|
||||
// The value's label resolves the node's display name via the network interface so the button reads as the name shown
|
||||
// in the Node Graph / Layers panels. The lookup uses `data.node_lookup_network_path` (set by the enclosing
|
||||
// `List<NodeId>` if rendering a path) so the resolution succeeds at any nesting depth. The button's icon
|
||||
// signals layer-vs-node kind. Falls back to "Node {id}" with no icon if the lookup misses.
|
||||
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
let label = node_id_display_label(*self, data.network_interface, &data.node_lookup_network_path);
|
||||
let mut button = TextButton::new(label)
|
||||
.on_update(move |_| DataPanelMessage::PushToElementPath { step: target.clone() }.into())
|
||||
.narrow(true);
|
||||
if data.network_interface.node_metadata(self, &data.node_lookup_network_path).is_some() {
|
||||
let icon = if data.network_interface.is_layer(self, &data.node_lookup_network_path) { "Layer" } else { "Node" };
|
||||
button = button.icon(icon);
|
||||
}
|
||||
vec![button.widget_instance()]
|
||||
}
|
||||
// The value page shows the node's kind, name (editable), lock/visibility toggles, and a "Select Layer/Node" action button.
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
// Shown inline as the node's icon, name, a button to select it, and visibility and lock toggles. The lookups use
|
||||
// `data.node_lookup_network_path` (set by the enclosing `List<NodeId>` if rendering a path) so they resolve at any nesting depth.
|
||||
fn value_widgets(&self, _target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
let node_id = *self;
|
||||
let network_interface = data.network_interface;
|
||||
let network_path = data.node_lookup_network_path.clone();
|
||||
let known = data.network_interface.node_metadata(&node_id, &network_path).is_some();
|
||||
let is_layer = known && data.network_interface.is_layer(&node_id, &network_path);
|
||||
let name = if known {
|
||||
data.network_interface.display_name(&node_id, &network_path)
|
||||
} else {
|
||||
"(node not found)".to_string()
|
||||
};
|
||||
let kind_widget = if known {
|
||||
IconLabel::new(if is_layer { "Layer" } else { "Node" }).widget_instance()
|
||||
} else {
|
||||
TextLabel::new("-").widget_instance()
|
||||
};
|
||||
let name_widget = if known {
|
||||
let path_for_rename = network_path.clone();
|
||||
TextInput::new(name)
|
||||
.tooltip_description(if is_layer { "Name of this layer." } else { "Name of this node." })
|
||||
.on_update(move |text_input| {
|
||||
NodeGraphMessage::SetDisplayName {
|
||||
|
||||
// An ID that no longer maps to a real node has nothing to show but itself
|
||||
if network_interface.node_metadata(&node_id, &network_path).is_none() {
|
||||
return vec![TextLabel::new(node_id_display_label(node_id, network_interface, &network_path)).widget_instance()];
|
||||
}
|
||||
|
||||
let is_layer = network_interface.is_layer(&node_id, &network_path);
|
||||
let is_locked = network_interface.is_locked(&node_id, &network_path);
|
||||
let is_visible = network_interface.is_visible(&node_id, &network_path);
|
||||
let icon = network_interface.node_icon(&node_id, &network_path);
|
||||
let name = network_interface.display_name(&node_id, &network_path);
|
||||
let in_open_network = network_path == data.selection_network_path;
|
||||
let already_selected = network_interface.selected_nodes_in_nested_network(&network_path).is_some_and(|selected| selected.0 == [node_id]);
|
||||
|
||||
let path_for_visibility = network_path.clone();
|
||||
let path_for_lock = network_path;
|
||||
|
||||
vec![
|
||||
IconLabel::new(icon).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
TextLabel::new(name).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
IconButton::new("SelectAll", 24)
|
||||
.disabled(!in_open_network || already_selected)
|
||||
.tooltip_label(if is_layer { "Select Layer" } else { "Select Node" })
|
||||
.tooltip_description(match (in_open_network, already_selected, is_layer) {
|
||||
(false, _, true) => "This layer is not in the part of the graph currently open.",
|
||||
(false, _, false) => "This node is not in the part of the graph currently open.",
|
||||
(true, true, true) => "This is already the selected layer.",
|
||||
(true, true, false) => "This is already the selected node.",
|
||||
(true, false, _) => "",
|
||||
})
|
||||
// Starts from the root of the newly selected node's data, since the current drill-down path means nothing there
|
||||
.on_update(move |_| Message::Batched {
|
||||
messages: Box::new([DataPanelMessage::TruncateElementPath { len: 0 }.into(), NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] }.into()]),
|
||||
})
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
IconButton::new(if is_visible { "EyeVisible" } else { "EyeHidden" }, 24)
|
||||
.hover_icon(if is_visible { "EyeHide" } else { "EyeShow" })
|
||||
.tooltip_label(if is_visible { "Hide" } else { "Show" })
|
||||
.on_update(move |_| {
|
||||
NodeGraphMessage::ToggleVisibility {
|
||||
node_id,
|
||||
network_path: path_for_rename.clone(),
|
||||
alias: text_input.value.clone(),
|
||||
skip_adding_history_step: false,
|
||||
network_path: path_for_visibility.clone(),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.max_width(200)
|
||||
.widget_instance()
|
||||
} else {
|
||||
TextLabel::new(name).widget_instance()
|
||||
};
|
||||
|
||||
let mut header = vec![kind_widget, Separator::new(SeparatorStyle::Related).widget_instance(), name_widget];
|
||||
|
||||
if known {
|
||||
let is_locked = data.network_interface.is_locked(&node_id, &network_path);
|
||||
let is_visible = data.network_interface.is_visible(&node_id, &network_path);
|
||||
|
||||
let path_for_lock = network_path.clone();
|
||||
let path_for_visibility = network_path.clone();
|
||||
|
||||
header.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
header.push(
|
||||
IconButton::new(if is_locked { "PadlockLocked" } else { "PadlockUnlocked" }, 24)
|
||||
.hover_icon(if is_locked { "PadlockUnlocked" } else { "PadlockLocked" })
|
||||
.tooltip_label(if is_locked { "Unlock" } else { "Lock" })
|
||||
.on_update(move |_| {
|
||||
NodeGraphMessage::ToggleLocked {
|
||||
node_id,
|
||||
network_path: path_for_lock.clone(),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
);
|
||||
header.push(
|
||||
IconButton::new(if is_visible { "EyeVisible" } else { "EyeHidden" }, 24)
|
||||
.hover_icon(if is_visible { "EyeHide" } else { "EyeShow" })
|
||||
.tooltip_label(if is_visible { "Hide" } else { "Show" })
|
||||
.on_update(move |_| {
|
||||
NodeGraphMessage::ToggleVisibility {
|
||||
node_id,
|
||||
network_path: path_for_visibility.clone(),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
);
|
||||
}
|
||||
|
||||
header.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
header.push(
|
||||
TextButton::new(if is_layer { "Select Layer" } else { "Select Node" })
|
||||
.tooltip_description(if is_layer { "Click to select this layer." } else { "Click to select this node." })
|
||||
.on_update(move |_| NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] }.into())
|
||||
.widget_instance(),
|
||||
);
|
||||
|
||||
vec![LayoutGroup::row(header)]
|
||||
IconButton::new(if is_locked { "PadlockLocked" } else { "PadlockUnlocked" }, 24)
|
||||
.hover_icon(if is_locked { "PadlockUnlocked" } else { "PadlockLocked" })
|
||||
.disabled(!is_layer)
|
||||
.tooltip_label(if is_locked { "Unlock" } else { "Lock" })
|
||||
.tooltip_description(if is_layer { "" } else { "Only layers can be locked." })
|
||||
.on_update(move |_| {
|
||||
NodeGraphMessage::ToggleLocked {
|
||||
node_id,
|
||||
network_path: path_for_lock.clone(),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
]
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(self.value_widgets(PathStep::Element(0), data))]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1251,13 +1227,11 @@ macro_rules! known_item_types {
|
||||
TextDenomination,
|
||||
DesaturateMethod,
|
||||
RedGreenBlue,
|
||||
RedGreenBlueAlpha,
|
||||
RelativeAbsolute,
|
||||
SelectiveColorChoice,
|
||||
TonalRange,
|
||||
AdjustmentChannel,
|
||||
HueSaturationRange,
|
||||
XY,
|
||||
ScaleType,
|
||||
ReferencePoint,
|
||||
CentroidType,
|
||||
|
||||
@@ -188,8 +188,8 @@ fn diff_attributes(out: &mut String, label: &str, stored: &document_graph_storag
|
||||
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));
|
||||
.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,
|
||||
|
||||
@@ -7,6 +7,7 @@ use crate::messages::portfolio::document::data_panel::DataPanelMessage;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::{OverlayContext, OverlaysType};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, GridSnapping};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{ChainNodeCopy, NodeTemplate};
|
||||
use crate::messages::portfolio::utility_types::PanelType;
|
||||
use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, IVec2, UVec2};
|
||||
@@ -89,6 +90,9 @@ pub enum DocumentMessage {
|
||||
GridVisibility {
|
||||
visible: bool,
|
||||
},
|
||||
LayersPanelHoverOverlays {
|
||||
context: OverlayContext,
|
||||
},
|
||||
BlendSelectedLayers,
|
||||
MorphSelectedLayers,
|
||||
ExpandFillStrokeOnSelectedLayers,
|
||||
@@ -103,6 +107,24 @@ pub enum DocumentMessage {
|
||||
ReorderPropertiesSection {
|
||||
node_id: NodeId,
|
||||
insert_index: usize,
|
||||
duplicate: bool,
|
||||
},
|
||||
MoveChainNodes {
|
||||
node_ids: Vec<NodeId>,
|
||||
layer: NodeId,
|
||||
insert_index: usize,
|
||||
},
|
||||
DuplicateChainNodes {
|
||||
node_ids: Vec<NodeId>,
|
||||
layer: NodeId,
|
||||
insert_index: usize,
|
||||
select_copies: bool,
|
||||
},
|
||||
PasteChainNodes {
|
||||
copies: Vec<ChainNodeCopy>,
|
||||
},
|
||||
PasteNodes {
|
||||
nodes: Vec<(NodeId, NodeTemplate)>,
|
||||
},
|
||||
MoveSelectedLayersToGroup {
|
||||
parent: LayerNodeIdentifier,
|
||||
@@ -162,6 +184,12 @@ pub enum DocumentMessage {
|
||||
ctrl: bool,
|
||||
shift: bool,
|
||||
},
|
||||
SelectChainNode {
|
||||
layer: NodeId,
|
||||
node_id: NodeId,
|
||||
ctrl: bool,
|
||||
shift: bool,
|
||||
},
|
||||
SetActivePanel {
|
||||
active_panel: PanelType,
|
||||
},
|
||||
@@ -171,6 +199,9 @@ pub enum DocumentMessage {
|
||||
SetGraphFadeArtwork {
|
||||
percentage: f64,
|
||||
},
|
||||
SetLayersPanelHoveredLayer {
|
||||
id: Option<NodeId>,
|
||||
},
|
||||
SetNodePinned {
|
||||
node_id: NodeId,
|
||||
pinned: bool,
|
||||
@@ -201,6 +232,10 @@ pub enum DocumentMessage {
|
||||
SetRenderMode {
|
||||
render_mode: RenderMode,
|
||||
},
|
||||
ShowNodeInGraph {
|
||||
node_id: NodeId,
|
||||
},
|
||||
ShowSelectionInGraph,
|
||||
AddTransaction,
|
||||
StartTransaction,
|
||||
EndTransaction,
|
||||
@@ -216,6 +251,7 @@ pub enum DocumentMessage {
|
||||
},
|
||||
ToggleNodePropertiesSectionExpanded {
|
||||
node_id: NodeId,
|
||||
recursive: bool,
|
||||
},
|
||||
ToggleSelectedVisibility,
|
||||
ToggleSelectedLocked,
|
||||
|
||||
@@ -17,18 +17,18 @@ use crate::messages::portfolio::document::data_panel::{DataPanelMessageContext,
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::{ModifyInputsContext, TransformIn};
|
||||
use crate::messages::portfolio::document::node_graph::NodeGraphMessageContext;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
||||
use crate::messages::portfolio::document::overlays::grid_overlays::{grid_overlay, overlay_options};
|
||||
use crate::messages::portfolio::document::overlays::utility_types::{OverlaysType, OverlaysVisibilitySettings, Pivot};
|
||||
use crate::messages::portfolio::document::properties_panel::properties_panel_message_handler::PropertiesPanelMessageContext;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
|
||||
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, PTZ};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate, OutputConnector};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, FlowType, InputConnector, NodeTemplate, OutputConnector};
|
||||
use crate::messages::portfolio::utility_types::PanelType;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::edit_target::EditTarget;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{self, get_blend_mode, get_fill, get_opacity};
|
||||
use crate::messages::tool::common_functionality::utility_functions::nudge_resize_bounds;
|
||||
use crate::messages::tool::tool_messages::select_tool::SelectToolPointerKeys;
|
||||
use crate::messages::tool::tool_messages::select_tool::{SelectToolPointerKeys, draw_layer_outline};
|
||||
use crate::messages::tool::tool_messages::tool_prelude::Key;
|
||||
use crate::messages::tool::utility_types::ToolType;
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
@@ -37,7 +37,7 @@ use document_graph_storage::Declarations;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::application_io::resource::ResourceId;
|
||||
use graph_craft::application_io::wgpu_available;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::value::{TaggedValue, deserialize_replacing_null_floats_with_zero};
|
||||
use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork};
|
||||
use graph_craft::list;
|
||||
use graphene_std::Cover;
|
||||
@@ -61,6 +61,7 @@ pub struct DocumentMessageContext<'a> {
|
||||
pub ipp: &'a InputPreprocessorMessageHandler,
|
||||
pub executor: &'a mut NodeGraphExecutor,
|
||||
pub current_tool: &'a ToolType,
|
||||
pub tool_edit_target: &'a EditTarget,
|
||||
pub preferences: &'a PreferencesMessageHandler,
|
||||
pub data_panel_open: bool,
|
||||
pub layers_panel_open: bool,
|
||||
@@ -70,6 +71,16 @@ pub struct DocumentMessageContext<'a> {
|
||||
pub fonts: &'a FontsMessageHandler,
|
||||
}
|
||||
|
||||
/// The selection split by how it's duplicated and copied.
|
||||
pub struct SelectionParts {
|
||||
/// The shallowest selected layers in the layer structure, which bring their content along.
|
||||
pub layers: Vec<LayerNodeIdentifier>,
|
||||
/// The selected reorderable nodes of other layers' chains, in the Layers panel's order.
|
||||
pub chain_nodes: Vec<NodeId>,
|
||||
/// Every other selected node, outside the content of the layers above.
|
||||
pub other_nodes: Vec<NodeId>,
|
||||
}
|
||||
|
||||
#[derive(derivative::Derivative, serde::Serialize, serde::Deserialize, ExtractField)]
|
||||
#[derivative(Clone, Debug)]
|
||||
#[serde(default)]
|
||||
@@ -164,6 +175,12 @@ pub struct DocumentMessageHandler {
|
||||
/// If the user clicks or Ctrl-clicks one layer, it becomes the start of the range selection and then Shift-clicking another layer selects all layers between the start and end.
|
||||
#[serde(skip)]
|
||||
layer_range_selection_reference: Option<LayerNodeIdentifier>,
|
||||
/// The ID of the chain node at the start of a range selection among a layer's chain node icons in the Layers panel, working like `layer_range_selection_reference`.
|
||||
#[serde(skip)]
|
||||
chain_node_range_selection_reference: Option<NodeId>,
|
||||
/// The layer under the pointer in the Layers panel, which gets a hover outline in the viewport.
|
||||
#[serde(skip)]
|
||||
layers_panel_hovered_layer: Option<LayerNodeIdentifier>,
|
||||
/// Whether or not the editor has executed the network to render the document yet. If this is opened as an inactive tab, it won't be loaded initially because the active tab is prioritized.
|
||||
#[serde(skip)]
|
||||
pub is_loaded: bool,
|
||||
@@ -209,6 +226,8 @@ impl Default for DocumentMessageHandler {
|
||||
saved_hash: None,
|
||||
auto_saved_hash: None,
|
||||
layer_range_selection_reference: None,
|
||||
chain_node_range_selection_reference: None,
|
||||
layers_panel_hovered_layer: None,
|
||||
is_loaded: false,
|
||||
}
|
||||
}
|
||||
@@ -223,6 +242,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
executor,
|
||||
viewport,
|
||||
current_tool,
|
||||
tool_edit_target,
|
||||
preferences,
|
||||
data_panel_open,
|
||||
layers_panel_open,
|
||||
@@ -254,6 +274,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
.process_message(message, responses, OverlaysMessageContext { visibility_settings, viewport });
|
||||
}
|
||||
DocumentMessage::PropertiesPanel(message) => {
|
||||
let wire_in_progress_output_types = self.node_graph_handler.wire_in_progress_output_types(&self.network_interface, &self.selection_network_path);
|
||||
let context = PropertiesPanelMessageContext {
|
||||
executor,
|
||||
document_id,
|
||||
@@ -264,6 +285,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
fonts,
|
||||
properties_panel_open,
|
||||
properties_panel_collapsed_sections: &self.properties_panel_collapsed_sections,
|
||||
wire_in_progress_output_types: &wire_in_progress_output_types,
|
||||
};
|
||||
self.properties_panel_message_handler.process_message(message, responses, context);
|
||||
}
|
||||
@@ -273,6 +295,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
responses,
|
||||
DataPanelMessageContext {
|
||||
network_interface: &mut self.network_interface,
|
||||
selection_network_path: &self.selection_network_path,
|
||||
data_panel_open,
|
||||
},
|
||||
);
|
||||
@@ -294,6 +317,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
navigation_handler: &self.navigation_handler,
|
||||
preferences,
|
||||
layers_panel_open,
|
||||
tool_edit_target,
|
||||
viewport,
|
||||
},
|
||||
);
|
||||
@@ -316,7 +340,13 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
AlignAxis::X => DVec2::X,
|
||||
AlignAxis::Y => DVec2::Y,
|
||||
};
|
||||
let Some(combined_box) = self.network_interface.selected_layers_artwork_bounding_box_viewport() else {
|
||||
// Locked layers stay put but still count toward the bounds the others align to
|
||||
let selected_nodes = self.network_interface.selected_nodes();
|
||||
let Some(combined_box) = selected_nodes
|
||||
.selected_visible_layers(&self.network_interface)
|
||||
.filter_map(|layer| self.metadata().bounding_box_viewport(layer))
|
||||
.reduce(Quad::combine_bounds)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -327,7 +357,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
};
|
||||
|
||||
let mut added_transaction = false;
|
||||
for layer in self.network_interface.selected_nodes().selected_unlocked_layers(&self.network_interface) {
|
||||
for layer in selected_nodes.selected_visible_and_unlocked_layers(&self.network_interface) {
|
||||
let Some(bbox) = self.metadata().bounding_box_viewport(layer) else {
|
||||
continue;
|
||||
};
|
||||
@@ -364,15 +394,15 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
layout: Layout::default(),
|
||||
layout_target: LayoutTarget::LayersPanelControlLeftBar,
|
||||
});
|
||||
responses.add(LayoutMessage::SendLayout {
|
||||
layout: Layout::default(),
|
||||
layout_target: LayoutTarget::LayersPanelControlRightBar,
|
||||
});
|
||||
|
||||
// Clear the bottom bar
|
||||
responses.add(LayoutMessage::SendLayout {
|
||||
layout: Layout::default(),
|
||||
layout_target: LayoutTarget::LayersPanelBottomBar,
|
||||
layout_target: LayoutTarget::LayersPanelBottomLeftBar,
|
||||
});
|
||||
responses.add(LayoutMessage::SendLayout {
|
||||
layout: Layout::default(),
|
||||
layout_target: LayoutTarget::LayersPanelBottomRightBar,
|
||||
});
|
||||
}
|
||||
DocumentMessage::CreateEmptyFolder => {
|
||||
@@ -412,6 +442,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
DocumentMessage::DeselectAllLayers => {
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![] });
|
||||
self.layer_range_selection_reference = None;
|
||||
self.chain_node_range_selection_reference = None;
|
||||
}
|
||||
DocumentMessage::DocumentHistoryBackward => self.undo_with_history(document_id, viewport, preferences.validate_storage_round_trip, responses),
|
||||
DocumentMessage::DocumentHistoryForward => self.redo_with_history(document_id, viewport, preferences.validate_storage_round_trip, responses),
|
||||
@@ -464,11 +495,15 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
}
|
||||
DocumentMessage::DuplicateSelectedLayers => {
|
||||
let SelectionParts { mut layers, chain_nodes, other_nodes } = self.partition_selection();
|
||||
if layers.is_empty() && chain_nodes.is_empty() && other_nodes.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
|
||||
// Layers in the layer structure are copied with their content into the stack beside their originals
|
||||
let mut new_dragging = Vec::new();
|
||||
let mut layers = self.network_interface.shallowest_unique_layers(&[]).collect::<Vec<_>>();
|
||||
|
||||
layers.sort_by_key(|layer| {
|
||||
let Some(parent) = layer.parent(self.metadata()) else { return usize::MAX };
|
||||
DocumentMessageHandler::get_calculated_insert_index(self.metadata(), &SelectedNodes(vec![layer.to_node()]), parent)
|
||||
@@ -488,7 +523,24 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
let nodes = new_dragging.iter().map(|layer| layer.to_node()).collect();
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes });
|
||||
|
||||
// Each chain node goes beside itself in its chain, as if duplicated one at a time
|
||||
for node_id in chain_nodes {
|
||||
responses.add(NodeGraphMessage::DuplicateChainNodes {
|
||||
node_ids: vec![node_id],
|
||||
destination: None,
|
||||
select_copies: true,
|
||||
});
|
||||
}
|
||||
|
||||
// The other nodes go into their primary flow, or loose when in none
|
||||
if !other_nodes.is_empty() {
|
||||
responses.add(NodeGraphMessage::DuplicateNodesInFlow { node_ids: other_nodes });
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
}
|
||||
DocumentMessage::DuplicateSelectedLayersTo { parent, insert_index } => {
|
||||
if !self.selection_network_path.is_empty() {
|
||||
@@ -582,11 +634,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
// Abort wire in progress of being connected
|
||||
else if self.node_graph_handler.wire_in_progress_from_connector.is_some() {
|
||||
self.node_graph_handler.wire_in_progress_from_connector = None;
|
||||
self.node_graph_handler.wire_in_progress_to_connector = None;
|
||||
self.node_graph_handler.wire_in_progress_type = FrontendGraphDataType::General;
|
||||
|
||||
responses.add(FrontendMessage::UpdateWirePathInProgress { wire_path: None });
|
||||
self.node_graph_handler.end_wire_in_progress(&mut self.network_interface, &self.selection_network_path, responses);
|
||||
responses.add(DocumentMessage::AbortTransaction);
|
||||
}
|
||||
// Close the context menu if it's open
|
||||
@@ -623,11 +671,11 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
FlipAxis::X => DVec2::new(-1., 1.),
|
||||
FlipAxis::Y => DVec2::new(1., -1.),
|
||||
};
|
||||
if let Some([min, max]) = self.network_interface.selected_unlocked_layers_bounding_box_viewport() {
|
||||
if let Some([min, max]) = self.network_interface.selected_visible_and_unlocked_layers_bounding_box_viewport() {
|
||||
let center = (max + min) / 2.;
|
||||
let bbox_trans = DAffine2::from_translation(-center);
|
||||
let mut added_transaction = false;
|
||||
for layer in self.network_interface.selected_nodes().selected_unlocked_layers(&self.network_interface) {
|
||||
for layer in self.network_interface.selected_nodes().selected_visible_and_unlocked_layers(&self.network_interface) {
|
||||
if !added_transaction {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
added_transaction = true;
|
||||
@@ -643,14 +691,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
DocumentMessage::RotateSelectedLayers { degrees } => {
|
||||
// Get the bounding box of selected layers in viewport space
|
||||
if let Some([min, max]) = self.network_interface.selected_unlocked_layers_bounding_box_viewport() {
|
||||
if let Some([min, max]) = self.network_interface.selected_visible_and_unlocked_layers_bounding_box_viewport() {
|
||||
// Calculate the center of the bounding box to use as rotation pivot
|
||||
let center = (max + min) / 2.;
|
||||
// Transform that moves pivot point to origin
|
||||
let bbox_trans = DAffine2::from_translation(-center);
|
||||
|
||||
let mut added_transaction = false;
|
||||
for layer in self.network_interface.selected_nodes().selected_unlocked_layers(&self.network_interface) {
|
||||
for layer in self.network_interface.selected_nodes().selected_visible_and_unlocked_layers(&self.network_interface) {
|
||||
if !added_transaction {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
added_transaction = true;
|
||||
@@ -714,6 +762,21 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.snapping_state.grid_snapping = visible;
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
}
|
||||
DocumentMessage::LayersPanelHoverOverlays { context: mut overlay_context } => {
|
||||
let Some(layer) = self.layers_panel_hovered_layer else { return };
|
||||
if !overlay_context.visibility_settings.hover_outline() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Outlined like the Select tool's hover, with groups and artboards shown by their bounding box
|
||||
if layer.has_children(self.metadata()) || self.network_interface.is_artboard(&layer.to_node(), &[]) {
|
||||
if let Some(bounds) = self.metadata().bounding_box_viewport(layer) {
|
||||
overlay_context.quad(Quad::from_box(bounds), None, None);
|
||||
}
|
||||
} else {
|
||||
draw_layer_outline(&mut overlay_context, self, layer, None);
|
||||
}
|
||||
}
|
||||
DocumentMessage::BlendSelectedLayers => {
|
||||
self.group_selected_layers(GroupFolderType::Blend, responses);
|
||||
}
|
||||
@@ -744,7 +807,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
DocumentMessage::MoveSelectedLayersTo { parent, insert_index } => {
|
||||
self.move_selected_layers_to(parent, insert_index, responses);
|
||||
}
|
||||
DocumentMessage::ReorderPropertiesSection { node_id, insert_index } => {
|
||||
DocumentMessage::ReorderPropertiesSection { node_id, insert_index, duplicate } => {
|
||||
// The Properties panel shows draggable sections in two cases, disambiguated by the current selection:
|
||||
// a single selected layer (reorder within its node chain) or no selection (reorder the pinned nodes).
|
||||
let selected_nodes = self.network_interface.selected_nodes_in_nested_network(&self.selection_network_path);
|
||||
@@ -763,20 +826,112 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
layers.sort();
|
||||
layers.dedup();
|
||||
|
||||
if layers.len() == 1 {
|
||||
// Reorder a node within the selected layer's chain by rewiring the graph
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::ReorderChainNode { node_id, insert_index });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
if let [layer] = *layers.as_slice() {
|
||||
let node_ids = vec![node_id];
|
||||
if duplicate {
|
||||
responses.add(DocumentMessage::DuplicateChainNodes {
|
||||
node_ids,
|
||||
layer,
|
||||
insert_index,
|
||||
select_copies: false,
|
||||
});
|
||||
} else {
|
||||
responses.add(DocumentMessage::MoveChainNodes { node_ids, layer, insert_index });
|
||||
}
|
||||
} else if layers.is_empty() && nodes.is_empty() {
|
||||
// Reorder a pinned node, which is purely a Properties panel display order (no graph rerender needed)
|
||||
// Reorder a pinned node, which is purely a Properties panel display order (no graph rerender needed, and nothing to duplicate into)
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::ReorderPinnedNode { node_id, insert_index });
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
}
|
||||
}
|
||||
DocumentMessage::MoveChainNodes { node_ids, layer, insert_index } => {
|
||||
// Move nodes within their layer's chain, or into another layer's, by rewiring the graph
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::MoveChainNodes { node_ids, layer, insert_index });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
}
|
||||
DocumentMessage::DuplicateChainNodes {
|
||||
node_ids,
|
||||
layer,
|
||||
insert_index,
|
||||
select_copies,
|
||||
} => {
|
||||
// Insert copies of nodes into a layer's chain by rewiring the graph
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
if select_copies {
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: Vec::new() });
|
||||
}
|
||||
responses.add(NodeGraphMessage::DuplicateChainNodes {
|
||||
node_ids,
|
||||
destination: Some((layer, insert_index)),
|
||||
select_copies,
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
}
|
||||
DocumentMessage::PasteChainNodes { copies } => {
|
||||
// Layers and their chains live in the document network, so a nested one open in the graph has no chain to paste into
|
||||
let (chain_nodes, layers) = if self.selection_network_path.is_empty() {
|
||||
let layers = self.network_interface.selected_nodes().selected_layers(self.metadata()).map(|layer| layer.to_node()).collect();
|
||||
(self.selected_reorderable_chain_nodes(), layers)
|
||||
} else {
|
||||
(Vec::new(), Vec::new())
|
||||
};
|
||||
|
||||
// Selected chain nodes interleave with the copies: over the same selection that was copied, each node gets its own copy beside it (like duplicating),
|
||||
// and over a different selection of the same size, the copies pair with those nodes in order. Otherwise, all the copies go beside every selected node.
|
||||
let mut insertions = Vec::new();
|
||||
let same_selection = chain_nodes.len() == copies.len() && copies.iter().all(|copy| chain_nodes.contains(©.source));
|
||||
if same_selection {
|
||||
insertions.extend(copies.iter().map(|copy| (ChainInsertionPoint::BesideNode(copy.source), vec![copy.clone()])));
|
||||
} else if chain_nodes.len() == copies.len() {
|
||||
insertions.extend(chain_nodes.iter().zip(&copies).map(|(node_id, copy)| (ChainInsertionPoint::BesideNode(*node_id), vec![copy.clone()])));
|
||||
} else {
|
||||
insertions.extend(chain_nodes.iter().map(|node_id| (ChainInsertionPoint::BesideNode(*node_id), copies.clone())));
|
||||
}
|
||||
|
||||
// Each selected layer gets all the copies at the end of its chain
|
||||
insertions.extend(layers.into_iter().map(|layer| (ChainInsertionPoint::BesideLayer(layer), copies.clone())));
|
||||
|
||||
// With no chain to go in, such as over an empty selection, the copies are pasted loose into the graph and shown there
|
||||
if insertions.is_empty() {
|
||||
let nodes = copies.into_iter().map(|copy| (copy.source, copy.into_loose_template())).collect();
|
||||
responses.add(NodeGraphMessage::InsertNodes { nodes });
|
||||
responses.add(DocumentMessage::ShowSelectionInGraph);
|
||||
return;
|
||||
}
|
||||
|
||||
// The pasted copies become the selection
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: Vec::new() });
|
||||
for (target, copies) in insertions {
|
||||
responses.add(NodeGraphMessage::PasteIntoChain { target, copies });
|
||||
}
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
}
|
||||
DocumentMessage::PasteNodes { nodes } => {
|
||||
// Over the same selection they were copied from, nodes are duplicated into their flow, and otherwise they're pasted loose into the graph and shown there
|
||||
let other_nodes = self.partition_selection().other_nodes;
|
||||
let copied = nodes.iter().map(|(node_id, _)| *node_id).collect::<HashSet<_>>();
|
||||
let selected = self.with_layer_content(&other_nodes).into_iter().collect::<HashSet<_>>();
|
||||
if !copied.is_empty() && copied == selected {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: Vec::new() });
|
||||
responses.add(NodeGraphMessage::DuplicateNodesInFlow { node_ids: other_nodes });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
return;
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::InsertNodes { nodes });
|
||||
responses.add(DocumentMessage::ShowSelectionInGraph);
|
||||
}
|
||||
DocumentMessage::MoveSelectedLayersToGroup { parent } => {
|
||||
// Group all shallowest unique selected layers in order
|
||||
let all_layers_to_group_sorted = self.network_interface.shallowest_unique_layers_sorted(&self.selection_network_path);
|
||||
@@ -1165,7 +1320,13 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
}
|
||||
DocumentMessage::SelectAllLayers => {
|
||||
if !self.overlays_visibility_settings.selection_outline() {
|
||||
// In the graph, select every node of the network it shows
|
||||
if self.graph_view_overlay_open {
|
||||
let Some(network_metadata) = self.network_interface.network_metadata(&self.selection_network_path) else {
|
||||
return;
|
||||
};
|
||||
let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect();
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1255,6 +1416,38 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
}
|
||||
}
|
||||
DocumentMessage::SelectChainNode { layer, node_id, ctrl, shift } => {
|
||||
// The layer's chain as listed beside it in the Layers panel, which a Shift-click range runs along
|
||||
let chain = self.network_interface.layer_chain_nodes(layer, &[]);
|
||||
|
||||
let selected_nodes = self.network_interface.selected_nodes();
|
||||
let range_start = self
|
||||
.chain_node_range_selection_reference
|
||||
.filter(|start| shift && selected_nodes.selected_nodes().any(|selected| selected == start))
|
||||
.and_then(|start| chain.iter().position(|id| *id == start));
|
||||
let clicked = chain.iter().position(|id| *id == node_id);
|
||||
|
||||
// Shift-clicking selects the range from the still-selected last clicked node in this chain, adding it with Ctrl
|
||||
if let (Some(start), Some(end)) = (range_start, clicked) {
|
||||
let nodes = chain[start.min(end)..=start.max(end)].to_vec();
|
||||
if ctrl {
|
||||
responses.add(NodeGraphMessage::SelectedNodesAdd { nodes });
|
||||
} else {
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, Ctrl-clicking toggles the node's selection while a plain click selects only it, either way starting a new range
|
||||
if !ctrl {
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] });
|
||||
} else if self.network_interface.selected_nodes().selected_nodes().any(|selected| *selected == node_id) {
|
||||
responses.add(NodeGraphMessage::SelectedNodesRemove { nodes: vec![node_id] });
|
||||
} else {
|
||||
responses.add(NodeGraphMessage::SelectedNodesAdd { nodes: vec![node_id] });
|
||||
}
|
||||
self.chain_node_range_selection_reference = Some(node_id);
|
||||
}
|
||||
DocumentMessage::SetActivePanel { active_panel } => {
|
||||
match active_panel {
|
||||
PanelType::Document => {
|
||||
@@ -1280,6 +1473,13 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.graph_fade_artwork_percentage = percentage;
|
||||
responses.add(FrontendMessage::UpdateGraphFadeArtwork { percentage });
|
||||
}
|
||||
DocumentMessage::SetLayersPanelHoveredLayer { id } => {
|
||||
let layer = id.filter(|id| self.network_interface.is_layer(id, &[])).map(LayerNodeIdentifier::new_unchecked);
|
||||
if layer != self.layers_panel_hovered_layer {
|
||||
self.layers_panel_hovered_layer = layer;
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
}
|
||||
}
|
||||
DocumentMessage::SetNodePinned { node_id, pinned } => {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::SetPinned { node_id, pinned });
|
||||
@@ -1349,6 +1549,23 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.render_mode = render_mode;
|
||||
responses.add_front(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
DocumentMessage::ShowNodeInGraph { node_id } => {
|
||||
// The node is in the document network, so the graph first leaves any nested network it's showing
|
||||
if !self.breadcrumb_network_path.is_empty() {
|
||||
responses.add(DocumentMessage::ExitNestedNetwork {
|
||||
steps_back: self.breadcrumb_network_path.len(),
|
||||
});
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] });
|
||||
responses.add(DocumentMessage::ShowSelectionInGraph);
|
||||
}
|
||||
DocumentMessage::ShowSelectionInGraph => {
|
||||
// Opens the graph on the selection, centered at 100% zoom
|
||||
responses.add(DocumentMessage::GraphViewOverlay { open: true });
|
||||
responses.add(NavigationMessage::FitViewportToSelection);
|
||||
responses.add(DocumentMessage::ZoomCanvasTo100Percent);
|
||||
}
|
||||
DocumentMessage::AddTransaction => {
|
||||
// Reverse order since they are added to the front
|
||||
responses.add_front(DocumentMessage::CommitTransaction);
|
||||
@@ -1435,12 +1652,27 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
DocumentMessage::ToggleNodePropertiesSectionExpanded { node_id } => {
|
||||
if let Some(index) = self.properties_panel_collapsed_sections.iter().position(|id| *id == node_id) {
|
||||
self.properties_panel_collapsed_sections.remove(index);
|
||||
} else {
|
||||
self.properties_panel_collapsed_sections.push(node_id);
|
||||
DocumentMessage::ToggleNodePropertiesSectionExpanded { node_id, recursive } => {
|
||||
let expand = self.properties_panel_collapsed_sections.contains(&node_id);
|
||||
|
||||
// Recursively, every section in the chain follows along, from its layer back to where another layer begins
|
||||
let network_path = &self.selection_network_path;
|
||||
let chain = recursive
|
||||
.then(|| self.network_interface.downstream_layer_for_chain_node(&node_id, network_path))
|
||||
.flatten()
|
||||
.map(|layer| std::iter::once(layer).chain(self.network_interface.layer_chain_nodes(layer, network_path)).collect::<Vec<_>>())
|
||||
// A node that only leads into a chain from the side, or into no layer at all, isn't part of one
|
||||
.filter(|chain| chain.contains(&node_id));
|
||||
let node_ids = chain.unwrap_or_else(|| vec![node_id]);
|
||||
|
||||
for node_id in node_ids {
|
||||
if expand {
|
||||
self.properties_panel_collapsed_sections.retain(|id| *id != node_id);
|
||||
} else if !self.properties_panel_collapsed_sections.contains(&node_id) {
|
||||
self.properties_panel_collapsed_sections.push(node_id);
|
||||
}
|
||||
}
|
||||
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
}
|
||||
DocumentMessage::ToggleSelectedLocked => responses.add(NodeGraphMessage::ToggleSelectedLocked),
|
||||
@@ -1565,20 +1797,21 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
log::error!("Ungrouping selected layers is only supported for the Document Network");
|
||||
return;
|
||||
}
|
||||
|
||||
// Artboards can't be ungrouped
|
||||
let folders: Vec<_> = self
|
||||
.network_interface
|
||||
.folders_sorted_by_most_nested(&self.selection_network_path)
|
||||
.into_iter()
|
||||
.filter(|&folder| folder != LayerNodeIdentifier::ROOT_PARENT && !self.network_interface.is_artboard(&folder.to_node(), &self.selection_network_path))
|
||||
.collect();
|
||||
if folders.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
|
||||
let folder_paths = self.network_interface.folders_sorted_by_most_nested(&self.selection_network_path);
|
||||
for folder in folder_paths {
|
||||
if folder == LayerNodeIdentifier::ROOT_PARENT {
|
||||
log::error!("ROOT_PARENT cannot be selected when ungrouping selected layers");
|
||||
continue;
|
||||
}
|
||||
|
||||
// Cannot ungroup artboard
|
||||
if self.network_interface.is_artboard(&folder.to_node(), &self.selection_network_path) {
|
||||
return;
|
||||
}
|
||||
|
||||
for folder in folders {
|
||||
responses.add(DocumentMessage::UngroupLayer { layer: folder });
|
||||
}
|
||||
|
||||
@@ -1639,6 +1872,13 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
} else {
|
||||
// The artwork behind the graph can be navigated too, so rerender it if its view changed
|
||||
let artwork_transform = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
|
||||
if artwork_transform != self.network_interface.document_metadata().document_to_viewport {
|
||||
self.network_interface.set_document_to_viewport_transform(artwork_transform);
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
let Some(network_metadata) = self.network_interface.network_metadata(&self.breadcrumb_network_path) else {
|
||||
return;
|
||||
};
|
||||
@@ -1776,11 +2016,20 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
common.extend(actions!(DocumentMessageDiscriminant::SaveDocumentAs));
|
||||
|
||||
// Deleting, duplicating, and hiding apply to any selected nodes, not just layers, such as chain nodes selected in the Layers panel
|
||||
if self.network_interface.selected_nodes().has_selected_nodes() {
|
||||
common.extend(actions!(DocumentMessageDiscriminant;
|
||||
DeleteSelectedLayers,
|
||||
DuplicateSelectedLayers,
|
||||
));
|
||||
if !self.graph_view_overlay_open {
|
||||
common.extend(actions!(DocumentMessageDiscriminant::ToggleSelectedVisibility));
|
||||
}
|
||||
}
|
||||
|
||||
// Additional actions if there are any selected layers
|
||||
if self.network_interface.selected_nodes().selected_layers(self.metadata()).next().is_some() {
|
||||
let mut select = actions!(DocumentMessageDiscriminant;
|
||||
DeleteSelectedLayers,
|
||||
DuplicateSelectedLayers,
|
||||
GroupSelectedLayers,
|
||||
BlendSelectedLayers,
|
||||
MorphSelectedLayers,
|
||||
@@ -1792,10 +2041,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
ToggleSelectedLocked
|
||||
);
|
||||
if !self.graph_view_overlay_open {
|
||||
select.extend(actions!(DocumentMessageDiscriminant;
|
||||
NudgeSelectedLayers,
|
||||
ToggleSelectedVisibility,
|
||||
));
|
||||
select.extend(actions!(DocumentMessageDiscriminant::NudgeSelectedLayers));
|
||||
}
|
||||
common.extend(select);
|
||||
}
|
||||
@@ -2174,7 +2420,7 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
pub fn deserialize_document(serialized_content: &str) -> Result<Self, EditorError> {
|
||||
let document_message_handler = serde_json::from_str::<DocumentMessageHandler>(serialized_content)
|
||||
let document_message_handler = deserialize_replacing_null_floats_with_zero::<DocumentMessageHandler>(serialized_content)
|
||||
.or_else(|e| {
|
||||
log::warn!("Failed to directly load document with the following error: {e}. Trying old DocumentMessageHandler.");
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
@@ -2571,6 +2817,72 @@ impl DocumentMessageHandler {
|
||||
.unwrap_or_else(|| self.network_interface.all_artboards().iter().next().copied().unwrap_or(LayerNodeIdentifier::ROOT_PARENT))
|
||||
}
|
||||
|
||||
/// The selection split the way it's duplicated and copied. Inside a nested network open in the graph, every selected node counts among the other nodes.
|
||||
pub fn partition_selection(&self) -> SelectionParts {
|
||||
let selected_nodes = self.network_interface.selected_nodes_in_nested_network(&self.selection_network_path).unwrap_or_default();
|
||||
let selected_nodes = selected_nodes.selected_nodes().copied().collect::<Vec<_>>();
|
||||
if !self.selection_network_path.is_empty() {
|
||||
return SelectionParts {
|
||||
layers: Vec::new(),
|
||||
chain_nodes: Vec::new(),
|
||||
other_nodes: selected_nodes,
|
||||
};
|
||||
}
|
||||
|
||||
let layers = self.network_interface.shallowest_unique_layers(&[]).collect::<Vec<_>>();
|
||||
let layer_nodes = layers.iter().map(|layer| layer.to_node()).collect::<Vec<_>>();
|
||||
let mut other_nodes = selected_nodes.into_iter().filter(|node_id| !layer_nodes.contains(node_id)).collect::<Vec<_>>();
|
||||
|
||||
// Usually only layers are selected, which skips walking their content
|
||||
let mut chain_nodes = Vec::new();
|
||||
if !other_nodes.is_empty() {
|
||||
let layer_content = self
|
||||
.network_interface
|
||||
.upstream_flow_back_from_nodes(layer_nodes, &[], FlowType::LayerChildrenUpstreamFlow)
|
||||
.collect::<HashSet<_>>();
|
||||
other_nodes.retain(|node_id| !layer_content.contains(node_id));
|
||||
|
||||
chain_nodes = self.selected_reorderable_chain_nodes().into_iter().filter(|node_id| other_nodes.contains(node_id)).collect();
|
||||
other_nodes.retain(|node_id| !chain_nodes.contains(node_id));
|
||||
}
|
||||
|
||||
SelectionParts { layers, chain_nodes, other_nodes }
|
||||
}
|
||||
|
||||
/// The given nodes along with the content of any layers among them, in the network open in the graph.
|
||||
pub fn with_layer_content(&self, node_ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let layers = node_ids
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|node_id| self.network_interface.is_layer(node_id, &self.selection_network_path))
|
||||
.collect();
|
||||
let content = self
|
||||
.network_interface
|
||||
.upstream_flow_back_from_nodes(layers, &self.selection_network_path, FlowType::LayerChildrenUpstreamFlow);
|
||||
|
||||
node_ids.iter().copied().chain(content).collect::<HashSet<_>>().into_iter().collect()
|
||||
}
|
||||
|
||||
/// The selected nodes that can be reordered in layers' chains, ordered by their layer's place in the Layers panel, then from the layer outward.
|
||||
pub fn selected_reorderable_chain_nodes(&self) -> Vec<NodeId> {
|
||||
let selected_nodes = self.network_interface.selected_nodes().selected_nodes().copied().collect::<HashSet<_>>();
|
||||
|
||||
// Only walk the layers' chains, in O(nodes in all chains), when something other than layers is selected
|
||||
if selected_nodes.iter().all(|node_id| self.network_interface.is_layer(node_id, &[])) {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let mut chain_nodes = Vec::new();
|
||||
for layer in self.metadata().all_layers() {
|
||||
for node_id in self.network_interface.reorderable_chain(layer.to_node(), &[]) {
|
||||
if selected_nodes.contains(&node_id) && !chain_nodes.contains(&node_id) {
|
||||
chain_nodes.push(node_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
chain_nodes
|
||||
}
|
||||
|
||||
pub fn get_calculated_insert_index(metadata: &DocumentMetadata, selected_nodes: &SelectedNodes, parent: LayerNodeIdentifier) -> usize {
|
||||
parent
|
||||
.children(metadata)
|
||||
@@ -3512,18 +3824,6 @@ impl DocumentMessageHandler {
|
||||
})
|
||||
.collect();
|
||||
|
||||
let has_selection = self.network_interface.selected_nodes().selected_layers(self.metadata()).next().is_some();
|
||||
let selection_all_visible = self
|
||||
.network_interface
|
||||
.selected_nodes()
|
||||
.selected_layers(self.metadata())
|
||||
.all(|layer| self.network_interface.is_visible(&layer.to_node(), &[]));
|
||||
let selection_all_locked = self
|
||||
.network_interface
|
||||
.selected_nodes()
|
||||
.selected_layers(self.metadata())
|
||||
.all(|layer| self.network_interface.is_locked(&layer.to_node(), &[]));
|
||||
|
||||
let widgets = vec![
|
||||
DropdownInput::new(blend_mode_menu_entries)
|
||||
.selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list_svg_subset()).map(|index| index as u32))
|
||||
@@ -3577,34 +3877,10 @@ impl DocumentMessageHandler {
|
||||
.tooltip_label("Fill Opacity")
|
||||
.widget_instance(),
|
||||
];
|
||||
let layers_panel_control_bar_left = Layout(vec![LayoutGroup::row(widgets)]);
|
||||
|
||||
let widgets = vec![
|
||||
IconButton::new(if selection_all_locked { "PadlockLocked" } else { "PadlockUnlocked" }, 24)
|
||||
.hover_icon(if selection_all_locked { "PadlockUnlocked" } else { "PadlockLocked" })
|
||||
.tooltip_label(if selection_all_locked { "Unlock Selected" } else { "Lock Selected" })
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::ToggleSelectedLocked))
|
||||
.on_update(|_| NodeGraphMessage::ToggleSelectedLocked.into())
|
||||
.disabled(!has_selection)
|
||||
.widget_instance(),
|
||||
IconButton::new(if selection_all_visible { "EyeVisible" } else { "EyeHidden" }, 24)
|
||||
.hover_icon(if selection_all_visible { "EyeHide" } else { "EyeShow" })
|
||||
.tooltip_label(if selection_all_visible { "Hide Selected" } else { "Show Selected" })
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::ToggleSelectedVisibility))
|
||||
.on_update(|_| DocumentMessage::ToggleSelectedVisibility.into())
|
||||
.disabled(!has_selection)
|
||||
.widget_instance(),
|
||||
];
|
||||
let layers_panel_control_bar_right = Layout(vec![LayoutGroup::row(widgets)]);
|
||||
|
||||
responses.add(LayoutMessage::SendLayout {
|
||||
layout: layers_panel_control_bar_left,
|
||||
layout: Layout(vec![LayoutGroup::row(widgets)]),
|
||||
layout_target: LayoutTarget::LayersPanelControlLeftBar,
|
||||
});
|
||||
responses.add(LayoutMessage::SendLayout {
|
||||
layout: layers_panel_control_bar_right,
|
||||
layout_target: LayoutTarget::LayersPanelControlRightBar,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn update_layers_panel_bottom_bar_widgets(&mut self, layers_panel_open: bool, responses: &mut VecDeque<Message>) {
|
||||
@@ -3619,6 +3895,31 @@ impl DocumentMessageHandler {
|
||||
let has_multiple_selection = selected_layers.next().is_some();
|
||||
for _ in selected_layers {}
|
||||
|
||||
// Visibility applies to every selected node, layer or not, while locking applies to layers
|
||||
let selection_all_visible = selected_nodes.selected_nodes().all(|node_id| self.network_interface.is_visible(node_id, &[]));
|
||||
let selection_all_locked = selected_nodes.selected_layers(self.metadata()).all(|layer| self.network_interface.is_locked(&layer.to_node(), &[]));
|
||||
|
||||
let widgets = vec![
|
||||
IconButton::new(if selection_all_visible { "EyeVisible" } else { "EyeHidden" }, 24)
|
||||
.hover_icon(if selection_all_visible { "EyeHide" } else { "EyeShow" })
|
||||
.tooltip_label(if selection_all_visible { "Hide Selected" } else { "Show Selected" })
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::ToggleSelectedVisibility))
|
||||
.on_update(|_| DocumentMessage::ToggleSelectedVisibility.into())
|
||||
.disabled(!selected_nodes.has_selected_nodes())
|
||||
.widget_instance(),
|
||||
IconButton::new(if selection_all_locked { "PadlockLocked" } else { "PadlockUnlocked" }, 24)
|
||||
.hover_icon(if selection_all_locked { "PadlockUnlocked" } else { "PadlockLocked" })
|
||||
.tooltip_label(if selection_all_locked { "Unlock Selected" } else { "Lock Selected" })
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::ToggleSelectedLocked))
|
||||
.on_update(|_| NodeGraphMessage::ToggleSelectedLocked.into())
|
||||
.disabled(!has_selection)
|
||||
.widget_instance(),
|
||||
];
|
||||
responses.add(LayoutMessage::SendLayout {
|
||||
layout: Layout(vec![LayoutGroup::row(widgets)]),
|
||||
layout_target: LayoutTarget::LayersPanelBottomLeftBar,
|
||||
});
|
||||
|
||||
let widgets = vec![
|
||||
PopoverButton::new()
|
||||
.icon("Node")
|
||||
@@ -3664,6 +3965,7 @@ impl DocumentMessageHandler {
|
||||
let group_folder_type = GroupFolderType::Layer;
|
||||
DocumentMessage::GroupSelectedLayers { group_folder_type }.into()
|
||||
})
|
||||
.drag_drop_kinds(DragDropKinds::Layers)
|
||||
.disabled(!has_selection)
|
||||
.widget_instance(),
|
||||
IconButton::new("NewLayer", 24)
|
||||
@@ -3671,18 +3973,21 @@ impl DocumentMessageHandler {
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::CreateEmptyFolder))
|
||||
.on_update(|_| DocumentMessage::CreateEmptyFolder.into())
|
||||
.on_drag_drop(|_| DocumentMessage::DuplicateSelectedLayers.into())
|
||||
.drag_drop_kinds(DragDropKinds::LayersAndChainNodes)
|
||||
.disabled(!has_selection && selected_nodes.has_selected_nodes())
|
||||
.widget_instance(),
|
||||
IconButton::new("Trash", 24)
|
||||
.tooltip_label("Delete Selected")
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::DeleteSelectedLayers))
|
||||
.on_update(|_| DocumentMessage::DeleteSelectedLayers.into())
|
||||
.on_drag_drop(|_| DocumentMessage::DeleteSelectedLayers.into())
|
||||
.disabled(!has_selection)
|
||||
.drag_drop_kinds(DragDropKinds::LayersAndChainNodes)
|
||||
.disabled(!selected_nodes.has_selected_nodes())
|
||||
.widget_instance(),
|
||||
];
|
||||
responses.add(LayoutMessage::SendLayout {
|
||||
layout: Layout(vec![LayoutGroup::row(widgets)]),
|
||||
layout_target: LayoutTarget::LayersPanelBottomBar,
|
||||
layout_target: LayoutTarget::LayersPanelBottomRightBar,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4127,6 +4432,37 @@ mod document_message_handler_tests {
|
||||
assert!(selected_nodes.selected_layers_contains(layers[2], document.metadata()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn select_all_selects_every_node_in_the_graph_but_only_layers_outside_it() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
editor.handle_message(DocumentMessage::DeselectAllLayers).await;
|
||||
|
||||
editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await;
|
||||
editor.handle_message(DocumentMessage::SelectAllLayers).await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let all_nodes: HashSet<_> = document.network_interface.document_network().nodes.keys().copied().collect();
|
||||
let selected: HashSet<_> = document.network_interface.selected_nodes().selected_nodes().copied().collect();
|
||||
assert!(
|
||||
all_nodes.iter().any(|node_id| !document.network_interface.is_layer(node_id, &[])),
|
||||
"The rectangle should bring non-layer nodes"
|
||||
);
|
||||
assert_eq!(selected, all_nodes, "In the graph, Select All should select every node");
|
||||
|
||||
editor.handle_message(DocumentMessage::GraphViewOverlay { open: false }).await;
|
||||
editor.handle_message(DocumentMessage::SelectAllLayers).await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let selected: Vec<_> = document.network_interface.selected_nodes().selected_nodes().copied().collect();
|
||||
assert!(!selected.is_empty(), "Outside the graph, Select All should select the layer");
|
||||
assert!(
|
||||
selected.iter().all(|node_id| document.network_interface.is_layer(node_id, &[])),
|
||||
"Outside the graph, Select All should select only layers"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_layer_rearrangement() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
@@ -4368,7 +4704,7 @@ mod document_message_handler_tests {
|
||||
})
|
||||
.await;
|
||||
|
||||
let instrumented = editor.eval_graph().await.unwrap();
|
||||
let instrumented = editor.eval_graph_until_finished().await.unwrap();
|
||||
|
||||
// The emptiness guards keep these assertions honest: a wrong `Output` type on `grab_all_input` yields no records at all, which would otherwise pass without checking anything
|
||||
let base_lengths: Vec<usize> = instrumented
|
||||
@@ -4389,4 +4725,33 @@ mod document_message_handler_tests {
|
||||
.count();
|
||||
assert_eq!(phantom_count, 0, "No stacked element should be a phantom None graphic");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn converting_to_an_infinite_canvas_adds_a_locked_background_at_the_bottom() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::NewArtboard {
|
||||
id: NodeId::new(),
|
||||
location: DVec2::ZERO,
|
||||
dimensions: DVec2::splat(200.),
|
||||
background: Color::WHITE,
|
||||
clip: true,
|
||||
})
|
||||
.await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
|
||||
editor.handle_message(DocumentMessage::RemoveArtboards).await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let network_interface = &document.network_interface;
|
||||
let root_layers: Vec<_> = LayerNodeIdentifier::ROOT_PARENT.children(document.metadata()).collect();
|
||||
assert!(root_layers.iter().all(|layer| !network_interface.is_artboard(&layer.to_node(), &[])), "No artboards should remain");
|
||||
assert_eq!(root_layers.len(), 2, "The artboard should become a plain layer above the background");
|
||||
assert_eq!(root_layers[0].children(document.metadata()).count(), 1, "The artboard's content should stay in its replacement layer");
|
||||
|
||||
let background = root_layers[1].to_node();
|
||||
assert_eq!(network_interface.display_name(&background, &[]), "Background");
|
||||
assert!(network_interface.is_locked(&background, &[]), "The background should be locked");
|
||||
}
|
||||
}
|
||||
+7
-1
@@ -7,7 +7,7 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface, OutputConnector};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::CollapsedLayers;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_clip_mode;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{get_clip_mode, new_background_layer};
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
@@ -413,6 +413,9 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
return;
|
||||
}
|
||||
|
||||
// Each artboard becomes one plain layer in its place, so the root stack keeps this many layers
|
||||
let root_layer_count = LayerNodeIdentifier::ROOT_PARENT.children(network_interface.document_metadata()).count();
|
||||
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::DeleteNodes {
|
||||
node_ids: network_interface.all_artboards().iter().map(|layer_node| layer_node.to_node()).collect(),
|
||||
@@ -490,6 +493,9 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
});
|
||||
}
|
||||
|
||||
// Like a new infinite canvas document, the artwork sits on a white background instead of transparency
|
||||
new_background_layer(root_layer_count, responses);
|
||||
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SelectedNodesUpdated);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
|
||||
@@ -19,4 +19,4 @@ pub(crate) use document_history::{CursorMoveError, DocumentHistory};
|
||||
#[doc(inline)]
|
||||
pub use document_message::{DocumentMessage, DocumentMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use document_message_handler::{DocumentMessageContext, DocumentMessageHandler};
|
||||
pub use document_message_handler::{DocumentMessageContext, DocumentMessageHandler, SelectionParts};
|
||||
@@ -6,21 +6,22 @@ use glam::DVec2;
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum NavigationMessage {
|
||||
// Messages
|
||||
BeginCanvasPan,
|
||||
BeginCanvasPan { artwork_behind_graph: bool },
|
||||
BeginCanvasTilt { was_dispatched_from_menu: bool },
|
||||
BeginCanvasZoom,
|
||||
BeginCanvasZoom { artwork_behind_graph: bool },
|
||||
CanvasPan { delta: DVec2 },
|
||||
CanvasPanAbortPrepare { x_not_y_axis: bool },
|
||||
CanvasPanAbort { x_not_y_axis: bool },
|
||||
CanvasPanByViewportFraction { delta: DVec2 },
|
||||
CanvasPanMouseWheel { use_y_as_x: bool },
|
||||
CanvasPanMouseWheel { use_y_as_x: bool, artwork_behind_graph: bool },
|
||||
CanvasTiltResetAndZoomTo100Percent,
|
||||
CanvasTiltSet { angle_radians: f64 },
|
||||
CanvasZoomDecrease { center_on_mouse: bool },
|
||||
CanvasZoomIncrease { center_on_mouse: bool },
|
||||
CanvasZoomMouseWheel,
|
||||
CanvasZoomMouseWheel { artwork_behind_graph: bool },
|
||||
CanvasZoomSet { zoom_factor: f64 },
|
||||
CanvasFlip,
|
||||
EndArtworkBehindGraph,
|
||||
EndCanvasPTZ { abort_transform: bool },
|
||||
EndCanvasPTZWithClick { commit_key: Key },
|
||||
FitViewportToBounds { bounds: [DVec2; 2], prevent_zoom_past_100: bool },
|
||||
|
||||
@@ -31,6 +31,8 @@ pub struct NavigationMessageHandler {
|
||||
mouse_position: ViewportPosition,
|
||||
finish_operation_with_click: bool,
|
||||
abortable_pan_start: Option<f64>,
|
||||
/// Whether the current drag navigates the artwork behind the open node graph, rather than the graph itself.
|
||||
artwork_behind_graph: bool,
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
@@ -46,6 +48,17 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
viewport,
|
||||
} = context;
|
||||
|
||||
// Until the drag or wheel scroll ends, act on the artwork as if the graph were closed
|
||||
if let NavigationMessage::BeginCanvasPan { artwork_behind_graph }
|
||||
| NavigationMessage::BeginCanvasZoom { artwork_behind_graph }
|
||||
| NavigationMessage::CanvasPanMouseWheel { artwork_behind_graph, .. }
|
||||
| NavigationMessage::CanvasZoomMouseWheel { artwork_behind_graph } = &message
|
||||
{
|
||||
self.artwork_behind_graph = *artwork_behind_graph && graph_view_overlay_open;
|
||||
}
|
||||
let graph_view_overlay_open = graph_view_overlay_open && !self.artwork_behind_graph;
|
||||
let wheel_scroll_on_artwork = self.artwork_behind_graph && matches!(message, NavigationMessage::CanvasPanMouseWheel { .. } | NavigationMessage::CanvasZoomMouseWheel { .. });
|
||||
|
||||
fn get_ptz<'a>(document_ptz: &'a PTZ, network_interface: &'a NodeNetworkInterface, graph_view_overlay_open: bool, breadcrumb_network_path: &[NodeId]) -> Option<&'a PTZ> {
|
||||
if !graph_view_overlay_open {
|
||||
Some(document_ptz)
|
||||
@@ -74,7 +87,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
let old_zoom = ptz.zoom();
|
||||
|
||||
match message {
|
||||
NavigationMessage::BeginCanvasPan => {
|
||||
NavigationMessage::BeginCanvasPan { .. } => {
|
||||
responses.add(FrontendMessage::UpdateMouseCursor { cursor: MouseCursorIcon::Grabbing });
|
||||
|
||||
HintData(vec![HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()])]).send_layout(responses);
|
||||
@@ -89,9 +102,9 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
let Some(ptz) = get_ptz(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
|
||||
return;
|
||||
};
|
||||
// If the node graph is open, prevent tilt and instead start panning
|
||||
// The node graph can't be tilted, so the tilt shortcut pans the artwork behind it instead
|
||||
if graph_view_overlay_open {
|
||||
responses.add(NavigationMessage::BeginCanvasPan);
|
||||
responses.add(NavigationMessage::BeginCanvasPan { artwork_behind_graph: true });
|
||||
} else {
|
||||
responses.add(FrontendMessage::UpdateMouseCursor { cursor: MouseCursorIcon::Default });
|
||||
HintData(vec![
|
||||
@@ -110,7 +123,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
self.finish_operation_with_click = was_dispatched_from_menu;
|
||||
}
|
||||
}
|
||||
NavigationMessage::BeginCanvasZoom => {
|
||||
NavigationMessage::BeginCanvasZoom { .. } => {
|
||||
let Some(ptz) = get_ptz(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
|
||||
return;
|
||||
};
|
||||
@@ -174,7 +187,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
ptz.pan += transformed_delta;
|
||||
responses.add(DocumentMessage::PTZUpdate);
|
||||
}
|
||||
NavigationMessage::CanvasPanMouseWheel { use_y_as_x } => {
|
||||
NavigationMessage::CanvasPanMouseWheel { use_y_as_x, .. } => {
|
||||
// On Mac, the OS already converts Shift+scroll into horizontal scrolling
|
||||
let delta = if use_y_as_x && !Editor::environment().is_mac() {
|
||||
(ipp.mouse.scroll_delta.y, 0.).into()
|
||||
@@ -231,7 +244,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
}
|
||||
responses.add(NavigationMessage::CanvasZoomSet { zoom_factor: new_scale });
|
||||
}
|
||||
NavigationMessage::CanvasZoomMouseWheel => {
|
||||
NavigationMessage::CanvasZoomMouseWheel { .. } => {
|
||||
let scroll = ipp.mouse.scroll_delta.scroll_delta();
|
||||
let mut zoom_factor = 1. + scroll.abs() * preferences.viewport_zoom_wheel_rate;
|
||||
if ipp.mouse.scroll_delta.y > 0. {
|
||||
@@ -291,6 +304,9 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
responses.add(MenuBarMessage::SendLayout);
|
||||
responses.add(PortfolioMessage::UpdateDocumentWidgets);
|
||||
}
|
||||
NavigationMessage::EndArtworkBehindGraph => {
|
||||
self.artwork_behind_graph = false;
|
||||
}
|
||||
NavigationMessage::EndCanvasPTZ { abort_transform } => {
|
||||
let Some(ptz) = get_ptz_mut(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
|
||||
log::error!("Could not get mutable PTZ in EndCanvasPTZ");
|
||||
@@ -323,6 +339,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
}
|
||||
// Reset the navigation operation now that it's done
|
||||
self.navigation_operation = NavigationOperation::None;
|
||||
self.artwork_behind_graph = false;
|
||||
|
||||
// Send the final messages to close out the operation
|
||||
responses.add(EventMessage::CanvasTransformed);
|
||||
@@ -482,6 +499,11 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
self.mouse_position = ipp.mouse.position;
|
||||
}
|
||||
}
|
||||
|
||||
// Queued behind the wheel scroll's pan or zoom, which still need the artwork as their target
|
||||
if wheel_scroll_on_artwork {
|
||||
responses.add(NavigationMessage::EndArtworkBehindGraph);
|
||||
}
|
||||
}
|
||||
|
||||
fn actions(&self) -> ActionList {
|
||||
|
||||
@@ -3,6 +3,7 @@ mod document_node_derive;
|
||||
use super::node_properties::choice::enum_choice;
|
||||
use super::node_properties::{self, ParameterWidgetsInfo, SliderRange};
|
||||
use super::utility_types::{FrontendNodeType, InputTypeConstraint};
|
||||
use crate::messages::frontend::IconName;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
InputMetadata, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, Vec2InputSettings, WidgetOverride,
|
||||
@@ -15,9 +16,7 @@ use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::value::*;
|
||||
use graph_craft::document::*;
|
||||
use graph_craft::{concrete, list};
|
||||
use graphene_std::extract_xy::XY;
|
||||
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType, RedGreenBlueAlpha};
|
||||
use graphene_std::raster_types::{CPU, Raster};
|
||||
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType};
|
||||
#[allow(unused_imports)]
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::Vector;
|
||||
@@ -35,6 +34,8 @@ pub struct NodePropertiesContext<'a> {
|
||||
pub document_name: &'a str,
|
||||
/// The node IDs whose Properties panel sections the user has collapsed.
|
||||
pub properties_panel_collapsed_sections: &'a [NodeId],
|
||||
/// The types a wire being dragged from an output could carry, so compatible inputs can be marked as drop targets.
|
||||
pub wire_in_progress_output_types: &'a [Type],
|
||||
}
|
||||
|
||||
impl NodePropertiesContext<'_> {
|
||||
@@ -130,6 +131,9 @@ pub struct DocumentNodeDefinition {
|
||||
/// Definition specific data. In order for the editor to access this data, the reference will be used.
|
||||
pub category: &'static str,
|
||||
|
||||
/// Name of the icon, from the frontend's icon registry, shown for this node in the node graph.
|
||||
pub icon: Option<&'static str>,
|
||||
|
||||
/// User-facing description of the node's functionality.
|
||||
pub description: Cow<'static, str>,
|
||||
|
||||
@@ -152,6 +156,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Custom Node",
|
||||
category: "General",
|
||||
icon: Some("NodeCustomNode"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
|
||||
..Default::default()
|
||||
@@ -162,6 +167,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Merge",
|
||||
category: "General",
|
||||
icon: Some("NodeMerge"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(5), 0)],
|
||||
@@ -233,6 +239,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Artboard",
|
||||
category: "General",
|
||||
icon: Some("NodeArtboard"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(4), 0)],
|
||||
@@ -340,6 +347,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Blend",
|
||||
category: "Vector",
|
||||
icon: Some("NodeBlend"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(16), 0)],
|
||||
@@ -514,6 +522,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Origins to Polyline",
|
||||
category: "Vector",
|
||||
icon: Some("NodeOriginsToPolyline"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(7), 0)],
|
||||
@@ -593,6 +602,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Load Image",
|
||||
category: "Web Request",
|
||||
icon: Some("NodeLoadImage"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
@@ -628,6 +638,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Rasterize",
|
||||
category: "Raster",
|
||||
icon: Some("NodeRasterize"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(2), 0)],
|
||||
@@ -676,117 +687,10 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
description: Cow::Borrowed("TODO"),
|
||||
properties: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Split Channels",
|
||||
category: "Raster: Channels",
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![
|
||||
NodeInput::value(TaggedValue::None, false),
|
||||
NodeInput::node(NodeId(0), 0),
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
NodeInput::node(NodeId(2), 0),
|
||||
NodeInput::node(NodeId(3), 0),
|
||||
],
|
||||
nodes: [
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::import(list!(Raster<CPU>), 0),
|
||||
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Red), false),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
|
||||
call_argument: generic!(T),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::import(list!(Raster<CPU>), 0),
|
||||
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Green), false),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
|
||||
call_argument: generic!(T),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::import(list!(Raster<CPU>), 0),
|
||||
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Blue), false),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
|
||||
call_argument: generic!(T),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 4)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::import(list!(Raster<CPU>), 0),
|
||||
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Alpha), false),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
|
||||
call_argument: generic!(T),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 6)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::type_default(list!(Raster<CPU>), true)],
|
||||
input_metadata: vec![("Image", "TODO").into()],
|
||||
output_names: vec!["".to_string(), "Red".to_string(), "Green".to_string(), "Blue".to_string(), "Alpha".to_string()],
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("TODO"),
|
||||
properties: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Split Vec2",
|
||||
category: "Math: Vec2",
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::value(TaggedValue::None, false), NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::import(item!(DVec2), 0), NodeInput::value(TaggedValue::XY(XY::X), false)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(extract_xy::extract_xy::IDENTIFIER),
|
||||
call_argument: generic!(T),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::import(item!(DVec2), 0), NodeInput::value(TaggedValue::XY(XY::Y), false)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(extract_xy::extract_xy::IDENTIFIER),
|
||||
call_argument: generic!(T),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), true)],
|
||||
input_metadata: vec![("Vec2", "TODO").into()],
|
||||
output_names: vec!["".to_string(), "X".to_string(), "Y".to_string()],
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed(
|
||||
"Decomposes the X and Y components of a vec2.\n\
|
||||
\n\
|
||||
The inverse of this node is **Combine Vec2**, which composes a vec2 from its X and Y components.",
|
||||
),
|
||||
properties: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Extract",
|
||||
category: "",
|
||||
icon: None,
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Extract,
|
||||
inputs: vec![NodeInput::type_default(concrete!(DocumentNode), true)],
|
||||
@@ -800,6 +704,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Regex Find",
|
||||
category: "Text: Regex",
|
||||
icon: Some("NodeRegexFind"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![
|
||||
@@ -872,6 +777,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Path",
|
||||
category: "Vector",
|
||||
icon: Some("NodePath"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
@@ -1671,7 +1577,7 @@ impl InputTypeConstraint {
|
||||
pub fn collect_node_types() -> Vec<FrontendNodeType> {
|
||||
DOCUMENT_NODE_TYPES
|
||||
.iter()
|
||||
.filter(|(_, definition)| !definition.category.is_empty())
|
||||
.filter(|(_, definition)| !registry::is_hidden_category(definition.category))
|
||||
.map(|(identifier, definition)| {
|
||||
let mut name = definition.node_template.display_name.clone();
|
||||
if name.is_empty() {
|
||||
@@ -1699,6 +1605,13 @@ pub fn collect_node_descriptions() -> Vec<(String, String)> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn collect_node_icons() -> Vec<(String, IconName)> {
|
||||
DOCUMENT_NODE_TYPES
|
||||
.iter()
|
||||
.filter_map(|(identifier, definition)| Some((identifier.serialized(), definition.icon?.to_string())))
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl DocumentNodeDefinition {
|
||||
/// Converts the [DocumentNodeDefinition] type to a [NodeTemplate], using the provided `input_override` and falling back to the default inputs.
|
||||
/// `input_override` does not have to be the correct length.
|
||||
@@ -1751,8 +1664,6 @@ mod test {
|
||||
})
|
||||
.await;
|
||||
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
|
||||
|
||||
editor.eval_graph().await.expect("the Origins to Polyline chain should type-resolve and evaluate");
|
||||
}
|
||||
|
||||
// Guards the unconnected Path input, whose default must match the rank of the Morph connector it feeds
|
||||
@@ -1772,8 +1683,6 @@ mod test {
|
||||
})
|
||||
.await;
|
||||
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
|
||||
|
||||
editor.eval_graph().await.expect("the Blend network should type-resolve and evaluate");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+18
@@ -38,10 +38,12 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
let NodeMetadata {
|
||||
display_name,
|
||||
category,
|
||||
icon,
|
||||
fields,
|
||||
description,
|
||||
properties,
|
||||
context_features,
|
||||
output_fields,
|
||||
..
|
||||
} = metadata;
|
||||
|
||||
@@ -66,6 +68,20 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
};
|
||||
|
||||
let inputs = preprocessor::node_inputs(fields, first_node_io);
|
||||
|
||||
// A multi-output node names each output after its field, leaving the hidden primary output unnamed
|
||||
let output_names = output_fields
|
||||
.as_ref()
|
||||
.map(|destructure| {
|
||||
(0..destructure.number_of_outputs())
|
||||
.map(|output_index| {
|
||||
let field = destructure.field_index_for_output(output_index).and_then(|field_index| destructure.fields.get(field_index));
|
||||
field.map_or_else(String::new, |field| field.name.to_string())
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
definitions_map.insert(
|
||||
identifier,
|
||||
DocumentNodeDefinition {
|
||||
@@ -85,9 +101,11 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
RegistryWidgetOverride::Custom(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Custom(str.to_string())),
|
||||
})
|
||||
.collect(),
|
||||
output_names,
|
||||
..Default::default()
|
||||
},
|
||||
category,
|
||||
icon: *icon,
|
||||
description: Cow::Borrowed(description),
|
||||
properties: *properties,
|
||||
},
|
||||
|
||||
@@ -2,9 +2,9 @@ use super::utility_types::Direction;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::Key;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{ImportOrExport, InputConnector, NodeTemplate, OutputConnector};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, ChainNodeCopy, ImportOrExport, InputConnector, NodeTemplate, OutputConnector, RootNode};
|
||||
use crate::messages::prelude::*;
|
||||
use glam::IVec2;
|
||||
use glam::{DVec2, IVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graph_craft::proto::GraphErrors;
|
||||
@@ -61,6 +61,9 @@ pub enum NodeGraphMessage {
|
||||
input_connector: InputConnector,
|
||||
},
|
||||
DisconnectRootNode,
|
||||
SetRootNodeToRestore {
|
||||
root_node_to_restore: RootNode,
|
||||
},
|
||||
EnterNestedNetwork,
|
||||
DuplicateSelectedNodes,
|
||||
ExposeInput {
|
||||
@@ -94,10 +97,23 @@ pub enum NodeGraphMessage {
|
||||
node_id: NodeId,
|
||||
parent: LayerNodeIdentifier,
|
||||
},
|
||||
ReorderChainNode {
|
||||
node_id: NodeId,
|
||||
MoveChainNodes {
|
||||
node_ids: Vec<NodeId>,
|
||||
layer: NodeId,
|
||||
insert_index: usize,
|
||||
},
|
||||
DuplicateChainNodes {
|
||||
node_ids: Vec<NodeId>,
|
||||
destination: Option<(NodeId, usize)>,
|
||||
select_copies: bool,
|
||||
},
|
||||
DuplicateNodesInFlow {
|
||||
node_ids: Vec<NodeId>,
|
||||
},
|
||||
PasteIntoChain {
|
||||
target: ChainInsertionPoint,
|
||||
copies: Vec<ChainNodeCopy>,
|
||||
},
|
||||
ReorderPinnedNode {
|
||||
node_id: NodeId,
|
||||
insert_index: usize,
|
||||
@@ -121,6 +137,18 @@ pub enum NodeGraphMessage {
|
||||
PointerOutsideViewport {
|
||||
shift: Key,
|
||||
},
|
||||
/// Sent every frame while a dragged wire hovers a node, to expand it once the hover delay passes.
|
||||
WireHoverTick,
|
||||
/// Begins dragging a wire out of an input connector shown in the Properties panel.
|
||||
StartWireFromPropertiesPanel {
|
||||
input_connector: InputConnector,
|
||||
editor_position: DVec2,
|
||||
},
|
||||
/// Reports whether the wire in progress is over the Properties panel, and which input connector there it hovers (at its editor position).
|
||||
SetWirePropertiesPanelHover {
|
||||
hovering_panel: bool,
|
||||
target: Option<(InputConnector, DVec2)>,
|
||||
},
|
||||
ShakeNode,
|
||||
UpdateNodeGraphWidth,
|
||||
RemoveImport {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2,11 +2,12 @@
|
||||
|
||||
use super::document_node_definitions::{NODE_OVERRIDES, NodePropertiesContext};
|
||||
use super::utility_types::FrontendGraphDataType;
|
||||
use crate::messages::layout::utility_types::tooltip_markdown::{escape_markdown, markdown_code_block, markdown_code_span};
|
||||
use crate::messages::layout::utility_types::math_expression::{MathExpressionTokens, math_expression_error, math_expression_error_ranges, math_expression_tokens};
|
||||
use crate::messages::layout::utility_types::tooltip_markdown::{escape_markdown, markdown_code_span};
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface, type_feeds_connector};
|
||||
use crate::messages::portfolio::fonts::utility_types::FontCatalogStyle;
|
||||
use crate::messages::portfolio::ingest::utility_types::{IngestAction, TypeFilter};
|
||||
use crate::messages::prelude::*;
|
||||
@@ -20,10 +21,9 @@ use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, No
|
||||
use graph_craft::{Type, concrete, item};
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::extract_xy::XY;
|
||||
use graphene_std::raster::{
|
||||
AdjustmentChannel, BlendMode, CellularDistanceFunction, CellularReturnType, Color, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RedGreenBlueAlpha,
|
||||
RelativeAbsolute, SelectiveColorChoice, TonalRange,
|
||||
AdjustmentChannel, BlendMode, CellularDistanceFunction, CellularReturnType, Color, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RelativeAbsolute,
|
||||
SelectiveColorChoice, TonalRange,
|
||||
};
|
||||
use graphene_std::raster_types::{CPU, GPU, Image, Raster};
|
||||
use graphene_std::text::{Font, TextAlign};
|
||||
@@ -41,7 +41,7 @@ use graphene_std::vector::style::{
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||
use graphene_std::{Artboard, Graphic, Vector};
|
||||
use graphene_std::{NodeParameter, ParameterRef};
|
||||
use math_parser::parser::MessagePart;
|
||||
use math_parser::parser::{MessagePart, ParseError};
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub(crate) fn string_properties(text: &str) -> Vec<LayoutGroup> {
|
||||
@@ -82,10 +82,13 @@ pub fn commit_value<T>(_: &T) -> Message {
|
||||
DocumentMessage::AddTransaction.into()
|
||||
}
|
||||
|
||||
pub fn expose_widget(node_id: NodeId, index: usize, data_type: FrontendGraphDataType, exposed: bool) -> WidgetInstance {
|
||||
pub fn expose_widget(node_id: NodeId, index: usize, data_type: FrontendGraphDataType, exposed: bool, wire_drop_target: bool) -> WidgetInstance {
|
||||
ParameterExposeButton::new()
|
||||
.exposed(exposed)
|
||||
.data_type(data_type)
|
||||
.node_id(node_id)
|
||||
.input_index(index as u32)
|
||||
.wire_drop_target(wire_drop_target)
|
||||
.tooltip_description(if exposed {
|
||||
"Stop exposing this parameter as a node input in the graph."
|
||||
} else {
|
||||
@@ -153,6 +156,7 @@ pub fn start_widgets(parameter_widgets_info: &ParameterWidgetsInfo) -> Vec<Widge
|
||||
parameter_widgets_info.index,
|
||||
parameter_widgets_info.input_type,
|
||||
input.is_exposed(),
|
||||
parameter_widgets_info.wire_drop_target,
|
||||
));
|
||||
}
|
||||
widgets.push(
|
||||
@@ -348,8 +352,6 @@ pub(crate) fn property_from_type(node_id: NodeId, index: usize, ty: &Type, optio
|
||||
Some(x) if id_is::<GradientInterpolation>(x) => enum_choice::<GradientInterpolation>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RealTimeMode>(x) => enum_choice::<RealTimeMode>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RedGreenBlue>(x) => enum_choice::<RedGreenBlue>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RedGreenBlueAlpha>(x) => enum_choice::<RedGreenBlueAlpha>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<XY>(x) => enum_choice::<XY>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StringCapitalization>(x) => enum_choice::<StringCapitalization>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<TextDenomination>(x) => enum_choice::<TextDenomination>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<NoiseType>(x) => enum_choice::<NoiseType>().for_socket(default_info).property_row(),
|
||||
@@ -417,58 +419,55 @@ pub fn text_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<WidgetIn
|
||||
widgets
|
||||
}
|
||||
|
||||
/// A math expression's text field, with a warning icon in the assist area giving the error in its tooltip while the expression fails to parse.
|
||||
/// A math expression's typeset text field, with a warning icon in the assist area giving the error in its tooltip while the expression fails to parse.
|
||||
pub fn math_expression_widget(mut parameter_widgets_info: ParameterWidgetsInfo, accepts_reducers: bool) -> Vec<WidgetInstance> {
|
||||
let Some(TaggedValue::String(expression)) = parameter_widgets_info.input().and_then(|input| input.as_non_exposed_value()) else {
|
||||
return text_widget(parameter_widgets_info);
|
||||
};
|
||||
let Some(error) = math_expression_error(expression, accepts_reducers) else {
|
||||
return text_widget(parameter_widgets_info);
|
||||
};
|
||||
let error = math_expression_error(expression, accepts_reducers);
|
||||
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(expression, accepts_reducers);
|
||||
let input = MathExpressionInput::new(expression.clone())
|
||||
.tokens(tokens)
|
||||
.tooltips(tooltips)
|
||||
.accepts_reducers(accepts_reducers)
|
||||
.errors(math_expression_error_ranges(expression, error.as_ref()))
|
||||
.on_update(parameter_widgets_info.update_value(|x: &MathExpressionInput| TaggedValue::String(x.value.clone())))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance();
|
||||
|
||||
// The 12px icon is padded to a checkbox's 16px so the field still lines up with the rows around it
|
||||
// The icon holds the assist area, blank without an error so an edit making or fixing one leaves the field in place, and its 12px is
|
||||
// padded to a checkbox's 16px so the field lines up with the rows around it
|
||||
let icon = match &error {
|
||||
Some(error) => IconLabel::new("Warning")
|
||||
.tooltip_label("Invalid Math Expression")
|
||||
.tooltip_description(math_expression_error_description(error)),
|
||||
None => IconLabel::new("Empty12px"),
|
||||
};
|
||||
parameter_widgets_info.blank_assist = false;
|
||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
IconLabel::new("Warning").tooltip_label("Invalid Math Expression").tooltip_description(error).widget_instance(),
|
||||
icon.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextInput::new(expression.clone())
|
||||
.on_update(parameter_widgets_info.update_value(|x: &TextInput| TaggedValue::String(x.value.clone())))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
input,
|
||||
]);
|
||||
widgets
|
||||
}
|
||||
|
||||
/// Why a math expression fails to parse, as tooltip Markdown, or `None` when it parses. Where the node applies a lone operator or
|
||||
/// function name like `+` or `min` across its items, that counts as valid too. An error at a place in the expression repeats the
|
||||
/// expression with carets under that place, as a compiler does.
|
||||
fn math_expression_error(expression: &str, accepts_reducers: bool) -> Option<String> {
|
||||
// A blank expression is unfinished rather than wrong, so it goes unflagged like any empty field
|
||||
if expression.trim().is_empty() || (accepts_reducers && math_parser::reducer::classify_reducer(expression, math_parser::context::NothingMap).is_some()) {
|
||||
return None;
|
||||
}
|
||||
let error = math_parser::ast::Node::try_parse_from_str(expression).err()?;
|
||||
|
||||
/// A parse error's messages as tooltip Markdown, leaving the places they point at for the field to underline.
|
||||
fn math_expression_error_description(error: &ParseError) -> String {
|
||||
// The quoted code may be the expression's own text, so it goes in a span nothing inside can close, and the prose is escaped
|
||||
let messages = error.messages().iter().map(|message| {
|
||||
let parts = message.parts().iter().map(|part| match part {
|
||||
MessagePart::Text(text) => escape_markdown(text),
|
||||
MessagePart::Code(code) => markdown_code_span(code),
|
||||
});
|
||||
let prose = parts.collect::<String>();
|
||||
|
||||
// The carets and their label line up under the expression's characters, with one caret where the span is empty, like at the end of the input
|
||||
let Some(span) = message.span() else { return prose };
|
||||
let indent = " ".repeat(expression.get(..span.start).map_or(0, |text| text.chars().count()));
|
||||
let carets = "^".repeat(expression.get(span.start..span.end).map_or(0, |text| text.chars().count()).max(1));
|
||||
format!("{prose}\n{}", markdown_code_block(&format!("{expression}\n{indent}{carets}\n{indent}error here")))
|
||||
parts.collect::<String>()
|
||||
});
|
||||
Some(messages.collect::<Vec<_>>().join("\n"))
|
||||
messages.collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
|
||||
pub fn text_area_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<WidgetInstance> {
|
||||
@@ -3150,20 +3149,19 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
|
||||
implementation_name
|
||||
};
|
||||
|
||||
let description = context
|
||||
let definition = context
|
||||
.network_interface
|
||||
.reference(&node_id, context.selection_network_path)
|
||||
.as_ref()
|
||||
.and_then(|identifier| resolve_document_node_type(identifier))
|
||||
.map(|definition| definition.description.to_string())
|
||||
.filter(|string| string != "TODO")
|
||||
.unwrap_or_default();
|
||||
.and_then(|identifier| resolve_document_node_type(identifier));
|
||||
let icon = Some(context.network_interface.node_icon(&node_id, context.selection_network_path).to_string());
|
||||
let description = definition.map(|definition| definition.description.to_string()).filter(|string| string != "TODO").unwrap_or_default();
|
||||
|
||||
let visible = context.network_interface.is_visible(&node_id, context.selection_network_path);
|
||||
let pinned = context.network_interface.is_pinned(&node_id, context.selection_network_path);
|
||||
let expanded = !context.properties_panel_collapsed_sections.contains(&node_id);
|
||||
|
||||
LayoutGroup::section(name, description, visible, pinned, expanded, node_id.0, Layout(layout))
|
||||
LayoutGroup::section(name, icon, 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
|
||||
@@ -3243,7 +3241,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
_ => None,
|
||||
};
|
||||
let backup_stops = match document_node.input_value(BackupGradientInput) {
|
||||
Some(TaggedValue::GradientRamp(ramp)) => ramp.clone(),
|
||||
Some(TaggedValue::GradientRamp(ramp)) if !ramp.stops.is_empty() => ramp.clone(),
|
||||
_ => GradientRamp::black_to_white(),
|
||||
};
|
||||
(backup_color, backup_stops)
|
||||
@@ -3522,6 +3520,8 @@ pub struct ParameterWidgetsInfo<'a> {
|
||||
input_type: FrontendGraphDataType,
|
||||
blank_assist: bool,
|
||||
exposable: bool,
|
||||
/// Whether a wire being dragged from an output could be connected to this parameter.
|
||||
wire_drop_target: bool,
|
||||
fonts: &'a FontsMessageHandler,
|
||||
}
|
||||
|
||||
@@ -3555,6 +3555,22 @@ impl<'a> ParameterWidgetsInfo<'a> {
|
||||
.displayed_type();
|
||||
let document_node = context.network_interface.document_node(&node_id, context.selection_network_path);
|
||||
|
||||
let wire_drop_target = !context.wire_in_progress_output_types.is_empty()
|
||||
&& context
|
||||
.network_interface
|
||||
.potential_valid_input_types(&InputConnector::node_at_index(node_id, index), context.selection_network_path)
|
||||
.iter()
|
||||
.any(|valid_type| context.wire_in_progress_output_types.iter().any(|output_type| type_feeds_connector(output_type, valid_type)));
|
||||
if !context.wire_in_progress_output_types.is_empty() {
|
||||
let valid_types = context
|
||||
.network_interface
|
||||
.potential_valid_input_types(&InputConnector::node_at_index(node_id, index), context.selection_network_path)
|
||||
.iter()
|
||||
.map(|valid_type| valid_type.nested_type().clone())
|
||||
.collect::<Vec<_>>();
|
||||
log::debug!("[wire-drag] Input {name} ({node_id}, {index}) has valid types {valid_types:?}, drop target: {wire_drop_target}");
|
||||
}
|
||||
|
||||
ParameterWidgetsInfo {
|
||||
document_id: context.document_id,
|
||||
network_interface: context.network_interface,
|
||||
@@ -3569,6 +3585,7 @@ impl<'a> ParameterWidgetsInfo<'a> {
|
||||
input_type,
|
||||
blank_assist,
|
||||
exposable: true,
|
||||
wire_drop_target,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3767,33 +3784,48 @@ mod tests {
|
||||
assert_ne!(wire_element(&TaggedValue::Integer(0).ty()), wire_element(&item!(f64)));
|
||||
}
|
||||
|
||||
fn description(expression: &str) -> Option<String> {
|
||||
math_expression_error(expression, false).map(|error| math_expression_error_description(&error))
|
||||
}
|
||||
|
||||
fn underlined(expression: &str) -> Vec<(u32, u32)> {
|
||||
let error = math_expression_error(expression, false);
|
||||
math_expression_error_ranges(expression, error.as_ref()).into_iter().map(|range| (range.start, range.end)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn math_expressions_are_flagged_only_when_they_fail_to_parse() {
|
||||
for (expression, accepts_reducers) in [("x * 2", false), ("", false), (" ", true), ("min", false), ("+", true), ("min", true)] {
|
||||
assert_eq!(math_expression_error(expression, accepts_reducers), None, "`{expression}`");
|
||||
assert!(math_expression_error(expression, accepts_reducers).is_none(), "`{expression}`");
|
||||
}
|
||||
|
||||
assert!(math_expression_error("2 +", false).is_some());
|
||||
assert!(math_expression_error("+", false).is_some(), "a lone reducer is an error where the node applies none");
|
||||
assert_eq!(math_expression_error("sin(I)", true).as_deref(), Some("A matrix stands where a value is needed"));
|
||||
assert_eq!(description("sin(I)").as_deref(), Some("A matrix stands where a value is needed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn math_expression_errors_quote_the_expression_safely() {
|
||||
// The expression's own text sits in code it can't close, while the message's own code keeps its formatting, and the expression
|
||||
// repeats in a block below with labeled carets under the error's span
|
||||
assert_eq!(math_expression_error("`abc", false).as_deref(), Some("`` `abc `` is not recognized\n```\n`abc\n^^^^\nerror here\n```"));
|
||||
assert_eq!(
|
||||
math_expression_error("7 % 3", false).as_deref(),
|
||||
Some("`%` is reserved for percentages, so the remainder is written `mod(a, b)`\n```\n7 % 3\n ^\n error here\n```")
|
||||
);
|
||||
assert!(math_expression_error("(1", false).unwrap().ends_with("\n(1\n ^\n error here\n```"));
|
||||
assert!(math_expression_error("πx @ 2", false).unwrap().ends_with("\nπx @ 2\n ^\n error here\n```"));
|
||||
assert!(!math_expression_error("sin(I)", false).unwrap().contains('^'), "a sort error has no place to point at");
|
||||
// The expression's own text sits in code it can't close, while the message's own code keeps its formatting
|
||||
assert_eq!(description("`abc").as_deref(), Some("`` `abc `` is not recognized"));
|
||||
assert_eq!(description("7 % 3").as_deref(), Some("`%` is reserved for percentages, so the remainder is written `mod(a, b)`"));
|
||||
|
||||
// A quoted token like `*` is a code span, so it can't pair with another into italics
|
||||
let error = math_expression_error("2 * * 3", false).unwrap();
|
||||
let prose = error.lines().next().unwrap();
|
||||
assert!(prose.starts_with("Found `*`, expected ") && !prose.split('`').step_by(2).any(|text| text.contains('*')), "{error}");
|
||||
let error = description("2 * * 3").unwrap();
|
||||
assert!(error.starts_with("Found `*`, expected ") && !error.split('`').step_by(2).any(|text| text.contains('*')), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn math_expression_errors_underline_the_place_they_point_at() {
|
||||
assert_eq!(underlined("`abc"), [(0, 4)]);
|
||||
assert_eq!(underlined("7 % 3"), [(2, 3)]);
|
||||
assert_eq!(underlined("πx @ 2"), [(3, 4)], "offsets count UTF-16 code units");
|
||||
assert_eq!(underlined("𝑥 @ 2"), [(3, 4)], "a character beyond the Basic Multilingual Plane is two units");
|
||||
assert!(underlined("sin(I)").is_empty(), "a sort error has no place to point at unless it blames a name");
|
||||
assert_eq!(underlined("i - r where r = -63..64"), [(12, 13)]);
|
||||
|
||||
// Where something is missing at the end, the character before it is underlined, past any whitespace
|
||||
assert_eq!(underlined("(1"), [(1, 2)]);
|
||||
assert_eq!(underlined("2 + "), [(2, 3)]);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||
use glam::DVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::{Type, simplify_identifier_name};
|
||||
|
||||
@@ -163,6 +165,19 @@ pub enum ContextMenuData {
|
||||
},
|
||||
}
|
||||
|
||||
/// The connector a wire being dragged starts from, which stays fixed while its other end follows the pointer.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum WireInProgressAnchor {
|
||||
/// Dragged from an output toward a compatible input.
|
||||
Output(OutputConnector),
|
||||
/// Dragged from an input toward a compatible output.
|
||||
Input {
|
||||
input_connector: InputConnector,
|
||||
/// Set when dragged out of the Properties panel, in viewport coordinates, since the input may not be exposed in the graph.
|
||||
properties_panel_position: Option<DVec2>,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ContextMenuInformation {
|
||||
|
||||
@@ -63,6 +63,13 @@ impl MessageHandler<OverlaysMessage, OverlaysMessageContext<'_>> for OverlaysMes
|
||||
viewport: *viewport,
|
||||
},
|
||||
});
|
||||
responses.add(DocumentMessage::LayersPanelHoverOverlays {
|
||||
context: OverlayContext {
|
||||
render_context: canvas_context.clone(),
|
||||
visibility_settings: visibility_settings.clone(),
|
||||
viewport: *viewport,
|
||||
},
|
||||
});
|
||||
for provider in &self.overlay_providers {
|
||||
responses.add(provider(OverlayContext {
|
||||
render_context: canvas_context.clone(),
|
||||
@@ -80,6 +87,7 @@ impl MessageHandler<OverlaysMessage, OverlaysMessageContext<'_>> for OverlaysMes
|
||||
|
||||
if visibility_settings.all() {
|
||||
responses.add(DocumentMessage::GridOverlays { context: overlay_context.clone() });
|
||||
responses.add(DocumentMessage::LayersPanelHoverOverlays { context: overlay_context.clone() });
|
||||
|
||||
for provider in &self.overlay_providers {
|
||||
responses.add(provider(overlay_context.clone()));
|
||||
|
||||
+4
@@ -1,3 +1,4 @@
|
||||
use graphene_std::Type;
|
||||
use graphene_std::uuid::NodeId;
|
||||
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
@@ -17,6 +18,7 @@ pub struct PropertiesPanelMessageContext<'a> {
|
||||
pub fonts: &'a FontsMessageHandler,
|
||||
pub properties_panel_open: bool,
|
||||
pub properties_panel_collapsed_sections: &'a [NodeId],
|
||||
pub wire_in_progress_output_types: &'a [Type],
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, ExtractField)]
|
||||
@@ -35,6 +37,7 @@ impl MessageHandler<PropertiesPanelMessage, PropertiesPanelMessageContext<'_>> f
|
||||
fonts,
|
||||
properties_panel_open,
|
||||
properties_panel_collapsed_sections,
|
||||
wire_in_progress_output_types,
|
||||
} = context;
|
||||
|
||||
match message {
|
||||
@@ -60,6 +63,7 @@ impl MessageHandler<PropertiesPanelMessage, PropertiesPanelMessageContext<'_>> f
|
||||
document_name,
|
||||
fonts,
|
||||
properties_panel_collapsed_sections,
|
||||
wire_in_progress_output_types,
|
||||
};
|
||||
let layout = Layout(NodeGraphMessageHandler::collate_properties(&mut node_properties_context));
|
||||
|
||||
|
||||
@@ -546,8 +546,6 @@ async fn image_node_with_no_file_still_evaluates() {
|
||||
value: TaggedValue::TypeDefault(item!(Resource)).into(),
|
||||
})
|
||||
.await;
|
||||
|
||||
editor.eval_graph().await.expect("an Image node with no file chosen should still evaluate");
|
||||
}
|
||||
|
||||
/// Undoing an image paste reverts the interaction's `AddResource` in the `Gdd` cursor while the runtime keeps
|
||||
|
||||
@@ -666,11 +666,18 @@ pub struct PTZ {
|
||||
/// Angle in radians.
|
||||
tilt: f64,
|
||||
/// Scale factor.
|
||||
#[serde(deserialize_with = "deserialize_clamped_zoom")]
|
||||
zoom: f64,
|
||||
/// Flipped status.
|
||||
pub flip: bool,
|
||||
}
|
||||
|
||||
/// A zoom outside the allowed range, like a non-finite one loaded as 0, would leave the view unusable.
|
||||
fn deserialize_clamped_zoom<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<f64, D::Error> {
|
||||
let zoom = <f64 as serde::Deserialize>::deserialize(deserializer)?;
|
||||
Ok(zoom.clamp(crate::consts::VIEWPORT_ZOOM_SCALE_MIN, crate::consts::VIEWPORT_ZOOM_SCALE_MAX))
|
||||
}
|
||||
|
||||
impl Default for PTZ {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
|
||||
@@ -25,6 +25,7 @@ mod validation;
|
||||
mod view;
|
||||
|
||||
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
|
||||
pub use resolved_types::type_feeds_connector;
|
||||
use store::Guarded;
|
||||
pub use store::NodeLocator;
|
||||
pub use template::*;
|
||||
@@ -54,6 +55,7 @@ use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, No
|
||||
use graphene_std::Appearance;
|
||||
use graphene_std::ContextDependencies;
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::registry::MULTI_OUTPUT_NODES;
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType, FreePoint};
|
||||
use graphene_std::vector::{Vector, VectorModificationType};
|
||||
@@ -90,6 +92,15 @@ pub struct NodeNetworkInterface {
|
||||
/// a set of changes.
|
||||
#[serde(skip)]
|
||||
deltas: Vec<EditorDelta>,
|
||||
/// The document network nodes the open transaction has written to, read from `deltas`, for the Layers panel to highlight during an edit like a drag.
|
||||
#[serde(skip)]
|
||||
transaction_edited_nodes: HashSet<NodeId>,
|
||||
/// How far into `deltas` the reading for `transaction_edited_nodes` has reached.
|
||||
#[serde(skip)]
|
||||
transaction_edited_nodes_scanned: usize,
|
||||
/// Whether `transaction_edited_nodes` changed since `update_transaction_edited_nodes` last reported it.
|
||||
#[serde(skip)]
|
||||
transaction_edited_nodes_changed: bool,
|
||||
}
|
||||
|
||||
impl Clone for NodeNetworkInterface {
|
||||
@@ -101,6 +112,9 @@ impl Clone for NodeNetworkInterface {
|
||||
resolved_types: Default::default(),
|
||||
transaction_status: TransactionStatus::Finished,
|
||||
deltas: Vec::new(),
|
||||
transaction_edited_nodes: HashSet::new(),
|
||||
transaction_edited_nodes_scanned: 0,
|
||||
transaction_edited_nodes_changed: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ use super::*;
|
||||
impl NodeNetworkInterface {
|
||||
pub fn start_transaction(&mut self) {
|
||||
self.transaction_status = TransactionStatus::Started;
|
||||
self.clear_transaction_edited_nodes();
|
||||
self.transaction_edited_nodes_scanned = self.deltas.len();
|
||||
}
|
||||
|
||||
pub fn transaction_modified(&mut self) {
|
||||
@@ -15,6 +17,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
pub fn finish_transaction(&mut self) {
|
||||
self.transaction_status = TransactionStatus::Finished;
|
||||
self.clear_transaction_edited_nodes();
|
||||
}
|
||||
|
||||
/// Mutably get the selected nodes for the network at the network_path. Every time they are mutated, the transient metadata for the top of the stack gets unloaded.
|
||||
@@ -646,8 +649,9 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
fn load_wire(&self, input: &InputConnector, graph_wire_style: GraphWireStyle, network_path: &[NodeId]) {
|
||||
// The export keeps its own solid wire while previewing, since previewing does not rewire it
|
||||
let Some(wire) = self.wire_path_from_input(input, graph_wire_style, false, network_path) else {
|
||||
// While previewing, the export's wire leads to the temporarily previewed node
|
||||
let dashed = *input == InputConnector::Export(0) && matches!(self.previewing(network_path), Previewing::Yes { .. });
|
||||
let Some(wire) = self.wire_path_from_input(input, graph_wire_style, dashed, network_path) else {
|
||||
log::error!("Could not load wire path from input");
|
||||
return;
|
||||
};
|
||||
@@ -759,14 +763,15 @@ impl NodeNetworkInterface {
|
||||
|
||||
let path_string = vector_wire.to_svg();
|
||||
let center_path_string = center_line.to_svg();
|
||||
let input_type = self.input_type(&input, network_path);
|
||||
let data_type = input_type.displayed_type();
|
||||
let is_list = input_type.is_list();
|
||||
// Styled by the root node's own output, since the export it leads to is connected to the previewed node instead
|
||||
let output_type = self.output_type(&upstream_output, network_path);
|
||||
let data_type = output_type.displayed_type();
|
||||
let is_list = output_type.is_list();
|
||||
let wire_path_update = Some(WirePath {
|
||||
path_string,
|
||||
data_type,
|
||||
thick,
|
||||
dashed: true,
|
||||
dashed: false,
|
||||
is_list,
|
||||
center_path_string,
|
||||
});
|
||||
|
||||
+577
-1
@@ -1,4 +1,6 @@
|
||||
use super::{InputConnector, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, OutputConnector, Previewing, RootNode, TransactionStatus};
|
||||
use super::{
|
||||
ChainInsertionPoint, FlowType, InputConnector, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, OutputConnector, Previewing, RootNode, TransactionStatus,
|
||||
};
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::Direction;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::document::NodeInput;
|
||||
@@ -291,6 +293,580 @@ async fn chain_membership_follows_wiring() {
|
||||
assert_invariants(&editor, "after forming and breaking a chain");
|
||||
}
|
||||
|
||||
fn fill_definition() -> DefinitionIdentifier {
|
||||
DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER)
|
||||
}
|
||||
|
||||
/// Builds a layer fed by the chain `near <- far <- source` (a generator fixed at the upstream end), with an outside node also wired into the near node's second input.
|
||||
async fn layer_with_chain(editor: &mut EditorTestUtils) -> (NodeId, NodeId, NodeId, NodeId, NodeId) {
|
||||
let layer = editor.create_node_by_name_at(merge_definition(), 30, 10).await;
|
||||
let near = editor.create_node_by_name_at(fill_definition(), 23, 10).await;
|
||||
let far = editor.create_node_by_name_at(fill_definition(), 16, 10).await;
|
||||
let source = editor.create_node_by_name_at(rectangle_definition(), 9, 10).await;
|
||||
let outside = editor.create_node_by_name_at(rectangle_definition(), 16, 20).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.set_to_node_or_layer(&layer, &[], true);
|
||||
network_interface.create_wire(&OutputConnector::primary_output(near), &InputConnector::layer_secondary_input(layer), &[]);
|
||||
network_interface.create_wire(&OutputConnector::primary_output(far), &InputConnector::primary_input(near), &[]);
|
||||
network_interface.create_wire(&OutputConnector::primary_output(source), &InputConnector::primary_input(far), &[]);
|
||||
network_interface.create_wire(&OutputConnector::primary_output(outside), &InputConnector::node_at_index(near, 1), &[]);
|
||||
|
||||
(layer, near, far, source, outside)
|
||||
}
|
||||
|
||||
/// The layer from `layer_with_chain` placed in an artboard, making it part of the layer structure that the Layers panel and clipboard act on.
|
||||
async fn layer_with_chain_in_artboard(editor: &mut EditorTestUtils) -> (NodeId, NodeId, NodeId, NodeId, NodeId) {
|
||||
let artboard = NodeId::new();
|
||||
editor.handle_message(new_artboard_message(artboard)).await;
|
||||
let nodes = layer_with_chain(editor).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
let artboard_layer = LayerNodeIdentifier::new(artboard, network_interface);
|
||||
network_interface.move_layer_to_stack(LayerNodeIdentifier::new(nodes.0, network_interface), artboard_layer, 0, &[]);
|
||||
|
||||
nodes
|
||||
}
|
||||
|
||||
fn chain_of(network_interface: &NodeNetworkInterface, layer: NodeId) -> Vec<NodeId> {
|
||||
network_interface.upstream_flow_back_from_nodes(vec![layer], &[], FlowType::HorizontalFlow).skip(1).collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reordering_chain_nodes_keeps_the_source_at_the_upstream_end() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, near, far, source, _) = layer_with_chain(&mut editor).await;
|
||||
|
||||
// Gap 2 is upstream of both reorderable nodes, beside the fixed source
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.reorder_chain_nodes(&[near], 2, &[]);
|
||||
assert_eq!(chain_of(network_interface, layer), vec![far, near, source]);
|
||||
|
||||
assert_invariants(&editor, "after reordering a chain node");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicating_chain_nodes_inserts_copies_that_keep_their_other_wires() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, near, far, source, outside) = layer_with_chain(&mut editor).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.duplicate_chain_nodes(&[near], Some((layer, 2)), &[]);
|
||||
|
||||
let chain = chain_of(network_interface, layer);
|
||||
assert_eq!(chain.len(), 4, "The copy should join the chain");
|
||||
assert_eq!(
|
||||
(chain[0], chain[1], chain[3]),
|
||||
(near, far, source),
|
||||
"The originals should keep their places, with the source still at the end"
|
||||
);
|
||||
|
||||
let copy = chain[2];
|
||||
assert!(network_interface.is_chain(©, &[]), "The copy should be positioned as a chain node");
|
||||
assert_eq!(
|
||||
network_interface.input_from_connector(&InputConnector::node_at_index(copy, 1), &[]),
|
||||
Some(&NodeInput::node(outside, 0)),
|
||||
"The copy should keep its original's other wires"
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after duplicating a chain node");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicating_chain_nodes_in_place_one_at_a_time_interleaves_the_copies() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, near, far, source, _) = layer_with_chain(&mut editor).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
let near_copy = network_interface.duplicate_chain_nodes(&[near], None, &[]);
|
||||
let far_copy = network_interface.duplicate_chain_nodes(&[far], None, &[]);
|
||||
assert_eq!((near_copy.len(), far_copy.len()), (1, 1));
|
||||
|
||||
// Each copy lands just downstream of its own original
|
||||
assert_eq!(chain_of(network_interface, layer), vec![near_copy[0], near, far_copy[0], far, source]);
|
||||
|
||||
assert_invariants(&editor, "after duplicating chain nodes in place");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pasting_a_chain_node_at_another_layers_chain_end_keeps_only_wires_that_exist() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (_, near, _, _, outside) = layer_with_chain(&mut editor).await;
|
||||
let other_layer = editor.create_node_by_name_at(merge_definition(), 30, 30).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.set_to_node_or_layer(&other_layer, &[], true);
|
||||
let copy = network_interface.copy_chain_node(&near, &[]).expect("The chain node should be copyable");
|
||||
|
||||
// Pasted while the outside node exists, the copy stays wired to it
|
||||
let pasted = network_interface.paste_into_chain(ChainInsertionPoint::BesideLayer(other_layer), vec![copy.clone()], &[]);
|
||||
assert_eq!(chain_of(network_interface, other_layer), pasted, "The copy should form the other layer's chain");
|
||||
assert_eq!(
|
||||
network_interface.input_from_connector(&InputConnector::node_at_index(pasted[0], 1), &[]),
|
||||
Some(&NodeInput::node(outside, 0))
|
||||
);
|
||||
|
||||
// Pasted where the outside node is missing, the copy takes the value it had
|
||||
network_interface.delete_nodes(vec![outside], false, &[]);
|
||||
let pasted_again = network_interface.paste_into_chain(ChainInsertionPoint::BesideLayer(other_layer), vec![copy], &[]);
|
||||
assert_eq!(
|
||||
chain_of(network_interface, other_layer),
|
||||
vec![pasted_again[0], pasted[0]],
|
||||
"Pasting at the chain's end should go beside the layer"
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
network_interface.input_from_connector(&InputConnector::node_at_index(pasted_again[0], 1), &[]),
|
||||
Some(NodeInput::Value { .. })
|
||||
),
|
||||
"A wire to a missing node should become its fallback value"
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after pasting chain nodes");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cutting_a_chain_node_and_pasting_it_back_keeps_its_wires() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, near, far, source, outside) = layer_with_chain_in_artboard(&mut editor).await;
|
||||
|
||||
// Cutting removes just the node, keeping the node that fed its second input
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![near] }).await;
|
||||
let clipboard = editor
|
||||
.handle_message(ClipboardMessage::CutLayers)
|
||||
.await
|
||||
.into_iter()
|
||||
.find_map(|message| match message {
|
||||
FrontendMessage::TriggerClipboardWrite { content } => Some(content),
|
||||
_ => None,
|
||||
})
|
||||
.expect("Cutting a chain node should write it to the clipboard");
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
assert_eq!(chain_of(network_interface, layer), vec![far, source], "Cutting should close the chain around the node");
|
||||
assert!(network_interface.document_node(&outside, &[]).is_some(), "Cutting should keep what fed the node's other inputs");
|
||||
|
||||
// Pasting with the layer selected puts the node back beside the layer, wired as before
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer] }).await;
|
||||
editor
|
||||
.handle_message(ClipboardMessage::ReadClipboard {
|
||||
content: ClipboardContentRaw::Text(clipboard),
|
||||
})
|
||||
.await;
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let chain = chain_of(network_interface, layer);
|
||||
assert_eq!(chain.len(), 3, "The pasted node should join the chain");
|
||||
assert_eq!(chain[1..], [far, source], "The pasted node should go beside the layer");
|
||||
assert_eq!(
|
||||
network_interface.input_from_connector(&InputConnector::node_at_index(chain[0], 1), &[]),
|
||||
Some(&NodeInput::node(outside, 0)),
|
||||
"The pasted node should be wired to what fed it before"
|
||||
);
|
||||
assert_eq!(
|
||||
network_interface.selected_nodes().selected_nodes().copied().collect::<Vec<_>>(),
|
||||
vec![chain[0]],
|
||||
"The pasted node should be selected"
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after cutting and pasting a chain node");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pasted_chain_nodes_go_beside_their_originals_or_pair_with_a_new_selection() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, near, far, source, _) = layer_with_chain_in_artboard(&mut editor).await;
|
||||
let copy = editor.active_document().network_interface.copy_chain_node(&near, &[]).expect("The chain node should be copyable");
|
||||
|
||||
// Over the same selection that was copied, the copy goes beside its original
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![near] }).await;
|
||||
editor.handle_message(DocumentMessage::PasteChainNodes { copies: vec![copy.clone()] }).await;
|
||||
let chain = chain_of(&editor.active_document().network_interface, layer);
|
||||
let first_copy = chain[0];
|
||||
assert_eq!(chain, vec![first_copy, near, far, source], "The copy should go beside the node it was copied from");
|
||||
|
||||
// Over a different selection of the same size, the copy pairs with that node instead
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![far] }).await;
|
||||
editor.handle_message(DocumentMessage::PasteChainNodes { copies: vec![copy] }).await;
|
||||
let chain = chain_of(&editor.active_document().network_interface, layer);
|
||||
let second_copy = chain[2];
|
||||
assert_eq!(chain, vec![first_copy, near, second_copy, far, source], "The copy should go beside the newly selected node");
|
||||
assert_eq!(
|
||||
editor.active_document().network_interface.selected_nodes().selected_nodes().copied().collect::<Vec<_>>(),
|
||||
vec![second_copy],
|
||||
"The pasted copy should become the selection"
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after pasting chain nodes over a selection");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn moving_a_chain_node_to_another_layer_closes_the_gap_it_leaves() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, near, far, source, _) = layer_with_chain(&mut editor).await;
|
||||
let other_layer = editor.create_node_by_name_at(merge_definition(), 30, 30).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.set_to_node_or_layer(&other_layer, &[], true);
|
||||
network_interface.move_chain_nodes(&[near], other_layer, 0, &[]);
|
||||
|
||||
assert_eq!(chain_of(network_interface, layer), vec![far, source], "The source chain should close up around the moved node");
|
||||
assert_eq!(chain_of(network_interface, other_layer), vec![near], "The moved node should form the other layer's chain");
|
||||
|
||||
assert_invariants(&editor, "after moving a chain node between layers");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_chain_node_reading_from_a_layer_joins_its_chain_only_as_an_unwired_copy() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, near, far, source, _) = layer_with_chain(&mut editor).await;
|
||||
let other_layer = editor.create_node_by_name_at(merge_definition(), 30, 30).await;
|
||||
|
||||
// The other layer feeds the near node's second input, so its chain taking the near node with that wire would close a cycle
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.set_to_node_or_layer(&other_layer, &[], true);
|
||||
network_interface.create_wire(&OutputConnector::primary_output(other_layer), &InputConnector::node_at_index(near, 1), &[]);
|
||||
|
||||
network_interface.move_chain_nodes(&[near], other_layer, 0, &[]);
|
||||
assert_eq!(chain_of(network_interface, layer), vec![near, far, source], "A refused move should leave the node in its own chain");
|
||||
assert!(chain_of(network_interface, other_layer).is_empty(), "A refused move should leave the other chain as it was");
|
||||
|
||||
let copies = network_interface.duplicate_chain_nodes(&[near], Some((other_layer, 0)), &[]);
|
||||
assert_eq!(chain_of(network_interface, other_layer), copies, "The copy should join the other chain");
|
||||
assert!(
|
||||
matches!(network_interface.input_from_connector(&InputConnector::node_at_index(copies[0], 1), &[]), Some(NodeInput::Value { .. })),
|
||||
"The copy's wire from the layer it joined should fall back to a value"
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after chain edits that would close a cycle");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicating_a_mixed_graph_selection_stacks_the_layers_and_offsets_the_other_nodes() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let artboard = NodeId::new();
|
||||
editor.handle_message(new_artboard_message(artboard)).await;
|
||||
let (layer, near, _, _, _) = layer_with_chain(&mut editor).await;
|
||||
let loose = editor.create_node_by_name_at(rectangle_definition(), 40, 40).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
let artboard_layer = LayerNodeIdentifier::new(artboard, network_interface);
|
||||
network_interface.move_layer_to_stack(LayerNodeIdentifier::new(layer, network_interface), artboard_layer, 0, &[]);
|
||||
|
||||
// The selected chain node comes along with its layer's copy, so only the loose node gets an offset copy of its own
|
||||
editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await;
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer, near, loose] }).await;
|
||||
editor.handle_message(NodeGraphMessage::DuplicateSelectedNodes).await;
|
||||
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let children = artboard_layer.children(network_interface.document_metadata()).map(|child| child.to_node()).collect::<Vec<_>>();
|
||||
assert_eq!(children.len(), 2, "The layer's copy should join the stack beside it");
|
||||
let layer_copy = *children.iter().find(|child| **child != layer).unwrap();
|
||||
assert_eq!(chain_of(network_interface, layer_copy).len(), 3, "The layer's copy should bring its own chain");
|
||||
|
||||
let selected = network_interface.selected_nodes().selected_nodes().copied().collect::<Vec<_>>();
|
||||
assert_eq!(selected.len(), 2, "Only the layer's copy and the loose node's copy should be selected");
|
||||
assert!(selected.contains(&layer_copy), "The layer's copy should be selected");
|
||||
let loose_copy = *selected.iter().find(|node| **node != layer_copy).unwrap();
|
||||
assert_eq!(
|
||||
network_interface.position(&loose_copy, &[]),
|
||||
network_interface.position(&loose, &[]).map(|position| position + IVec2::new(2, 2))
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after duplicating a mixed selection of layers and nodes");
|
||||
}
|
||||
|
||||
/// A generator feeding three nodes in a row through their primary inputs, outside any layer.
|
||||
async fn floating_flow(editor: &mut EditorTestUtils) -> (NodeId, NodeId, NodeId, NodeId) {
|
||||
let generator = editor.create_node_by_name_at(rectangle_definition(), 0, 40).await;
|
||||
let first = editor.create_node_by_name_at(fill_definition(), 7, 40).await;
|
||||
let middle = editor.create_node_by_name_at(fill_definition(), 14, 40).await;
|
||||
let last = editor.create_node_by_name_at(fill_definition(), 21, 40).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.create_wire(&OutputConnector::primary_output(generator), &InputConnector::primary_input(first), &[]);
|
||||
network_interface.create_wire(&OutputConnector::primary_output(first), &InputConnector::primary_input(middle), &[]);
|
||||
network_interface.create_wire(&OutputConnector::primary_output(middle), &InputConnector::primary_input(last), &[]);
|
||||
|
||||
(generator, first, middle, last)
|
||||
}
|
||||
|
||||
async fn duplicate_selection(editor: &mut EditorTestUtils, nodes: Vec<NodeId>) -> Vec<NodeId> {
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes }).await;
|
||||
editor.handle_message(DocumentMessage::DuplicateSelectedLayers).await;
|
||||
editor.active_document().network_interface.selected_nodes().selected_nodes().copied().collect()
|
||||
}
|
||||
|
||||
fn primary_input_of(network_interface: &NodeNetworkInterface, node_id: NodeId) -> Option<NodeInput> {
|
||||
network_interface.input_from_connector(&InputConnector::primary_input(node_id), &[]).cloned()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicating_a_node_inside_a_flow_puts_its_copy_right_after_it() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (_, _, middle, last) = floating_flow(&mut editor).await;
|
||||
|
||||
let copies = duplicate_selection(&mut editor, vec![middle]).await;
|
||||
assert_eq!(copies.len(), 1, "The copy should become the selection");
|
||||
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
assert_eq!(
|
||||
primary_input_of(network_interface, copies[0]),
|
||||
Some(NodeInput::node(middle, 0)),
|
||||
"The copy should be fed by the original"
|
||||
);
|
||||
assert_eq!(
|
||||
primary_input_of(network_interface, last),
|
||||
Some(NodeInput::node(copies[0], 0)),
|
||||
"The copy should feed what the original fed"
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after duplicating a node inside a flow");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicating_the_end_of_a_flow_extends_it() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (_, _, _, last) = floating_flow(&mut editor).await;
|
||||
|
||||
let copies = duplicate_selection(&mut editor, vec![last]).await;
|
||||
assert_eq!(copies.len(), 1, "The copy should become the selection");
|
||||
assert_eq!(
|
||||
primary_input_of(&editor.active_document().network_interface, copies[0]),
|
||||
Some(NodeInput::node(last, 0)),
|
||||
"The copy should extend the flow from the original"
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after duplicating the end of a flow");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicating_a_solo_node_or_a_generator_makes_an_offset_copy_outside_the_flow() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (generator, first, _, _) = floating_flow(&mut editor).await;
|
||||
let solo = editor.create_node_by_name_at(fill_definition(), 0, 60).await;
|
||||
|
||||
let copies = duplicate_selection(&mut editor, vec![generator, solo]).await;
|
||||
assert_eq!(copies.len(), 2, "Both copies should become the selection");
|
||||
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
assert_eq!(
|
||||
primary_input_of(network_interface, first),
|
||||
Some(NodeInput::node(generator, 0)),
|
||||
"The generator should still feed the flow"
|
||||
);
|
||||
for copy in copies {
|
||||
let original = if network_interface.reference(©, &[]) == network_interface.reference(&generator, &[]) {
|
||||
generator
|
||||
} else {
|
||||
solo
|
||||
};
|
||||
assert_eq!(
|
||||
network_interface.position(©, &[]),
|
||||
network_interface.position(&original, &[]).map(|position| position + IVec2::new(2, 2)),
|
||||
"A copy outside the flow should sit offset from its original"
|
||||
);
|
||||
assert!(
|
||||
!matches!(primary_input_of(network_interface, copy), Some(NodeInput::Node { .. })),
|
||||
"A copy outside the flow should not be wired into it"
|
||||
);
|
||||
}
|
||||
|
||||
assert_invariants(&editor, "after duplicating nodes outside any flow");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicating_a_floating_layer_in_a_stack_puts_its_copy_above_it_with_its_content() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, _, _, _, _) = layer_with_chain(&mut editor).await;
|
||||
let layer_above = editor.create_node_by_name_at(merge_definition(), 30, 0).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.set_to_node_or_layer(&layer_above, &[], true);
|
||||
network_interface.create_wire(&OutputConnector::primary_output(layer), &InputConnector::primary_input(layer_above), &[]);
|
||||
|
||||
let copies = duplicate_selection(&mut editor, vec![layer]).await;
|
||||
assert_eq!(copies.len(), 1, "The copy should become the selection");
|
||||
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
assert!(network_interface.is_layer(&copies[0], &[]), "The copy should be a layer");
|
||||
assert_eq!(
|
||||
primary_input_of(network_interface, copies[0]),
|
||||
Some(NodeInput::node(layer, 0)),
|
||||
"The copy should be stacked on the original"
|
||||
);
|
||||
assert_eq!(
|
||||
primary_input_of(network_interface, layer_above),
|
||||
Some(NodeInput::node(copies[0], 0)),
|
||||
"The layer above should now be stacked on the copy"
|
||||
);
|
||||
assert_eq!(chain_of(network_interface, copies[0]).len(), 3, "The copy should bring a copy of the layer's chain");
|
||||
|
||||
assert_invariants(&editor, "after duplicating a floating layer in a stack");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicating_a_solo_floating_layer_makes_an_offset_copy_with_its_content() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, _, _, _, _) = layer_with_chain(&mut editor).await;
|
||||
|
||||
let copies = duplicate_selection(&mut editor, vec![layer]).await;
|
||||
assert_eq!(copies.len(), 1, "The copy should become the selection");
|
||||
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
assert!(network_interface.is_layer(&copies[0], &[]), "The copy should be a layer");
|
||||
assert_eq!(chain_of(network_interface, copies[0]).len(), 3, "The copy should bring a copy of the layer's chain");
|
||||
assert_eq!(
|
||||
network_interface.position(&copies[0], &[]),
|
||||
network_interface.position(&layer, &[]).map(|position| position + IVec2::new(2, 2)),
|
||||
"The copy should sit offset from the original"
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after duplicating a solo floating layer");
|
||||
}
|
||||
|
||||
async fn copy_in_graph(editor: &mut EditorTestUtils, nodes: Vec<NodeId>) -> String {
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes }).await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::Copy)
|
||||
.await
|
||||
.into_iter()
|
||||
.find_map(|message| match message {
|
||||
FrontendMessage::TriggerClipboardWrite { content } => Some(content),
|
||||
_ => None,
|
||||
})
|
||||
.expect("Copying nodes should write them to the clipboard")
|
||||
}
|
||||
|
||||
async fn paste(editor: &mut EditorTestUtils, clipboard: String) -> Vec<NodeId> {
|
||||
editor
|
||||
.handle_message(ClipboardMessage::ReadClipboard {
|
||||
content: ClipboardContentRaw::Text(clipboard),
|
||||
})
|
||||
.await;
|
||||
editor.active_document().network_interface.selected_nodes().selected_nodes().copied().collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pasting_graph_nodes_over_their_copied_selection_duplicates_them_into_the_flow() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (_, _, middle, last) = floating_flow(&mut editor).await;
|
||||
|
||||
let clipboard = copy_in_graph(&mut editor, vec![middle]).await;
|
||||
let pasted = paste(&mut editor, clipboard).await;
|
||||
assert_eq!(pasted.len(), 1, "The pasted copy should become the selection");
|
||||
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
assert_eq!(
|
||||
primary_input_of(network_interface, pasted[0]),
|
||||
Some(NodeInput::node(middle, 0)),
|
||||
"The copy should be fed by the original"
|
||||
);
|
||||
assert_eq!(
|
||||
primary_input_of(network_interface, last),
|
||||
Some(NodeInput::node(pasted[0], 0)),
|
||||
"The copy should feed what the original fed"
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after pasting graph nodes over their copied selection");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pasting_graph_nodes_over_an_empty_selection_puts_loose_copies_in_the_graph() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (_, _, middle, last) = floating_flow(&mut editor).await;
|
||||
|
||||
let clipboard = copy_in_graph(&mut editor, vec![middle]).await;
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: Vec::new() }).await;
|
||||
let pasted = paste(&mut editor, clipboard).await;
|
||||
assert_eq!(pasted.len(), 1, "The pasted copy should become the selection");
|
||||
|
||||
let document = editor.active_document();
|
||||
assert!(
|
||||
!matches!(primary_input_of(&document.network_interface, pasted[0]), Some(NodeInput::Node { .. })),
|
||||
"The pasted copy should be outside any flow"
|
||||
);
|
||||
assert_eq!(
|
||||
primary_input_of(&document.network_interface, last),
|
||||
Some(NodeInput::node(middle, 0)),
|
||||
"The flow should be left as it was"
|
||||
);
|
||||
assert!(document.graph_view_overlay_open(), "The graph should open to show the pasted copy");
|
||||
|
||||
assert_invariants(&editor, "after pasting graph nodes over an empty selection");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pasting_chain_nodes_over_an_empty_selection_puts_loose_copies_in_the_graph() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, near, far, source, _) = layer_with_chain_in_artboard(&mut editor).await;
|
||||
let copy = editor.active_document().network_interface.copy_chain_node(&near, &[]).expect("The chain node should be copyable");
|
||||
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: Vec::new() }).await;
|
||||
editor.handle_message(DocumentMessage::PasteChainNodes { copies: vec![copy] }).await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let pasted = document.network_interface.selected_nodes().selected_nodes().copied().collect::<Vec<_>>();
|
||||
assert_eq!(pasted.len(), 1, "The pasted copy should become the selection");
|
||||
assert!(
|
||||
!matches!(primary_input_of(&document.network_interface, pasted[0]), Some(NodeInput::Node { .. })),
|
||||
"The pasted copy should be outside any flow"
|
||||
);
|
||||
assert_eq!(chain_of(&document.network_interface, layer), vec![near, far, source], "The chain should be left as it was");
|
||||
assert!(document.graph_view_overlay_open(), "The graph should open to show the pasted copy");
|
||||
|
||||
assert_invariants(&editor, "after pasting chain nodes over an empty selection");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_copied_layer_pastes_the_same_whether_copied_in_the_graph_or_not() {
|
||||
for copied_in_graph in [false, true] {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, _, _, _, _) = layer_with_chain_in_artboard(&mut editor).await;
|
||||
|
||||
editor.handle_message(DocumentMessage::GraphViewOverlay { open: copied_in_graph }).await;
|
||||
let clipboard = copy_in_graph(&mut editor, vec![layer]).await;
|
||||
editor.handle_message(DocumentMessage::GraphViewOverlay { open: false }).await;
|
||||
let pasted = paste(&mut editor, clipboard).await;
|
||||
assert_eq!(pasted.len(), 1, "Only the pasted layer should be selected (copied in the graph: {copied_in_graph})");
|
||||
|
||||
// The copy goes on top of the stack its original is in, bringing its chain along
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let metadata = network_interface.document_metadata();
|
||||
let parent = LayerNodeIdentifier::new(layer, network_interface).parent(metadata);
|
||||
assert!(parent.is_some(), "The original layer should be in the layer structure");
|
||||
assert_eq!(
|
||||
parent.and_then(|parent| parent.children(metadata).next()).map(|child| child.to_node()),
|
||||
Some(pasted[0]),
|
||||
"The pasted layer should go on top of the stack (copied in the graph: {copied_in_graph})"
|
||||
);
|
||||
assert_eq!(
|
||||
chain_of(network_interface, pasted[0]).len(),
|
||||
3,
|
||||
"The pasted layer should bring its chain (copied in the graph: {copied_in_graph})"
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after pasting a copied layer");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn move_layer_to_stack_builds_the_layer_stack() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
+31
-8
@@ -4,7 +4,7 @@ use super::{InputMetadata, InputPersistentMetadata};
|
||||
use document_graph_storage::attr::network as network_attr;
|
||||
use document_graph_storage::attr::node as node_attr;
|
||||
use document_graph_storage::from_runtime::{ConversionError, DeclarationBytes};
|
||||
use document_graph_storage::{AttributeDelta, Attributes, Implementation, NodeMetadataSource, PathResolver, Position, Registry, RegistryDelta, ScopedConversion, TimeStamp, Value};
|
||||
use document_graph_storage::{AttributeDelta, AttributeValue, Attributes, Implementation, NodeMetadataSource, PathResolver, Position, Registry, RegistryDelta, ScopedConversion, TimeStamp, Value};
|
||||
use document_graph_storage::{convert_input_attributes, convert_resource_entry, encode_input_ui_attributes, encode_node_ui_attributes, node_value_resource_refs, value_resource_ref};
|
||||
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry};
|
||||
use graph_craft::document::NodeId;
|
||||
@@ -381,15 +381,37 @@ fn construct_structural_additions(
|
||||
// A node the registry already holds is updated rather than rebuilt: rebuilding would clear the
|
||||
// `ui::*` attributes it carries, and restating those would clobber whatever a concurrent peer
|
||||
// wrote to its name, lock or pin.
|
||||
match batch.node(id).is_some() {
|
||||
true => {
|
||||
match batch.node(id) {
|
||||
Some(held) => {
|
||||
// The swap did not write the slots' `ui::*` attributes, so they carry over to the slots that survive it with
|
||||
// their stamps, tombstones and the held floor, losing to a concurrent write. The other attributes the new implementation
|
||||
// lacks go by tombstone instead.
|
||||
let inputs = node
|
||||
.inputs()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, slot)| {
|
||||
let mut slot = slot.clone();
|
||||
if let Some(previous) = held.inputs().get(index) {
|
||||
for (key, value) in previous.attributes.iter() {
|
||||
if key.starts_with("ui::") {
|
||||
slot.attributes.insert(key.clone(), value.clone());
|
||||
} else if !value.deleted && !slot.attributes.contains_key(key) {
|
||||
slot.attributes.insert(key.clone(), AttributeValue::deleted(TimeStamp::ORIGIN));
|
||||
}
|
||||
}
|
||||
slot.attributes.set_floor(previous.attributes.floor());
|
||||
}
|
||||
slot
|
||||
})
|
||||
.collect();
|
||||
ops.push(RegistryDelta::SetNodeImplementation {
|
||||
id,
|
||||
implementation: node.implementation().clone(),
|
||||
});
|
||||
ops.push(RegistryDelta::SetNodeInputs { id, inputs: node.inputs().to_vec() });
|
||||
ops.push(RegistryDelta::SetNodeInputs { id, inputs });
|
||||
}
|
||||
false => ops.push(RegistryDelta::AddNode { id, node: node.clone() }),
|
||||
None => ops.push(RegistryDelta::AddNode { id, node: node.clone() }),
|
||||
}
|
||||
batch.record_addition(id, node);
|
||||
}
|
||||
@@ -497,6 +519,7 @@ fn construct_metadata_snapshot(
|
||||
let current = batch
|
||||
.network(network_id)
|
||||
.and_then(|network| network.attributes.get(node_attr::ui::REFERENCE))
|
||||
.filter(|value| !value.deleted)
|
||||
.map(|value| value.value.clone());
|
||||
if current != target {
|
||||
ops.push(RegistryDelta::ChangeNetworkAttribute {
|
||||
@@ -533,19 +556,19 @@ fn construct_metadata_snapshot(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every `ui::` attribute of `encoded`, plus a clear for each `ui::` key of `current` that `encoded`
|
||||
/// Every `ui::` attribute of `encoded`, plus a clear for each live `ui::` key of `current` that `encoded`
|
||||
/// does not carry. Values are compared only to decide what to clear, never to skip a write.
|
||||
///
|
||||
/// Restating a value that already matches looks redundant but is load-bearing: `current` is the
|
||||
/// registry as it stood before the batch, and these writes follow an op in the same batch that
|
||||
/// rebuilt what they describe. A value the pre-batch state agrees with may already have been cleared
|
||||
/// by that op, so skipping it would leave the attribute missing.
|
||||
fn ui_attribute_writes(current: Option<&Attributes>, encoded: &Attributes) -> Vec<AttributeDelta> {
|
||||
pub(super) fn ui_attribute_writes(current: Option<&Attributes>, encoded: &Attributes) -> Vec<AttributeDelta> {
|
||||
let owned = |key: &str| key.starts_with("ui::");
|
||||
let mut deltas = Vec::new();
|
||||
|
||||
if let Some(current) = current {
|
||||
for key in current.keys() {
|
||||
for (key, _) in current.live() {
|
||||
if owned(key) && !encoded.contains_key(key) {
|
||||
deltas.push(AttributeDelta { key: key.clone(), value: None });
|
||||
}
|
||||
|
||||
+36
-1
@@ -1,6 +1,6 @@
|
||||
use super::DocumentNodePersistentMetadata;
|
||||
use super::InputConnector;
|
||||
use super::editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange, construct_batch};
|
||||
use super::editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange, construct_batch, ui_attribute_writes};
|
||||
use super::storage_metadata::StorageMetadataView;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use document_graph_storage::delta::compute_deltas;
|
||||
@@ -611,4 +611,39 @@ async fn swapping_an_implementation_leaves_the_node_in_place() {
|
||||
!deltas.iter().any(|delta| matches!(delta, EditorDelta::NodeMetadataSnapshot { node_id, .. } if *node_id == node)),
|
||||
"the node's own metadata should not be restated by a swap that did not write it"
|
||||
);
|
||||
|
||||
// The slots that survive the swap keep the names and descriptions the registry holds for them.
|
||||
let Some((id, inputs)) = ops.iter().find_map(|op| match op {
|
||||
RegistryDelta::SetNodeInputs { id, inputs } => Some((id, inputs)),
|
||||
_ => None,
|
||||
}) else {
|
||||
panic!("the swap should restate the slots")
|
||||
};
|
||||
let held: Vec<_> = working.node_instances[id]
|
||||
.inputs()
|
||||
.iter()
|
||||
.take(inputs.len())
|
||||
.flat_map(|slot| slot.attributes.live().filter(|(key, _)| key.starts_with("ui::")))
|
||||
.collect();
|
||||
assert!(!held.is_empty(), "the surviving slots should hold ui attributes for this to check anything");
|
||||
for (index, slot) in inputs.iter().enumerate() {
|
||||
for (key, value) in working.node_instances[id].inputs()[index].attributes.live().filter(|(key, _)| key.starts_with("ui::")) {
|
||||
assert_eq!(slot.attributes.get(key), Some(value), "slot {index} lost {key}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A `ui::` key the registry already holds as deleted is not cleared again on every snapshot.
|
||||
#[test]
|
||||
fn a_deleted_ui_key_is_not_cleared_again() {
|
||||
use document_graph_storage::{AttributeValue, Attributes, TimeStamp, Value};
|
||||
let at = TimeStamp { counter: 3, peer: PeerId(1) };
|
||||
let current: Attributes = [
|
||||
("ui::name".to_string(), AttributeValue::deleted(at)),
|
||||
("ui::locked".to_string(), AttributeValue::new(Value::Bool(true), at)),
|
||||
]
|
||||
.into_iter()
|
||||
.collect();
|
||||
let writes = ui_attribute_writes(Some(¤t), &Attributes::new());
|
||||
assert_eq!(writes.iter().map(|write| write.key.as_str()).collect::<Vec<_>>(), ["ui::locked"]);
|
||||
}
|
||||
@@ -32,10 +32,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
let number_of_outputs = match &document_node.implementation {
|
||||
DocumentNodeImplementation::Network(network) => network.exports.len(),
|
||||
_ => 1,
|
||||
};
|
||||
let number_of_outputs = self.number_of_outputs(node_id, network_path);
|
||||
// If the node has a hidden primary output, do not display the first output
|
||||
let start_index = if self.hidden_primary_output(node_id, network_path) { 1 } else { 0 };
|
||||
for output_index in start_index..number_of_outputs {
|
||||
|
||||
@@ -309,12 +309,11 @@ impl NodeNetworkInterface {
|
||||
.reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
pub fn selected_unlocked_layers_bounding_box_viewport(&self) -> Option<[DVec2; 2]> {
|
||||
self.selected_nodes()
|
||||
.0
|
||||
.iter()
|
||||
.filter(|node| self.is_layer(node, &[]) && !self.is_locked(node, &[]))
|
||||
.filter_map(|layer| self.document_metadata.bounding_box_viewport(LayerNodeIdentifier::new(*layer, self)))
|
||||
pub fn selected_visible_and_unlocked_layers_bounding_box_viewport(&self) -> Option<[DVec2; 2]> {
|
||||
let selected_nodes = self.selected_nodes();
|
||||
selected_nodes
|
||||
.selected_visible_and_unlocked_layers(self)
|
||||
.filter_map(|layer| self.document_metadata.bounding_box_viewport(layer))
|
||||
.reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
|
||||
@@ -1242,65 +1242,323 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
/// Reorders a node within its layer's horizontal chain so it ends up at `insert_index` among the chain's nodes,
|
||||
/// where index 0 is the node closest to the layer. The connection feeding the top (most-upstream end) of the chain
|
||||
/// is preserved, as are each node's other (non-primary) inputs.
|
||||
pub fn reorder_chain_node(&mut self, node_id: NodeId, insert_index: usize, network_path: &[NodeId]) {
|
||||
let Some(layer) = self.downstream_layer_for_chain_node(&node_id, network_path) else {
|
||||
log::error!("Could not find downstream layer for chain node {node_id} in reorder_chain_node");
|
||||
/// Moves nodes within their layer's horizontal chain, keeping their relative order, so they end up together at the `insert_index`
|
||||
/// gap among the chain's reorderable nodes, where gap 0 is beside the layer. The connection feeding the top (most-upstream end)
|
||||
/// of the chain is preserved, as are each node's other (non-primary) inputs.
|
||||
pub fn reorder_chain_nodes(&mut self, node_ids: &[NodeId], insert_index: usize, network_path: &[NodeId]) {
|
||||
let Some((layer, reorderable, tail_input)) = self.reorderable_chain_nodes(node_ids, network_path) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// The nodes in the layer's chain, ordered from closest-to-layer outward, stopping at the next layer
|
||||
let chain = self
|
||||
.upstream_flow_back_from_nodes(vec![layer], network_path, FlowType::HorizontalFlow)
|
||||
.skip(1)
|
||||
.take_while(|upstream_id| !self.is_layer(upstream_id, network_path))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// A source node (no primary input) stays pinned at the most-upstream end; only the nodes below it reorder
|
||||
let pinned_source = chain.last().copied().filter(|last| !self.has_primary_input(last, network_path));
|
||||
let reorderable = &chain[..chain.len() - pinned_source.is_some() as usize];
|
||||
|
||||
let Some(from) = reorderable.iter().position(|id| *id == node_id) else {
|
||||
log::error!("Node {node_id} is not a reorderable node in its layer's chain in reorder_chain_node");
|
||||
return;
|
||||
};
|
||||
|
||||
// The drop gap is measured against the reorderable nodes that still include the dragged node, so shift it down by one if the node is being removed from before the gap
|
||||
let to = (if insert_index > from { insert_index - 1 } else { insert_index }).min(reorderable.len() - 1);
|
||||
if to == from {
|
||||
// The drop gap is measured against the reorderable nodes that still include the moving ones, so it shifts down by each moving node before it
|
||||
let (moving, mut new_order): (Vec<NodeId>, Vec<NodeId>) = reorderable.iter().copied().partition(|id| node_ids.contains(id));
|
||||
let to = reorderable[..insert_index.min(reorderable.len())].iter().filter(|id| !node_ids.contains(id)).count();
|
||||
new_order.splice(to..to, moving);
|
||||
if new_order == reorderable {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut new_order = reorderable.to_vec();
|
||||
new_order.remove(from);
|
||||
new_order.insert(to, node_id);
|
||||
self.rewire_chain(layer, &new_order, tail_input, network_path);
|
||||
}
|
||||
|
||||
// The most-upstream reorderable node connects up to the pinned source, or else whatever fed the top of the chain
|
||||
let tail_input = if let Some(source) = pinned_source {
|
||||
NodeInput::node(source, 0)
|
||||
/// Moves nodes from their layer's horizontal chain into the given layer's chain (which may be the same one), keeping their relative order, so they end up
|
||||
/// together at the `insert_index` gap among that chain's reorderable nodes, where gap 0 is beside the layer. Both chains keep what fed their upstream ends.
|
||||
pub fn move_chain_nodes(&mut self, node_ids: &[NodeId], layer: NodeId, insert_index: usize, network_path: &[NodeId]) {
|
||||
let Some((source_layer, source_reorderable, source_tail_input)) = self.reorderable_chain_nodes(node_ids, network_path) else {
|
||||
return;
|
||||
};
|
||||
if source_layer == layer {
|
||||
self.reorder_chain_nodes(node_ids, insert_index, network_path);
|
||||
return;
|
||||
}
|
||||
let Some((target_reorderable, target_tail_input)) = self.layer_chain(layer, network_path) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Close the gap the nodes leave in their own chain
|
||||
let (moving, remaining): (Vec<NodeId>, Vec<NodeId>) = source_reorderable.iter().copied().partition(|id| node_ids.contains(id));
|
||||
for node_id in &moving {
|
||||
self.disconnect_input(&InputConnector::primary_input(*node_id), network_path);
|
||||
}
|
||||
self.rewire_chain(source_layer, &remaining, source_tail_input.clone(), network_path);
|
||||
|
||||
// Then splice them into the other layer's chain, or restore both chains if that would close a cycle
|
||||
let mut new_order = target_reorderable.clone();
|
||||
let insert_index = insert_index.min(new_order.len());
|
||||
new_order.splice(insert_index..insert_index, moving);
|
||||
if !self.rewire_chain(layer, &new_order, target_tail_input.clone(), network_path) {
|
||||
self.rewire_chain(layer, &target_reorderable, target_tail_input, network_path);
|
||||
self.rewire_chain(source_layer, &source_reorderable, source_tail_input, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Duplicates nodes in their layer's horizontal chain, inserting the copies together (in the originals' relative order) beside the originals, or into the
|
||||
/// `destination` layer's chain (which may be the same one) at the given gap among its reorderable nodes, where gap 0 is beside the layer. The copies keep the
|
||||
/// originals' other (non-primary) inputs, including their connections. Returns the IDs of the copies.
|
||||
pub fn duplicate_chain_nodes(&mut self, node_ids: &[NodeId], destination: Option<(NodeId, usize)>, network_path: &[NodeId]) -> Vec<NodeId> {
|
||||
let Some((source_layer, reorderable, _)) = self.reorderable_chain_nodes(node_ids, network_path) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let (layer, insert_index) = destination.unwrap_or_else(|| (source_layer, reorderable.iter().position(|id| node_ids.contains(id)).unwrap_or_default()));
|
||||
|
||||
let copies = reorderable.iter().filter(|id| node_ids.contains(id)).filter_map(|id| self.copy_chain_node(id, network_path)).collect();
|
||||
self.insert_into_chain(layer, copies, insert_index, network_path)
|
||||
}
|
||||
|
||||
/// Duplicates a node into its primary flow (wires into primary inputs, layers' chain inputs, and exports): a node feeding the flow gets its copy right after it,
|
||||
/// taking over what it fed there, and a node only fed by the flow gets its copy appended to extend the chain. A layer's copy brings a copy of its content.
|
||||
/// Returns the copy, or `None` for a node in no flow (a solo node, or a generator without a primary input), which is left to be duplicated loose.
|
||||
pub fn duplicate_node_in_flow(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> Option<NodeId> {
|
||||
if !self.has_primary_input(node_id, network_path) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let flow_outputs = self
|
||||
.with_outward_wires(network_path, |outward_wires| outward_wires.get(&OutputConnector::primary_output(*node_id)).cloned().unwrap_or_default())?
|
||||
.into_iter()
|
||||
.filter(|input| self.is_flow_input(input, network_path))
|
||||
.collect::<Vec<_>>();
|
||||
let fed_by_flow = matches!(
|
||||
self.input_from_connector(&InputConnector::primary_input(*node_id), network_path),
|
||||
Some(NodeInput::Node { .. } | NodeInput::Import { .. })
|
||||
);
|
||||
if flow_outputs.is_empty() && !fed_by_flow {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (copy, reconnections) = if self.is_layer(node_id, network_path) {
|
||||
(self.insert_layer_copy(node_id, network_path)?, Vec::new())
|
||||
} else {
|
||||
let Some(input) = self.input_from_connector(&InputConnector::primary_input(*chain.last().unwrap()), network_path).cloned() else {
|
||||
log::error!("Could not get the upstream input of the chain in reorder_chain_node");
|
||||
return;
|
||||
// Offset from the original like a loose copy, unless joining a chain or stack positions it
|
||||
let mut node_copy = self.copy_chain_node(node_id, network_path)?;
|
||||
node_copy.template.node_type_metadata = NodeTypePersistentMetadata::node(self.position(node_id, network_path).unwrap_or_default() + IVec2::new(2, 2));
|
||||
self.insert_copy(node_copy, network_path)?
|
||||
};
|
||||
|
||||
// The copy takes over what the original fed in the flow and is fed by the original, then gets back its other wires (refusing any that would close a cycle)
|
||||
for input in &flow_outputs {
|
||||
self.set_input(input, NodeInput::node(copy, 0), network_path);
|
||||
}
|
||||
self.set_input(&InputConnector::primary_input(copy), NodeInput::node(*node_id, 0), network_path);
|
||||
for (input_connector, input) in reconnections {
|
||||
self.set_input(&input_connector, input, network_path);
|
||||
}
|
||||
|
||||
Some(copy)
|
||||
}
|
||||
|
||||
/// Whether an input carries a node's primary flow onward: a primary input, a layer's chain input, or an export.
|
||||
fn is_flow_input(&self, input: &InputConnector, network_path: &[NodeId]) -> bool {
|
||||
match input {
|
||||
InputConnector::Node { input_index: 0, .. } | InputConnector::Export(_) => true,
|
||||
InputConnector::Node { node_id, input_index: 1 } => self.is_layer(node_id, network_path),
|
||||
InputConnector::Node { .. } => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Inserts a copy of a layer along with its own copy of the layer's content, offset from the original. Returns the copy of the layer.
|
||||
fn insert_layer_copy(&mut self, layer: &NodeId, network_path: &[NodeId]) -> Option<NodeId> {
|
||||
let mut copy_ids = HashMap::from([(*layer, NodeId(0))]);
|
||||
for (index, node_id) in self.upstream_flow_back_from_nodes(vec![*layer], network_path, FlowType::LayerChildrenUpstreamFlow).enumerate() {
|
||||
copy_ids.insert(node_id, NodeId(index as u64 + 1));
|
||||
}
|
||||
|
||||
let nodes = self.copy_nodes(©_ids, network_path).collect::<Vec<_>>();
|
||||
let new_ids = nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect::<HashMap<_, _>>();
|
||||
let copy = *new_ids.get(&NodeId(0))?;
|
||||
self.insert_node_group(nodes, new_ids, network_path);
|
||||
|
||||
Some(copy)
|
||||
}
|
||||
|
||||
/// Inserts copied nodes together (in their given order) into a layer's chain at the insertion point. Returns the IDs of the new nodes.
|
||||
pub fn paste_into_chain(&mut self, target: ChainInsertionPoint, copies: Vec<ChainNodeCopy>, network_path: &[NodeId]) -> Vec<NodeId> {
|
||||
let (layer, insert_index) = match target {
|
||||
ChainInsertionPoint::BesideLayer(layer) => (layer, 0),
|
||||
ChainInsertionPoint::BesideNode(node_id) => {
|
||||
let Some((layer, reorderable, _)) = self.reorderable_chain_nodes(&[node_id], network_path) else {
|
||||
return Vec::new();
|
||||
};
|
||||
(layer, reorderable.iter().position(|id| *id == node_id).unwrap_or_default())
|
||||
}
|
||||
};
|
||||
|
||||
self.insert_into_chain(layer, copies, insert_index, network_path)
|
||||
}
|
||||
|
||||
/// Copies a node from a layer's chain so it can be inserted into a chain here or in another document.
|
||||
pub fn copy_chain_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<ChainNodeCopy> {
|
||||
// Placed where its original is until the chain it's inserted into positions it
|
||||
let mut template = self.create_node_template(node_id, network_path)?;
|
||||
template.node_type_metadata = NodeTypePersistentMetadata::node(self.position(node_id, network_path).unwrap_or_default());
|
||||
|
||||
let fallback_values = template
|
||||
.inputs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, input)| matches!(input, NodeInput::Node { .. } | NodeInput::Import { .. }))
|
||||
.map(|(index, _)| {
|
||||
(
|
||||
index,
|
||||
NodeInput::value(self.tagged_value_from_input(&InputConnector::node_at_index(*node_id, index), network_path), true),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
Some(ChainNodeCopy {
|
||||
source: *node_id,
|
||||
template,
|
||||
fallback_values,
|
||||
})
|
||||
}
|
||||
|
||||
/// The nodes of a layer's chain that can be reordered (all but a source node fixed at its upstream end), ordered from the layer outward.
|
||||
pub fn reorderable_chain(&self, layer: NodeId, network_path: &[NodeId]) -> Vec<NodeId> {
|
||||
self.layer_chain(layer, network_path).map(|(reorderable, _)| reorderable).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// All nodes in a layer's chain, ordered from the layer outward, stopping where the next layer begins (since flow turns from horizontal to vertical there).
|
||||
pub fn layer_chain_nodes(&self, layer: NodeId, network_path: &[NodeId]) -> Vec<NodeId> {
|
||||
self.upstream_flow_back_from_nodes(vec![layer], network_path, FlowType::HorizontalFlow)
|
||||
.skip(1)
|
||||
.take_while(|upstream_id| !self.is_layer(upstream_id, network_path))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Inserts copied nodes together (in their given order) into a layer's chain at the `insert_index` gap among its reorderable nodes, where gap 0 is beside
|
||||
/// the layer. Each copy stays wired to whatever fed its other (non-primary) inputs where that exists here without closing a cycle, or else takes their
|
||||
/// fallback values. Returns the IDs of the new nodes, or none when they can't join the chain.
|
||||
fn insert_into_chain(&mut self, layer: NodeId, copies: Vec<ChainNodeCopy>, insert_index: usize, network_path: &[NodeId]) -> Vec<NodeId> {
|
||||
let Some((reorderable, tail_input)) = self.layer_chain(layer, network_path) else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let mut new_ids = Vec::new();
|
||||
let mut reconnections = Vec::new();
|
||||
for copy in copies {
|
||||
let Some((new_id, copy_reconnections)) = self.insert_copy(copy, network_path) else { continue };
|
||||
new_ids.push(new_id);
|
||||
reconnections.extend(copy_reconnections);
|
||||
}
|
||||
|
||||
let mut new_order = reorderable.clone();
|
||||
let insert_index = insert_index.min(new_order.len());
|
||||
new_order.splice(insert_index..insert_index, new_ids.iter().copied());
|
||||
|
||||
// Copies that would close a cycle are removed, and the chain is put back as it was
|
||||
if !self.rewire_chain(layer, &new_order, tail_input.clone(), network_path) {
|
||||
self.rewire_chain(layer, &reorderable, tail_input, network_path);
|
||||
self.delete_nodes(new_ids, false, network_path);
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
// Reconnected only once the copies are in the chain, so a wire that would close a cycle through it is refused and leaves the fallback value
|
||||
for (input_connector, input) in reconnections {
|
||||
self.set_input(&input_connector, input, network_path);
|
||||
}
|
||||
|
||||
new_ids
|
||||
}
|
||||
|
||||
/// Inserts a copied node with its wired inputs set to their fallback values (as `insert_node` requires). Returns the new node along with the wires to
|
||||
/// restore to its other (non-primary) inputs where their sources exist here, which the caller reconnects once the node is wired in so the bookkeeping
|
||||
/// stays current and a wire that would close a cycle is refused.
|
||||
fn insert_copy(&mut self, copy: ChainNodeCopy, network_path: &[NodeId]) -> Option<(NodeId, Vec<(InputConnector, NodeInput)>)> {
|
||||
let ChainNodeCopy { mut template, fallback_values, .. } = copy;
|
||||
let new_id = NodeId::new();
|
||||
|
||||
let mut reconnections = Vec::new();
|
||||
for (index, fallback_value) in fallback_values {
|
||||
let Some(input) = template.inputs.get_mut(index) else { continue };
|
||||
let wired_input = std::mem::replace(input, fallback_value);
|
||||
if index == 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
// A copy from another document names sources missing here, so they're looked up without logging an error
|
||||
let source_exists = match &wired_input {
|
||||
NodeInput::Node { node_id, .. } => self.nested_network(network_path).is_some_and(|network| network.nodes.contains_key(node_id)),
|
||||
NodeInput::Import { import_index, .. } => *import_index < self.number_of_imports(network_path),
|
||||
_ => false,
|
||||
};
|
||||
input
|
||||
if source_exists {
|
||||
reconnections.push((InputConnector::node_at_index(new_id, index), wired_input));
|
||||
}
|
||||
}
|
||||
if template.inputs.iter().any(|input| matches!(input, NodeInput::Node { .. } | NodeInput::Import { .. })) {
|
||||
log::error!("A copied node is missing the fallback value for a wired input in insert_copy");
|
||||
return None;
|
||||
}
|
||||
|
||||
self.insert_node(new_id, template, network_path);
|
||||
Some((new_id, reconnections))
|
||||
}
|
||||
|
||||
/// The layer whose chain the given nodes belong to, along with what `layer_chain` gives for it. Fails unless every given node is a reorderable node of that chain.
|
||||
fn reorderable_chain_nodes(&self, node_ids: &[NodeId], network_path: &[NodeId]) -> Option<(NodeId, Vec<NodeId>, NodeInput)> {
|
||||
let first_node_id = node_ids.first()?;
|
||||
let Some(layer) = self.downstream_layer_for_chain_node(first_node_id, network_path) else {
|
||||
log::error!("Could not find downstream layer for chain node {first_node_id} in reorderable_chain_nodes");
|
||||
return None;
|
||||
};
|
||||
let (reorderable, tail_input) = self.layer_chain(layer, network_path)?;
|
||||
|
||||
if let Some(node_id) = node_ids.iter().find(|node_id| !reorderable.contains(node_id)) {
|
||||
log::error!("Node {node_id} is not a reorderable node in the same layer's chain in reorderable_chain_nodes");
|
||||
return None;
|
||||
}
|
||||
|
||||
Some((layer, reorderable, tail_input))
|
||||
}
|
||||
|
||||
/// A layer chain's reorderable nodes (all but a source node fixed at its upstream end) ordered from the layer outward, and whatever feeds the chain's upstream end.
|
||||
fn layer_chain(&self, layer: NodeId, network_path: &[NodeId]) -> Option<(Vec<NodeId>, NodeInput)> {
|
||||
if !self.is_layer(&layer, network_path) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let chain = self.layer_chain_nodes(layer, network_path);
|
||||
|
||||
// A source node (no primary input) stays pinned at the most-upstream end; only the nodes below it reorder
|
||||
let pinned_source = chain.last().copied().filter(|last| !self.has_primary_input(last, network_path));
|
||||
let reorderable = chain[..chain.len() - pinned_source.is_some() as usize].to_vec();
|
||||
|
||||
// The most-upstream reorderable node connects up to the pinned source, or else whatever fed the top of the chain (or the layer, when the chain is empty)
|
||||
let tail_input = match (pinned_source, chain.last()) {
|
||||
(Some(source), _) => NodeInput::node(source, 0),
|
||||
(None, Some(last)) => self.input_from_connector(&InputConnector::primary_input(*last), network_path)?.clone(),
|
||||
(None, None) => self.input_from_connector(&InputConnector::layer_secondary_input(layer), network_path)?.clone(),
|
||||
};
|
||||
|
||||
Some((reorderable, tail_input))
|
||||
}
|
||||
|
||||
/// Rewires a layer's chain to run through `new_order` from the layer outward, with the last node fed by `tail_input`.
|
||||
/// Returns whether that took, since a connection that would close a cycle is refused.
|
||||
fn rewire_chain(&mut self, layer: NodeId, new_order: &[NodeId], tail_input: NodeInput, network_path: &[NodeId]) -> bool {
|
||||
let intended_chain = Some((new_order.to_vec(), tail_input.clone()));
|
||||
|
||||
// With no nodes left in the chain, the layer is fed directly by what fed its upstream end
|
||||
let (Some(&first), Some(&last)) = (new_order.first(), new_order.last()) else {
|
||||
self.set_input(&InputConnector::layer_secondary_input(layer), tail_input, network_path);
|
||||
return self.layer_chain(layer, network_path) == intended_chain;
|
||||
};
|
||||
|
||||
// Disconnect first so the rewiring can't transiently form a cycle (the pinned source keeps its wiring)
|
||||
for &chain_node in reorderable {
|
||||
for &chain_node in new_order {
|
||||
self.disconnect_input(&InputConnector::primary_input(chain_node), network_path);
|
||||
}
|
||||
|
||||
// Rewire in the new order: layer's secondary input -> new_order[0] -> ... -> new_order[last] -> tail input
|
||||
self.set_input(&InputConnector::layer_secondary_input(layer), NodeInput::node(new_order[0], 0), network_path);
|
||||
self.set_input(&InputConnector::layer_secondary_input(layer), NodeInput::node(first, 0), network_path);
|
||||
for pair in new_order.windows(2) {
|
||||
self.set_input(&InputConnector::primary_input(pair[0]), NodeInput::node(pair[1], 0), network_path);
|
||||
}
|
||||
self.set_input(&InputConnector::primary_input(*new_order.last().unwrap()), tail_input, network_path);
|
||||
self.set_input(&InputConnector::primary_input(last), tail_input, network_path);
|
||||
|
||||
// Re-establish chain positioning for the reordered nodes
|
||||
self.force_set_upstream_to_chain(&new_order[0], network_path);
|
||||
// Re-establish chain positioning for the rewired nodes
|
||||
self.force_set_upstream_to_chain(&first, network_path);
|
||||
|
||||
self.layer_chain(layer, network_path) == intended_chain
|
||||
}
|
||||
}
|
||||
+33
-9
@@ -945,11 +945,19 @@ impl NodeNetworkInterface {
|
||||
|
||||
pub fn start_previewing_without_restore(&mut self, network_path: &[NodeId]) {
|
||||
// Some logic will have to be performed to prevent the graph positions from being completely changed when the export changes to some previewed node
|
||||
let Some(mut network) = self.network_mut(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in start_previewing_without_restore");
|
||||
return;
|
||||
};
|
||||
network.set_previewing(Previewing::Yes { root_node_to_restore: None });
|
||||
self.set_previewing_state(Previewing::Yes { root_node_to_restore: None }, network_path);
|
||||
}
|
||||
|
||||
/// While previewing, changes which node output the export is reconnected to once the preview ends.
|
||||
pub fn set_root_node_to_restore(&mut self, root_node_to_restore: RootNode, network_path: &[NodeId]) {
|
||||
if let Previewing::Yes { .. } = self.previewing(network_path) {
|
||||
self.set_previewing_state(
|
||||
Previewing::Yes {
|
||||
root_node_to_restore: Some(root_node_to_restore),
|
||||
},
|
||||
network_path,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn stop_previewing(&mut self, network_path: &[NodeId]) {
|
||||
@@ -964,11 +972,18 @@ impl NodeNetworkInterface {
|
||||
);
|
||||
}
|
||||
|
||||
self.set_previewing_state(Previewing::No, network_path);
|
||||
}
|
||||
|
||||
fn set_previewing_state(&mut self, previewing: Previewing, network_path: &[NodeId]) {
|
||||
let Some(mut network) = self.network_mut(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in stop_previewing");
|
||||
log::error!("Could not get nested network_metadata in set_previewing_state");
|
||||
return;
|
||||
};
|
||||
network.set_previewing(Previewing::No);
|
||||
network.set_previewing(previewing);
|
||||
|
||||
// The export's wire is dashed only while previewing
|
||||
self.unload_wire(&InputConnector::Export(0), network_path);
|
||||
}
|
||||
|
||||
pub fn set_display_name(&mut self, node_id: &NodeId, display_name: String, network_path: &[NodeId]) {
|
||||
@@ -985,6 +1000,16 @@ impl NodeNetworkInterface {
|
||||
self.invalidate_node_appearance(node_id, network_path);
|
||||
}
|
||||
|
||||
/// Replaces the full list of output port names for a node. Used by document migrations that turn a single-output node
|
||||
/// into a multi-output one, since the port labels are otherwise unnamed and fall back to the type name.
|
||||
pub fn set_output_names(&mut self, node_id: &NodeId, output_names: Vec<String>, network_path: &[NodeId]) {
|
||||
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
|
||||
log::error!("Could not get node {node_id} in set_output_names");
|
||||
return;
|
||||
};
|
||||
node.set_output_names(output_names);
|
||||
}
|
||||
|
||||
pub fn set_import_export_name(&mut self, name: String, index: ImportOrExport, network_path: &[NodeId]) {
|
||||
let Some((encapsulating_node_id, encapsulating_network_path)) = network_path.split_last() else {
|
||||
log::error!("Could not get encapsulating network in set_import_export_name");
|
||||
@@ -1244,7 +1269,6 @@ impl NodeNetworkInterface {
|
||||
self.disconnect_input(&InputConnector::Export(0), network_path);
|
||||
}
|
||||
}
|
||||
let Some(mut network) = self.network_mut(network_path) else { return };
|
||||
network.set_previewing(new_previewing_state);
|
||||
self.set_previewing_state(new_previewing_state, network_path);
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,11 @@ impl NodeNetworkInterface {
|
||||
self.transaction_status
|
||||
}
|
||||
|
||||
/// The document network nodes the open transaction has written to, as of the last [`Self::update_transaction_edited_nodes`].
|
||||
pub fn transaction_edited_nodes(&self) -> &HashSet<NodeId> {
|
||||
&self.transaction_edited_nodes
|
||||
}
|
||||
|
||||
pub fn selected_nodes(&self) -> SelectedNodes {
|
||||
self.selected_nodes_in_nested_network(&[]).unwrap_or_default()
|
||||
}
|
||||
@@ -510,6 +515,13 @@ impl NodeNetworkInterface {
|
||||
self.query(network_path, "reference", |view| view.reference(node_id)).flatten()
|
||||
}
|
||||
|
||||
/// The icon of the node's definition, or the Custom Node icon when its definition has none or can't be found.
|
||||
pub fn node_icon(&self, node_id: &NodeId, network_path: &[NodeId]) -> &'static str {
|
||||
self.reference(node_id, network_path)
|
||||
.and_then(|reference| resolve_document_node_type(&reference)?.icon)
|
||||
.unwrap_or("NodeCustomNode")
|
||||
}
|
||||
|
||||
pub fn implementation(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&DocumentNodeImplementation> {
|
||||
self.query(network_path, "implementation", |view| view.implementation(node_id))
|
||||
}
|
||||
|
||||
+136
-30
@@ -4,6 +4,7 @@ use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNodeImplementation, InlineRust, NodeInput};
|
||||
use graph_craft::proto::{GraphErrorType, GraphErrors};
|
||||
use graph_craft::{ProtoNodeIdentifier, Type, concrete};
|
||||
use graphene_std::NodeIOTypes;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use interpreted_executor::dynamic_executor::{NodeTypes, ResolvedDocumentNodeTypesDelta};
|
||||
use interpreted_executor::node_registry::NODE_REGISTRY;
|
||||
@@ -11,6 +12,23 @@ use interpreted_executor::node_registry::NODE_REGISTRY;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface, OutputConnector};
|
||||
|
||||
/// Whether a `source` type can feed a `connector` type, directly or through the `input_adapter` node the compiler inserts to convert elements (such as `Color` into `Graphic`).
|
||||
pub fn type_feeds_connector(source: &Type, connector: &Type) -> bool {
|
||||
let source = source.nested_type();
|
||||
let connector = connector.nested_type();
|
||||
if source == connector {
|
||||
return true;
|
||||
}
|
||||
|
||||
let (Type::Item(element) | Type::List(element)) = connector else { return false };
|
||||
let adapter = ProtoNodeIdentifier::with_owned_string(format!("input_adapter<{}>", element.identifier_name()));
|
||||
NODE_REGISTRY.get(&adapter).is_some_and(|implementations| {
|
||||
implementations
|
||||
.keys()
|
||||
.any(|node_io| node_io.return_value.nested_type() == connector && node_io.inputs.first().is_some_and(|input| input.nested_type() == source))
|
||||
})
|
||||
}
|
||||
|
||||
// This file contains utility methods for interfacing with the resolved types returned from the compiler
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ResolvedDocumentNodeTypes {
|
||||
@@ -81,7 +99,7 @@ impl TypeSource {
|
||||
}
|
||||
}
|
||||
|
||||
/// Used when searching for nodes in the add Node popup.
|
||||
/// Used when searching for nodes in the add node menu.
|
||||
pub fn add_node_string(self) -> Option<String> {
|
||||
self.compiled_nested_type().map(|ty| format!("type:{ty}"))
|
||||
}
|
||||
@@ -290,31 +308,10 @@ impl NodeNetworkInterface {
|
||||
|
||||
intersection.into_iter().collect::<Vec<_>>()
|
||||
}
|
||||
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => {
|
||||
let Some(implementations) = NODE_REGISTRY.get(proto_node_identifier) else {
|
||||
// The compiler removes the passthrough node, so it's expected to be absent from the registry
|
||||
if proto_node_identifier != &graphene_std::ops::passthrough::IDENTIFIER {
|
||||
log::error!("Proto node `{proto_node_identifier:?}` not found in the node registry, in potential_valid_input_types");
|
||||
}
|
||||
return Vec::new();
|
||||
};
|
||||
let number_of_inputs = self.number_of_inputs(node_id, network_path);
|
||||
implementations
|
||||
.keys()
|
||||
.filter_map(|node_io| {
|
||||
// Check if this NodeIOTypes implementation is valid for the other inputs
|
||||
let valid_implementation = (0..number_of_inputs).filter(|iterator_index| iterator_index != input_index).all(|iterator_index| {
|
||||
let input_type = self.input_type_not_invalid(&InputConnector::node_at_index(*node_id, iterator_index), network_path);
|
||||
// TODO: Fix type checking for different call arguments
|
||||
// For example a node input of (Footprint) -> Vector would not be compatible with a node that is called with () and returns Vector
|
||||
node_io.inputs.get(iterator_index).map(|ty| ty.nested_type()) == input_type.compiled_nested_type()
|
||||
});
|
||||
|
||||
// If so, then return the input at the chosen index
|
||||
if valid_implementation { node_io.inputs.get(*input_index).cloned() } else { None }
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => self
|
||||
.implementations_matching_inputs(proto_node_identifier, node_id, Some(*input_index), network_path)
|
||||
.filter_map(|node_io| node_io.inputs.get(*input_index).cloned())
|
||||
.collect::<Vec<_>>(),
|
||||
DocumentNodeImplementation::Extract => {
|
||||
log::error!("Input types for extract node not supported");
|
||||
Vec::new()
|
||||
@@ -322,6 +319,63 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
/// The types an output could produce: its compiled type, or else the return types of the registry implementations matching its node's inputs.
|
||||
pub fn potential_output_types(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Vec<Type> {
|
||||
if let Some(compiled_type) = self.output_type(output_connector, network_path).compiled_nested_type() {
|
||||
return vec![compiled_type.clone()];
|
||||
}
|
||||
|
||||
// Nodes outside the compiled graph, such as disconnected ones, have no resolved type
|
||||
let OutputConnector::Node { node_id, output_index: 0 } = output_connector else {
|
||||
log::debug!("[wire-drag] No registry fallback for {output_connector:?}");
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) else {
|
||||
log::debug!("[wire-drag] No registry fallback for non-proto node implementation {:?}", self.implementation(node_id, network_path));
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let all_implementations = NODE_REGISTRY.get(proto_node_identifier).map(|implementations| implementations.keys().cloned().collect::<Vec<_>>());
|
||||
let input_types = (0..self.number_of_inputs(node_id, network_path))
|
||||
.map(|index| self.input_type_not_invalid(&InputConnector::node_at_index(*node_id, index), network_path))
|
||||
.collect::<Vec<_>>();
|
||||
log::debug!("[wire-drag] Registry fallback for {proto_node_identifier:?} with input types {input_types:?} among implementations {all_implementations:?}");
|
||||
|
||||
self.implementations_matching_inputs(proto_node_identifier, node_id, None, network_path)
|
||||
.map(|node_io| node_io.return_value.nested_type().clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The registry implementations of a proto node whose inputs accept the node's current input types, ignoring `disregarded_input_index`.
|
||||
fn implementations_matching_inputs<'a>(
|
||||
&'a self,
|
||||
proto_node_identifier: &ProtoNodeIdentifier,
|
||||
node_id: &'a NodeId,
|
||||
disregarded_input_index: Option<usize>,
|
||||
network_path: &'a [NodeId],
|
||||
) -> impl Iterator<Item = &'static NodeIOTypes> + 'a {
|
||||
let implementations = NODE_REGISTRY.get(proto_node_identifier);
|
||||
|
||||
// The compiler removes the passthrough node, so it's expected to be absent from the registry
|
||||
if implementations.is_none() && proto_node_identifier != &graphene_std::ops::passthrough::IDENTIFIER {
|
||||
log::error!("Proto node `{proto_node_identifier:?}` not found in the node registry");
|
||||
}
|
||||
|
||||
let number_of_inputs = self.number_of_inputs(node_id, network_path);
|
||||
implementations.into_iter().flat_map(|implementations| implementations.keys()).filter(move |node_io| {
|
||||
(0..number_of_inputs).filter(|index| Some(*index) != disregarded_input_index).all(|index| {
|
||||
let input_type = self.input_type_not_invalid(&InputConnector::node_at_index(*node_id, index), network_path);
|
||||
// TODO: Fix type checking for different call arguments
|
||||
// For example a node input of (Footprint) -> Vector would not be compatible with a node that is called with () and returns Vector
|
||||
match (input_type.compiled_nested_type(), node_io.inputs.get(index)) {
|
||||
(Some(source), Some(connector)) => type_feeds_connector(source, connector),
|
||||
(None, None) => true,
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Performs a downstream traversal to ensure input type will work in the full context of the graph.
|
||||
pub fn complete_valid_input_types(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Vec<Type> {
|
||||
match input_connector {
|
||||
@@ -377,6 +431,20 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a multi-output node is framed over a list, which happens when a list reaches any input its single-item variant takes as an `Item`.
|
||||
fn multi_output_node_is_mapped(&self, node_id: &NodeId, identifier: &ProtoNodeIdentifier, mapped_type: &Type, network_path: &[NodeId]) -> bool {
|
||||
let Some(implementations) = NODE_REGISTRY.get(identifier) else { return false };
|
||||
let Some(single_item_variant) = implementations.keys().find(|node_io| node_io.return_value.nested_type() != mapped_type) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
single_item_variant
|
||||
.inputs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.any(|(input_index, declared_type)| matches!(declared_type.nested_type(), Type::Item(_)) && self.input_type(&InputConnector::node_at_index(*node_id, input_index), network_path).is_list())
|
||||
}
|
||||
|
||||
pub fn output_type(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> TypeSource {
|
||||
match output_connector {
|
||||
OutputConnector::Node { node_id, output_index } => {
|
||||
@@ -395,10 +463,26 @@ impl NodeNetworkInterface {
|
||||
DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::ops::passthrough::IDENTIFIER => {
|
||||
self.input_type(&InputConnector::primary_input(*node_id), network_path)
|
||||
}
|
||||
DocumentNodeImplementation::ProtoNode(_) => match self.resolved_types.types.get(&[network_path, &[*node_id]].concat()) {
|
||||
Some(resolved_type) => TypeSource::Compiled(resolved_type.output.clone()),
|
||||
None => TypeSource::Unknown,
|
||||
},
|
||||
DocumentNodeImplementation::ProtoNode(identifier) => {
|
||||
// A multi-output proto node's field output types are recorded in the registry, as lists in its mapped variant.
|
||||
// The hidden primary output has no field, so it falls through to the compiled types below.
|
||||
if let Some(metadata) = graphene_std::registry::MULTI_OUTPUT_NODES.get(identifier)
|
||||
&& let Some(field_index) = metadata.field_index_for_output(*output_index)
|
||||
{
|
||||
return match metadata.fields.get(field_index) {
|
||||
Some(field) => {
|
||||
let is_mapped = self.multi_output_node_is_mapped(node_id, identifier, &metadata.mapped_type, network_path);
|
||||
TypeSource::Compiled(if is_mapped { field.mapped_ty.clone() } else { field.ty.clone() })
|
||||
}
|
||||
None => TypeSource::Error("Output index out of range for proto node"),
|
||||
};
|
||||
}
|
||||
|
||||
match self.resolved_types.types.get(&[network_path, &[*node_id]].concat()) {
|
||||
Some(resolved_type) => TypeSource::Compiled(resolved_type.output.clone()),
|
||||
None => TypeSource::Unknown,
|
||||
}
|
||||
}
|
||||
DocumentNodeImplementation::Extract => TypeSource::Compiled(concrete!(())),
|
||||
}
|
||||
}
|
||||
@@ -435,3 +519,25 @@ impl NodeNetworkInterface {
|
||||
intersection.into_iter().collect::<Vec<_>>()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::type_feeds_connector;
|
||||
use graph_craft::item;
|
||||
use graphene_std::vector::style::DashPattern;
|
||||
use graphene_std::{Color, Graphic};
|
||||
|
||||
#[test]
|
||||
fn input_adapter_conversions_feed_connectors() {
|
||||
assert!(type_feeds_connector(&item!(f64), &item!(f64)), "identical types should match directly");
|
||||
assert!(
|
||||
type_feeds_connector(&item!(Color), &item!(Graphic)),
|
||||
"a color paint should feed a graphic paint connector through its input adapter"
|
||||
);
|
||||
assert!(
|
||||
type_feeds_connector(&item!(f64), &item!(DashPattern)),
|
||||
"a number should feed a dash pattern connector through its input adapter"
|
||||
);
|
||||
assert!(!type_feeds_connector(&item!(f64), &item!(Graphic)), "a number has no conversion into a graphic");
|
||||
}
|
||||
}
|
||||
+47
-2
@@ -319,16 +319,61 @@ impl NodeNetworkInterface {
|
||||
self.network.network().nested_network(network_path).is_some() && self.network_metadata.nested_metadata(network_path).is_some()
|
||||
}
|
||||
|
||||
/// Takes what the writes since the last drain changed, in write order, leaving the buffer empty.
|
||||
/// Takes what the writes since the last drain changed, in write order, leaving the buffer empty
|
||||
/// after reading it for the nodes an open transaction has written to.
|
||||
pub(crate) fn take_deltas(&mut self) -> Vec<EditorDelta> {
|
||||
self.scan_transaction_edited_nodes();
|
||||
self.transaction_edited_nodes_scanned = 0;
|
||||
std::mem::take(&mut self.deltas)
|
||||
}
|
||||
|
||||
/// Drops what the writes since the last drain changed, for writes that are not edits to the document.
|
||||
/// Drops what the writes since the last drain changed, for writes that are not edits to the document,
|
||||
/// after reading it for the nodes an open transaction has written to.
|
||||
pub(crate) fn discard_deltas(&mut self) {
|
||||
self.scan_transaction_edited_nodes();
|
||||
self.transaction_edited_nodes_scanned = 0;
|
||||
self.deltas.clear();
|
||||
}
|
||||
|
||||
/// Reads the open transaction's writes since the last call, returning whether that changed which nodes it has written to.
|
||||
pub fn update_transaction_edited_nodes(&mut self) -> bool {
|
||||
self.scan_transaction_edited_nodes();
|
||||
std::mem::take(&mut self.transaction_edited_nodes_changed)
|
||||
}
|
||||
|
||||
/// Notes the document network nodes that the unread writes of an open transaction added, or set an input value of.
|
||||
fn scan_transaction_edited_nodes(&mut self) {
|
||||
if self.transaction_status != TransactionStatus::Finished {
|
||||
let new_deltas = self.deltas.get(self.transaction_edited_nodes_scanned..).unwrap_or_default();
|
||||
let edited_nodes = new_deltas
|
||||
.iter()
|
||||
.filter_map(|delta| match delta {
|
||||
EditorDelta::Graph(RuntimeDelta::AddNode { network_path, node_id, .. } | RuntimeDelta::ReplaceNode { network_path, node_id, .. }) if network_path.is_empty() => Some(*node_id),
|
||||
// Judged by what the input holds now, since splicing in a node briefly disconnects a wire to a placeholder value
|
||||
EditorDelta::Graph(RuntimeDelta::SetInput {
|
||||
network_path, node_id, input_index, ..
|
||||
}) if network_path.is_empty() => {
|
||||
let input = self.input_from_connector(&InputConnector::node_at_index(*node_id, *input_index), &[]);
|
||||
input.is_some_and(|input| input.as_value().is_some()).then_some(*node_id)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
for node_id in edited_nodes {
|
||||
self.transaction_edited_nodes_changed |= self.transaction_edited_nodes.insert(node_id);
|
||||
}
|
||||
}
|
||||
self.transaction_edited_nodes_scanned = self.deltas.len();
|
||||
}
|
||||
|
||||
pub(super) fn clear_transaction_edited_nodes(&mut self) {
|
||||
if !self.transaction_edited_nodes.is_empty() {
|
||||
self.transaction_edited_nodes.clear();
|
||||
self.transaction_edited_nodes_changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops the network's link to the definition it was instantiated from, which no longer describes it
|
||||
/// once its signature is edited.
|
||||
pub(crate) fn clear_encapsulating_reference(&mut self, network_path: &[NodeId]) {
|
||||
|
||||
@@ -29,6 +29,46 @@ pub fn ellipse_path(corner1: DVec2, corner2: DVec2) -> BezPath {
|
||||
path
|
||||
}
|
||||
|
||||
/// A copy of a node from a layer's chain, which can be inserted into a chain in this or another document.
|
||||
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ChainNodeCopy {
|
||||
/// The node that was copied.
|
||||
pub source: NodeId,
|
||||
pub template: NodeTemplate,
|
||||
/// The value of each input wired to another node, which the copy takes where that node is missing.
|
||||
pub fallback_values: Vec<(usize, NodeInput)>,
|
||||
}
|
||||
|
||||
impl ChainNodeCopy {
|
||||
/// The copied node with each of its wired inputs taking its fallback value, placed offset from its original, for pasting outside any flow.
|
||||
pub fn into_loose_template(self) -> NodeTemplate {
|
||||
let mut template = self.template;
|
||||
for (index, fallback_value) in self.fallback_values {
|
||||
if let Some(input) = template.inputs.get_mut(index) {
|
||||
*input = fallback_value;
|
||||
}
|
||||
}
|
||||
|
||||
if let NodeTypePersistentMetadata::Node(NodePersistentMetadata {
|
||||
position: NodePosition::Absolute(position),
|
||||
}) = &mut template.node_type_metadata
|
||||
{
|
||||
*position += IVec2::new(2, 2);
|
||||
}
|
||||
|
||||
template
|
||||
}
|
||||
}
|
||||
|
||||
/// Where copied nodes go when inserted into a layer's chain.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ChainInsertionPoint {
|
||||
/// Beside a node in a layer's chain, just downstream of it.
|
||||
BesideNode(NodeId),
|
||||
/// At the downstream end of a layer's chain, beside the layer.
|
||||
BesideLayer(NodeId),
|
||||
}
|
||||
|
||||
#[derive(PartialEq)]
|
||||
pub enum FlowType {
|
||||
/// Iterate over all upstream nodes (inclusive) from every input (the primary and all secondary).
|
||||
|
||||
@@ -244,6 +244,8 @@ impl<'a, 'p> NetworkView<'a, 'p> {
|
||||
pub fn number_of_outputs(&self, node_id: &NodeId) -> Result<usize, NetworkError> {
|
||||
Ok(match self.implementation(node_id)? {
|
||||
DocumentNodeImplementation::Network(nested_network) => nested_network.exports.len(),
|
||||
// A multi-output proto node has an output for each field of the struct it returns
|
||||
DocumentNodeImplementation::ProtoNode(identifier) => MULTI_OUTPUT_NODES.get(identifier).map_or(1, |metadata| metadata.number_of_outputs()),
|
||||
_ => 1,
|
||||
})
|
||||
}
|
||||
@@ -264,6 +266,7 @@ impl<'a, 'p> NetworkView<'a, 'p> {
|
||||
pub fn hidden_primary_output(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
|
||||
Ok(match self.implementation(node_id)? {
|
||||
DocumentNodeImplementation::Network(network) => network.exports.first().is_none_or(|input| !input.is_exposed()),
|
||||
DocumentNodeImplementation::ProtoNode(identifier) => MULTI_OUTPUT_NODES.get(identifier).is_some_and(|metadata| metadata.hidden_primary_output()),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
|
||||
use super::network_interface::NodeNetworkInterface;
|
||||
use crate::messages::frontend::IconName;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use glam::DVec2;
|
||||
use graph_craft::document::{NodeId, NodeNetwork};
|
||||
@@ -30,7 +31,22 @@ pub struct LayerPanelEntry {
|
||||
#[serde(rename = "implementationName")]
|
||||
pub implementation_name: String,
|
||||
#[serde(rename = "iconName")]
|
||||
pub icon_name: Option<IconName>,
|
||||
pub icon_name: IconName,
|
||||
/// The nodes in the chain feeding this layer, in the graph's left-to-right order.
|
||||
#[serde(rename = "chainNodes")]
|
||||
pub chain_nodes: Vec<LayerPanelChainNode>,
|
||||
/// The data type flowing from the chain into the layer, which colors the connector between them.
|
||||
#[serde(rename = "chainDataType")]
|
||||
pub chain_data_type: FrontendGraphDataType,
|
||||
/// How the active tool edits the layer node itself, if it does, for the tooltip of its outlined icon.
|
||||
#[serde(rename = "toolTargetDescription")]
|
||||
pub tool_target_description: Option<String>,
|
||||
/// Whether an edit in progress, like a drag, has written to the layer node itself, which brightens its icon's outline.
|
||||
#[serde(rename = "editInProgress")]
|
||||
pub edit_in_progress: bool,
|
||||
/// The node the active tool would add to the chain to edit this layer, shown ghosted where it would go.
|
||||
#[serde(rename = "toolTargetInsertion")]
|
||||
pub tool_target_insertion: Option<LayerPanelChainInsertion>,
|
||||
pub alias: String,
|
||||
#[serde(rename = "inSelectedNetwork")]
|
||||
pub in_selected_network: bool,
|
||||
@@ -45,6 +61,37 @@ pub struct LayerPanelEntry {
|
||||
pub clippable: bool,
|
||||
}
|
||||
|
||||
/// A node in the chain feeding a layer, shown as a button with its icon in the layer's row.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
|
||||
pub struct LayerPanelChainNode {
|
||||
pub id: NodeId,
|
||||
pub icon: IconName,
|
||||
pub name: String,
|
||||
/// Whether the node is selected, shown in every layer whose chain shares it.
|
||||
pub selected: bool,
|
||||
/// Whether the node can be dragged to reorder it, unlike a source node (with no primary input) fixed at the chain's upstream end.
|
||||
pub reorderable: bool,
|
||||
pub visible: bool,
|
||||
/// How the active tool edits this node, if it does, for the tooltip of its outlined icon.
|
||||
#[serde(rename = "toolTargetDescription")]
|
||||
pub tool_target_description: Option<String>,
|
||||
/// Whether an edit in progress, like a drag, has written to this node, which brightens its outline.
|
||||
#[serde(rename = "editInProgress")]
|
||||
pub edit_in_progress: bool,
|
||||
}
|
||||
|
||||
/// A node not yet in a layer's chain, which the active tool would add there.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
|
||||
pub struct LayerPanelChainInsertion {
|
||||
/// The position among the chain nodes, counted from the upstream end.
|
||||
pub index: u32,
|
||||
pub icon: IconName,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
}
|
||||
|
||||
/// IMPORTANT: the same node may appear multiple times.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
|
||||
|
||||
@@ -14,6 +14,8 @@ use graph_craft::{Type, concrete, item, list};
|
||||
use graphene_std::Color;
|
||||
use graphene_std::ParameterRef;
|
||||
use graphene_std::ProtoNodeIdentifier;
|
||||
use graphene_std::extract_xy::XY;
|
||||
use graphene_std::raster::RedGreenBlueAlpha;
|
||||
use graphene_std::text::{TextAlign, TypesettingConfig};
|
||||
use graphene_std::transform::ScaleType;
|
||||
use graphene_std::uuid::NodeId;
|
||||
@@ -53,6 +55,13 @@ fn into_group_aliases() -> impl Iterator<Item = &'static &'static str> {
|
||||
.flat_map(|replacement| replacement.aliases)
|
||||
}
|
||||
|
||||
/// Clears a migrated node's stored display name if it was only the replaced node's default name, so it shows its new node's name instead.
|
||||
fn reset_default_display_name(document: &mut DocumentMessageHandler, node_id: &NodeId, network_path: &[NodeId], old_default_name: &str) {
|
||||
if document.network_interface.display_name(node_id, network_path) == old_default_name {
|
||||
document.network_interface.set_display_name(node_id, String::new(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
// ================================
|
||||
// blending
|
||||
@@ -82,10 +91,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::animation::animation_time::IDENTIFIER,
|
||||
aliases: &["graphene_core::animation::AnimationTimeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::extract_xy::extract_xy::IDENTIFIER,
|
||||
aliases: &["graphene_core::ops::ExtractXyNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::ops::passthrough::IDENTIFIER,
|
||||
aliases: &[
|
||||
@@ -428,8 +433,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"math_nodes::AsU64Node",
|
||||
],
|
||||
},
|
||||
// The old 'Vec2 Value' node took separate X and Y inputs, a role now filled by 'Combine Vec2', while the new 'Vec2 Value' node takes a single vec2 input.
|
||||
// Old references (including these older aliases) are remapped here to `vec_2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Combine Vec2' node.
|
||||
// The old 'Vec2 Value' node took separate X and Y inputs, a role now filled by 'Numbers to Vec2', while the new 'Vec2 Value' node takes a single vec2 input.
|
||||
// Old references (including these older aliases) are remapped here to `vec_2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Numbers to Vec2' node.
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::vec_2_value::IDENTIFIER,
|
||||
aliases: &[
|
||||
@@ -440,6 +445,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_math_nodes::CoordinateValueNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER,
|
||||
aliases: &["math_nodes::CombineVec2Node"],
|
||||
},
|
||||
// ================================
|
||||
// path bool
|
||||
// ================================
|
||||
@@ -502,8 +511,12 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::std_nodes::combine_channels::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::std_nodes::CombineChannelsNode", "graphene_std::raster::CombineChannelsNode"],
|
||||
node: graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER,
|
||||
aliases: &[
|
||||
"raster_nodes::std_nodes::CombineChannelsNode",
|
||||
"graphene_raster_nodes::std_nodes::CombineChannelsNode",
|
||||
"graphene_std::raster::CombineChannelsNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::dehaze::dehaze::IDENTIFIER,
|
||||
@@ -525,14 +538,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::raster_nodes::std_nodes::extend_image_to_bounds::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::std_nodes::ExtendImageToBoundsNode", "graphene_std::raster::ExtendImageToBoundsNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::adjustments::extract_channel::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_raster_nodes::adjustments::ExtractChannelNode",
|
||||
"graphene_core::raster::adjustments::ExtractChannelNode",
|
||||
"graphene_core::raster::ExtractChannelNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::adjustments::gamma_correction::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::adjustments::GammaCorrectionNode", "graphene_core::raster::adjustments::GammaCorrectionNode"],
|
||||
@@ -935,10 +940,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::vector::scatter_points::IDENTIFIER,
|
||||
aliases: &["graphene_core::vector::PoissonDiskPointsNode", "core_types::vector::PoissonDiskPointsNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::vector::position_on_path::IDENTIFIER,
|
||||
aliases: &["graphene_core::vector::PositionOnPathNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::vector::round_corners::IDENTIFIER,
|
||||
aliases: &["graphene_core::vector::RoundCornersNode"],
|
||||
@@ -971,10 +972,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::vector::stroke::IDENTIFIER,
|
||||
aliases: &["graphene_core::vector::StrokeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::vector::tangent_on_path::IDENTIFIER,
|
||||
aliases: &["graphene_core::vector::TangentOnPathNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::vector::as_vector::IDENTIFIER,
|
||||
aliases: &[
|
||||
@@ -1385,6 +1382,199 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// The "Split Vec2", "Split Vector2", and "Split Channels" wrapper networks became the multi-output `vec2_to_numbers` and `image_to_channels` proto nodes.
|
||||
// A wrapper saved before these gained a hidden primary output had each field one output lower, so its wires shift up by one.
|
||||
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: replacing the outer network impl orphans its child paths.
|
||||
let split_wrapper_replacements = [
|
||||
("Split Vec2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||
("Split Vector2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||
("Split Channels", graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER),
|
||||
];
|
||||
for (old_reference, new_identifier) in split_wrapper_replacements {
|
||||
let split_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter_map(|(node_id, _, path)| (document.network_interface.reference(node_id, &path) == Some(DefinitionIdentifier::Network(old_reference.into()))).then_some((*node_id, path)))
|
||||
.collect();
|
||||
for (node_id, network_path) in &split_nodes {
|
||||
let old_output_count = document.network_interface.number_of_outputs(node_id, network_path);
|
||||
let output_shift = usize::from(!document.network_interface.hidden_primary_output(node_id, network_path));
|
||||
|
||||
// Pre-load `outward_wires` so the chain-break check inside `set_input` resolves the original upstream→node wire from cache
|
||||
// rather than triggering a fresh rebuild from the (already-mutated) post-`replace_inputs` state, which would orphan wires.
|
||||
let downstream_by_output: Vec<Vec<InputConnector>> = match document.network_interface.outward_wires(network_path) {
|
||||
Some(outward_wires) if output_shift > 0 => (0..old_output_count)
|
||||
.map(|output_index| outward_wires.get(&OutputConnector::node(*node_id, output_index)).cloned().unwrap_or_default())
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
|
||||
let new_reference = DefinitionIdentifier::ProtoNode(new_identifier.clone());
|
||||
let Some(definition) = resolve_document_node_type(&new_reference) else { continue };
|
||||
let mut node_template = definition.default_node_template();
|
||||
let output_names = definition.node_template.output_names.clone();
|
||||
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
|
||||
continue;
|
||||
};
|
||||
document.network_interface.set_output_names(node_id, output_names, network_path);
|
||||
reset_default_display_name(document, node_id, network_path, old_reference);
|
||||
|
||||
if let Some(input) = old_inputs.first() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), input.clone(), network_path);
|
||||
}
|
||||
|
||||
for (old_output_index, downstream) in downstream_by_output.iter().enumerate() {
|
||||
for input_connector in downstream {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(input_connector, NodeInput::node(*node_id, old_output_index + output_shift), network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The standalone "Extract XY" and "Extract Channel" nodes were removed in favor of the multi-output "Vec2 to Numbers" and "Image to Channels" nodes.
|
||||
// Convert each to its replacement, moving its downstream wires to the field output for the axis or channel it extracted.
|
||||
const EXTRACT_XY: [&str; 2] = ["graphene_core::extract_xy::ExtractXyNode", "graphene_core::ops::ExtractXyNode"];
|
||||
const EXTRACT_CHANNEL: [&str; 4] = [
|
||||
"raster_nodes::adjustments::ExtractChannelNode",
|
||||
"graphene_raster_nodes::adjustments::ExtractChannelNode",
|
||||
"graphene_core::raster::adjustments::ExtractChannelNode",
|
||||
"graphene_core::raster::ExtractChannelNode",
|
||||
];
|
||||
let extract_nodes: Vec<(NodeId, Vec<NodeId>, ProtoNodeIdentifier, &str)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter_map(|(node_id, node, path)| {
|
||||
let DocumentNodeImplementation::ProtoNode(protonode_id) = &node.implementation else { return None };
|
||||
let name = protonode_id.as_str().split('<').next().unwrap_or_default();
|
||||
if EXTRACT_XY.contains(&name) {
|
||||
Some((*node_id, path, graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER, "Extract XY"))
|
||||
} else if EXTRACT_CHANNEL.contains(&name) {
|
||||
Some((*node_id, path, graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER, "Extract Channel"))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
for (node_id, network_path, new_identifier, old_default_name) in &extract_nodes {
|
||||
// Capture the old output's downstream connections before mutating, so they can be moved to the extracted field's output
|
||||
let downstream_from_output = document
|
||||
.network_interface
|
||||
.outward_wires(network_path)
|
||||
.and_then(|outward_wires| outward_wires.get(&OutputConnector::node(*node_id, 0)))
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(new_identifier.clone())) else {
|
||||
continue;
|
||||
};
|
||||
let mut node_template = definition.default_node_template();
|
||||
let output_names = definition.node_template.output_names.clone();
|
||||
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
|
||||
continue;
|
||||
};
|
||||
document.network_interface.set_output_names(node_id, output_names, network_path);
|
||||
reset_default_display_name(document, node_id, network_path, old_default_name);
|
||||
|
||||
if let Some(input) = old_inputs.first() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), input.clone(), network_path);
|
||||
}
|
||||
|
||||
// The field outputs follow the hidden primary output, in X, Y or red, green, blue, alpha order
|
||||
let output_index = match old_inputs.get(1).and_then(|input| input.as_value()) {
|
||||
Some(TaggedValue::XY(XY::X) | TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Red)) => 1,
|
||||
Some(TaggedValue::XY(XY::Y) | TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Green)) => 2,
|
||||
Some(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Blue)) => 3,
|
||||
Some(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Alpha)) => 4,
|
||||
_ => {
|
||||
log::warn!("Old \"{old_default_name}\" node {node_id} has no fixed axis or channel to migrate, so its wires use the first field output");
|
||||
1
|
||||
}
|
||||
};
|
||||
for input_connector in &downstream_from_output {
|
||||
document.network_interface.set_input(input_connector, NodeInput::node(*node_id, output_index), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// "Position on Path" and "Tangent on Path" were merged into the multi-output "Evaluate Path" node, with position at output 0 and tangent direction at output 1.
|
||||
// Tangent instances get an "Inverse Tangent" node inserted to turn that direction back into the angle their downstream wires expect.
|
||||
const POSITION_ON_PATH: &str = "graphene_core::vector::PositionOnPathNode";
|
||||
const TANGENT_ON_PATH: &str = "graphene_core::vector::TangentOnPathNode";
|
||||
let evaluate_path_nodes: Vec<(NodeId, Vec<NodeId>, bool)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter_map(|(node_id, node, path)| {
|
||||
let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return None };
|
||||
match identifier.as_str() {
|
||||
POSITION_ON_PATH => Some((*node_id, path, false)),
|
||||
TANGENT_ON_PATH => Some((*node_id, path, true)),
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
for (node_id, network_path, is_tangent) in &evaluate_path_nodes {
|
||||
// Capture the old output's downstream connections before mutating, so a tangent node's wires can be moved onto the inserted angle conversion
|
||||
let downstream_from_output = document
|
||||
.network_interface
|
||||
.outward_wires(network_path)
|
||||
.and_then(|outward_wires| outward_wires.get(&OutputConnector::node(*node_id, 0)))
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
let new_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::evaluate_path::IDENTIFIER);
|
||||
let Some(definition) = resolve_document_node_type(&new_reference) else { continue };
|
||||
let mut node_template = definition.default_node_template();
|
||||
let output_names = definition.node_template.output_names.clone();
|
||||
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
|
||||
continue;
|
||||
};
|
||||
// The old single-output nodes have no output names, so set them to match the new multi-output node's "Position", "Tangent", and "Normal" ports
|
||||
document.network_interface.set_output_names(node_id, output_names, network_path);
|
||||
reset_default_display_name(document, node_id, network_path, if *is_tangent { "Tangent on Path" } else { "Position on Path" });
|
||||
|
||||
// Forward the shared inputs: content, progression, reverse, and parameterized distance
|
||||
for (index, input) in old_inputs.iter().take(4).enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
|
||||
}
|
||||
|
||||
if *is_tangent && !downstream_from_output.is_empty() {
|
||||
let Some(inverse_tangent_definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::tangent_inverse::IDENTIFIER)) else {
|
||||
log::error!("Could not resolve the Inverse Tangent node while migrating Tangent on Path node {node_id}");
|
||||
continue;
|
||||
};
|
||||
|
||||
// Feed the tangent direction into the inserted "Inverse Tangent" node, carrying over the old radians input (true when absent, since radians was once the only option)
|
||||
let inverse_tangent_id = NodeId::new();
|
||||
document
|
||||
.network_interface
|
||||
.insert_node(inverse_tangent_id, inverse_tangent_definition.default_node_template(), network_path);
|
||||
let radians = old_inputs.get(4).cloned().unwrap_or_else(|| NodeInput::value(TaggedValue::Bool(true), false));
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(inverse_tangent_id, 1), radians, network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(inverse_tangent_id, 0), NodeInput::node(*node_id, 1), network_path);
|
||||
|
||||
if let Some(position) = document.network_interface.position(node_id, network_path) {
|
||||
document.network_interface.shift_absolute_node_position(&inverse_tangent_id, position + IVec2::new(7, 0), network_path);
|
||||
}
|
||||
|
||||
// Move the tangent node's downstream connections from its old single output to the inserted angle conversion
|
||||
for input_connector in &downstream_from_output {
|
||||
document.network_interface.set_input(input_connector, NodeInput::node(inverse_tangent_id, 0), network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Record which old text nodes are chain-positioned now, before `migrate_node`'s staged input-count migrations run, since those set
|
||||
// the upstream chain to absolute; the split below re-chains exactly the nodes that were originally part of a layer chain.
|
||||
let text_nodes_in_chain: std::collections::HashSet<NodeId> = document
|
||||
@@ -1408,6 +1598,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
for (node_id, node, network_path) in &nodes {
|
||||
migrate_node(node_id, node, network_path, document, reset_node_definitions_on_open);
|
||||
}
|
||||
create_layer_stacks(document);
|
||||
|
||||
// The old geometry-producing "Text" node was split into the current "Text" (`String[]`) -> converter pair, which reuses the same proto
|
||||
// identifier. Runs after `migrate_node` normalizes old text nodes to the legacy 13-input layout, distinguished from the current 12-input
|
||||
@@ -2243,22 +2434,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Bool(true), false), network_path);
|
||||
}
|
||||
|
||||
// Upgrade the 'Tangent on Path' node to include a boolean input for whether the output should be in radians, which was previously the only option but is now not the default
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::tangent_on_path::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)?;
|
||||
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 2), old_inputs[2].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 3), old_inputs[3].clone(), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 4), NodeInput::value(TaggedValue::Bool(true), false), network_path);
|
||||
}
|
||||
|
||||
// Upgrade the Modulo node to include a boolean input for whether the output should be always positive, which was previously not an option
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::modulo::IDENTIFIER) && inputs_count == 2 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
@@ -2274,10 +2449,10 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
}
|
||||
|
||||
// Convert the old 'Vec2 Value' node, identified by its leftover 3-input shape with separate X and Y inputs,
|
||||
// into the 'Combine Vec2' node which now fills that role (the new 'Vec2 Value' node instead takes a single vec2 input)
|
||||
// into the 'Numbers to Vec2' node which now fills that role (the new 'Vec2 Value' node instead takes a single vec2 input)
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::vec_2_value::IDENTIFIER) && inputs_count == 3 {
|
||||
let combine_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::combine_vec_2::IDENTIFIER);
|
||||
let mut node_template = resolve_document_node_type(&combine_vec2_reference)?.default_node_template();
|
||||
let numbers_to_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER);
|
||||
let mut node_template = resolve_document_node_type(&numbers_to_vec2_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)?;
|
||||
@@ -3102,34 +3277,35 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
}
|
||||
}
|
||||
|
||||
// ==================================
|
||||
// PUT ALL MIGRATIONS ABOVE THIS LINE
|
||||
// ==================================
|
||||
Some(())
|
||||
}
|
||||
|
||||
// Ensure layers are positioned as stacks if they are upstream siblings of another layer
|
||||
/// Ensure layers are positioned as stacks if they are upstream siblings of another layer
|
||||
fn create_layer_stacks(document: &mut DocumentMessageHandler) {
|
||||
document.network_interface.load_structure();
|
||||
let all_layers = LayerNodeIdentifier::ROOT_PARENT.descendants(document.network_interface.document_metadata()).collect::<Vec<_>>();
|
||||
for layer in all_layers {
|
||||
let (downstream_node, input_index) = document
|
||||
let Some((downstream_node, input_index)) = document
|
||||
.network_interface
|
||||
.outward_wires(&[])
|
||||
.and_then(|outward_wires| outward_wires.get(&OutputConnector::node(layer.to_node(), 0)))
|
||||
.and_then(|outward_wires| outward_wires.first())
|
||||
.and_then(|input_connector| input_connector.node_id().map(|node_id| (node_id, input_connector.input_index())))?;
|
||||
.and_then(|input_connector| input_connector.node_id().map(|node_id| (node_id, input_connector.input_index())))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
// If the downstream node is a layer and the input is the first input and the current layer is not in a stack
|
||||
if input_index == 0 && document.network_interface.is_layer(&downstream_node, &[]) && !document.network_interface.is_stack(&layer.to_node(), &[]) {
|
||||
// Ensure the layer is horizontally aligned with the downstream layer to prevent changing the layout of old files
|
||||
let (Some(layer_position), Some(downstream_position)) = (document.network_interface.position(&layer.to_node(), &[]), document.network_interface.position(&downstream_node, &[])) else {
|
||||
log::error!("Could not get position for layer {:?} or downstream node {} when opening file", layer.to_node(), downstream_node);
|
||||
return None;
|
||||
continue;
|
||||
};
|
||||
if layer_position.x == downstream_position.x {
|
||||
document.network_interface.set_stack_position_calculated_offset(&layer.to_node(), &downstream_node, &[]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Migrates document nodes whose catalog definitions have been removed.
|
||||
@@ -3273,6 +3449,37 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_floats_load_as_zero() {
|
||||
use crate::messages::portfolio::document::utility_types::misc::PTZ;
|
||||
use graph_craft::document::value::deserialize_replacing_null_floats_with_zero;
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Example {
|
||||
position: DVec2,
|
||||
scale: f64,
|
||||
opacity: Option<f64>,
|
||||
}
|
||||
|
||||
let content = "{\n\t\"position\": [1.5, null],\n\t\"scale\": null,\n\t\"opacity\": null\n}";
|
||||
let example = deserialize_replacing_null_floats_with_zero::<Example>(content).expect("a `null` in place of a float should load");
|
||||
assert_eq!(example.position, DVec2::new(1.5, 0.));
|
||||
assert_eq!(example.scale, 0.);
|
||||
assert_eq!(example.opacity, None);
|
||||
|
||||
// A `null` standing in for something other than a float is still an error
|
||||
let content = r#"{"position": null, "scale": 1, "opacity": 1}"#;
|
||||
assert!(deserialize_replacing_null_floats_with_zero::<Example>(content).is_err());
|
||||
|
||||
// Node input values are parsed from an intermediate JSON value, which carries no error positions
|
||||
let input = serde_json::from_str::<NodeInput>(r#"{"Value":{"tagged_value":{"DVec2":[null,2.5]},"exposed":false}}"#).expect("a `null` in a node input value should load");
|
||||
assert_eq!(input.as_value(), Some(&TaggedValue::DVec2(DVec2::new(0., 2.5))));
|
||||
|
||||
// A zoom of 0 would make the view's transform singular
|
||||
let ptz = deserialize_replacing_null_floats_with_zero::<PTZ>(r#"{"pan":[0.0,0.0],"tilt":0.0,"zoom":null,"flip":false}"#).expect("a `null` zoom should load");
|
||||
assert_eq!(ptz.zoom(), crate::consts::VIEWPORT_ZOOM_SCALE_MIN);
|
||||
}
|
||||
|
||||
// The removed-definition blocks above abort silently via `?` if their swap target ever leaves the catalog
|
||||
#[test]
|
||||
fn removed_definition_swap_targets_resolve() {
|
||||
|
||||
@@ -18,6 +18,7 @@ use crate::messages::portfolio::document_storage_io::{
|
||||
use crate::messages::preferences::SelectionMode;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::resource_storage::ResourcesHandle;
|
||||
use crate::messages::tool::common_functionality::edit_target::EditTarget;
|
||||
use crate::messages::tool::utility_types::{HintData, ToolType};
|
||||
use crate::messages::viewport::ToPhysical;
|
||||
use crate::node_graph_executor::{ExportConfig, NodeGraphExecutor};
|
||||
@@ -37,6 +38,7 @@ pub struct PortfolioMessageContext<'a> {
|
||||
pub preferences: &'a PreferencesMessageHandler,
|
||||
pub animation: &'a AnimationMessageHandler,
|
||||
pub current_tool: &'a ToolType,
|
||||
pub tool_edit_target: &'a EditTarget,
|
||||
pub reset_node_definitions_on_open: bool,
|
||||
pub timing_information: TimingInformation,
|
||||
pub viewport: &'a ViewportMessageHandler,
|
||||
@@ -71,6 +73,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
preferences,
|
||||
animation,
|
||||
current_tool,
|
||||
tool_edit_target,
|
||||
reset_node_definitions_on_open,
|
||||
timing_information,
|
||||
viewport,
|
||||
@@ -89,6 +92,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
fonts: &self.fonts,
|
||||
executor: &mut self.executor,
|
||||
current_tool,
|
||||
tool_edit_target,
|
||||
preferences,
|
||||
viewport,
|
||||
resource_storage,
|
||||
@@ -96,7 +100,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
layers_panel_open: self.workspace.panel_layout.is_panel_visible(PanelType::Layers) && !self.workspace.panel_layout.focus_document,
|
||||
properties_panel_open: self.workspace.panel_layout.is_panel_visible(PanelType::Properties) && !self.workspace.panel_layout.focus_document,
|
||||
};
|
||||
document.process_message(message, responses, document_inputs)
|
||||
document.process_message(message, responses, document_inputs);
|
||||
refresh_transaction_edited_nodes(document, true, responses);
|
||||
}
|
||||
}
|
||||
PortfolioMessage::PersistentState(message) => {
|
||||
@@ -169,6 +174,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
// Send the information for tooltips and categories for each node/input.
|
||||
responses.add(FrontendMessage::SendUIMetadata {
|
||||
node_descriptions: document_node_definitions::collect_node_descriptions(),
|
||||
node_icons: document_node_definitions::collect_node_icons(),
|
||||
node_types: document_node_definitions::collect_node_types(),
|
||||
});
|
||||
}
|
||||
@@ -180,6 +186,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
fonts: &self.fonts,
|
||||
executor: &mut self.executor,
|
||||
current_tool,
|
||||
tool_edit_target,
|
||||
preferences,
|
||||
viewport,
|
||||
resource_storage,
|
||||
@@ -187,7 +194,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
layers_panel_open: self.workspace.panel_layout.is_panel_visible(PanelType::Layers) && !self.workspace.panel_layout.focus_document,
|
||||
properties_panel_open: self.workspace.panel_layout.is_panel_visible(PanelType::Properties) && !self.workspace.panel_layout.focus_document,
|
||||
};
|
||||
document.process_message(message, responses, document_inputs)
|
||||
document.process_message(message, responses, document_inputs);
|
||||
refresh_transaction_edited_nodes(document, self.active_document_id == Some(document_id), responses);
|
||||
}
|
||||
}
|
||||
PortfolioMessage::AutoSaveActiveDocument => {
|
||||
@@ -1268,6 +1276,13 @@ impl PortfolioMessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// Lets the Layers panel brighten the nodes an edit in progress, like a drag, has written to so far.
|
||||
fn refresh_transaction_edited_nodes(document: &mut DocumentMessageHandler, is_active: bool, responses: &mut VecDeque<Message>) {
|
||||
if document.network_interface.update_transaction_edited_nodes() && is_active {
|
||||
responses.add(NodeGraphMessage::UpdateLayerPanel);
|
||||
}
|
||||
}
|
||||
|
||||
/// The name an opened file gets: the given name, else the file stem of its path, else empty so the portfolio generates one.
|
||||
fn opened_document_name(name: Option<String>, path: Option<&Path>) -> String {
|
||||
name.filter(|name| !name.trim().is_empty())
|
||||
|
||||
@@ -388,7 +388,7 @@ impl WorkspaceMessageHandler {
|
||||
fn destroy_panel_layouts(panel_type: PanelType, responses: &mut VecDeque<Message>) {
|
||||
let targets: &[LayoutTarget] = match panel_type {
|
||||
PanelType::Properties => &[LayoutTarget::PropertiesPanel],
|
||||
PanelType::Layers => &[LayoutTarget::LayersPanelControlLeftBar, LayoutTarget::LayersPanelControlRightBar, LayoutTarget::LayersPanelBottomBar],
|
||||
PanelType::Layers => &[LayoutTarget::LayersPanelControlLeftBar, LayoutTarget::LayersPanelBottomLeftBar, LayoutTarget::LayersPanelBottomRightBar],
|
||||
PanelType::Data => &[LayoutTarget::DataPanel],
|
||||
PanelType::Document | PanelType::Welcome => return,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::NodeId;
|
||||
|
||||
/// What a tool edits in each layer, picked out per layer by [`EditTarget::resolve`] with the same lookups the tool's edits use.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub enum EditTarget {
|
||||
/// The tool doesn't edit layers.
|
||||
#[default]
|
||||
Nothing,
|
||||
/// The downstream-most visible node with this definition in the layer's chain (or the layer node itself), or else the one `insertion` adds.
|
||||
ChainNode { definition: DefinitionIdentifier, insertion: Insertion },
|
||||
/// The first of these which applies to the layer, by their order here rather than their order in the chain.
|
||||
FirstApplicable(Vec<EditTarget>),
|
||||
}
|
||||
|
||||
/// Whether, and where, a tool adds the node it edits to a layer's chain that lacks one.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Insertion {
|
||||
Never,
|
||||
/// As the chain's most downstream node, directly feeding the layer.
|
||||
BesideLayer,
|
||||
/// Beside the layer, only in layers with vector content.
|
||||
BesideVectorLayer,
|
||||
/// Beside the layer, only in layers with vector content, but upstream of a visible Stroke node there so the stroke keeps painting on top.
|
||||
UnderStroke,
|
||||
}
|
||||
|
||||
/// The node an [`EditTarget`] picks out in a layer.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ResolvedEditTarget {
|
||||
/// A node in the layer's chain, or the layer node itself.
|
||||
Edited(NodeId),
|
||||
/// A node the tool would add, at this position among the chain nodes counted from the upstream end.
|
||||
Inserted { definition: DefinitionIdentifier, index: usize },
|
||||
}
|
||||
|
||||
impl ResolvedEditTarget {
|
||||
/// The existing node to outline, which is none when the tool would add one.
|
||||
pub fn outlined_node(&self) -> Option<NodeId> {
|
||||
match self {
|
||||
Self::Edited(node) => Some(*node),
|
||||
Self::Inserted { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The tooltip description of the node in a Layers panel row.
|
||||
pub fn tooltip_description(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Edited(_) => "Edited by the active tool.",
|
||||
Self::Inserted { .. } => "Inserted here when the active tool edits this layer.",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EditTarget {
|
||||
pub fn proto_node(identifier: ProtoNodeIdentifier, insertion: Insertion) -> Self {
|
||||
Self::ChainNode {
|
||||
definition: DefinitionIdentifier::ProtoNode(identifier),
|
||||
insertion,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn network_node(name: &str, insertion: Insertion) -> Self {
|
||||
Self::ChainNode {
|
||||
definition: DefinitionIdentifier::Network(name.into()),
|
||||
insertion,
|
||||
}
|
||||
}
|
||||
|
||||
/// The Transform node, which transform edits insert beside the layer when it's missing.
|
||||
pub fn transform() -> Self {
|
||||
Self::proto_node(graphene_std::transform_nodes::transform::IDENTIFIER, Insertion::BesideLayer)
|
||||
}
|
||||
|
||||
/// The Path node, which vector edits insert beside a layer with vector content when it's missing.
|
||||
pub fn path() -> Self {
|
||||
Self::network_node("Path", Insertion::BesideVectorLayer)
|
||||
}
|
||||
|
||||
/// The Fill node, which paint edits insert under any Stroke node beside a layer with vector content when it's missing.
|
||||
pub fn fill() -> Self {
|
||||
Self::proto_node(graphene_std::vector_nodes::fill::IDENTIFIER, Insertion::UnderStroke)
|
||||
}
|
||||
|
||||
pub fn resolve(&self, layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<ResolvedEditTarget> {
|
||||
match self {
|
||||
Self::Nothing => None,
|
||||
Self::ChainNode { definition, insertion } => Self::resolve_chain_node(definition, *insertion, layer, network_interface),
|
||||
Self::FirstApplicable(targets) => targets.iter().find_map(|target| target.resolve(layer, network_interface)),
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_chain_node(definition: &DefinitionIdentifier, insertion: Insertion, layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<ResolvedEditTarget> {
|
||||
if let Some(node_id) = ModifyInputsContext::locate_node_in_layer_chain(definition, layer, network_interface) {
|
||||
return Some(ResolvedEditTarget::Edited(node_id));
|
||||
}
|
||||
|
||||
let has_vector_content = network_interface.document_metadata().layer_vector_data.contains_key(&layer);
|
||||
let chain = network_interface.layer_chain_nodes(layer.to_node(), &[]);
|
||||
let index = match insertion {
|
||||
Insertion::Never => return None,
|
||||
Insertion::BesideVectorLayer | Insertion::UnderStroke if !has_vector_content => return None,
|
||||
Insertion::BesideLayer | Insertion::BesideVectorLayer => chain.len(),
|
||||
Insertion::UnderStroke => {
|
||||
let stroke = DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
|
||||
let beside_stroke = chain
|
||||
.first()
|
||||
.is_some_and(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&stroke) && network_interface.is_visible(node_id, &[]));
|
||||
chain.len() - usize::from(beside_stroke)
|
||||
}
|
||||
};
|
||||
|
||||
Some(ResolvedEditTarget::Inserted {
|
||||
definition: definition.clone(),
|
||||
index,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -227,6 +227,28 @@ pub fn new_svg_layer(svg: String, transform: glam::DAffine2, center: bool, id: N
|
||||
LayerNodeIdentifier::new_unchecked(id)
|
||||
}
|
||||
|
||||
/// Create the locked, solid white "Background" layer that an infinite canvas document begins with, at the given index of the root stack.
|
||||
pub fn new_background_layer(insert_index: usize, responses: &mut VecDeque<Message>) {
|
||||
let node_id = NodeId::new();
|
||||
|
||||
responses.add(GraphOperationMessage::NewColorFillLayer {
|
||||
node_id,
|
||||
color: Color::WHITE,
|
||||
parent: LayerNodeIdentifier::ROOT_PARENT,
|
||||
insert_index,
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetDisplayNameImpl {
|
||||
node_id,
|
||||
network_path: Vec::new(),
|
||||
alias: "Background".to_string(),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetLocked {
|
||||
node_id,
|
||||
network_path: Vec::new(),
|
||||
locked: true,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn new_custom(id: NodeId, nodes: Vec<(NodeId, NodeTemplate)>, parent: LayerNodeIdentifier, responses: &mut VecDeque<Message>) -> LayerNodeIdentifier {
|
||||
responses.add(GraphOperationMessage::NewCustomLayer { id, nodes, parent, insert_index: 0 });
|
||||
responses.add(GraphOperationMessage::SetUpstreamToChain {
|
||||
|
||||
Loaded 100 of 274 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user