mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6a463712a4 |
No files matched your search
@@ -1,2 +1,2 @@
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/ca7dd793caba8999ec33fde99bb721a69c3d221f.tar.gz
|
||||
77e8a6b68d67a8d5fcfd6268a6b7938ac9322d877378c6563e933a57df6da821
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/6687dc6d3d8552948458d00d35e2bee3a40ab66b.tar.gz
|
||||
7663b4a35f377a5d3363430a725a1d5f634fbdc56adca5e43167786b8fe1b253
|
||||
@@ -7,15 +7,9 @@ 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>
|
||||
@@ -36,10 +30,6 @@ 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
|
||||
@@ -65,12 +55,9 @@ jobs:
|
||||
cargo run -p crate-hierarchy-viz -- website/generated
|
||||
cargo run -p editor-message-tree -- website/generated
|
||||
|
||||
- name: 🔧 Install website and frontend npm dependencies
|
||||
- name: 🔧 Install website npm dependencies
|
||||
run: |
|
||||
# The website is linted by the frontend's ESLint config and the tools it installs
|
||||
cd frontend
|
||||
npm ci
|
||||
cd ../website
|
||||
cd website
|
||||
npm ci
|
||||
|
||||
- name: 📃 Generate node catalog documentation
|
||||
|
||||
+2
-22
@@ -61,9 +61,7 @@ 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;
|
||||
@@ -72,26 +70,8 @@ in
|
||||
|
||||
devShells = withArgs (
|
||||
{ lib, ... }:
|
||||
let
|
||||
shell = lib.makeOverridable (lib.call ./dev.nix);
|
||||
in
|
||||
{
|
||||
default = shell {
|
||||
desktop = true;
|
||||
};
|
||||
full = shell {
|
||||
desktop = true;
|
||||
x11 = true;
|
||||
playwright = true;
|
||||
};
|
||||
minimal = shell { };
|
||||
x11 = shell {
|
||||
desktop = true;
|
||||
x11 = true;
|
||||
};
|
||||
playwright = shell {
|
||||
playwright = true;
|
||||
};
|
||||
default = lib.call ./dev.nix;
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
@@ -31,12 +31,13 @@ let
|
||||
}).buildRustPackage
|
||||
(finalAttrs: {
|
||||
pname = "rustc_codegen_spirv";
|
||||
version = "0.10.0";
|
||||
src = pkgs.fetchCrate {
|
||||
inherit (finalAttrs) pname version;
|
||||
sha256 = "sha256-QluNI2TdJI0j2CBOeAbB9DfOv+8LqzWk7siZyT1WWLU=";
|
||||
version = "0.10.0-alpha.1";
|
||||
src = pkgs.fetchgit {
|
||||
url = "https://github.com/Rust-GPU/rust-gpu";
|
||||
rev = "2fff75a21a1909945ac85f5818843dd9960004d7";
|
||||
sha256 = "sha256-clUt4jUh4D9EmoXZFgur1RrMYob4X5jti2e2hvBnAx8=";
|
||||
};
|
||||
cargoHash = "sha256-vvviUccnip+j60Ml1vqLNJ49KyEF40VLUoV1TMALHMs=";
|
||||
cargoHash = "sha256-9dGb+RDYpJKaIhkMPkZAx1M1VGE3gMfCD2T84i1VtV8=";
|
||||
cargoBuildFlags = [
|
||||
"-p"
|
||||
"rustc_codegen_spirv"
|
||||
|
||||
+52
-80
@@ -3,90 +3,62 @@
|
||||
deps,
|
||||
self,
|
||||
system,
|
||||
lib,
|
||||
...
|
||||
}:
|
||||
|
||||
{
|
||||
desktop ? false,
|
||||
x11 ? false,
|
||||
playwright ? false,
|
||||
}:
|
||||
|
||||
let
|
||||
features = [
|
||||
{
|
||||
packages = [
|
||||
pkgs.pkg-config
|
||||
libs = [
|
||||
pkgs.wayland
|
||||
pkgs.vulkan-loader
|
||||
pkgs.libGL
|
||||
pkgs.openssl
|
||||
pkgs.libraw
|
||||
|
||||
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";
|
||||
};
|
||||
}
|
||||
))
|
||||
# X11 Support
|
||||
pkgs.libxkbcommon
|
||||
pkgs.libXcursor
|
||||
pkgs.libxcb
|
||||
pkgs.libX11
|
||||
];
|
||||
|
||||
libs = lib.concatMap (feature: feature.libs or [ ]) features;
|
||||
in
|
||||
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;
|
||||
};
|
||||
}
|
||||
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
|
||||
)
|
||||
@@ -30,13 +30,12 @@ pkgs.cef-binary.overrideAttrs {
|
||||
postInstall = ''
|
||||
rm -r $out/* $out/.* || true
|
||||
strip ./Release/*.so*
|
||||
mkdir $out/lib
|
||||
mv ./Release/* $out/lib/
|
||||
mv ./Release/* $out/
|
||||
find "./Resources/locales" -maxdepth 1 -type f ! -name 'en-US.pak' -delete
|
||||
mv ./Resources/* $out/lib/
|
||||
mv ./include $out/lib/
|
||||
mv ./Resources/* $out/
|
||||
mv ./include $out/
|
||||
|
||||
cat ./CREDITS.html | ${pkgs.xz}/bin/xz -9 -e -c > $out/lib/CREDITS.html.xz
|
||||
cat ./CREDITS.html | ${pkgs.xz}/bin/xz -9 -e -c > $out/CREDITS.html.xz
|
||||
|
||||
echo '${
|
||||
builtins.toJSON {
|
||||
@@ -44,6 +43,6 @@ pkgs.cef-binary.overrideAttrs {
|
||||
name = builtins.baseNameOf url;
|
||||
sha1 = "";
|
||||
}
|
||||
}' > $out/lib/archive.json
|
||||
}' > $out/archive.json
|
||||
'';
|
||||
}
|
||||
@@ -20,7 +20,6 @@ let
|
||||
pkgs.libGL
|
||||
pkgs.openssl
|
||||
pkgs.libraw
|
||||
self.packages.${system}.graphite-cef
|
||||
# X11 Support
|
||||
pkgs.libxkbcommon
|
||||
pkgs.libXcursor
|
||||
@@ -51,7 +50,7 @@ let
|
||||
pkgs.pkg-config
|
||||
pkgs.lld
|
||||
];
|
||||
env.CEF_PATH = "${self.packages.${system}.graphite-cef}/lib";
|
||||
env.CEF_PATH = self.packages.${system}.graphite-cef;
|
||||
buildPhase =
|
||||
let
|
||||
profile = if dev then "dev" else "release";
|
||||
@@ -100,7 +99,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}/lib";
|
||||
CEF_PATH = self.packages.${system}.graphite-cef;
|
||||
};
|
||||
|
||||
postPatch = ''
|
||||
@@ -149,7 +148,7 @@ deps.crane.lib.buildPackage (
|
||||
remove-references-to -t "${common.cargoVendorDir}" $out/bin/graphite
|
||||
|
||||
patchelf \
|
||||
--set-rpath "${pkgs.lib.makeLibraryPath libs}" \
|
||||
--set-rpath "${pkgs.lib.makeLibraryPath libs}:${self.packages.${system}.graphite-cef}" \
|
||||
--add-needed libGL.so \
|
||||
--add-needed libEGL.so \
|
||||
$out/bin/graphite
|
||||
|
||||
Generated
+45
-151
@@ -317,7 +317,7 @@ name = "blending-nodes"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graphic-types",
|
||||
"node-macro",
|
||||
"serde",
|
||||
@@ -359,7 +359,7 @@ dependencies = [
|
||||
"bytemuck",
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graphene-hash",
|
||||
"graphic-types",
|
||||
"half",
|
||||
@@ -377,7 +377,7 @@ version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graphene-hash",
|
||||
"serde",
|
||||
]
|
||||
@@ -471,9 +471,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cargo-gpu-install"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "668b4bd1b59810c4f907eeb36bb0f0a450c824219b2e599b9b8ef2b3ae056e94"
|
||||
version = "0.10.0-alpha.1"
|
||||
source = "git+https://github.com/Rust-GPU/rust-gpu.git?rev=2fff75a21a1909945ac85f5818843dd9960004d7#2fff75a21a1909945ac85f5818843dd9960004d7"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"cargo_metadata 0.21.0",
|
||||
@@ -830,20 +829,11 @@ version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
|
||||
|
||||
[[package]]
|
||||
name = "control-protocol"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"glam 0.33.12",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "convert_case"
|
||||
version = "0.12.0"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1af709f1f33454bf52eadfc8c78b3b9ef9cb26fb54d16dc9cd9a7299f899fd1b"
|
||||
checksum = "baaaa0ecca5b51987b9423ccdc971514dd8b0bb7b4060b983d3664dad3f1f89f"
|
||||
dependencies = [
|
||||
"unicode-segmentation",
|
||||
]
|
||||
@@ -913,7 +903,7 @@ dependencies = [
|
||||
"color",
|
||||
"ctor",
|
||||
"dyn-any",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graphene-hash",
|
||||
"image",
|
||||
"kurbo",
|
||||
@@ -1180,13 +1170,6 @@ version = "0.1.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8"
|
||||
|
||||
[[package]]
|
||||
name = "diffrast"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"glam 0.33.12",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
@@ -1402,7 +1385,7 @@ name = "dyn-any"
|
||||
version = "0.3.1"
|
||||
dependencies = [
|
||||
"dyn-any-derive",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"reqwest",
|
||||
]
|
||||
|
||||
@@ -1977,9 +1960,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "glam"
|
||||
version = "0.33.12"
|
||||
version = "0.33.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "37bfe73dc8ec21f54d181e5a60554327ec3f1c600c455a75ccbfc65d2106a6c4"
|
||||
checksum = "928452f9c953e142b2f0973e4bd5f34445fcaa8069556ea97a3c9d34d15a4cf8"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"libm",
|
||||
@@ -2055,9 +2038,8 @@ dependencies = [
|
||||
"core-types",
|
||||
"criterion",
|
||||
"dyn-any",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graph-craft",
|
||||
"graphene-animation",
|
||||
"graphene-application-io",
|
||||
"graphene-core",
|
||||
"graphene-hash",
|
||||
@@ -2084,17 +2066,6 @@ dependencies = [
|
||||
"wgpu-executor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "graphene-animation"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"dyn-any",
|
||||
"glam 0.33.12",
|
||||
"graphene-hash",
|
||||
"kurbo",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "graphene-application-io"
|
||||
version = "0.0.0"
|
||||
@@ -2102,7 +2073,7 @@ dependencies = [
|
||||
"blake3",
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"log",
|
||||
@@ -2119,7 +2090,7 @@ version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graphene-application-io",
|
||||
"log",
|
||||
"serde",
|
||||
@@ -2157,8 +2128,7 @@ version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam 0.33.12",
|
||||
"graphene-animation",
|
||||
"glam 0.33.10",
|
||||
"graphene-hash",
|
||||
"graphic-types",
|
||||
"log",
|
||||
@@ -2173,7 +2143,7 @@ dependencies = [
|
||||
name = "graphene-hash"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graphene-hash-derive",
|
||||
]
|
||||
|
||||
@@ -2208,7 +2178,7 @@ dependencies = [
|
||||
"bytemuck",
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graph-craft",
|
||||
"graphene-application-io",
|
||||
"graphene-canvas-utils",
|
||||
@@ -2229,7 +2199,6 @@ dependencies = [
|
||||
"transform-nodes",
|
||||
"vector-nodes",
|
||||
"vector-types",
|
||||
"vectorize-nodes",
|
||||
"vello",
|
||||
"vello_encoding",
|
||||
"wasm-bindgen",
|
||||
@@ -2246,7 +2215,7 @@ dependencies = [
|
||||
"brush-types",
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graphic-types",
|
||||
"node-macro",
|
||||
"rand",
|
||||
@@ -2262,7 +2231,7 @@ dependencies = [
|
||||
"brush-types",
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graphene-hash",
|
||||
"node-macro",
|
||||
"raster-types",
|
||||
@@ -2283,7 +2252,7 @@ dependencies = [
|
||||
"dirs",
|
||||
"fd-lock",
|
||||
"futures",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graphite-desktop-ui",
|
||||
"graphite-desktop-wrapper",
|
||||
"interprocess",
|
||||
@@ -2410,7 +2379,7 @@ dependencies = [
|
||||
"dyn-any",
|
||||
"env_logger",
|
||||
"futures",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graph-craft",
|
||||
"graphene-hash",
|
||||
"graphene-std",
|
||||
@@ -2430,7 +2399,6 @@ dependencies = [
|
||||
"serde_bytes",
|
||||
"serde_json",
|
||||
"simplecss",
|
||||
"snapping",
|
||||
"spin",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
@@ -3020,9 +2988,8 @@ dependencies = [
|
||||
"criterion",
|
||||
"dyn-any",
|
||||
"futures",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graph-craft",
|
||||
"graphene-animation",
|
||||
"graphene-core",
|
||||
"graphene-std",
|
||||
"gungraun",
|
||||
@@ -3460,9 +3427,7 @@ name = "math-nodes"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam 0.33.12",
|
||||
"graphene-core",
|
||||
"glam 0.33.10",
|
||||
"graphic-types",
|
||||
"log",
|
||||
"math-parser",
|
||||
@@ -3674,7 +3639,7 @@ dependencies = [
|
||||
"bytemuck",
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graphene-hash",
|
||||
"half",
|
||||
"log",
|
||||
@@ -4116,7 +4081,7 @@ name = "path-bool-nodes"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graphic-types",
|
||||
"linesweeper",
|
||||
"log",
|
||||
@@ -4432,15 +4397,10 @@ checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
|
||||
name = "preprocessor"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"futures",
|
||||
"glam 0.33.12",
|
||||
"graph-craft",
|
||||
"graphene-std",
|
||||
"interpreted-executor",
|
||||
"log",
|
||||
"node-macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4652,13 +4612,11 @@ name = "raster-nodes"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"color",
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"fastnoise-lite",
|
||||
"futures",
|
||||
"glam 0.33.12",
|
||||
"graphene-core",
|
||||
"glam 0.33.10",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"image",
|
||||
@@ -4705,7 +4663,7 @@ dependencies = [
|
||||
"bytemuck",
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graphene-hash",
|
||||
"image",
|
||||
"node-macro",
|
||||
@@ -4893,7 +4851,7 @@ dependencies = [
|
||||
"brush-types",
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
@@ -4916,7 +4874,7 @@ version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graphene-core",
|
||||
"graphic-types",
|
||||
"kurbo",
|
||||
@@ -5076,9 +5034,8 @@ checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"
|
||||
|
||||
[[package]]
|
||||
name = "rustc_codegen_spirv-types"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d703f5624720c5b6012f4b88d6e6766f43ed50d80144eaffd6791c3270754cdc"
|
||||
version = "0.10.0-alpha.1"
|
||||
source = "git+https://github.com/Rust-GPU/rust-gpu.git?rev=2fff75a21a1909945ac85f5818843dd9960004d7#2fff75a21a1909945ac85f5818843dd9960004d7"
|
||||
dependencies = [
|
||||
"rspirv",
|
||||
"semver",
|
||||
@@ -5628,15 +5585,6 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "snapping"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"glam 0.33.12",
|
||||
"kurbo",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
version = "0.6.0"
|
||||
@@ -5679,9 +5627,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "spirv-builder"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "57fa119866f0311546e5309b18770b72141c25d185452c11a812be2c7b9d84e9"
|
||||
version = "0.10.0-alpha.1"
|
||||
source = "git+https://github.com/Rust-GPU/rust-gpu.git?rev=2fff75a21a1909945ac85f5818843dd9960004d7#2fff75a21a1909945ac85f5818843dd9960004d7"
|
||||
dependencies = [
|
||||
"cargo_metadata 0.21.0",
|
||||
"log",
|
||||
@@ -5696,16 +5643,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "spirv-std"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d98471765e294d4dd6289350e3633b5c5ba57bb382c3287d83e69ee737179e0"
|
||||
version = "0.10.0-alpha.1"
|
||||
source = "git+https://github.com/Rust-GPU/rust-gpu.git?rev=2fff75a21a1909945ac85f5818843dd9960004d7#2fff75a21a1909945ac85f5818843dd9960004d7"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bytemuck",
|
||||
"glam 0.30.10",
|
||||
"glam 0.31.1",
|
||||
"glam 0.32.1",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"libm",
|
||||
"num-traits",
|
||||
"spirv-std-macros",
|
||||
@@ -5714,9 +5660,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "spirv-std-macros"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13a6a0d063d4dd003e43818135b7aa4a30c41c48b5d0efe2cac02220448d4f19"
|
||||
version = "0.10.0-alpha.1"
|
||||
source = "git+https://github.com/Rust-GPU/rust-gpu.git?rev=2fff75a21a1909945ac85f5818843dd9960004d7#2fff75a21a1909945ac85f5818843dd9960004d7"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -5726,9 +5671,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "spirv-std-types"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "655632248eaaa205cea4656bc73c8285cbd8109fc784010b24ea6bd0bab79ac1"
|
||||
version = "0.10.0-alpha.1"
|
||||
source = "git+https://github.com/Rust-GPU/rust-gpu.git?rev=2fff75a21a1909945ac85f5818843dd9960004d7#2fff75a21a1909945ac85f5818843dd9960004d7"
|
||||
|
||||
[[package]]
|
||||
name = "stable_deref_trait"
|
||||
@@ -5950,7 +5894,7 @@ dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"fancy-regex",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"ipsum",
|
||||
@@ -6288,13 +6232,6 @@ version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
|
||||
|
||||
[[package]]
|
||||
name = "tracer"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"glam 0.33.12",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing"
|
||||
version = "0.1.41"
|
||||
@@ -6362,7 +6299,7 @@ name = "transform-nodes"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graphic-types",
|
||||
"node-macro",
|
||||
"rand",
|
||||
@@ -6616,7 +6553,7 @@ dependencies = [
|
||||
"delaunator",
|
||||
"dyn-any",
|
||||
"futures",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graphene-core",
|
||||
"graphene-hash",
|
||||
"graphic-types",
|
||||
@@ -6644,7 +6581,7 @@ dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"fixedbitset",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graphene-hash",
|
||||
"kurbo",
|
||||
"log",
|
||||
@@ -6661,24 +6598,6 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorize-nodes"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"futures",
|
||||
"glam 0.33.12",
|
||||
"graphene-hash",
|
||||
"graphic-types",
|
||||
"kurbo",
|
||||
"log",
|
||||
"node-macro",
|
||||
"raster-types",
|
||||
"vector-types",
|
||||
"vtrace",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vello"
|
||||
version = "0.10.0"
|
||||
@@ -6730,15 +6649,6 @@ version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "vtrace"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"diffrast",
|
||||
"glam 0.33.12",
|
||||
"tracer",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "walkdir"
|
||||
version = "2.5.0"
|
||||
@@ -6963,22 +6873,6 @@ dependencies = [
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "web-editor-driver"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"clap",
|
||||
"control-protocol",
|
||||
"getrandom 0.3.3",
|
||||
"glam 0.33.12",
|
||||
"image",
|
||||
"interprocess",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "web-sys"
|
||||
version = "0.3.98"
|
||||
@@ -7134,7 +7028,7 @@ dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"futures",
|
||||
"glam 0.33.12",
|
||||
"glam 0.33.10",
|
||||
"graphene-application-io",
|
||||
"node-macro",
|
||||
"raster-types",
|
||||
|
||||
+4
-12
@@ -16,9 +16,7 @@ members = [
|
||||
"libraries/dyn-any",
|
||||
"libraries/math-parser",
|
||||
"libraries/ipsum",
|
||||
"libraries/snapping",
|
||||
"libraries/wgpu-sync",
|
||||
"libraries/control-protocol",
|
||||
"node-graph/libraries/graphene-hash",
|
||||
"node-graph/libraries/*",
|
||||
"node-graph/nodes/*",
|
||||
@@ -37,7 +35,6 @@ members = [
|
||||
"tools/third-party-licenses",
|
||||
"tools/editor-message-tree",
|
||||
"tools/node-docs",
|
||||
"tools/web-editor-driver",
|
||||
]
|
||||
default-members = [
|
||||
"editor",
|
||||
@@ -45,7 +42,6 @@ default-members = [
|
||||
"libraries/dyn-any",
|
||||
"libraries/math-parser",
|
||||
"libraries/ipsum",
|
||||
"libraries/snapping",
|
||||
"node-graph/graph-craft",
|
||||
"node-graph/interpreted-executor",
|
||||
"node-graph/node-macro",
|
||||
@@ -81,7 +77,6 @@ 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" }
|
||||
@@ -97,8 +92,6 @@ text-nodes = { path = "node-graph/nodes/text" }
|
||||
transform-nodes = { path = "node-graph/nodes/transform" }
|
||||
vector-nodes = { path = "node-graph/nodes/vector" }
|
||||
repeat-nodes = { path = "node-graph/nodes/repeat" }
|
||||
vectorize-nodes = { path = "node-graph/nodes/vectorize" }
|
||||
vtrace = { path = "../vtrace/vtrace" }
|
||||
math-nodes = { path = "node-graph/nodes/math" }
|
||||
path-bool-nodes = { path = "node-graph/nodes/path-bool" }
|
||||
graph-craft = { path = "node-graph/graph-craft" }
|
||||
@@ -113,10 +106,8 @@ wgpu-executor = { path = "node-graph/libraries/wgpu-executor" }
|
||||
wgpu-sync = { path = "libraries/wgpu-sync" }
|
||||
graphite-proc-macros = { path = "proc-macros" }
|
||||
graphite-editor = { path = "editor" }
|
||||
control-protocol = { path = "libraries/control-protocol" }
|
||||
graphene-canvas-utils = { path = "node-graph/libraries/canvas-utils" }
|
||||
ipsum = { path = "libraries/ipsum" }
|
||||
snapping = { path = "libraries/snapping" }
|
||||
|
||||
# Workspace dependencies
|
||||
rustc-hash = "2.0"
|
||||
@@ -132,7 +123,7 @@ env_logger = "0.11"
|
||||
log = "0.4"
|
||||
bitflags = { version = "2.4", features = ["serde"] }
|
||||
ctor = "0.2"
|
||||
convert_case = "0.12"
|
||||
convert_case = "0.8"
|
||||
titlecase = "3.6"
|
||||
fancy-regex = "0.18.0"
|
||||
unicode-segmentation = "1.13.2"
|
||||
@@ -251,8 +242,9 @@ spin = "0.10"
|
||||
clap = "4.5"
|
||||
|
||||
# Ensure these are kept in sync with .nix/deps/rust-gpu.nix
|
||||
spirv-std = { version = "0.10.0", features = ["bytemuck"] }
|
||||
cargo-gpu-install = { version = "0.10.0", default-features = false }
|
||||
# Git commit required for glam=0.33 support (TODO: use release when new version is published. Last publish was Apr 17)
|
||||
spirv-std = { git = "https://github.com/Rust-GPU/rust-gpu.git", rev = "2fff75a21a1909945ac85f5818843dd9960004d7", features = ["bytemuck"] }
|
||||
cargo-gpu-install = { git = "https://github.com/Rust-GPU/rust-gpu.git", rev = "2fff75a21a1909945ac85f5818843dd9960004d7", default-features = false }
|
||||
|
||||
qrcodegen = "1.8"
|
||||
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
|
||||
|
||||
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":{"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
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":fLine truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"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}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"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],[3,4],[4,1]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]]]},"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_deduplicLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[194878846429432339,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3Line truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::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}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"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":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_value":{"CellularReturnType":"CellValue"},"exposed":false}},{"Value":{"tagged_value":{"Number":1.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::NoisePatternNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6565638614909771142,{"inputs":[{"Node":{"node_id":7624113397561636853,"output_index":0}},{"Node":{"node_id":80924370013313595,"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":{"GeLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"I64":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"I64":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_vaLine truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"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}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"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::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":1,"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":""}}],[3,{"inputs":[{"Node":{"node_id":2,"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":""}}],[4,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"List":{"Concrete":{"nameLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sLine truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"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
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"outLine truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":Line truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":Line truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]]},"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,10 +134,6 @@ 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,
|
||||
|
||||
@@ -152,8 +152,8 @@ impl<L: Layout> Gdd<L> {
|
||||
redo_stack: self.session.redo_stack().to_vec(),
|
||||
next_node_counter: self.session.next_node_counter(),
|
||||
last_hot_sequence: self.session.last_hot_sequence(),
|
||||
retired_marks: self.session.retired_marks().clone(),
|
||||
clock_counter: self.session.clock_counter(),
|
||||
settled: self.session.settled_marks().clone(),
|
||||
clock: self.session.clock_counter(),
|
||||
view_settings: self.view_settings.clone(),
|
||||
network_view_settings: self.network_view_settings.clone(),
|
||||
};
|
||||
@@ -198,15 +198,8 @@ 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. 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
|
||||
};
|
||||
// `bootstrap_from_registry` reconstructs the whole document from it alone.
|
||||
let snapshot = if options.include_history { export_session.retired_registry() } else { export_session.registry() };
|
||||
sink.write_entry(&io::path_for(self.layout.registry_basename(), codecs.registry), &codecs.registry.write_single(snapshot)?)?;
|
||||
}
|
||||
|
||||
|
||||
@@ -162,9 +162,9 @@ impl<L: Layout> Gdd<L> {
|
||||
}
|
||||
|
||||
session.restore_hot_sequence(session_state.last_hot_sequence);
|
||||
session.restore_clock_counter(session_state.clock_counter);
|
||||
// Before the hot log replays, so a retired op in it is dropped rather than staged again.
|
||||
session.absorb_retired_marks(&session_state.retired_marks);
|
||||
session.restore_clock(session_state.clock);
|
||||
// Before the hot log replays, so a settled op in it is dropped rather than staged again.
|
||||
session.absorb_settled_marks(&session_state.settled);
|
||||
replay_hot_log(&working, &layout, codecs.hot_log, &mut session).await?;
|
||||
|
||||
Ok(Self {
|
||||
|
||||
@@ -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.replay_hot_op(op.clone())?;
|
||||
self.session.apply_hot_op(op.clone())?;
|
||||
self.append_hot_frame(&op)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -176,8 +176,6 @@ impl<L: Layout> Gdd<L> {
|
||||
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: Value) -> Result<(), Error> {
|
||||
if self.session.annotate_delta(rev, key, value) {
|
||||
self.rewrite_history()?;
|
||||
// The annotation ticked the clock, which a reopen must not hand out again.
|
||||
self.persist_session_state()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -202,8 +200,8 @@ impl<L: Layout> Gdd<L> {
|
||||
redo_stack: self.session.redo_stack().to_vec(),
|
||||
next_node_counter: self.session.next_node_counter(),
|
||||
last_hot_sequence: self.session.last_hot_sequence(),
|
||||
retired_marks: self.session.retired_marks().clone(),
|
||||
clock_counter: self.session.clock_counter(),
|
||||
settled: self.session.settled_marks().clone(),
|
||||
clock: self.session.clock_counter(),
|
||||
view_settings: self.view_settings.clone(),
|
||||
network_view_settings: self.network_view_settings.clone(),
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//!
|
||||
//! Lives in `session.json`. Rewritten on retirement.
|
||||
|
||||
use document_graph_storage::{HotSequence, NetworkId, PeerId, RetiredMarks, Rev, UserId, Value};
|
||||
use document_graph_storage::{HotSequence, NetworkId, PeerId, Rev, SettledHotOps, UserId, Value};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
@@ -15,7 +15,8 @@ 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.
|
||||
/// The person using this device, which the peer registers as, so authorship and undo follow the person
|
||||
/// across the peer ids they accumulate.
|
||||
#[serde(default)]
|
||||
pub user_id: UserId,
|
||||
/// Local-chain cursor. Points at the most recently applied retired delta, or `None` on an empty
|
||||
@@ -34,7 +35,8 @@ pub struct SessionState {
|
||||
/// collide on minted IDs.
|
||||
#[serde(default)]
|
||||
pub next_node_counter: u64,
|
||||
/// The last hot op sequence this peer authored, so a reopen never reuses one.
|
||||
/// The sequence of the last hot op this peer authored, feeding [`document_graph_storage::HotOp::sequence`], so a
|
||||
/// reopen never reuses a spent sequence.
|
||||
#[serde(default)]
|
||||
pub last_hot_sequence: HotSequence,
|
||||
/// Per-peer view settings (PTZ, rulers, overlays, snapping, panel collapse). Local to the viewer,
|
||||
@@ -45,10 +47,12 @@ pub struct SessionState {
|
||||
/// Per-peer like [`view_settings`](Self::view_settings); opaque `ui::nav::*` / `ui::previewing` blobs.
|
||||
#[serde(default)]
|
||||
pub network_view_settings: BTreeMap<NetworkId, BTreeMap<String, Value>>,
|
||||
/// The retired hot op marks, so a late copy re-sent after a reopen is dropped rather than retired again.
|
||||
/// Which hot ops are retired, so a late copy a peer re-sends after a reopen is dropped rather than retired a second
|
||||
/// time. About one sequence per author; runs only for ops in flight when saved.
|
||||
#[serde(default)]
|
||||
pub retired_marks: RetiredMarks,
|
||||
/// The Lamport counter, so a reopen never mints a spent stamp.
|
||||
pub settled: SettledHotOps,
|
||||
/// The Lamport counter, so a reopen never mints a stamp already spent, even one no op in history or the hot log
|
||||
/// carries any more.
|
||||
#[serde(default)]
|
||||
pub clock_counter: u64,
|
||||
pub clock: u64,
|
||||
}
|
||||
@@ -695,33 +695,3 @@ 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");
|
||||
});
|
||||
}
|
||||
@@ -24,7 +24,7 @@ fn network_with_one_node() -> NodeNetwork {
|
||||
|
||||
/// A whole-document stage after a recorded batch stages nothing new: restating the batch would fail on the node it added.
|
||||
#[test]
|
||||
fn restaging_the_whole_document_after_a_batch_stages_nothing() {
|
||||
fn a_whole_document_stage_after_a_recorded_batch_stages_nothing_new() {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(21), 1, "ed".into(), "std".into()).unwrap();
|
||||
let store = HashMapResourceStorage::new();
|
||||
let resources = ResourceRegistry::new();
|
||||
@@ -69,7 +69,8 @@ fn a_reopen_keeps_unretired_hot_ops_out_of_the_retired_snapshot() {
|
||||
});
|
||||
}
|
||||
|
||||
/// A reused sequence would let a peer's retired marks drop the new op.
|
||||
/// A reopen continues this peer's clock and run of hot op sequences, with ops still hot and after they all retired,
|
||||
/// since a reused sequence would let a peer's settled marks drop the new op.
|
||||
#[test]
|
||||
fn a_reopen_continues_the_hot_op_sequence() {
|
||||
use document_graph_storage::{AttributeDelta, RegistryDelta, Value};
|
||||
@@ -79,6 +80,7 @@ fn a_reopen_continues_the_hot_op_sequence() {
|
||||
value: Some(Value::from(serde_json::json!(value))),
|
||||
},
|
||||
};
|
||||
// Stages one op and returns the sequence it got.
|
||||
fn stage(gdd: &mut GddV1, op: RegistryDelta) -> u64 {
|
||||
gdd.stage_constructed_ops(vec![op], &Default::default(), &HashMapResourceStorage::new()).unwrap();
|
||||
gdd.session().hot_log().last().unwrap().sequence.0
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{AttributeDelta, TimeStamp, Value, ValueError, from_value, to_value};
|
||||
use crate::{TimeStamp, Value, ValueError, from_value, to_value};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, btree_map};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Attribute keys. Glob-import (`use crate::attr::*`) at conversion sites.
|
||||
///
|
||||
@@ -8,7 +8,8 @@ use std::collections::{BTreeMap, btree_map};
|
||||
/// keys live on `Node.inputs_attributes[i]`; per-network keys live on `Network.attributes`.
|
||||
pub mod attr;
|
||||
|
||||
/// An attribute value and when it was last set. A deleted key stays as a stamped tombstone, which readers see as absent.
|
||||
/// A type-erased attribute value paired with the timestamp at which it was last set. A deleted key
|
||||
/// stays as a stamped tombstone, so an older write loses in either arrival order; readers see it as absent.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AttributeValue {
|
||||
pub value: Value,
|
||||
@@ -33,189 +34,59 @@ impl 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,
|
||||
/// Attribute maps. Each entity carries an `attributes_timestamp`: when its map was last written whole, by an
|
||||
/// addition or a whole-list input write. A key absent from the map is deleted as of that stamp, so an older
|
||||
/// write is dropped and an older tombstone is redundant.
|
||||
pub type Attributes = BTreeMap<String, AttributeValue>;
|
||||
|
||||
/// The live entries of an attribute map: every key that is not a tombstone.
|
||||
pub fn live(attributes: &Attributes) -> impl Iterator<Item = (&String, &AttributeValue)> {
|
||||
attributes.iter().filter(|(_, value)| !value.deleted)
|
||||
}
|
||||
|
||||
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`.
|
||||
pub fn set(&mut self, key: &str, value: Value, timestamp: TimeStamp) {
|
||||
self.insert(key.to_string(), AttributeValue::new(value, timestamp));
|
||||
}
|
||||
fn set(&mut self, key: &str, value: Value, timestamp: TimeStamp);
|
||||
|
||||
/// Serializes `value` and inserts it under `key`.
|
||||
pub fn set_serialized<T: serde::Serialize>(&mut self, key: &str, value: &T, timestamp: TimeStamp) -> Result<(), ValueError> {
|
||||
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.
|
||||
pub fn set_if_not_default<T: serde::Serialize + PartialEq>(&mut self, key: &str, value: &T, default: &T, timestamp: TimeStamp) -> Result<(), ValueError> {
|
||||
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(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 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())
|
||||
impl AttributesWrite for Attributes {
|
||||
fn set(&mut self, key: &str, value: Value, timestamp: TimeStamp) {
|
||||
self.insert(key.to_string(), AttributeValue::new(value, timestamp));
|
||||
}
|
||||
}
|
||||
|
||||
/// 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`.
|
||||
pub fn get_or<T: serde::de::DeserializeOwned>(&self, key: &str, default: T) -> T {
|
||||
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()`.
|
||||
pub fn get_or_default<T: serde::de::DeserializeOwned + Default>(&self, key: &str) -> T {
|
||||
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 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()
|
||||
impl AttributesRead for Attributes {
|
||||
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())
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,6 @@ pub mod node {
|
||||
pub const LOCKED: &str = "ui::locked";
|
||||
pub const PINNED: &str = "ui::pinned";
|
||||
pub const OUTPUT_NAMES: &str = "ui::output_names";
|
||||
pub const OUTPUT_DESCRIPTIONS: &str = "ui::output_descriptions";
|
||||
pub const REFERENCE: &str = "ui::reference"; // TODO: Remove?
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
use crate::{Attributes, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev};
|
||||
use crate::{
|
||||
AttributeValue, Attributes, AttributesWrite, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Prior, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId,
|
||||
Value, attr, compute_rev,
|
||||
};
|
||||
use graphene_resource::ResourceHash;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Content-addressed delta: `id` is `blake3_128(parents, author, timestamp, delta_type)`.
|
||||
///
|
||||
/// `reverse` is undo bookkeeping that depends on local state, so it is stored but left out of the identity hash.
|
||||
/// `reverse` is state-dependent undo bookkeeping (what the op overwrote, captured as it applied), so it's
|
||||
/// serialized for storage but excluded from the identity hash: two peers applying the same forward delta to
|
||||
/// different local states would otherwise compute different Revs for the same logical op.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Delta {
|
||||
pub id: Rev,
|
||||
@@ -13,20 +18,22 @@ pub struct Delta {
|
||||
pub author: PeerId,
|
||||
pub timestamp: TimeStamp,
|
||||
pub kind: RegistryDelta,
|
||||
pub reverse: RegistryDelta,
|
||||
/// What every slot `kind` wrote held before it, stamps included, in write order. See [`Prior`].
|
||||
pub reverse: Vec<Prior>,
|
||||
/// Local, mutable annotations on this commit (interaction-end marker, future commit messages / labels).
|
||||
/// Deliberately excluded from `compute_rev`: relabeling a commit must not change its content-addressed
|
||||
/// identity, and two peers annotating the same op differently must still dedup to one `Rev`.
|
||||
#[serde(default)]
|
||||
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.
|
||||
/// When the delta entered history, in Unix milliseconds by the clock of the peer that retired it; display only,
|
||||
/// and outside the rev like `attributes`. Zero means unrecorded, saving the tag byte an `Option` costs per delta;
|
||||
/// read it through [`retired_at`](Self::retired_at). Last, since the history codec is positional.
|
||||
#[serde(default)]
|
||||
pub(crate) retired_at_ms: u64,
|
||||
}
|
||||
|
||||
impl Delta {
|
||||
pub fn new(parent: Option<Rev>, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: RegistryDelta) -> Self {
|
||||
pub fn new(parent: Option<Rev>, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: Vec<Prior>) -> Self {
|
||||
let id = compute_rev(parent, author, timestamp, &kind);
|
||||
Self {
|
||||
id,
|
||||
@@ -54,7 +61,7 @@ impl Delta {
|
||||
parent,
|
||||
author,
|
||||
timestamp,
|
||||
reverse: kind.clone(),
|
||||
reverse: Vec::new(),
|
||||
kind,
|
||||
attributes: Attributes::default(),
|
||||
retired_at_ms: 0,
|
||||
@@ -193,7 +200,8 @@ pub enum RegistryDelta {
|
||||
id: ResourceId,
|
||||
key: SourceKey,
|
||||
},
|
||||
/// Registers a device's `PeerId` to the `UserId` behind it; the newest registration wins.
|
||||
/// Registers a device's `PeerId` to the `UserId` behind it. LWW per peer, so a device that changes person
|
||||
/// registers again and the newest registration wins wherever it lands.
|
||||
RegisterPeer {
|
||||
peer: PeerId,
|
||||
user: UserId,
|
||||
@@ -208,6 +216,8 @@ pub enum RegistryDelta {
|
||||
Merge {
|
||||
extra_parents: Vec<Rev>,
|
||||
},
|
||||
/// The last op of its author's transaction. Changes nothing, and retirement drops it.
|
||||
EndTransaction,
|
||||
// Allow for future delta types without a model change
|
||||
Other(Value),
|
||||
}
|
||||
@@ -219,11 +229,19 @@ pub struct AttributeDelta {
|
||||
pub value: Option<Value>,
|
||||
}
|
||||
|
||||
pub(crate) fn reverse_attribute_delta(delta: &AttributeDelta, attributes: &Attributes) -> AttributeDelta {
|
||||
AttributeDelta {
|
||||
key: delta.key.clone(),
|
||||
value: attributes.get(&delta.key).filter(|previous| !previous.deleted).map(|previous| previous.value.clone()),
|
||||
/// Lands a single-key write. `floor` is the map's `attributes_timestamp`; see [`Attributes`]. A deletion
|
||||
/// leaves a tombstone.
|
||||
pub(crate) fn apply_attribute_delta(delta: AttributeDelta, timestamp: TimeStamp, attributes: &mut Attributes, floor: TimeStamp) {
|
||||
let AttributeDelta { key, value } = delta;
|
||||
let decided = attributes.get(&key).map_or(floor, |existing| existing.timestamp);
|
||||
if timestamp <= decided {
|
||||
return;
|
||||
}
|
||||
let entry = match value {
|
||||
Some(value) => AttributeValue::new(value, timestamp),
|
||||
None => AttributeValue::deleted(timestamp),
|
||||
};
|
||||
attributes.insert(key, entry);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -231,14 +249,8 @@ 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),
|
||||
);
|
||||
fn a_missing_retirement_time_costs_what_a_zero_costs_and_round_trips() {
|
||||
let base = Delta::new(None, PeerId(1), TimeStamp { counter: 1, peer: PeerId(1) }, RegistryDelta::EndTransaction, Vec::new());
|
||||
let mut stamped = base.clone();
|
||||
stamped.retired_at_ms = 1_790_000_000_000;
|
||||
|
||||
|
||||
@@ -196,14 +196,14 @@ 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.live() {
|
||||
for (key, _) in crate::attributes::live(from) {
|
||||
if to.get(key).is_none_or(|value| value.deleted) {
|
||||
deltas.push(AttributeDelta { key: key.clone(), value: None });
|
||||
}
|
||||
}
|
||||
|
||||
// Compare by `value` only; the per-entry `timestamp` is derived from the diff, not part of it.
|
||||
for (key, to_value) in to.live() {
|
||||
for (key, to_value) in crate::attributes::live(to) {
|
||||
if from.get(key).is_none_or(|from_value| from_value.deleted || from_value.value != to_value.value) {
|
||||
deltas.push(AttributeDelta {
|
||||
key: key.clone(),
|
||||
@@ -287,6 +287,7 @@ mod tests {
|
||||
input: NodeInput::Import { index: 0 },
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
attributes: Attributes::new(),
|
||||
attributes_timestamp: TimeStamp::ORIGIN,
|
||||
});
|
||||
|
||||
let deltas = compute_deltas(&from, &to);
|
||||
@@ -298,7 +299,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_compute_deltas_change_network_attribute() {
|
||||
use crate::TimeStamp;
|
||||
use crate::{AttributesWrite, TimeStamp};
|
||||
|
||||
let mut from = Registry::default();
|
||||
from.networks.insert(NetworkId(0), Network::default());
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use std::collections::btree_map::Entry;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::hash::Hash;
|
||||
|
||||
use crate::{
|
||||
Attributes, CrdtError, Delta, ExportSlot, History, HotOp, HotSequence, Implementation, InputSlot, LamportClock, MAX_EXPORT_SLOTS, MAX_INPUT_SLOTS, Network, NetworkId, Node, NodeId, NodeInput,
|
||||
PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, RetiredMarks, Rev, SourceValue, TimeStamp, Tombstone, UserId, Value, reverse_attribute_delta,
|
||||
PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, Rev, SettledHotOps, SourceValue, TimeStamp, Tombstone, UserId, apply_attribute_delta,
|
||||
};
|
||||
use std::borrow::Cow;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Document {
|
||||
@@ -17,8 +17,9 @@ pub struct Document {
|
||||
pub(crate) hot_log: Vec<HotOp>,
|
||||
/// The stamps of the hot log's ops, so a re-announced op is recognised without a scan.
|
||||
pub(crate) hot_timestamps: HashSet<TimeStamp>,
|
||||
/// Which hot ops are retired into history, so a late copy is dropped.
|
||||
pub(crate) retired: RetiredMarks,
|
||||
/// Which hot ops are retired into history, so a late copy is dropped;
|
||||
/// retired deltas keep no link back to their hot ops.
|
||||
pub(crate) settled: SettledHotOps,
|
||||
/// The registry as of the last retirement, with no un-retired hot ops applied. Retirement computes
|
||||
/// each delta's `reverse` against this (so LWW reverses capture the true pre-op value, not the
|
||||
/// hot-polluted working state) and advances it. It equals the working registry whenever the hot log is
|
||||
@@ -33,8 +34,10 @@ pub struct Document {
|
||||
pub(crate) redo_stack: Vec<Rev>,
|
||||
pub(crate) clock: LamportClock,
|
||||
pub(crate) peer: PeerId,
|
||||
/// The person behind this peer; what `RegisterPeer` records for it.
|
||||
pub(crate) user: UserId,
|
||||
/// The latest retired commit a peer holds: commits after it undo silently, commits up to it stay.
|
||||
/// Latest retired commit on the local chain that a peer holds. Commits after it can be undone silently; commits up
|
||||
/// to it are published and stay. `None` means nothing published yet.
|
||||
pub(crate) last_broadcast_rev: Option<Rev>,
|
||||
/// Shared-monotonic counter feeding `next_node_id`. Bumped on every mint regardless of which
|
||||
/// peer is calling; collision avoidance comes from hashing `(self.peer, counter)`, so two peers
|
||||
@@ -45,6 +48,7 @@ pub struct Document {
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// An empty document for `peer`, at the origin of its clock.
|
||||
pub(crate) fn empty(peer: PeerId, user: UserId) -> Self {
|
||||
Self {
|
||||
working_registry: Registry::default(),
|
||||
@@ -52,7 +56,7 @@ impl Document {
|
||||
history: History::new(),
|
||||
hot_log: Vec::new(),
|
||||
hot_timestamps: HashSet::new(),
|
||||
retired: RetiredMarks::default(),
|
||||
settled: SettledHotOps::default(),
|
||||
head: None,
|
||||
redo_stack: Vec::new(),
|
||||
clock: LamportClock::new(peer),
|
||||
@@ -76,41 +80,40 @@ impl Document {
|
||||
NodeId(u64::from_le_bytes(truncated))
|
||||
}
|
||||
|
||||
/// Apply a delta's `reverse` as the new forward op (silent-zone undo). Force-applied: structural
|
||||
/// ops are idempotent, and LWW arms assign the reverse value unconditionally even though it carries
|
||||
/// the same timestamp as the forward op it undoes.
|
||||
pub(crate) fn revert_delta(&mut self, target: RegistryTarget, mut delta: Delta) -> Result<(), CrdtError> {
|
||||
for parent in delta.all_parents() {
|
||||
if !self.history.contains(parent) {
|
||||
return Err(CrdtError::NotFoundInHistory(parent));
|
||||
}
|
||||
/// Put back what a delta overwrote in the retired snapshot (silent-zone undo), leaving it as folding history up
|
||||
/// to the delta's parent would. The working registry follows: it is the same registry when nothing is hot.
|
||||
pub(crate) fn revert_delta(&mut self, delta: &Delta) {
|
||||
crate::prior::restore(&mut self.retired_snapshot, &delta.reverse);
|
||||
if self.hot_log.is_empty() {
|
||||
crate::prior::restore(&mut self.working_registry, &delta.reverse);
|
||||
}
|
||||
std::mem::swap(&mut delta.kind, &mut delta.reverse);
|
||||
self.apply_op_with(target, delta.kind, delta.timestamp, ApplyMode::Force)
|
||||
}
|
||||
|
||||
/// Stage a local op onto the working registry and the hot log, skipping the retired check so local work is never dropped.
|
||||
pub(crate) fn stage_hot_op(&mut self, hot_op: HotOp, mode: ApplyMode) -> Result<(), CrdtError> {
|
||||
/// Apply a locally staged op: LWW into the registry, append to the hot log, leave history and `head`
|
||||
/// alone. Skips the retirement check, so staging never silently drops local work; outside callers use
|
||||
/// [`Session::apply_hot_op`](crate::Session::apply_hot_op).
|
||||
pub(crate) fn apply_hot_op(&mut self, hot_op: HotOp, mode: ApplyMode) -> Result<(), CrdtError> {
|
||||
self.apply_op_with(RegistryTarget::Working, hot_op.op.clone(), hot_op.timestamp, mode)?;
|
||||
self.hot_timestamps.insert(hot_op.timestamp);
|
||||
self.hot_log.push(hot_op);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Replay a persisted or received hot op. One already retired or held changes nothing.
|
||||
/// Replay a hot op recovered from persisted state or received from a peer. Replaying one already
|
||||
/// reflected in the registry changes nothing.
|
||||
pub fn replay_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
|
||||
// Seeing an op is enough to know what it implies, whether or not it applies: its stamp, and for one of our own a
|
||||
// spent sequence, should the persisted counter lag.
|
||||
self.clock.observe(hot_op.timestamp);
|
||||
if hot_op.timestamp.peer == self.peer {
|
||||
self.last_hot_sequence = self.last_hot_sequence.max(hot_op.sequence);
|
||||
}
|
||||
if self.retired.covers(hot_op.id()) {
|
||||
// Re-adding a settled op would leave a hot log entry no retirement will ever name.
|
||||
if self.settled.covers(hot_op.id()) {
|
||||
return Ok(());
|
||||
}
|
||||
// A re-announcement of a held op must not become a second copy.
|
||||
if self.hot_timestamps.contains(&hot_op.timestamp) {
|
||||
return Ok(());
|
||||
}
|
||||
// Our own ops raise the sequence counter too, should the persisted one lag behind the hot log.
|
||||
if hot_op.timestamp.peer == self.peer {
|
||||
self.last_hot_sequence = self.last_hot_sequence.max(hot_op.sequence);
|
||||
}
|
||||
|
||||
self.apply_op_idempotent(hot_op.op.clone(), hot_op.timestamp)?;
|
||||
self.hot_timestamps.insert(hot_op.timestamp);
|
||||
@@ -119,9 +122,9 @@ impl Document {
|
||||
}
|
||||
|
||||
/// Take on a peer's marks as well as this peer's. Returns whether a hot op was dropped.
|
||||
pub(crate) fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> bool {
|
||||
self.retired.absorb(remote);
|
||||
self.drop_retired_hot_ops()
|
||||
pub(crate) fn absorb_settled(&mut self, remote: &SettledHotOps) -> bool {
|
||||
self.settled.absorb(remote);
|
||||
self.drop_settled_hot_ops()
|
||||
}
|
||||
|
||||
/// Bring the stamp index back in line after the hot log was filtered as a whole.
|
||||
@@ -129,21 +132,22 @@ impl Document {
|
||||
self.hot_timestamps = self.hot_log.iter().map(|hot_op| hot_op.timestamp).collect();
|
||||
}
|
||||
|
||||
/// Re-derive working as the snapshot plus every hot op, for a change that cannot apply in place. O(registry), so rare.
|
||||
/// Re-derive the working registry as the retired snapshot plus every hot op, for a change that cannot
|
||||
/// be applied in place. O(N + L), for rare paths only.
|
||||
pub(crate) fn rebuild_working(&mut self) {
|
||||
self.working_registry = self.retired_snapshot.clone();
|
||||
for hot_op in std::mem::take(&mut self.hot_log) {
|
||||
// No op fails on a referent, and one failing otherwise must not be lost.
|
||||
// Nothing is deferred, so this cannot fail on a referent; don't strand the op over anything else.
|
||||
let _ = self.apply_op_idempotent(hot_op.op.clone(), hot_op.timestamp);
|
||||
self.hot_log.push(hot_op);
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop retired hot ops and re-derive working without them: their effect returns with their deltas.
|
||||
fn drop_retired_hot_ops(&mut self) -> bool {
|
||||
/// Drop settled hot ops and re-derive the working registry without them; their effect comes back with their deltas.
|
||||
fn drop_settled_hot_ops(&mut self) -> bool {
|
||||
let before = self.hot_log.len();
|
||||
let retired = &self.retired;
|
||||
self.hot_log.retain(|hot_op| !retired.covers(hot_op.id()));
|
||||
let settled = &self.settled;
|
||||
self.hot_log.retain(|hot_op| !settled.covers(hot_op.id()));
|
||||
let dropped = self.hot_log.len() != before;
|
||||
if dropped {
|
||||
self.resync_hot_timestamps();
|
||||
@@ -168,21 +172,21 @@ impl Document {
|
||||
fn registry_mut(&mut self, target: RegistryTarget) -> &mut Registry {
|
||||
match target {
|
||||
RegistryTarget::Working => &mut self.working_registry,
|
||||
RegistryTarget::Retired => &mut self.retired_snapshot,
|
||||
RegistryTarget::Snapshot => &mut self.retired_snapshot,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn registry_ref(&self, target: RegistryTarget) -> &Registry {
|
||||
match target {
|
||||
RegistryTarget::Working => &self.working_registry,
|
||||
RegistryTarget::Retired => &self.retired_snapshot,
|
||||
RegistryTarget::Snapshot => &self.retired_snapshot,
|
||||
}
|
||||
}
|
||||
|
||||
/// A fresh local edit against the working registry; see [`ApplyMode::Strict`].
|
||||
/// A fresh local edit against the working registry; see [`ApplyMode::Live`].
|
||||
#[cfg(test)]
|
||||
pub(crate) fn apply_op(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
|
||||
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Strict)
|
||||
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Live)
|
||||
}
|
||||
|
||||
/// An op from a peer or from persisted state, against the working registry.
|
||||
@@ -190,38 +194,36 @@ impl Document {
|
||||
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Idempotent)
|
||||
}
|
||||
|
||||
/// Silent-zone undo/redo rewind against the working registry: structural ops are idempotent, and
|
||||
/// LWW arms assign unconditionally. We own the single-writer chain here, so the precomputed reverse
|
||||
/// (undo) or forward (redo) value is authoritative even though its timestamp ties what it replaces.
|
||||
pub(crate) fn force_apply_op(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
|
||||
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Force)
|
||||
}
|
||||
|
||||
/// Applies one op. Every field, 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.
|
||||
/// Applies one op. Every field of the registry is last-writer-wins on a timestamp, whether an entity
|
||||
/// exists included, so the registry folds to the same values whatever order the ops land in:
|
||||
///
|
||||
/// - An addition writes every field of the entity at its stamp, and is evidence it exists from then.
|
||||
/// - A removal is evidence the entity does not exist from its stamp. Its content stays as a tombstone,
|
||||
/// and the removal's snapshot folds in like any other write.
|
||||
/// - A write, or a reference from another entity's op, is evidence the entity exists at its stamp, so it
|
||||
/// revives an older removal; an older write lands on the tombstone, for a later revival to see.
|
||||
/// - A write to an entity never seen lands on a placeholder until its addition arrives; see [`write()`].
|
||||
pub(crate) fn apply_op_with(&mut self, target: RegistryTarget, op: RegistryDelta, timestamp: TimeStamp, mode: ApplyMode) -> Result<(), CrdtError> {
|
||||
// Advance the local clock past every observed op, including ones that subsequently no-op or
|
||||
// error. Observation is about causality knowledge, not about whether the op took effect.
|
||||
self.clock.observe(timestamp);
|
||||
|
||||
let strict = mode == ApplyMode::Strict;
|
||||
let force = mode == ApplyMode::Force;
|
||||
let live = mode == ApplyMode::Live;
|
||||
|
||||
let registry = self.registry_mut(target);
|
||||
match op {
|
||||
RegistryDelta::AddNode { id, node } => {
|
||||
if strict && registry.node_instances.contains_key(&id) {
|
||||
if live && registry.node_instances.contains_key(&id) {
|
||||
return Err(CrdtError::NodeAlreadyExists(id));
|
||||
}
|
||||
write_network(registry, node.network, timestamp, mode, |_| Ok(()))?;
|
||||
add_entity(&mut registry.node_instances, &mut registry.removed_nodes, id, node, timestamp, force);
|
||||
add(&mut registry.node_instances, &mut registry.removed_nodes, id, node, timestamp);
|
||||
}
|
||||
RegistryDelta::RemoveNode { id, snapshot } => {
|
||||
remove_entity(&mut registry.node_instances, &mut registry.removed_nodes, id, snapshot, timestamp, force);
|
||||
remove(&mut registry.node_instances, &mut registry.removed_nodes, id, snapshot, timestamp);
|
||||
}
|
||||
RegistryDelta::SetNodeInputs { id, mut inputs } => {
|
||||
inputs.iter_mut().for_each(|slot| stamp_listed_slot(slot, timestamp));
|
||||
inputs.iter_mut().for_each(|slot| stamp_slot(slot, timestamp));
|
||||
let referenced: Vec<NodeId> = inputs
|
||||
.iter()
|
||||
.filter_map(|slot| match slot.input {
|
||||
@@ -231,12 +233,7 @@ impl Document {
|
||||
.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);
|
||||
}
|
||||
merge_inputs(node, inputs, timestamp);
|
||||
Ok(())
|
||||
})?;
|
||||
for referenced in referenced {
|
||||
@@ -251,7 +248,7 @@ impl Document {
|
||||
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 {
|
||||
if timestamp > input.timestamp {
|
||||
input.input = new_input;
|
||||
input.timestamp = timestamp;
|
||||
}
|
||||
@@ -267,7 +264,7 @@ impl Document {
|
||||
write_network(registry, network, timestamp, mode, |_| Ok(()))?;
|
||||
}
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
if force || timestamp > node.implementation_timestamp {
|
||||
if timestamp > node.implementation_timestamp {
|
||||
node.implementation = implementation;
|
||||
node.implementation_timestamp = timestamp;
|
||||
}
|
||||
@@ -276,14 +273,14 @@ impl Document {
|
||||
}
|
||||
RegistryDelta::ChangeNodeAttribute { id, delta } => {
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
node.attributes.apply_delta(delta, timestamp, force);
|
||||
apply_attribute_delta(delta, timestamp, &mut node.attributes, node.attributes_timestamp);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => {
|
||||
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);
|
||||
apply_attribute_delta(delta, timestamp, &mut input.attributes, input.attributes_timestamp);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
@@ -299,16 +296,11 @@ impl Document {
|
||||
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::default());
|
||||
}
|
||||
|
||||
let existing = &mut net.exports[slot_idx];
|
||||
if force || timestamp > existing.timestamp {
|
||||
if timestamp > existing.timestamp {
|
||||
existing.target = export;
|
||||
existing.timestamp = timestamp;
|
||||
}
|
||||
@@ -319,23 +311,23 @@ impl Document {
|
||||
}
|
||||
}
|
||||
RegistryDelta::AddNetwork { id, network } => {
|
||||
if strict && registry.networks.contains_key(&id) {
|
||||
if live && registry.networks.contains_key(&id) {
|
||||
return Err(CrdtError::NetworkAlreadyExists(id));
|
||||
}
|
||||
add_entity(&mut registry.networks, &mut registry.removed_networks, id, network, timestamp, force);
|
||||
add(&mut registry.networks, &mut registry.removed_networks, id, network, timestamp);
|
||||
}
|
||||
RegistryDelta::RemoveNetwork { id, snapshot } => {
|
||||
remove_entity(&mut registry.networks, &mut registry.removed_networks, id, snapshot, timestamp, force);
|
||||
remove(&mut registry.networks, &mut registry.removed_networks, id, snapshot, timestamp);
|
||||
}
|
||||
RegistryDelta::ChangeNetworkAttribute { id, delta } => {
|
||||
write_network(registry, id, timestamp, mode, |net| {
|
||||
net.attributes.apply_delta(delta, timestamp, force);
|
||||
apply_attribute_delta(delta, timestamp, &mut net.attributes, net.attributes_timestamp);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
RegistryDelta::SetResourceHash { id, hash } => {
|
||||
upsert_resource(registry, id, timestamp, |entry| {
|
||||
if force || timestamp > entry.hash_timestamp {
|
||||
if timestamp > entry.hash_timestamp {
|
||||
entry.hash = hash;
|
||||
entry.hash_timestamp = timestamp;
|
||||
}
|
||||
@@ -344,246 +336,126 @@ impl Document {
|
||||
RegistryDelta::AddSource { id, key, source } => {
|
||||
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) }
|
||||
entry.set_source(key, value);
|
||||
});
|
||||
}
|
||||
RegistryDelta::RemoveSource { id, key } => {
|
||||
// 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);
|
||||
}
|
||||
entry.remove_source(&key, timestamp);
|
||||
});
|
||||
}
|
||||
RegistryDelta::AddResource { id, entry } => {
|
||||
add_entity(&mut registry.resources, &mut registry.removed_resources, id, entry, timestamp, force);
|
||||
add(&mut registry.resources, &mut registry.removed_resources, id, entry, timestamp);
|
||||
}
|
||||
RegistryDelta::RemoveResource { id, snapshot } => {
|
||||
remove_entity(&mut registry.resources, &mut registry.removed_resources, id, snapshot, timestamp, force);
|
||||
remove(&mut registry.resources, &mut registry.removed_resources, id, snapshot, timestamp);
|
||||
}
|
||||
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 });
|
||||
if registry.peer_users.get(&peer).is_none_or(|existing| timestamp > existing.at) {
|
||||
registry.peer_users.insert(peer, PeerRegistration { user, at: timestamp });
|
||||
}
|
||||
}
|
||||
RegistryDelta::ChangeDocumentAttribute { delta } => {
|
||||
registry.attributes.apply_delta(delta, timestamp, force);
|
||||
apply_attribute_delta(delta, timestamp, &mut registry.attributes, TimeStamp::ORIGIN);
|
||||
}
|
||||
// Merge is a structural sync point only; it mutates no registry state.
|
||||
RegistryDelta::Merge { .. } | RegistryDelta::Other(_) => {}
|
||||
RegistryDelta::Merge { .. } | RegistryDelta::EndTransaction | RegistryDelta::Other(_) => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Compute the inverse of `delta` against the registry named by `target`. Retirement passes
|
||||
/// [`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, .. } => 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 = 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 } => RegistryDelta::ChangeNodeAttribute {
|
||||
id,
|
||||
delta: reverse_attribute_delta(delta, node(id).attributes()),
|
||||
},
|
||||
&RegistryDelta::ChangeNodeInputAttribute { id, index, ref delta } => {
|
||||
let node = node(id);
|
||||
let input = node.inputs().get(index as usize).unwrap_or(&unset);
|
||||
RegistryDelta::ChangeNodeInputAttribute {
|
||||
id,
|
||||
index,
|
||||
delta: reverse_attribute_delta(delta, &input.attributes),
|
||||
}
|
||||
}
|
||||
&RegistryDelta::SetNetworkExport { id, index, .. } => {
|
||||
// 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 empty = Attributes::new();
|
||||
let current = network(id).map_or(&empty, |net| &net.attributes);
|
||||
RegistryDelta::ChangeNetworkAttribute {
|
||||
id,
|
||||
delta: reverse_attribute_delta(delta, current),
|
||||
}
|
||||
}
|
||||
RegistryDelta::ChangeDocumentAttribute { delta } => RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: reverse_attribute_delta(delta, ®istry.attributes),
|
||||
},
|
||||
// Registrations are append-only and not user-undoable; reverse is the same op,
|
||||
// which applies as a no-op on the already-registered PeerId.
|
||||
&RegistryDelta::RegisterPeer { peer, user } => RegistryDelta::RegisterPeer { peer, user },
|
||||
&RegistryDelta::SetResourceHash { id, .. } => RegistryDelta::SetResourceHash {
|
||||
id,
|
||||
hash: resource(id).and_then(|entry| entry.hash),
|
||||
},
|
||||
&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,
|
||||
key,
|
||||
source: existing.source.clone(),
|
||||
},
|
||||
// The slot was empty: undo removes what this op added.
|
||||
None => RegistryDelta::RemoveSource { id, key },
|
||||
},
|
||||
&RegistryDelta::RemoveSource { id, key } => match resource(id).and_then(|entry| entry.source(&key)) {
|
||||
Some(existing) => RegistryDelta::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: existing.source.clone(),
|
||||
},
|
||||
// Nothing to restore; reverse is a no-op removal.
|
||||
None => RegistryDelta::RemoveSource { id, key },
|
||||
},
|
||||
&RegistryDelta::AddResource { id, .. } => match registry.resources.get(&id) {
|
||||
// Overwrote an existing entry: undo restores it.
|
||||
Some(existing) => RegistryDelta::AddResource { id, entry: existing.clone() },
|
||||
// Created a new entry: undo removes what this op added (snapshot is empty since there was nothing prior).
|
||||
None => RegistryDelta::RemoveResource {
|
||||
id,
|
||||
snapshot: ResourceEntry::default(),
|
||||
},
|
||||
},
|
||||
&RegistryDelta::RemoveResource { id, .. } => {
|
||||
let snapshot = registry.resources.get(&id).cloned().unwrap_or_default();
|
||||
RegistryDelta::AddResource { id, entry: snapshot }
|
||||
}
|
||||
RegistryDelta::Merge { extra_parents } => RegistryDelta::Merge { extra_parents: extra_parents.clone() },
|
||||
&RegistryDelta::Other(_) => RegistryDelta::Other(Value::None),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// An entity whose existence and every field are last-writer-wins on a timestamp.
|
||||
pub(crate) trait Entity: Sized {
|
||||
pub(crate) trait Presence: Sized {
|
||||
/// The newest stamp of an addition or a write: the latest evidence the entity exists.
|
||||
fn presence(&self) -> TimeStamp;
|
||||
fn set_presence(&mut self, timestamp: TimeStamp);
|
||||
/// Stamps every field at `timestamp`, the way an addition writes all of them.
|
||||
fn stamp_all(&mut self, timestamp: TimeStamp);
|
||||
fn set_presence(&mut self, at: TimeStamp);
|
||||
/// Stamps every field at `at`, the way an addition writes all of them.
|
||||
fn stamp_all(&mut self, at: TimeStamp);
|
||||
/// Folds `other` in, keeping whichever value of each field is newer.
|
||||
fn merge(&mut self, other: Self);
|
||||
/// Content for writes to land on before the addition, every field at the origin so the addition's win.
|
||||
/// Dead content for an entity nothing has added yet, for writes to land on until an addition comes.
|
||||
/// Every field is at the origin, so the addition's values win.
|
||||
fn placeholder() -> Self;
|
||||
}
|
||||
|
||||
impl Entity for Node {
|
||||
impl Presence for Node {
|
||||
fn presence(&self) -> TimeStamp {
|
||||
self.presence
|
||||
}
|
||||
fn set_presence(&mut self, timestamp: TimeStamp) {
|
||||
self.presence = timestamp;
|
||||
fn set_presence(&mut self, at: TimeStamp) {
|
||||
self.presence = at;
|
||||
}
|
||||
fn placeholder() -> Self {
|
||||
Node::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(0)), 0)
|
||||
}
|
||||
fn stamp_all(&mut self, 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 stamp_all(&mut self, at: TimeStamp) {
|
||||
self.presence = at;
|
||||
self.added = at;
|
||||
self.inputs_timestamp = at;
|
||||
self.implementation_timestamp = at;
|
||||
self.inputs.iter_mut().for_each(|slot| stamp_slot(slot, at));
|
||||
stamp_attributes(&mut self.attributes, &mut self.attributes_timestamp, at);
|
||||
}
|
||||
fn merge(&mut self, other: Self) {
|
||||
if other.network_timestamp > self.network_timestamp {
|
||||
if other.added > self.added {
|
||||
self.network = other.network;
|
||||
self.network_timestamp = other.network_timestamp;
|
||||
self.added = other.added;
|
||||
}
|
||||
if other.implementation_timestamp > self.implementation_timestamp {
|
||||
self.implementation = other.implementation;
|
||||
self.implementation_timestamp = other.implementation_timestamp;
|
||||
}
|
||||
merge_inputs(self, other.inputs, other.inputs_timestamp);
|
||||
self.attributes.merge(other.attributes);
|
||||
merge_attributes(&mut self.attributes, &mut self.attributes_timestamp, other.attributes, other.attributes_timestamp);
|
||||
self.presence = self.presence.max(other.presence);
|
||||
}
|
||||
}
|
||||
|
||||
impl Entity for Network {
|
||||
impl Presence for Network {
|
||||
fn presence(&self) -> TimeStamp {
|
||||
self.presence
|
||||
}
|
||||
fn set_presence(&mut self, timestamp: TimeStamp) {
|
||||
self.presence = timestamp;
|
||||
fn set_presence(&mut self, at: TimeStamp) {
|
||||
self.presence = at;
|
||||
}
|
||||
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 stamp_all(&mut self, at: TimeStamp) {
|
||||
self.presence = at;
|
||||
self.exports.iter_mut().for_each(|slot| slot.timestamp = at);
|
||||
stamp_attributes(&mut self.attributes, &mut self.attributes_timestamp, at);
|
||||
}
|
||||
fn merge(&mut self, other: Self) {
|
||||
// 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;
|
||||
let len = self.exports.len().max(other.exports.len());
|
||||
self.exports.resize_with(len, ExportSlot::default);
|
||||
for (slot, incoming) in self.exports.iter_mut().zip(other.exports) {
|
||||
if incoming.timestamp > slot.timestamp {
|
||||
*slot = incoming;
|
||||
}
|
||||
}
|
||||
self.exports = newer;
|
||||
self.exports_timestamp = shape;
|
||||
self.attributes.merge(other.attributes);
|
||||
merge_attributes(&mut self.attributes, &mut self.attributes_timestamp, other.attributes, other.attributes_timestamp);
|
||||
self.presence = self.presence.max(other.presence);
|
||||
}
|
||||
}
|
||||
|
||||
impl Entity for ResourceEntry {
|
||||
impl Presence for ResourceEntry {
|
||||
fn presence(&self) -> TimeStamp {
|
||||
self.presence
|
||||
}
|
||||
fn set_presence(&mut self, timestamp: TimeStamp) {
|
||||
self.presence = timestamp;
|
||||
fn set_presence(&mut self, at: TimeStamp) {
|
||||
self.presence = at;
|
||||
}
|
||||
fn placeholder() -> Self {
|
||||
ResourceEntry::default()
|
||||
}
|
||||
fn stamp_all(&mut self, timestamp: TimeStamp) {
|
||||
self.presence = timestamp;
|
||||
self.hash_timestamp = timestamp;
|
||||
self.stamp_sources(timestamp);
|
||||
fn stamp_all(&mut self, at: TimeStamp) {
|
||||
self.presence = at;
|
||||
self.hash_timestamp = at;
|
||||
self.stamp_sources(at);
|
||||
}
|
||||
fn merge(&mut self, other: Self) {
|
||||
if other.hash_timestamp > self.hash_timestamp {
|
||||
@@ -595,31 +467,45 @@ impl Entity for ResourceEntry {
|
||||
}
|
||||
}
|
||||
|
||||
fn stamp_slot(slot: &mut InputSlot, timestamp: TimeStamp) {
|
||||
slot.timestamp = timestamp;
|
||||
slot.attributes.stamp(timestamp);
|
||||
fn stamp_slot(slot: &mut InputSlot, at: TimeStamp) {
|
||||
slot.timestamp = at;
|
||||
stamp_attributes(&mut slot.attributes, &mut slot.attributes_timestamp, at);
|
||||
}
|
||||
|
||||
/// 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);
|
||||
/// Writes the map whole at `at`: the floor deletes every other key without a tombstone per key.
|
||||
fn stamp_attributes(attributes: &mut Attributes, floor: &mut TimeStamp, at: TimeStamp) {
|
||||
attributes.retain(|_, value| !value.deleted);
|
||||
attributes.values_mut().for_each(|value| value.timestamp = at);
|
||||
*floor = at;
|
||||
}
|
||||
|
||||
/// Folds 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))
|
||||
/// Folds `other` in key by key. A key only one map holds is dead when the other map's floor is newer, since
|
||||
/// that map was written whole after it; an entry stamped exactly at a floor was written by that whole-map
|
||||
/// write and survives. Where both hold a key, the newer entry wins.
|
||||
fn merge_attributes(attributes: &mut Attributes, floor: &mut TimeStamp, other: Attributes, other_floor: TimeStamp) {
|
||||
attributes.retain(|_, value| value.timestamp >= other_floor);
|
||||
for (key, value) in other {
|
||||
match attributes.entry(key) {
|
||||
Entry::Occupied(entry) if value.timestamp > entry.get().timestamp => *entry.into_mut() = value,
|
||||
Entry::Vacant(entry) if value.timestamp >= *floor => {
|
||||
entry.insert(value);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
*floor = (*floor).max(other_floor);
|
||||
}
|
||||
|
||||
/// Folds an input list stamped `at` into the node's. The newer list decides the slot count, except that a
|
||||
/// slot written after that shape still exists, with the gap up to it filled by unset slots stamped by the
|
||||
/// shape. A slot both lists hold keeps its newer value, and its attributes fold key by key. A whole-list
|
||||
/// write and a per-slot write thus land the same in either order.
|
||||
fn merge_inputs(node: &mut Node, other: Vec<InputSlot>, at: TimeStamp) {
|
||||
let (mut newer, shape, older) = if at > node.inputs_timestamp {
|
||||
(other, at, std::mem::take(&mut node.inputs))
|
||||
} else {
|
||||
(std::mem::take(&mut node.inputs), node.inputs_timestamp, other)
|
||||
};
|
||||
// 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 {
|
||||
@@ -632,7 +518,7 @@ fn merge_inputs(node: &mut Node, other: Vec<InputSlot>, timestamp: TimeStamp) {
|
||||
slot.input = incoming.input;
|
||||
slot.timestamp = incoming.timestamp;
|
||||
}
|
||||
slot.attributes.merge(incoming.attributes);
|
||||
merge_attributes(&mut slot.attributes, &mut slot.attributes_timestamp, incoming.attributes, incoming.attributes_timestamp);
|
||||
}
|
||||
node.inputs = newer;
|
||||
node.inputs_timestamp = shape;
|
||||
@@ -640,16 +526,21 @@ fn merge_inputs(node: &mut Node, other: Vec<InputSlot>, timestamp: TimeStamp) {
|
||||
|
||||
/// The newest write the slot carries, its attributes included.
|
||||
fn slot_newest(slot: &InputSlot) -> TimeStamp {
|
||||
slot.timestamp.max(slot.attributes.newest())
|
||||
slot.attributes
|
||||
.values()
|
||||
.map(|value| value.timestamp)
|
||||
.fold(slot.timestamp.max(slot.attributes_timestamp), TimeStamp::max)
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
/// The slot at `index` for a write at `at`. A slot past the end comes into being when the write is newer
|
||||
/// than the list's shape, as in [`merge_inputs`], and is `None` when the shape is newer. For a fresh local
|
||||
/// edit the index is out of bounds.
|
||||
fn slot_for_write(node: &mut Node, index: usize, at: TimeStamp, mode: ApplyMode) -> Result<Option<&mut InputSlot>, CrdtError> {
|
||||
if index >= node.inputs.len() {
|
||||
if index >= MAX_INPUT_SLOTS || mode == ApplyMode::Strict {
|
||||
if index >= MAX_INPUT_SLOTS || mode == ApplyMode::Live {
|
||||
return Err(CrdtError::InputIndexOutOfBounds(index));
|
||||
}
|
||||
if mode != ApplyMode::Force && timestamp <= node.inputs_timestamp {
|
||||
if at <= node.inputs_timestamp {
|
||||
return Ok(None);
|
||||
}
|
||||
let shape = node.inputs_timestamp;
|
||||
@@ -663,17 +554,18 @@ fn content_mut<'a, K: Hash + Eq + Copy, T>(live: &'a mut HashMap<K, T>, dead: &'
|
||||
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) {
|
||||
/// Brings a removed entity back when its presence has grown past its removal. A placeholder stays dead
|
||||
/// whatever its presence.
|
||||
fn settle<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K) {
|
||||
if dead.get(&id).is_some_and(|mark| !mark.placeholder && mark.content.presence() > mark.at) {
|
||||
let mark = dead.remove(&id).expect("checked above");
|
||||
live.insert(id, mark.content);
|
||||
}
|
||||
}
|
||||
|
||||
/// Folds 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) {
|
||||
/// Folds `content` into whatever is held under `id`, or holds it as new. Content comes from an addition or
|
||||
/// a removal's snapshot, so it proves the entity was added and a placeholder holding it stops being one.
|
||||
fn fold<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, content: T) {
|
||||
if let Some(mark) = dead.get_mut(&id).filter(|mark| mark.placeholder) {
|
||||
// The placeholder holds only early writes: they land on the real content as if the addition came first.
|
||||
let early = std::mem::replace(&mut mark.content, content);
|
||||
@@ -684,78 +576,66 @@ fn merge_entity<K: Hash + Eq + Copy, T: Entity>(live: &mut HashMap<K, T>, dead:
|
||||
} else {
|
||||
live.insert(id, content);
|
||||
}
|
||||
revive_if_newer(live, dead, id);
|
||||
settle(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);
|
||||
/// An addition at `at`: every field of `content` is written at `at`, and the entity exists from then
|
||||
/// unless a newer removal holds it dead.
|
||||
fn add<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, mut content: T, at: TimeStamp) {
|
||||
content.stamp_all(at);
|
||||
fold(live, dead, id, content);
|
||||
}
|
||||
|
||||
/// A removal at `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);
|
||||
/// A removal at `at`: the entity is dead from then unless a newer addition or write holds it live. The
|
||||
/// snapshot folds in first, so a removal of an entity never seen still lands and its addition loses when
|
||||
/// it arrives.
|
||||
fn remove<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, snapshot: T, at: TimeStamp) {
|
||||
fold(live, dead, id, snapshot);
|
||||
if let Some(mark) = dead.get_mut(&id) {
|
||||
mark.timestamp = if force { timestamp } else { mark.timestamp.max(timestamp) };
|
||||
} else if live.get(&id).is_some_and(|content| force || timestamp > content.presence()) {
|
||||
mark.at = mark.at.max(at);
|
||||
} else if live.get(&id).is_some_and(|content| at > content.presence()) {
|
||||
let content = live.remove(&id).expect("checked above");
|
||||
dead.insert(
|
||||
id,
|
||||
Tombstone {
|
||||
content,
|
||||
timestamp,
|
||||
placeholder: false,
|
||||
},
|
||||
);
|
||||
dead.insert(id, Tombstone { content, at, 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>(
|
||||
/// A write at `at` to the entity under `id`, applied by `write` to its content wherever it sits. The
|
||||
/// write is evidence the entity exists at `at`, so it revives an older removal. A write to an entity
|
||||
/// never seen lands on a placeholder tombstone that stays dead until an addition folds into it, so ops
|
||||
/// land the same in any order and nothing is deferred. For a fresh local edit the entity is `missing()`.
|
||||
fn write<K: Hash + Eq + Copy, T: Presence>(
|
||||
live: &mut HashMap<K, T>,
|
||||
dead: &mut HashMap<K, Tombstone<T>>,
|
||||
id: K,
|
||||
timestamp: TimeStamp,
|
||||
at: TimeStamp,
|
||||
mode: ApplyMode,
|
||||
missing: impl FnOnce() -> CrdtError,
|
||||
f: impl FnOnce(&mut T) -> Result<(), CrdtError>,
|
||||
write: 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 {
|
||||
if mode == ApplyMode::Live {
|
||||
return Err(missing());
|
||||
}
|
||||
dead.insert(
|
||||
id,
|
||||
Tombstone {
|
||||
content: T::placeholder(),
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
at: TimeStamp::ORIGIN,
|
||||
placeholder: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
let content = content_mut(live, dead, id).expect("held above");
|
||||
if let Err(error) = f(content) {
|
||||
if let Err(error) = write(content) {
|
||||
// A rejected op changes nothing, so the placeholder made for it goes too.
|
||||
if unseen {
|
||||
dead.remove(&id);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
content.set_presence(content.presence().max(timestamp));
|
||||
if force && let Some(mark) = dead.remove(&id) {
|
||||
live.insert(id, mark.content);
|
||||
}
|
||||
revive_if_newer(live, dead, id);
|
||||
content.set_presence(content.presence().max(at));
|
||||
settle(live, dead, id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -763,43 +643,36 @@ fn write_entity<K: Hash + Eq + Copy, T: Entity>(
|
||||
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)),
|
||||
Some(&id) if mode == ApplyMode::Live => 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,
|
||||
)
|
||||
/// [`write()`] to a node; with a no-op `f`, records a reference to it.
|
||||
fn write_node(registry: &mut Registry, id: NodeId, at: TimeStamp, mode: ApplyMode, f: impl FnOnce(&mut Node) -> Result<(), CrdtError>) -> Result<(), CrdtError> {
|
||||
write(&mut registry.node_instances, &mut registry.removed_nodes, id, at, mode, || CrdtError::TargetNodeDoesNotExist(id), f)
|
||||
}
|
||||
|
||||
fn write_network(registry: &mut Registry, id: NetworkId, 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)
|
||||
fn write_network(registry: &mut Registry, id: NetworkId, at: TimeStamp, mode: ApplyMode, f: impl FnOnce(&mut Network) -> Result<(), CrdtError>) -> Result<(), CrdtError> {
|
||||
write(&mut registry.networks, &mut registry.removed_networks, id, at, mode, || CrdtError::NetworkDoesNotExist(id), f)
|
||||
}
|
||||
|
||||
/// [`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)) {
|
||||
/// Like [`write()`] for a resource, except that an entry never seen is created first, since single-field
|
||||
/// resource ops are upserts. Every other field starts at the origin, so a later addition fills them in.
|
||||
fn upsert_resource(registry: &mut Registry, id: ResourceId, at: TimeStamp, f: impl FnOnce(&mut ResourceEntry)) {
|
||||
if !registry.resources.contains_key(&id) && !registry.removed_resources.contains_key(&id) {
|
||||
registry.resources.insert(
|
||||
id,
|
||||
ResourceEntry {
|
||||
presence: timestamp,
|
||||
presence: at,
|
||||
..ResourceEntry::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
let entry = content_mut(&mut registry.resources, &mut registry.removed_resources, id).expect("held above");
|
||||
f(entry);
|
||||
entry.set_presence(entry.presence().max(timestamp));
|
||||
revive_if_newer(&mut registry.resources, &mut registry.removed_resources, id);
|
||||
entry.set_presence(entry.presence().max(at));
|
||||
settle(&mut registry.resources, &mut registry.removed_resources, id);
|
||||
}
|
||||
|
||||
/// Which of a [`Document`]'s two registries an apply targets: the working copy (retired state plus
|
||||
@@ -808,16 +681,15 @@ fn upsert_resource(registry: &mut Registry, id: ResourceId, timestamp: TimeStamp
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum RegistryTarget {
|
||||
Working,
|
||||
Retired,
|
||||
Snapshot,
|
||||
}
|
||||
|
||||
/// How [`Document::apply_op_with`] treats what it finds.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum ApplyMode {
|
||||
/// A fresh local edit: adding what exists or writing to what was never seen is an error.
|
||||
Strict,
|
||||
/// A fresh local edit: adding what exists, or writing to what was never seen, is an error, since a local
|
||||
/// edit cannot mean either.
|
||||
Live,
|
||||
/// An op from a peer or from persisted state: every arm is a timestamp comparison.
|
||||
Idempotent,
|
||||
/// 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::{
|
||||
ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ProtoNode, ROOT_NETWORK, Registry, ResourceHash, ResourceId, TimeStamp, Value, ValueError, from_value,
|
||||
to_value,
|
||||
AttributesWrite, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ProtoNode, ROOT_NETWORK, Registry, ResourceHash, ResourceId, TimeStamp, Value,
|
||||
ValueError, from_value, to_value,
|
||||
};
|
||||
|
||||
fn map_serialization_error(key: &str) -> impl FnOnce(ValueError) -> ConversionError + '_ {
|
||||
@@ -346,8 +346,8 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
|
||||
Network {
|
||||
presence: TimeStamp::ORIGIN,
|
||||
exports,
|
||||
exports_timestamp: TimeStamp::ORIGIN,
|
||||
attributes,
|
||||
attributes_timestamp: TimeStamp::ORIGIN,
|
||||
},
|
||||
);
|
||||
ctx.network_ids.insert(metadata_path.to_vec(), network_id);
|
||||
@@ -421,13 +421,13 @@ 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 {
|
||||
input: convert_input(input, parent_path, network_id, ctx.ids(metadata_path))?,
|
||||
timestamp,
|
||||
attributes: input_attrs,
|
||||
attributes_timestamp: timestamp,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -443,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::empty_at(timestamp);
|
||||
let mut attributes = crate::Attributes::new();
|
||||
attributes
|
||||
.set_if_not_default(node::CALL_ARGUMENT, &doc_node.call_argument, &concrete!(Context), timestamp)
|
||||
.map_err(map_serialization_error(node::CALL_ARGUMENT))?;
|
||||
@@ -461,12 +461,13 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
|
||||
|
||||
Ok(Node {
|
||||
presence: timestamp,
|
||||
network_timestamp: timestamp,
|
||||
added: timestamp,
|
||||
inputs_timestamp: timestamp,
|
||||
implementation,
|
||||
implementation_timestamp: timestamp,
|
||||
inputs,
|
||||
attributes,
|
||||
attributes_timestamp: timestamp,
|
||||
network: network_id,
|
||||
})
|
||||
}
|
||||
@@ -549,13 +550,6 @@ fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
|
||||
.map_err(map_serialization_error(node::ui::OUTPUT_NAMES))?;
|
||||
}
|
||||
|
||||
let output_descriptions = metadata.output_descriptions(metadata_path, runtime_node_id);
|
||||
if output_descriptions.iter().any(|description| !description.is_empty()) {
|
||||
attributes
|
||||
.set_serialized(node::ui::OUTPUT_DESCRIPTIONS, &output_descriptions, timestamp)
|
||||
.map_err(map_serialization_error(node::ui::OUTPUT_DESCRIPTIONS))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -838,8 +832,8 @@ impl<'m> ScopedConversion<'m> {
|
||||
Network {
|
||||
presence: TimeStamp::ORIGIN,
|
||||
exports,
|
||||
exports_timestamp: TimeStamp::ORIGIN,
|
||||
attributes,
|
||||
attributes_timestamp: TimeStamp::ORIGIN,
|
||||
},
|
||||
);
|
||||
Ok(())
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use crate::{CrdtError, Delta, RegistryDelta, ResourceHash, Rev, TimeStamp, Value};
|
||||
use crate::{AttributesWrite, CrdtError, Delta, RegistryDelta, ResourceHash, Rev, TimeStamp, Value};
|
||||
|
||||
/// Every mutator maintains the indexes, so the tips and named hashes are probes, not scans of a growing history.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -65,9 +65,6 @@ impl History {
|
||||
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) {
|
||||
@@ -90,61 +87,6 @@ impl History {
|
||||
self.deltas.iter()
|
||||
}
|
||||
|
||||
/// Absorb `incoming` (dedup by `Rev`) and canonically re-sort the whole combined history.
|
||||
///
|
||||
/// The sort is deterministic (topological, ties broken by `Rev`), so two peers that absorb the same
|
||||
/// delta set produce byte-identical history, not merely two different valid orderings. This is the
|
||||
/// history-convergence mechanism: arrival order is erased. Callers update the registry separately
|
||||
/// (LWW apply is commutative, so the registry converges regardless of order).
|
||||
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) {
|
||||
for delta in incoming {
|
||||
self.push(delta);
|
||||
}
|
||||
self.canonical_sort();
|
||||
}
|
||||
|
||||
/// Re-order `deltas` into the canonical topological order and rebuild the index: parents precede
|
||||
/// children, and among deltas whose parents are all emitted the lowest `Rev` goes first. O(V + E).
|
||||
fn canonical_sort(&mut self) {
|
||||
// Unsatisfied in-history parent count per delta, plus reverse edges to decrement as parents emit.
|
||||
let mut pending_parents: HashMap<Rev, usize> = HashMap::with_capacity(self.deltas.len());
|
||||
let mut children: HashMap<Rev, Vec<Rev>> = HashMap::new();
|
||||
for delta in &self.deltas {
|
||||
let in_history_parents = delta.all_parents().filter(|parent| self.index.contains_key(parent)).count();
|
||||
pending_parents.insert(delta.id, in_history_parents);
|
||||
for parent in delta.all_parents() {
|
||||
if self.index.contains_key(&parent) {
|
||||
children.entry(parent).or_default().push(delta.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Ready set as a min-heap on `Rev` (via `Reverse`) so ties resolve deterministically.
|
||||
let mut ready: std::collections::BinaryHeap<std::cmp::Reverse<Rev>> = pending_parents.iter().filter(|(_, count)| **count == 0).map(|(rev, _)| std::cmp::Reverse(*rev)).collect();
|
||||
|
||||
let mut order: Vec<Rev> = Vec::with_capacity(self.deltas.len());
|
||||
while let Some(std::cmp::Reverse(rev)) = ready.pop() {
|
||||
order.push(rev);
|
||||
for child in children.get(&rev).into_iter().flatten() {
|
||||
let count = pending_parents.get_mut(child).expect("child is in history");
|
||||
*count -= 1;
|
||||
if *count == 0 {
|
||||
ready.push(std::cmp::Reverse(*child));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// `order` is a permutation of the existing revs, so reorder `deltas` to match and rebuild the index.
|
||||
let mut by_rev: HashMap<Rev, Delta> = self.deltas.drain(..).map(|delta| (delta.id, delta)).collect();
|
||||
self.index.clear();
|
||||
for (position, rev) in order.iter().enumerate() {
|
||||
if let Some(delta) = by_rev.remove(rev) {
|
||||
self.index.insert(*rev, position);
|
||||
self.deltas.push(delta);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `roots` and everything reachable from them through all parent links. Unknown roots are skipped.
|
||||
pub(crate) fn ancestors(&self, roots: impl IntoIterator<Item = Rev>) -> HashSet<Rev> {
|
||||
let mut seen = HashSet::new();
|
||||
|
||||
@@ -7,6 +7,7 @@ pub mod document;
|
||||
pub mod history;
|
||||
pub mod ids;
|
||||
pub mod model;
|
||||
mod prior;
|
||||
pub mod registry;
|
||||
pub mod resources;
|
||||
pub mod session;
|
||||
@@ -25,6 +26,7 @@ pub use document::*;
|
||||
pub use history::History;
|
||||
pub use ids::*;
|
||||
pub use model::*;
|
||||
pub use prior::{NetworkField, NodeField, Prior};
|
||||
pub use registry::*;
|
||||
pub use resources::*;
|
||||
pub use session::*;
|
||||
|
||||
@@ -28,7 +28,6 @@ pub struct NodeMetadataEntry {
|
||||
/// returns an error if this length does not match the node's input count.
|
||||
pub input_metadata: Vec<InputMetadataEntry>,
|
||||
pub output_names: Vec<String>,
|
||||
pub output_descriptions: Vec<String>,
|
||||
}
|
||||
|
||||
/// Per-network metadata. Separate from `NodeMetadataEntry` since these are
|
||||
@@ -80,10 +79,6 @@ pub trait NodeMetadataSource {
|
||||
fn output_names(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Vec<String> {
|
||||
Vec::new()
|
||||
}
|
||||
/// Indexed like `output_names`, where a missing or empty entry is no description. Stored as one `ui::output_descriptions` attribute.
|
||||
fn output_descriptions(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Vec<String> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn input_name(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId, _input_index: usize) -> Option<&str> {
|
||||
None
|
||||
|
||||
@@ -4,23 +4,28 @@ 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).
|
||||
/// The latest addition or write, so a concurrent removal resolves by last-writer-wins rather than
|
||||
/// arrival order. See [`Registry::removed_nodes`](crate::Registry::removed_nodes).
|
||||
#[serde(default)]
|
||||
pub(crate) presence: TimeStamp,
|
||||
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) added: TimeStamp,
|
||||
/// When the input list last changed shape, so whole-list and per-slot writes resolve the same in either
|
||||
/// order: the list follows the newer write, and a slot both lists held keeps its newer value.
|
||||
#[serde(default)]
|
||||
pub(crate) inputs_timestamp: TimeStamp,
|
||||
pub(crate) implementation: Implementation,
|
||||
/// When the implementation was last written, so a swap resolves by last-writer-wins rather than by
|
||||
/// the order ops happen to arrive in. Absent from documents written before swaps were expressible.
|
||||
#[serde(default)]
|
||||
pub(crate) implementation_timestamp: TimeStamp,
|
||||
pub(crate) inputs: Vec<InputSlot>,
|
||||
/// 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,
|
||||
/// When `attributes` was last written whole; see [`Attributes`].
|
||||
#[serde(default)]
|
||||
pub(crate) attributes_timestamp: TimeStamp,
|
||||
pub(crate) network: NetworkId,
|
||||
}
|
||||
|
||||
impl Node {
|
||||
@@ -62,12 +67,13 @@ impl Node {
|
||||
pub fn new(network: NetworkId, implementation: Implementation, inputs: usize) -> Self {
|
||||
Self {
|
||||
presence: TimeStamp::ORIGIN,
|
||||
network_timestamp: TimeStamp::ORIGIN,
|
||||
added: TimeStamp::ORIGIN,
|
||||
inputs_timestamp: TimeStamp::ORIGIN,
|
||||
implementation,
|
||||
implementation_timestamp: TimeStamp::ORIGIN,
|
||||
inputs: vec![InputSlot::unset(TimeStamp::ORIGIN); inputs],
|
||||
attributes: Attributes::new(),
|
||||
attributes_timestamp: TimeStamp::ORIGIN,
|
||||
network,
|
||||
}
|
||||
}
|
||||
@@ -85,11 +91,14 @@ pub struct InputSlot {
|
||||
pub input: NodeInput,
|
||||
pub timestamp: TimeStamp,
|
||||
pub attributes: Attributes,
|
||||
/// When `attributes` was last written whole; see [`Attributes`].
|
||||
#[serde(default)]
|
||||
pub attributes_timestamp: TimeStamp,
|
||||
}
|
||||
|
||||
impl InputSlot {
|
||||
/// A slot holding nothing, stamped `timestamp`.
|
||||
pub fn unset(timestamp: TimeStamp) -> Self {
|
||||
/// A slot holding nothing, stamped `at`.
|
||||
pub fn unset(at: TimeStamp) -> Self {
|
||||
// `to_runtime` reads this back as a `TaggedValue`, whose unit `None` variant encodes as this string.
|
||||
// Pinned by `unset_input_slot_deserializes_as_tagged_value_none`.
|
||||
Self {
|
||||
@@ -97,8 +106,9 @@ impl InputSlot {
|
||||
value: Value::Str("None".to_string()),
|
||||
exposed: false,
|
||||
},
|
||||
timestamp,
|
||||
attributes: Attributes::empty_at(timestamp),
|
||||
timestamp: at,
|
||||
attributes: Attributes::new(),
|
||||
attributes_timestamp: at,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -136,12 +146,12 @@ pub struct Network {
|
||||
#[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,
|
||||
/// When `attributes` was last written whole; see [`Attributes`].
|
||||
#[serde(default)]
|
||||
pub attributes_timestamp: TimeStamp,
|
||||
}
|
||||
|
||||
impl Network {
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
use crate::{
|
||||
AttributeValue, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, TimeStamp,
|
||||
Tombstone,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::hash::Hash;
|
||||
|
||||
/// What a slot held before a delta wrote it, with its own stamps. Undo puts these back as they were, bypassing
|
||||
/// LWW, so the registry is again exactly what folding history up to the delta's parent gives. Never sent or
|
||||
/// applied as an op.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum Prior {
|
||||
/// The whole entity, live or tombstoned. `None, None` means it didn't exist, so undoing an addition leaves no
|
||||
/// tombstone behind.
|
||||
Node {
|
||||
id: NodeId,
|
||||
live: Option<Node>,
|
||||
removed: Option<Tombstone<Node>>,
|
||||
},
|
||||
Network {
|
||||
id: NetworkId,
|
||||
live: Option<Network>,
|
||||
removed: Option<Tombstone<Network>>,
|
||||
},
|
||||
Resource {
|
||||
id: ResourceId,
|
||||
live: Option<ResourceEntry>,
|
||||
removed: Option<Tombstone<ResourceEntry>>,
|
||||
},
|
||||
/// One field of a live node, and the node's presence, which every write moves.
|
||||
NodeField {
|
||||
id: NodeId,
|
||||
presence: TimeStamp,
|
||||
field: NodeField,
|
||||
},
|
||||
/// One field of a live network, and its presence.
|
||||
NetworkField {
|
||||
id: NetworkId,
|
||||
presence: TimeStamp,
|
||||
field: NetworkField,
|
||||
},
|
||||
DocumentAttribute {
|
||||
key: String,
|
||||
previous: Option<AttributeValue>,
|
||||
},
|
||||
PeerUser {
|
||||
peer: PeerId,
|
||||
previous: Option<PeerRegistration>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum NodeField {
|
||||
/// Only the presence moved, by a reference from another entity's op.
|
||||
Presence,
|
||||
Attribute {
|
||||
key: String,
|
||||
previous: Option<AttributeValue>,
|
||||
},
|
||||
Input {
|
||||
index: u32,
|
||||
previous: InputSlot,
|
||||
},
|
||||
InputAttribute {
|
||||
index: u32,
|
||||
key: String,
|
||||
previous: Option<AttributeValue>,
|
||||
},
|
||||
Inputs {
|
||||
previous: Vec<InputSlot>,
|
||||
inputs_timestamp: TimeStamp,
|
||||
},
|
||||
Implementation {
|
||||
previous: Implementation,
|
||||
implementation_timestamp: TimeStamp,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum NetworkField {
|
||||
/// Only the presence moved, by a node added to or implemented by it.
|
||||
Presence,
|
||||
Attribute {
|
||||
key: String,
|
||||
previous: Option<AttributeValue>,
|
||||
},
|
||||
Exports {
|
||||
previous: Vec<ExportSlot>,
|
||||
},
|
||||
}
|
||||
|
||||
/// What `op` is about to write in `registry`, in write order. Taken before the op applies.
|
||||
pub(crate) fn capture(registry: &Registry, op: &RegistryDelta) -> Vec<Prior> {
|
||||
let mut priors = Vec::new();
|
||||
let node_input = |input: &NodeInput| match input {
|
||||
NodeInput::Node { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
};
|
||||
match op {
|
||||
RegistryDelta::AddNode { id, node } => {
|
||||
priors.push(network_field(registry, node.network, |_| NetworkField::Presence));
|
||||
priors.push(whole_node(registry, *id));
|
||||
}
|
||||
RegistryDelta::RemoveNode { id, .. } => priors.push(whole_node(registry, *id)),
|
||||
RegistryDelta::SetNodeInputs { id, inputs } => {
|
||||
priors.push(node_field(registry, *id, |node| NodeField::Inputs {
|
||||
previous: node.inputs.clone(),
|
||||
inputs_timestamp: node.inputs_timestamp,
|
||||
}));
|
||||
priors.extend(
|
||||
inputs
|
||||
.iter()
|
||||
.filter_map(|slot| node_input(&slot.input))
|
||||
.map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)),
|
||||
);
|
||||
}
|
||||
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
|
||||
priors.push(node_field(registry, *id, |node| {
|
||||
input_field(node, *index, |slot| NodeField::Input {
|
||||
index: *index,
|
||||
previous: slot.clone(),
|
||||
})
|
||||
}));
|
||||
priors.extend(node_input(new_input).map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)));
|
||||
}
|
||||
RegistryDelta::SetNodeImplementation { id, implementation } => {
|
||||
if let Implementation::Network(network) = implementation {
|
||||
priors.push(network_field(registry, *network, |_| NetworkField::Presence));
|
||||
}
|
||||
priors.push(node_field(registry, *id, |node| NodeField::Implementation {
|
||||
previous: node.implementation.clone(),
|
||||
implementation_timestamp: node.implementation_timestamp,
|
||||
}));
|
||||
}
|
||||
RegistryDelta::ChangeNodeAttribute { id, delta } => priors.push(node_field(registry, *id, |node| NodeField::Attribute {
|
||||
key: delta.key.clone(),
|
||||
previous: node.attributes.get(&delta.key).cloned(),
|
||||
})),
|
||||
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => priors.push(node_field(registry, *id, |node| {
|
||||
input_field(node, *index, |slot| NodeField::InputAttribute {
|
||||
index: *index,
|
||||
key: delta.key.clone(),
|
||||
previous: slot.attributes.get(&delta.key).cloned(),
|
||||
})
|
||||
})),
|
||||
RegistryDelta::SetNetworkExport { id, export, .. } => {
|
||||
priors.push(network_field(registry, *id, |network| NetworkField::Exports { previous: network.exports.clone() }));
|
||||
priors.extend(export.as_ref().and_then(node_input).map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)));
|
||||
}
|
||||
RegistryDelta::AddNetwork { id, .. } | RegistryDelta::RemoveNetwork { id, .. } => priors.push(whole_network(registry, *id)),
|
||||
RegistryDelta::ChangeNetworkAttribute { id, delta } => {
|
||||
priors.push(network_field(registry, *id, |network| NetworkField::Attribute {
|
||||
key: delta.key.clone(),
|
||||
previous: network.attributes.get(&delta.key).cloned(),
|
||||
}));
|
||||
}
|
||||
RegistryDelta::AddResource { id, .. }
|
||||
| RegistryDelta::RemoveResource { id, .. }
|
||||
| RegistryDelta::SetResourceHash { id, .. }
|
||||
| RegistryDelta::AddSource { id, .. }
|
||||
| RegistryDelta::RemoveSource { id, .. } => priors.push(Prior::Resource {
|
||||
id: *id,
|
||||
live: registry.resources.get(id).cloned(),
|
||||
removed: registry.removed_resources.get(id).cloned(),
|
||||
}),
|
||||
RegistryDelta::RegisterPeer { peer, .. } => priors.push(Prior::PeerUser {
|
||||
peer: *peer,
|
||||
previous: registry.peer_users.get(peer).copied(),
|
||||
}),
|
||||
RegistryDelta::ChangeDocumentAttribute { delta } => priors.push(Prior::DocumentAttribute {
|
||||
key: delta.key.clone(),
|
||||
previous: registry.attributes.get(&delta.key).cloned(),
|
||||
}),
|
||||
RegistryDelta::Merge { .. } | RegistryDelta::EndTransaction | RegistryDelta::Other(_) => {}
|
||||
}
|
||||
priors
|
||||
}
|
||||
|
||||
/// Puts back what `priors` recorded, newest write first.
|
||||
pub(crate) fn restore(registry: &mut Registry, priors: &[Prior]) {
|
||||
for prior in priors.iter().rev() {
|
||||
match prior {
|
||||
Prior::Node { id, live, removed } => put_whole(&mut registry.node_instances, &mut registry.removed_nodes, *id, live.as_ref(), removed.as_ref()),
|
||||
Prior::Network { id, live, removed } => put_whole(&mut registry.networks, &mut registry.removed_networks, *id, live.as_ref(), removed.as_ref()),
|
||||
Prior::Resource { id, live, removed } => put_whole(&mut registry.resources, &mut registry.removed_resources, *id, live.as_ref(), removed.as_ref()),
|
||||
Prior::NodeField { id, presence, field } => {
|
||||
let Some(node) = registry.node_instances.get_mut(id) else {
|
||||
debug_assert!(false, "a field prior is taken from a live node, which the later priors put back");
|
||||
continue;
|
||||
};
|
||||
node.presence = *presence;
|
||||
match field {
|
||||
NodeField::Presence => {}
|
||||
NodeField::Attribute { key, previous } => put_attribute(&mut node.attributes, key, previous.as_ref()),
|
||||
NodeField::Input { index, previous } => {
|
||||
if let Some(slot) = node.inputs.get_mut(*index as usize) {
|
||||
*slot = previous.clone();
|
||||
}
|
||||
}
|
||||
NodeField::InputAttribute { index, key, previous } => {
|
||||
if let Some(slot) = node.inputs.get_mut(*index as usize) {
|
||||
put_attribute(&mut slot.attributes, key, previous.as_ref());
|
||||
}
|
||||
}
|
||||
NodeField::Inputs { previous, inputs_timestamp } => {
|
||||
node.inputs = previous.clone();
|
||||
node.inputs_timestamp = *inputs_timestamp;
|
||||
}
|
||||
NodeField::Implementation { previous, implementation_timestamp } => {
|
||||
node.implementation = previous.clone();
|
||||
node.implementation_timestamp = *implementation_timestamp;
|
||||
}
|
||||
}
|
||||
}
|
||||
Prior::NetworkField { id, presence, field } => {
|
||||
let Some(network) = registry.networks.get_mut(id) else {
|
||||
debug_assert!(false, "a field prior is taken from a live network, which the later priors put back");
|
||||
continue;
|
||||
};
|
||||
network.presence = *presence;
|
||||
match field {
|
||||
NetworkField::Presence => {}
|
||||
NetworkField::Attribute { key, previous } => put_attribute(&mut network.attributes, key, previous.as_ref()),
|
||||
NetworkField::Exports { previous } => network.exports = previous.clone(),
|
||||
}
|
||||
}
|
||||
Prior::DocumentAttribute { key, previous } => put_attribute(&mut registry.attributes, key, previous.as_ref()),
|
||||
Prior::PeerUser { peer, previous } => match previous {
|
||||
Some(registration) => _ = registry.peer_users.insert(*peer, *registration),
|
||||
None => _ = registry.peer_users.remove(peer),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn whole_node(registry: &Registry, id: NodeId) -> Prior {
|
||||
Prior::Node {
|
||||
id,
|
||||
live: registry.node_instances.get(&id).cloned(),
|
||||
removed: registry.removed_nodes.get(&id).cloned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn whole_network(registry: &Registry, id: NetworkId) -> Prior {
|
||||
Prior::Network {
|
||||
id,
|
||||
live: registry.networks.get(&id).cloned(),
|
||||
removed: registry.removed_networks.get(&id).cloned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// One field of a live node; anything else, a write that lands on a tombstone or a placeholder, records the
|
||||
/// whole entity.
|
||||
fn node_field(registry: &Registry, id: NodeId, field: impl FnOnce(&Node) -> NodeField) -> Prior {
|
||||
match registry.node_instances.get(&id) {
|
||||
Some(node) => Prior::NodeField {
|
||||
id,
|
||||
presence: node.presence,
|
||||
field: field(node),
|
||||
},
|
||||
None => whole_node(registry, id),
|
||||
}
|
||||
}
|
||||
|
||||
fn network_field(registry: &Registry, id: NetworkId, field: impl FnOnce(&Network) -> NetworkField) -> Prior {
|
||||
match registry.networks.get(&id) {
|
||||
Some(network) => Prior::NetworkField {
|
||||
id,
|
||||
presence: network.presence,
|
||||
field: field(network),
|
||||
},
|
||||
None => whole_network(registry, id),
|
||||
}
|
||||
}
|
||||
|
||||
/// A write to one slot, or to the whole list when the slot doesn't exist yet, since writing past the end grows it.
|
||||
fn input_field(node: &Node, index: u32, field: impl FnOnce(&InputSlot) -> NodeField) -> NodeField {
|
||||
match node.inputs.get(index as usize) {
|
||||
Some(slot) => field(slot),
|
||||
None => NodeField::Inputs {
|
||||
previous: node.inputs.clone(),
|
||||
inputs_timestamp: node.inputs_timestamp,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn put_whole<K: Hash + Eq + Copy, T: Clone>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, was_live: Option<&T>, was_removed: Option<&Tombstone<T>>) {
|
||||
match was_live {
|
||||
Some(content) => _ = live.insert(id, content.clone()),
|
||||
None => _ = live.remove(&id),
|
||||
}
|
||||
match was_removed {
|
||||
Some(mark) => _ = dead.insert(id, mark.clone()),
|
||||
None => _ = dead.remove(&id),
|
||||
}
|
||||
}
|
||||
|
||||
fn put_attribute(attributes: &mut crate::Attributes, key: &str, previous: Option<&AttributeValue>) {
|
||||
match previous {
|
||||
Some(value) => _ = attributes.insert(key.to_string(), value.clone()),
|
||||
None => _ = attributes.remove(key),
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,12 @@ use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceEntry,
|
||||
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.
|
||||
/// The live document: what exists and what it holds.
|
||||
///
|
||||
/// Every field is last-writer-wins on a timestamp, including whether an entity exists, so the registry
|
||||
/// depends on the set of ops applied and not their order. A removed entity keeps a tombstone stamped with
|
||||
/// the removal: an op stamped earlier is dropped in either arrival order, and one stamped later revives the
|
||||
/// entity from it. The live maps hold only what exists.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Registry {
|
||||
pub node_instances: HashMap<NodeId, Node>,
|
||||
@@ -12,7 +15,9 @@ pub struct Registry {
|
||||
/// Content-addressable resources (images, fonts, eventually proto-node declarations) referenced
|
||||
/// by `ResourceId`. See [`ResourceStore`].
|
||||
pub resources: ResourceStore,
|
||||
/// Which person each device is, from `RegistryDelta::RegisterPeer`, so undo and authorship scope by person.
|
||||
/// Which person each device is, registered via `RegistryDelta::RegisterPeer` by a device's first
|
||||
/// contribution and whenever its user changes. Lets undo and history authorship scope by person across
|
||||
/// the peer ids one person accumulates.
|
||||
pub peer_users: HashMap<PeerId, PeerRegistration>,
|
||||
pub attributes: Attributes,
|
||||
/// Tombstones of removed nodes, so an op on one is ordered against its removal whichever arrives first.
|
||||
@@ -26,44 +31,39 @@ pub struct Registry {
|
||||
pub removed_resources: HashMap<ResourceId, Tombstone<ResourceEntry>>,
|
||||
}
|
||||
|
||||
/// A device's registration to a person, and when it was made.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PeerRegistration {
|
||||
pub user: UserId,
|
||||
pub timestamp: TimeStamp,
|
||||
pub at: TimeStamp,
|
||||
}
|
||||
|
||||
/// A removed entity's content, for reviving it, and its removal stamp.
|
||||
/// A removed entity: its content, for reviving it, and when it was removed, for ordering later-arriving
|
||||
/// ops against the removal.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Tombstone<T> {
|
||||
pub content: T,
|
||||
pub timestamp: TimeStamp,
|
||||
/// Nothing has added the entity yet: it stays dead until an addition folds in, the content holding writes that came first.
|
||||
pub at: TimeStamp,
|
||||
/// Nothing has added the entity yet, so it stays dead until an addition folds in; the content only holds
|
||||
/// writes that arrived ahead of it. See [`Registry::removed_nodes`].
|
||||
#[serde(default)]
|
||||
pub placeholder: bool,
|
||||
}
|
||||
|
||||
impl Registry {
|
||||
/// The node under `id`, live or as removed, for a reference to a node the runtime cannot hold.
|
||||
/// The node under `id`, live or as it was when removed. For a reference to a node the runtime cannot
|
||||
/// hold, which still needs the id the node had there.
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub(crate) fn node_or_removed(&self, id: NodeId) -> Option<&Node> {
|
||||
self.node_instances.get(&id).or_else(|| self.removed_nodes.get(&id).map(|mark| &mark.content))
|
||||
}
|
||||
|
||||
/// The network under `id`, live or as it was when removed.
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub(crate) fn network_or_removed(&self, id: NetworkId) -> Option<&Network> {
|
||||
self.networks.get(&id).or_else(|| self.removed_networks.get(&id).map(|mark| &mark.content))
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -133,10 +133,10 @@ impl Registry {
|
||||
}
|
||||
|
||||
pub(crate) fn attributes_value_equal(a: &Attributes, b: &Attributes) -> bool {
|
||||
if a.live().count() != b.live().count() {
|
||||
if crate::attributes::live(a).count() != crate::attributes::live(b).count() {
|
||||
return false;
|
||||
}
|
||||
a.live().all(|(key, value)| b.get(key).is_some_and(|other| !other.deleted && value.value == other.value))
|
||||
crate::attributes::live(a).all(|(key, value)| b.get(key).is_some_and(|other| !other.deleted && value.value == other.value))
|
||||
}
|
||||
|
||||
/// Value-level resource comparison: same resolved hashes and same source chains (keyed by
|
||||
@@ -154,86 +154,48 @@ pub(crate) fn resources_value_equal(a: &ResourceStore, b: &ResourceStore) -> boo
|
||||
})
|
||||
}
|
||||
|
||||
/// Stable identity for any timestamp in a `Registry`, tombstoned content and existence stamps included. Used by
|
||||
/// `order_consistent`.
|
||||
/// Stable identity for any timestamped slot in a `Registry`. 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),
|
||||
Resource(ResourceId, &'static str),
|
||||
ResourceHash(ResourceId),
|
||||
ResourceSource(ResourceId, SourceKey),
|
||||
Document(&'static str),
|
||||
PeerRegistration(PeerId),
|
||||
}
|
||||
|
||||
fn collect_timestamps(registry: &Registry) -> HashMap<TimestampKey, TimeStamp> {
|
||||
let mut out = HashMap::new();
|
||||
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 (node_id, node) in ®istry.node_instances {
|
||||
for (i, slot) in node.inputs.iter().enumerate() {
|
||||
out.insert(TimestampKey::NodeInput(id, i), slot.timestamp);
|
||||
out.insert(TimestampKey::NodeInputFloor(id, i), slot.attributes.floor());
|
||||
out.insert(TimestampKey::NodeInput(*node_id, i), slot.timestamp);
|
||||
for (key, value) in &slot.attributes {
|
||||
out.insert(TimestampKey::NodeInputAttribute(id, i, key.clone()), value.timestamp);
|
||||
out.insert(TimestampKey::NodeInputAttribute(*node_id, i, key.clone()), value.timestamp);
|
||||
}
|
||||
}
|
||||
for (key, value) in &node.attributes {
|
||||
out.insert(TimestampKey::NodeAttribute(id, key.clone()), value.timestamp);
|
||||
out.insert(TimestampKey::NodeAttribute(*node_id, key.clone()), value.timestamp);
|
||||
}
|
||||
}
|
||||
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 (network_id, network) in ®istry.networks {
|
||||
for (i, slot) in network.exports.iter().enumerate() {
|
||||
out.insert(TimestampKey::NetworkExport(id, i), slot.timestamp);
|
||||
out.insert(TimestampKey::NetworkExport(*network_id, i), slot.timestamp);
|
||||
}
|
||||
for (key, value) in &network.attributes {
|
||||
out.insert(TimestampKey::NetworkAttribute(id, key.clone()), value.timestamp);
|
||||
out.insert(TimestampKey::NetworkAttribute(*network_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);
|
||||
}
|
||||
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 (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);
|
||||
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,7 +18,8 @@ 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.
|
||||
/// A removed source stays as a stamped tombstone, so an older addition loses in either arrival order;
|
||||
/// readers see it as absent.
|
||||
#[serde(default)]
|
||||
pub deleted: bool,
|
||||
}
|
||||
@@ -44,7 +45,8 @@ pub struct ResourceEntry {
|
||||
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.
|
||||
/// When `sources` was last written whole, by an addition of the entry. A key the chain does not hold is
|
||||
/// deleted as of then, as with [`Attributes`](crate::Attributes).
|
||||
pub sources_timestamp: TimeStamp,
|
||||
pub hash: Option<ResourceHash>,
|
||||
pub hash_timestamp: TimeStamp,
|
||||
@@ -135,7 +137,7 @@ impl ResourceEntry {
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
fn decided(&self, key: &SourceKey) -> TimeStamp {
|
||||
self.find(key).map_or(self.sources_timestamp, |index| self.sources[index].1.timestamp)
|
||||
}
|
||||
|
||||
@@ -146,14 +148,15 @@ impl ResourceEntry {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
/// Writes the chain whole at `at`: the floor deletes every other key without a tombstone per key.
|
||||
pub(crate) fn stamp_sources(&mut self, at: TimeStamp) {
|
||||
self.sources.retain(|(_, value)| !value.deleted);
|
||||
self.sources.iter_mut().for_each(|(_, value)| value.timestamp = timestamp);
|
||||
self.sources_timestamp = timestamp;
|
||||
self.sources.iter_mut().for_each(|(_, value)| value.timestamp = at);
|
||||
self.sources_timestamp = at;
|
||||
}
|
||||
|
||||
/// Folds another chain in key by key, as attribute maps merge.
|
||||
/// Folds another chain in key by key, the way attribute maps merge: a key only one chain holds is
|
||||
/// dead when the other chain's floor is newer than it, and the newer entry wins where both hold a key.
|
||||
pub(crate) fn merge_sources(&mut self, other: Vec<(SourceKey, SourceValue)>, other_floor: TimeStamp) {
|
||||
self.sources.retain(|(_, value)| value.timestamp >= other_floor);
|
||||
for (key, value) in other {
|
||||
@@ -166,38 +169,29 @@ impl ResourceEntry {
|
||||
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.
|
||||
/// Insert or LWW-overwrite the entry at `key`. A re-set at an existing key wins only if `value`'s
|
||||
/// timestamp is strictly newer; a fresh key is inserted in sorted position.
|
||||
pub fn set_source(&mut self, key: SourceKey, value: SourceValue) {
|
||||
if value.timestamp > self.deciding_timestamp(&key) {
|
||||
if value.timestamp > self.decided(&key) {
|
||||
self.put(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
/// Like [`set_source`](Self::set_source) but assigns unconditionally (silent-zone rewind, or building an entry).
|
||||
/// Like [`set_source`](Self::set_source) but assigns unconditionally, for building an entry.
|
||||
pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) {
|
||||
self.put(key, value);
|
||||
}
|
||||
|
||||
/// Remove the source at `key` if `timestamp` is newer than what decides it, leaving a tombstone. Returns whether it landed.
|
||||
/// Remove the source at `key` if what decides it is strictly older than `timestamp` (LWW), leaving a
|
||||
/// tombstone. Returns whether the removal landed.
|
||||
pub fn remove_source(&mut self, key: &SourceKey, timestamp: TimeStamp) -> bool {
|
||||
if timestamp <= self.deciding_timestamp(key) {
|
||||
if timestamp <= self.decided(key) {
|
||||
return false;
|
||||
}
|
||||
self.put(*key, SourceValue::deleted(timestamp));
|
||||
true
|
||||
}
|
||||
|
||||
/// Like [`remove_source`](Self::remove_source) but removes unconditionally (silent-zone rewind).
|
||||
pub fn force_remove_source(&mut self, key: &SourceKey) -> bool {
|
||||
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)) {
|
||||
Ok(index) => {
|
||||
self.sources.remove(index);
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
|
||||
@@ -29,12 +29,14 @@ impl Session {
|
||||
Self::with_peer(PeerId(core_types::uuid::generate_uuid()))
|
||||
}
|
||||
|
||||
/// A session for `peer` standing for itself as a person, for tests and tools without a stored identity.
|
||||
/// A session for `peer` standing for itself as a person. For tests and tools without a stored identity;
|
||||
/// a working copy wants [`with_identity`](Self::with_identity).
|
||||
pub fn with_peer(peer: PeerId) -> Self {
|
||||
Self::with_identity(peer, UserId(peer.0))
|
||||
}
|
||||
|
||||
/// A session for device `peer` used by person `user`, whom its registration records.
|
||||
/// A session for device `peer` used by person `user`. The user is what the peer's registration records,
|
||||
/// and what undo and history authorship scope by.
|
||||
pub fn with_identity(peer: PeerId, user: UserId) -> Self {
|
||||
Self {
|
||||
document: Document::empty(peer, user),
|
||||
@@ -50,11 +52,18 @@ impl Session {
|
||||
self.document.user
|
||||
}
|
||||
|
||||
/// The person a peer is registered to, if its registration has landed here.
|
||||
pub fn user_of(&self, peer: PeerId) -> Option<UserId> {
|
||||
let registered = || self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user);
|
||||
(peer == self.document.peer).then_some(self.document.user).or_else(registered)
|
||||
}
|
||||
|
||||
/// Whether `peer` is this person: this device, or another registered to the same user. Undo in a
|
||||
/// session scopes by this, so a fresh copy of a document still undoes what its user did from another.
|
||||
pub fn is_mine(&self, peer: PeerId) -> bool {
|
||||
self.user_of(peer) == Some(self.document.user)
|
||||
}
|
||||
|
||||
pub fn registry(&self) -> &Registry {
|
||||
&self.document.working_registry
|
||||
}
|
||||
@@ -146,7 +155,7 @@ impl Session {
|
||||
/// `PeerId → UserId` mapping is established (and, under causal delivery, observed by other peers)
|
||||
/// before any of its edits. A no-op batch doesn't register, since registration rides a real edit.
|
||||
pub(crate) fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
// A batch is staged whole or not at all.
|
||||
// A batch is staged whole or not at all: a refused op takes back the ones before it, which reached nothing yet.
|
||||
let mut pending: Vec<RegistryDelta> = ops.into_iter().collect();
|
||||
if pending.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
@@ -157,7 +166,7 @@ impl Session {
|
||||
pending.insert(0, RegistryDelta::RegisterPeer { peer, user });
|
||||
}
|
||||
|
||||
// A reused sequence would fall under the retired marks, so a batch running past the end is refused.
|
||||
// Reusing a sequence would let retirement marks drop the new op, so a batch that would run past the end is refused whole.
|
||||
if self.document.last_hot_sequence.0.checked_add(pending.len() as u64).is_none() {
|
||||
return Err(CrdtError::SequencesExhausted);
|
||||
}
|
||||
@@ -171,7 +180,7 @@ impl Session {
|
||||
timestamp: self.document.clock.tick(),
|
||||
sequence,
|
||||
};
|
||||
if let Err(error) = self.document.stage_hot_op(hot_op.clone(), ApplyMode::Strict) {
|
||||
if let Err(error) = self.document.apply_hot_op(hot_op.clone(), ApplyMode::Live) {
|
||||
// The run continues where it was, so no sequence goes unused.
|
||||
self.document.last_hot_sequence = sequence_before;
|
||||
if !staged.is_empty() {
|
||||
@@ -190,8 +199,10 @@ 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, 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.
|
||||
/// Operates on the *retired snapshot*: each `reverse` is captured from it and the forward op applied to it, so
|
||||
/// the reverse holds the true pre-op state rather than the hot-polluted working state. The
|
||||
/// working registry already reflects these ops (they were staged as hot ops before retirement, or
|
||||
/// equal the snapshot when there are none), so it is left untouched.
|
||||
///
|
||||
/// `idempotent`: pass `true` when the snapshot already reflects the op (retirement of an already-
|
||||
/// applied hot op) so duplicate structural inserts no-op rather than error.
|
||||
@@ -199,10 +210,11 @@ impl Session {
|
||||
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.
|
||||
/// [`commit_ops`](Self::commit_ops) for ops authored elsewhere, paired with the timestamp they were
|
||||
/// authored at (`None` to mint one). The delta's timestamp is what the registry resolves LWW on, so
|
||||
/// retirement passes the op's own.
|
||||
fn commit_ops_authored_at(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Option<TimeStamp>)>, idempotent: bool) -> Result<Vec<Rev>, CrdtError> {
|
||||
let target = RegistryTarget::Retired;
|
||||
let target = RegistryTarget::Snapshot;
|
||||
let ops = ops.into_iter();
|
||||
let mut produced = Vec::with_capacity(ops.size_hint().0);
|
||||
|
||||
@@ -214,7 +226,7 @@ impl Session {
|
||||
self.document.redo_stack.clear();
|
||||
}
|
||||
|
||||
let reverse = self.document.compute_reverse_delta(target, &op)?;
|
||||
let reverse = crate::prior::capture(self.document.registry_ref(target), &op);
|
||||
let timestamp = authored_at.unwrap_or_else(|| self.document.clock.tick());
|
||||
let parent = self.document.head;
|
||||
let author = timestamp.peer;
|
||||
@@ -228,7 +240,7 @@ impl Session {
|
||||
{
|
||||
return Err(CrdtError::NotFoundInHistory(parent));
|
||||
}
|
||||
let mode = if idempotent { ApplyMode::Idempotent } else { ApplyMode::Strict };
|
||||
let mode = if idempotent { ApplyMode::Idempotent } else { ApplyMode::Live };
|
||||
self.document.apply_op_with(target, delta.kind.clone(), delta.timestamp, mode)?;
|
||||
self.document.history.push(delta);
|
||||
self.document.head = Some(rev);
|
||||
@@ -282,14 +294,21 @@ impl Session {
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
/// Which hot ops are done with, for a peer catching up and for persisting. See [`RetiredMarks`].
|
||||
pub fn retired_marks(&self) -> &RetiredMarks {
|
||||
&self.document.retired
|
||||
/// Apply a hot op from another peer. Idempotent, and a no-op for one history already covers: a late
|
||||
/// delivery must not put a retired op back in the hot log.
|
||||
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
|
||||
self.document.replay_hot_op(hot_op)
|
||||
}
|
||||
|
||||
/// Take on a peer's marks, or this peer's persisted ones, dropping the hot ops they cover.
|
||||
pub fn absorb_retired_marks(&mut self, remote: &RetiredMarks) {
|
||||
self.document.absorb_retired_marks(remote);
|
||||
/// Which hot ops are done with, for a peer catching up and for persisting. See [`SettledHotOps`].
|
||||
pub fn settled_marks(&self) -> &SettledHotOps {
|
||||
&self.document.settled
|
||||
}
|
||||
|
||||
/// Take on a peer's marks, or this peer's persisted ones: whatever they cover that the hot log still holds is
|
||||
/// dropped, and the working registry re-derived without it.
|
||||
pub fn absorb_settled_marks(&mut self, remote: &SettledHotOps) {
|
||||
self.document.absorb_settled(remote);
|
||||
}
|
||||
|
||||
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
|
||||
@@ -298,40 +317,11 @@ impl Session {
|
||||
self.document.replay_hot_op(hot_op)
|
||||
}
|
||||
|
||||
/// Integrate `incoming` retired deltas from another branch and emit a [`RegistryDelta::Merge`]
|
||||
/// joining the resulting tips, returning the new merge `Rev` (or `None` if `incoming` adds nothing).
|
||||
/// Applies each incoming op to the registry, then hands the set to [`History::merge`]. Incoming
|
||||
/// deltas must arrive in causal order.
|
||||
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) -> Result<Option<Rev>, CrdtError> {
|
||||
let mut absorbed: Vec<Delta> = Vec::new();
|
||||
for delta in incoming {
|
||||
if self.document.history.contains(delta.id) {
|
||||
continue;
|
||||
}
|
||||
self.document.apply_op_idempotent(delta.kind.clone(), delta.timestamp)?;
|
||||
absorbed.push(delta);
|
||||
}
|
||||
if absorbed.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
self.document.history.merge(absorbed);
|
||||
let tips = self.document.history.tips();
|
||||
let timestamp = self.document.clock.tick();
|
||||
let merge = Delta::merge(tips, self.document.peer, timestamp);
|
||||
let merge_rev = merge.id;
|
||||
// The merge's parents are the current tips, so it sorts last: `push` preserves the canonical
|
||||
// order without re-sorting the whole history.
|
||||
self.document.history.push(merge);
|
||||
self.document.head = Some(merge_rev);
|
||||
|
||||
// Merge runs with an empty hot log; keep the retired snapshot in step with the working registry.
|
||||
self.document.retired_snapshot = self.document.working_registry.clone();
|
||||
Ok(Some(merge_rev))
|
||||
}
|
||||
|
||||
/// The retired snapshot as history alone gives it: the fold of `head`'s ancestry, leaving out undone deltas kept for redo.
|
||||
/// The retired snapshot as history alone produces it, independent of arrival order and the hot log.
|
||||
/// Folded over `head`'s ancestry only: an undone delta stays in the DAG for redo to find, and folding
|
||||
/// all of history would restore work the user undid.
|
||||
pub fn snapshot_from_history(&self) -> Result<Registry, CrdtError> {
|
||||
// Every op lands the same whatever order it arrives in, so applying each once is the fold.
|
||||
let reachable = self.document.history.ancestors(self.document.head);
|
||||
let mut scratch = Document::empty(self.document.peer, self.document.user);
|
||||
for delta in self.document.history.iter().filter(|delta| reachable.contains(&delta.id)) {
|
||||
@@ -344,12 +334,14 @@ impl Session {
|
||||
self.document.history.len()
|
||||
}
|
||||
|
||||
/// The hot ops stamped at or before `up_to`, which [`retire`](Self::retire) drains.
|
||||
/// The hot ops stamped at or before `up_to`, which [`retire`](Self::retire) drains. Sent with the deltas,
|
||||
/// since a lagging op can arrive below the cutoff afterwards.
|
||||
pub fn hot_ops_up_to(&self, up_to: TimeStamp) -> Vec<HotOpId> {
|
||||
self.document.hot_log.iter().filter(|hot_op| hot_op.timestamp <= up_to).map(HotOp::id).collect()
|
||||
}
|
||||
|
||||
/// Promote the given hot ops into retired deltas in hot-log order, each keeping its authored stamp.
|
||||
/// Promote the given hot ops into retired deltas, in hot-log order, each keeping the timestamp it was
|
||||
/// authored at. Markers commit nothing. Ops not in the log are ignored.
|
||||
///
|
||||
/// One retired delta per hot op.
|
||||
pub fn retire_hot_ops(&mut self, ids: &[HotOpId]) -> Result<Vec<Rev>, CrdtError> {
|
||||
@@ -357,9 +349,12 @@ impl Session {
|
||||
let (drained, kept): (Vec<HotOp>, Vec<HotOp>) = self.document.hot_log.drain(..).partition(|hot_op| wanted.contains(&hot_op.id()));
|
||||
self.document.hot_log = kept;
|
||||
self.document.resync_hot_timestamps();
|
||||
self.document.retired.extend(drained.iter().map(HotOp::id));
|
||||
self.document.settled.extend(drained.iter().map(HotOp::id));
|
||||
|
||||
let ops = drained.into_iter().map(|hot_op| (hot_op.op, Some(hot_op.timestamp)));
|
||||
let ops = drained
|
||||
.into_iter()
|
||||
.filter(|hot_op| !matches!(hot_op.op, RegistryDelta::EndTransaction))
|
||||
.map(|hot_op| (hot_op.op, Some(hot_op.timestamp)));
|
||||
self.commit_ops_authored_at(ops, true)
|
||||
}
|
||||
|
||||
@@ -383,33 +378,31 @@ impl Session {
|
||||
self.document.history.annotate(rev, key, value, timestamp)
|
||||
}
|
||||
|
||||
/// Whether there is a retired commit at `head` that can be undone in the silent zone (a commit
|
||||
/// after `last_broadcast_rev`). `head == 0` is the empty history; published commits aren't
|
||||
/// silently undoable (that needs a forward reverse-delta op, deferred until transport lands).
|
||||
///
|
||||
/// The earliest interaction (the document's loaded/created base) is *not* undoable: undoing it would
|
||||
/// rewind into the pre-base state, which legacy never offers (opening a document gives an empty undo
|
||||
/// history). We detect "head is on the earliest interaction" by walking `head`'s interaction back along
|
||||
/// first-parents and checking whether it bottoms out at the root with no earlier interaction boundary to
|
||||
/// land on. If so, there is nothing before this interaction to undo to, so undo is disabled.
|
||||
/// Whether the interaction at `head` can be undone in the silent zone: it is this user's own, holds no merge, and
|
||||
/// nothing in it was published, since rewinding a step peers hold would diverge from them. The document's first
|
||||
/// interaction is not undoable, as opening a document starts with an empty undo history.
|
||||
pub fn can_undo(&self) -> bool {
|
||||
let Some(head) = self.document.head else { return false };
|
||||
if self.document.last_broadcast_rev == Some(head) {
|
||||
return false;
|
||||
}
|
||||
self.interaction_start_parent(head).is_some()
|
||||
self.document.head.is_some_and(|head| self.interaction_start_parent(head, true).is_some())
|
||||
}
|
||||
|
||||
/// Walk the interaction containing `rev` back along first-parents to its first delta, returning the
|
||||
/// rev the cursor would rest on after undoing this interaction, or `None` if that is the root (the
|
||||
/// earliest interaction, which is not undoable). Mirrors the boundary condition in [`undo`](Self::undo):
|
||||
/// stop when the parent is an `interaction_end` boundary or the root.
|
||||
fn interaction_start_parent(&self, rev: Rev) -> Option<Rev> {
|
||||
let mut current = rev;
|
||||
/// The rev the cursor rests on once the interaction ending at `end` is undone: the parent where the previous
|
||||
/// interaction ended, a merge, or another user's delta begins. `None` when `end` is a merge, the interaction starts
|
||||
/// at the root, or, for a `silent` undo, it is not this user's or holds a published delta.
|
||||
fn interaction_start_parent(&self, end: Rev, silent: bool) -> Option<Rev> {
|
||||
let history = &self.document.history;
|
||||
let mut current = history.get(end)?;
|
||||
let user = self.user_of(current.author);
|
||||
if matches!(current.kind, RegistryDelta::Merge { .. }) || (silent && user != Some(self.document.user)) {
|
||||
return None;
|
||||
}
|
||||
let boundary = |delta: &Delta| delta.is_interaction_end() || matches!(delta.kind, RegistryDelta::Merge { .. }) || self.user_of(delta.author) != user;
|
||||
loop {
|
||||
let parent = self.document.history.get(current)?.parent?;
|
||||
if self.document.history.get(parent).is_some_and(|d| d.is_interaction_end()) {
|
||||
return Some(parent);
|
||||
if silent && self.document.last_broadcast_rev == Some(current.id) {
|
||||
return None;
|
||||
}
|
||||
let parent = history.get(current.parent?)?;
|
||||
if boundary(parent) {
|
||||
return Some(parent.id);
|
||||
}
|
||||
current = parent;
|
||||
}
|
||||
@@ -419,37 +412,22 @@ impl Session {
|
||||
!self.document.redo_stack.is_empty()
|
||||
}
|
||||
|
||||
/// Silent-zone undo of one *interaction*: revert deltas walking `head` back along first-parents until
|
||||
/// it reaches the previous interaction boundary (a delta marked `interaction_end`) or the empty root. One
|
||||
/// interaction spans several deltas (one `commit_from_runtime` batch), so undo reverts the whole run,
|
||||
/// not a single delta — matching the legacy per-interaction undo granularity. The undone interaction's
|
||||
/// `head` rev is pushed onto the redo stack. Reflog semantics: the DAG is never rewritten.
|
||||
/// Silent-zone undo of one interaction: put back what its deltas overwrote, newest first, until `head` rests where it
|
||||
/// began (see [`can_undo`](Self::can_undo)). Its `head` rev goes on the redo stack; the DAG is not rewritten.
|
||||
pub fn undo(&mut self) -> Result<Rev, CrdtError> {
|
||||
if !self.can_undo() {
|
||||
return Err(CrdtError::NothingToUndo);
|
||||
}
|
||||
let checkpoint = self.document.head.ok_or(CrdtError::NothingToUndo)?;
|
||||
let base = self.interaction_start_parent(checkpoint, true).ok_or(CrdtError::NothingToUndo)?;
|
||||
|
||||
// Revert this interaction's last delta, then keep going back until `head` rests on the previous
|
||||
// interaction's boundary (its `interaction_end` delta) or the root.
|
||||
loop {
|
||||
let rev = self.document.head.ok_or(CrdtError::NothingToUndo)?;
|
||||
while let Some(rev) = self.document.head.filter(|&rev| rev != base) {
|
||||
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
|
||||
let parent = delta.parent;
|
||||
|
||||
self.document.revert_delta(RegistryTarget::Working, delta)?;
|
||||
self.document.head = parent;
|
||||
|
||||
match parent {
|
||||
None => break,
|
||||
Some(parent) if self.document.history.get(parent).is_some_and(|d| d.is_interaction_end()) => break,
|
||||
Some(_) => {}
|
||||
}
|
||||
self.document.revert_delta(&delta);
|
||||
self.document.head = delta.parent;
|
||||
}
|
||||
|
||||
// Undo runs with an empty hot log, so keep the retired snapshot in lockstep with the rewound
|
||||
// working registry (the next interaction's reverses are computed against it).
|
||||
self.document.retired_snapshot = self.document.working_registry.clone();
|
||||
// With ops hot, working is the rewound snapshot plus them.
|
||||
if !self.document.hot_log.is_empty() {
|
||||
self.document.rebuild_working();
|
||||
}
|
||||
self.document.redo_stack.push(checkpoint);
|
||||
Ok(checkpoint)
|
||||
}
|
||||
@@ -469,15 +447,20 @@ impl Session {
|
||||
forward.push(delta);
|
||||
}
|
||||
|
||||
// Force-apply so each forward value wins the LWW tie against the reverse that undo force-applied
|
||||
// at the same timestamp. Symmetric with `revert_delta`.
|
||||
// Undo left the snapshot exactly at the fold up to `head`, so applying the deltas as retirement did folds
|
||||
// them in again, a newer write merged in before them still winning over theirs.
|
||||
let hot = !self.document.hot_log.is_empty();
|
||||
for delta in forward.into_iter().rev() {
|
||||
self.document.force_apply_op(delta.kind.clone(), delta.timestamp)?;
|
||||
self.document.apply_op_with(RegistryTarget::Snapshot, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
|
||||
if !hot {
|
||||
self.document.apply_op_with(RegistryTarget::Working, delta.kind, delta.timestamp, ApplyMode::Idempotent)?;
|
||||
}
|
||||
}
|
||||
if hot {
|
||||
self.document.rebuild_working();
|
||||
}
|
||||
self.document.head = Some(checkpoint);
|
||||
|
||||
// Redo runs with an empty hot log; keep the retired snapshot in lockstep with the working registry.
|
||||
self.document.retired_snapshot = self.document.working_registry.clone();
|
||||
Ok(checkpoint)
|
||||
}
|
||||
|
||||
@@ -513,7 +496,7 @@ 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 and `SetResourceHash`.
|
||||
/// bytes. Walks current resources plus each delta's `AddResource`/`RemoveResource` snapshot.
|
||||
pub fn all_referenced_resource_hashes(&self) -> HashSet<ResourceHash> {
|
||||
let mut hashes: HashSet<ResourceHash> = self.document.working_registry.resources.values().filter_map(|entry| entry.hash).collect();
|
||||
hashes.extend(self.document.history.resource_hashes());
|
||||
@@ -596,22 +579,25 @@ impl Session {
|
||||
self.document.next_node_counter
|
||||
}
|
||||
|
||||
/// The last hot op sequence this peer authored, carried across a reload so none is spent twice.
|
||||
/// The sequence of the last hot op this peer authored, which is how many it has. Carried across a reload, so no
|
||||
/// sequence is spent twice.
|
||||
pub fn last_hot_sequence(&self) -> HotSequence {
|
||||
self.document.last_hot_sequence
|
||||
}
|
||||
|
||||
/// The Lamport counter, persisted so a reopen never mints a spent stamp, even one nothing carries any more.
|
||||
/// The Lamport counter, persisted so a reopen never mints a stamp it already spent, even one no op in history or
|
||||
/// the hot log carries any more.
|
||||
pub fn clock_counter(&self) -> u64 {
|
||||
self.document.clock.counter
|
||||
}
|
||||
|
||||
/// Continue the Lamport clock after a load. Raises only, like observing an op.
|
||||
pub fn restore_clock_counter(&mut self, counter: u64) {
|
||||
pub fn restore_clock(&mut self, counter: u64) {
|
||||
self.document.clock.counter = self.document.clock.counter.max(counter);
|
||||
}
|
||||
|
||||
/// Restore the hot op sequence after a load. Raises only, as replaying the hot log may already have.
|
||||
/// Restore the authored-op count after a load, keeping a fresh op off a spent sequence. Raises only:
|
||||
/// replaying a persisted hot log afterwards cannot lower it.
|
||||
pub fn restore_hot_sequence(&mut self, sequence: HotSequence) {
|
||||
self.document.last_hot_sequence = self.document.last_hot_sequence.max(sequence);
|
||||
}
|
||||
@@ -645,7 +631,7 @@ pub struct HotOp {
|
||||
}
|
||||
|
||||
impl HotOp {
|
||||
/// Identifies the op in the retired marks, which track a contiguous prefix per author.
|
||||
/// Identifies the op in the settled marks, which track a contiguous prefix per author.
|
||||
pub fn id(&self) -> HotOpId {
|
||||
HotOpId {
|
||||
peer: self.timestamp.peer,
|
||||
@@ -670,20 +656,22 @@ impl HotSequence {
|
||||
}
|
||||
}
|
||||
|
||||
/// One hot op's author and position in its run, as the retired marks name it.
|
||||
/// One hot op's author and position in its run. Retirement names promoted ops by these, which tells a
|
||||
/// receiver which prefix history covers.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct HotOpId {
|
||||
pub peer: PeerId,
|
||||
pub sequence: HotSequence,
|
||||
}
|
||||
|
||||
/// Which hot ops are retired: each author's gap-free prefix, plus runs past it while ops are in flight. Persisted, so
|
||||
/// a late copy of a retired op is dropped.
|
||||
/// Which hot ops are retired into history: `settled_up_to` is each author's gap-free prefix, and `settled_beyond`
|
||||
/// the settled ops past it. Gaps exist only while ops are in flight, so an author collapses to its prefix. Replicated and persisted, so a
|
||||
/// late copy of a settled op is dropped wherever it lands.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct RetiredMarks {
|
||||
pub retired_up_to: HashMap<PeerId, HotSequence>,
|
||||
/// retired ops past their author's prefix, as inclusive runs, one per gap in flight.
|
||||
pub retired_runs: HashMap<PeerId, Vec<(HotSequence, HotSequence)>>,
|
||||
pub struct SettledHotOps {
|
||||
pub settled_up_to: HashMap<PeerId, HotSequence>,
|
||||
/// Settled ops past their author's prefix, as inclusive runs, one per gap in flight.
|
||||
pub settled_beyond: HashMap<PeerId, Vec<(HotSequence, HotSequence)>>,
|
||||
}
|
||||
|
||||
/// Sort and coalesce runs, joining any that touch or abut.
|
||||
@@ -698,41 +686,41 @@ fn coalesce(runs: &mut Vec<(HotSequence, HotSequence)>) {
|
||||
});
|
||||
}
|
||||
|
||||
impl RetiredMarks {
|
||||
impl SettledHotOps {
|
||||
/// Whether history already holds this hot op.
|
||||
pub fn covers(&self, id: HotOpId) -> bool {
|
||||
self.retired_up_to.get(&id.peer).is_some_and(|&through| id.sequence <= through)
|
||||
self.settled_up_to.get(&id.peer).is_some_and(|&through| id.sequence <= through)
|
||||
|| self
|
||||
.retired_runs
|
||||
.settled_beyond
|
||||
.get(&id.peer)
|
||||
.is_some_and(|runs| runs.iter().any(|&(start, end)| (start..=end).contains(&id.sequence)))
|
||||
}
|
||||
|
||||
/// Take on `remote`'s coverage as well as this one's.
|
||||
pub(crate) fn absorb(&mut self, remote: &Self) {
|
||||
for (&peer, &remote_through) in &remote.retired_up_to {
|
||||
let through = self.retired_up_to.entry(peer).or_default();
|
||||
for (&peer, &remote_through) in &remote.settled_up_to {
|
||||
let through = self.settled_up_to.entry(peer).or_default();
|
||||
*through = (*through).max(remote_through);
|
||||
}
|
||||
for (&peer, runs) in &remote.retired_runs {
|
||||
self.retired_runs.entry(peer).or_default().extend(runs.iter().copied());
|
||||
for (&peer, runs) in &remote.settled_beyond {
|
||||
self.settled_beyond.entry(peer).or_default().extend(runs.iter().copied());
|
||||
}
|
||||
self.compact();
|
||||
}
|
||||
|
||||
/// Record newly retired ops.
|
||||
/// Record newly settled ops.
|
||||
pub fn extend(&mut self, retired: impl IntoIterator<Item = HotOpId>) {
|
||||
for id in retired {
|
||||
self.retired_runs.entry(id.peer).or_default().push((id.sequence, id.sequence));
|
||||
self.settled_beyond.entry(id.peer).or_default().push((id.sequence, id.sequence));
|
||||
}
|
||||
self.compact();
|
||||
}
|
||||
|
||||
/// Fold runs that continue their author's prefix into `retired_up_to`, leaving only those past a gap.
|
||||
/// Fold runs that continue their author's prefix into `settled_up_to`, leaving only those past a gap.
|
||||
fn compact(&mut self) {
|
||||
for (&peer, runs) in &mut self.retired_runs {
|
||||
for (&peer, runs) in &mut self.settled_beyond {
|
||||
coalesce(runs);
|
||||
let mut through = self.retired_up_to.get(&peer).copied().unwrap_or(HotSequence::NONE);
|
||||
let mut through = self.settled_up_to.get(&peer).copied().unwrap_or(HotSequence::NONE);
|
||||
let joined = runs.iter().take_while(|&&(start, end)| {
|
||||
let joins = start <= through.next();
|
||||
if joins {
|
||||
@@ -743,10 +731,10 @@ impl RetiredMarks {
|
||||
let joined = joined.count();
|
||||
runs.drain(..joined);
|
||||
if through != HotSequence::NONE {
|
||||
self.retired_up_to.insert(peer, through);
|
||||
self.settled_up_to.insert(peer, through);
|
||||
}
|
||||
}
|
||||
self.retired_runs.retain(|_, runs| !runs.is_empty());
|
||||
self.settled_beyond.retain(|_, runs| !runs.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{AttributeDelta, CrdtError, HotOpId, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, RegistryDelta, Session, UserId, Value};
|
||||
|
||||
fn set_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
pub(super) fn set_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: AttributeDelta {
|
||||
key: key.to_string(),
|
||||
@@ -9,26 +9,28 @@ fn set_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
}
|
||||
}
|
||||
|
||||
fn add_network(id: u64) -> RegistryDelta {
|
||||
pub(super) 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.
|
||||
/// Retirement takes the ops under the cutoff in any log order: every op commutes, so the snapshot folds to
|
||||
/// the working registry's values with a later-stamped op left hot.
|
||||
#[test]
|
||||
fn retirement_takes_the_ops_under_the_cutoff_in_any_applied_order() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
// The log is in arrival order: a guest's later-stamped op sits ahead of an earlier one.
|
||||
// A guest's late-stamped op sits ahead of an earlier-stamped one: the log is in arrival order, stamps
|
||||
// are the authors' clocks.
|
||||
let hot = |op, counter, peer| crate::HotOp {
|
||||
op,
|
||||
timestamp: crate::TimeStamp { counter, peer: PeerId(peer) },
|
||||
sequence: crate::HotSequence(1),
|
||||
};
|
||||
let (late, own) = (hot(add_network(9), 50, 2), hot(set_attribute("x", 1), 20, 3));
|
||||
host.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.apply_hot_op(late.clone()).expect("the late-stamped op lands first");
|
||||
host.apply_hot_op(own.clone()).expect("the earlier-stamped op lands second");
|
||||
assert_eq!(host.hot_ops_up_to(own.timestamp).len(), 1, "only the op under the cutoff retires");
|
||||
|
||||
host.retire(own.timestamp).expect("retire");
|
||||
@@ -42,8 +44,10 @@ fn retirement_takes_the_ops_under_the_cutoff_in_any_applied_order() {
|
||||
assert!(host.registry().value_equal(host.retired_registry()));
|
||||
}
|
||||
|
||||
/// A device's registration to a person is a write like any other: a later one replaces it, and a peer that
|
||||
/// receives the two in the other order ends up with the same mapping.
|
||||
#[test]
|
||||
fn newest_peer_registration_wins_in_any_order() {
|
||||
fn a_peers_registration_is_the_newest_by_stamp_whatever_order_it_lands() {
|
||||
// Registration rides the staging path, so the steps go through the hot log and retire.
|
||||
fn stage_and_retire(session: &mut Session, op: RegistryDelta) {
|
||||
let hot = session.stage_ops([op]).expect("stage");
|
||||
@@ -54,7 +58,7 @@ fn newest_peer_registration_wins_in_any_order() {
|
||||
stage_and_retire(&mut device, set_attribute("first", 1));
|
||||
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(10));
|
||||
|
||||
// The person at the device changes, so the next batch registers again.
|
||||
// The person at the device changes: the next batch registers again, and the newer registration wins.
|
||||
device.document.user = UserId(20);
|
||||
stage_and_retire(&mut device, set_attribute("second", 2));
|
||||
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(20));
|
||||
@@ -77,6 +81,7 @@ fn a_batch_past_the_last_sequence_is_refused_whole() {
|
||||
assert!(session.hot_log().is_empty());
|
||||
}
|
||||
|
||||
/// The settled marks carry over a reopen, so a late copy of a retired op is dropped rather than retired again.
|
||||
#[test]
|
||||
fn a_reopened_session_drops_a_late_copy_of_a_retired_op() {
|
||||
let op = crate::HotOp {
|
||||
@@ -85,17 +90,19 @@ fn a_reopened_session_drops_a_late_copy_of_a_retired_op() {
|
||||
sequence: crate::HotSequence(1),
|
||||
};
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
host.replay_hot_op(op.clone()).unwrap();
|
||||
host.apply_hot_op(op.clone()).unwrap();
|
||||
host.retire(op.timestamp).unwrap();
|
||||
|
||||
let mut reopened = Session::load(PeerId(1), UserId(1), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
|
||||
reopened.absorb_retired_marks(host.retired_marks());
|
||||
reopened.replay_hot_op(op.clone()).unwrap();
|
||||
reopened.absorb_settled_marks(host.settled_marks());
|
||||
reopened.apply_hot_op(op.clone()).unwrap();
|
||||
assert!(reopened.hot_log().is_empty());
|
||||
assert!(reopened.retire(op.timestamp).unwrap().is_empty());
|
||||
assert_eq!(reopened.history_len(), host.history_len());
|
||||
}
|
||||
|
||||
/// A local op naming a node never seen is refused before it writes anything, its target included, so the working
|
||||
/// registry stays the snapshot plus the hot log.
|
||||
#[test]
|
||||
fn a_refused_local_op_leaves_the_working_registry_unchanged() {
|
||||
let mut s = Session::with_peer(PeerId(1));
|
||||
@@ -119,7 +126,8 @@ fn a_refused_local_op_leaves_the_working_registry_unchanged() {
|
||||
assert_eq!(s.registry(), &before, "the refused op's write to node 1 stayed in the working registry");
|
||||
}
|
||||
|
||||
/// The caller only gets the error, so ops left staged would never be persisted or sent.
|
||||
/// A batch refused partway stages nothing: the caller only gets the error, so ops left staged would never be persisted
|
||||
/// or sent.
|
||||
#[test]
|
||||
fn a_refused_batch_stages_nothing() {
|
||||
let mut s = Session::with_peer(PeerId(1));
|
||||
@@ -145,34 +153,13 @@ fn a_refused_batch_stages_nothing() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retired_marks_round_trip_through_json() {
|
||||
let mut marks = crate::RetiredMarks::default();
|
||||
fn settled_marks_round_trip_through_json() {
|
||||
let mut marks = crate::SettledHotOps::default();
|
||||
let id = |peer: u64, sequence: u64| HotOpId {
|
||||
peer: PeerId(peer),
|
||||
sequence: crate::HotSequence(sequence),
|
||||
};
|
||||
marks.extend([id(1, 1), id(1, 2), id(1, 5), id(u64::MAX, 3)]);
|
||||
let json = serde_json::to_string(&marks).unwrap();
|
||||
assert_eq!(serde_json::from_str::<crate::RetiredMarks>(&json).unwrap(), marks);
|
||||
}
|
||||
|
||||
/// A late copy of one of this peer's own ops that is already retired still raises the sequence and the clock, so the
|
||||
/// next op this peer stages takes a fresh sequence and a later stamp.
|
||||
#[test]
|
||||
fn a_retired_late_copy_still_advances_the_sequence_and_the_clock() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
let own = crate::HotOp {
|
||||
op: set_attribute("k", 1),
|
||||
timestamp: crate::TimeStamp { counter: 50, peer: PeerId(1) },
|
||||
sequence: crate::HotSequence(7),
|
||||
};
|
||||
let mut marks = crate::RetiredMarks::default();
|
||||
marks.extend([own.id()]);
|
||||
session.absorb_retired_marks(&marks);
|
||||
session.replay_hot_op(own.clone()).expect("a retired copy is dropped");
|
||||
|
||||
let staged = session.stage_ops([set_attribute("k", 2)]).expect("stage");
|
||||
let next = staged.last().expect("staged");
|
||||
assert!(next.sequence > own.sequence, "a fresh sequence");
|
||||
assert!(next.timestamp > own.timestamp, "a later stamp");
|
||||
assert_eq!(serde_json::from_str::<crate::SettledHotOps>(&json).unwrap(), marks);
|
||||
}
|
||||
@@ -4,7 +4,7 @@ use graph_craft::concrete;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
|
||||
|
||||
use crate::InputSlot;
|
||||
use crate::{Delta, Document, HotOp, Network, NetworkId, NoMetadata, Node, NodeId, PeerId, ROOT_NETWORK, RegistryDelta, RegistryTarget, Session, TimeStamp, Value};
|
||||
use crate::{Delta, Document, HotOp, Network, NetworkId, NoMetadata, Node, NodeId, PeerId, ROOT_NETWORK, RegistryDelta, Session, TimeStamp, Value};
|
||||
|
||||
fn fresh_document(peer: PeerId) -> Document {
|
||||
Session::with_peer(peer).document
|
||||
@@ -20,7 +20,7 @@ fn remove_node_op(node_id: NodeId) -> RegistryDelta {
|
||||
/// Commit a single op to a document as a retired delta. Mints a fresh timestamp, links to
|
||||
/// current head, applies, records in history, advances head.
|
||||
fn commit_op(document: &mut Document, op: RegistryDelta) {
|
||||
let reverse = document.compute_reverse_delta(RegistryTarget::Working, &op).expect("compute_reverse_delta failed");
|
||||
let reverse = crate::prior::capture(&document.working_registry, &op);
|
||||
let timestamp = document.clock.tick();
|
||||
let delta = Delta::new(document.head, document.peer, timestamp, op, reverse);
|
||||
let rev = delta.id;
|
||||
@@ -44,7 +44,7 @@ fn apply_hot_op_advances_clock_past_observed_timestamp() {
|
||||
};
|
||||
|
||||
document
|
||||
.stage_hot_op(hot_op, crate::document::ApplyMode::Strict)
|
||||
.apply_hot_op(hot_op, crate::document::ApplyMode::Live)
|
||||
.expect("RemoveNode on absent node is a no-op, not an error");
|
||||
|
||||
assert!(
|
||||
@@ -160,7 +160,7 @@ fn history_is_causal_and_deterministic() {
|
||||
}
|
||||
}
|
||||
|
||||
fn set_document_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
pub(super) fn set_document_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: crate::AttributeDelta {
|
||||
key: key.to_string(),
|
||||
@@ -169,73 +169,6 @@ fn set_document_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
}
|
||||
}
|
||||
|
||||
/// Two peers that each integrate the other's concurrent branch converge to byte-identical history:
|
||||
/// the merge commit is parent-set-addressed (same `Rev` on both) and the canonical sort erases the
|
||||
/// arrival-order difference. Exercises `Session::merge`, the `Merge` variant, and `canonical_sort`.
|
||||
#[test]
|
||||
fn merge_converges_to_identical_history() {
|
||||
// Shared base commit, then a concurrent edit on each peer's own clone of that base.
|
||||
let mut session_a = Session::with_peer(PeerId(1));
|
||||
session_a.commit_op_for_test(set_document_attribute("compute::base", 0)).expect("base commit");
|
||||
let mut session_b = session_a.clone();
|
||||
|
||||
session_a.commit_op_for_test(set_document_attribute("compute::a", 1)).expect("A edit");
|
||||
session_b.commit_op_for_test(set_document_attribute("compute::b", 2)).expect("B edit");
|
||||
|
||||
// Cross-merge: feed each peer the other's full delta set. The shared base dedups by `Rev`.
|
||||
let deltas_a = session_a.cloned_deltas();
|
||||
let deltas_b = session_b.cloned_deltas();
|
||||
let merge_a = session_a.merge(deltas_b).expect("merge into A failed").expect("A produced a merge");
|
||||
let merge_b = session_b.merge(deltas_a).expect("merge into B failed").expect("B produced a merge");
|
||||
|
||||
assert_eq!(merge_a, merge_b, "same tips must mint the identical parent-set-addressed merge commit");
|
||||
|
||||
let order_a: Vec<crate::Rev> = session_a.history().map(|d| d.id).collect();
|
||||
let order_b: Vec<crate::Rev> = session_b.history().map(|d| d.id).collect();
|
||||
assert_eq!(order_a, order_b, "both peers must converge to byte-identical history order");
|
||||
assert_eq!(session_a.head_rev(), session_b.head_rev(), "both peers land on the same merge head");
|
||||
}
|
||||
|
||||
/// Resurrection must reach into a merged-in branch: a network added then removed on the other peer's
|
||||
/// branch lives only under the merge's secondary parent, so a `SetNetworkExport` targeting it after
|
||||
/// the merge can only restore it by traversing all ancestors (not the primary-parent chain).
|
||||
#[test]
|
||||
fn resurrection_reaches_across_a_merge() {
|
||||
let network_id = NetworkId(7);
|
||||
|
||||
// Shared base, then peer B adds and removes network 7 on its own branch.
|
||||
let mut session_a = Session::with_peer(PeerId(1));
|
||||
session_a.commit_op_for_test(set_document_attribute("compute::base", 0)).expect("base commit");
|
||||
let mut session_b = session_a.clone();
|
||||
|
||||
session_a.commit_op_for_test(set_document_attribute("compute::a", 1)).expect("A edit");
|
||||
session_b
|
||||
.commit_op_for_test(RegistryDelta::AddNetwork {
|
||||
id: network_id,
|
||||
network: Network::default(),
|
||||
})
|
||||
.expect("B AddNetwork");
|
||||
session_b
|
||||
.commit_op_for_test(RegistryDelta::RemoveNetwork {
|
||||
id: network_id,
|
||||
snapshot: Network::default(),
|
||||
})
|
||||
.expect("B RemoveNetwork");
|
||||
|
||||
// A merges B's branch: 7's AddNetwork now lives only under the merge's secondary parent.
|
||||
session_a.merge(session_b.cloned_deltas()).expect("merge failed");
|
||||
|
||||
// A SetNetworkExport on 7 must resurrect it by walking into the merged-in branch. Before the
|
||||
// all-ancestors fix this failed with NetworkNotInHistory (the primary-parent walk missed B's branch).
|
||||
session_a
|
||||
.commit_op_for_test(RegistryDelta::SetNetworkExport {
|
||||
id: network_id,
|
||||
index: 0,
|
||||
export: None,
|
||||
})
|
||||
.expect("resurrection must find the AddNetwork on the merged-in branch");
|
||||
}
|
||||
|
||||
/// Committing the same NodeNetwork twice must produce zero history entries on the second commit.
|
||||
/// Without value-only diffing in compute_deltas, the second commit would emit spurious
|
||||
/// ChangeNodeInput / ChangeNodeAttribute ops because self.registry has real timestamps while the
|
||||
@@ -293,7 +226,7 @@ fn first_contribution_registers_the_peer() {
|
||||
|
||||
/// A SetExport newer than a network's removal revives the network from its tombstone instead of erroring.
|
||||
#[test]
|
||||
fn set_network_export_revives_a_removed_network() {
|
||||
fn set_export_revives_a_removed_network() {
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
let network_id = NetworkId(7);
|
||||
|
||||
@@ -356,7 +289,8 @@ fn add_node_revives_its_removed_network() {
|
||||
assert!(document.working_registry.node_instances.contains_key(&node_id), "the node itself should also be present");
|
||||
}
|
||||
|
||||
/// Two peers reverting one removal: the second revival is not newer than the first, so it lands once.
|
||||
/// The same revival arriving twice, from two peers reverting one removal, lands once: the second copy
|
||||
/// is not newer than what the first wrote.
|
||||
#[test]
|
||||
fn the_same_revival_arriving_twice_lands_once() {
|
||||
use crate::Node;
|
||||
@@ -420,6 +354,11 @@ fn source_key(priority: f64, peer: u64) -> SourceKey {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the map holds a live value under `key`: a deleted key stays as a tombstone.
|
||||
fn holds(attributes: &crate::Attributes, key: &str) -> bool {
|
||||
crate::attributes::live(attributes).any(|(held, _)| held == key)
|
||||
}
|
||||
|
||||
fn ts(counter: u64, peer: u64) -> TimeStamp {
|
||||
TimeStamp { counter, peer: PeerId(peer) }
|
||||
}
|
||||
@@ -519,85 +458,147 @@ fn register_resource_hash_is_last_writer_wins() {
|
||||
assert_eq!(document.working_registry.resources.get(&id).unwrap().hash, Some(hash_b), "later resolve wins");
|
||||
}
|
||||
|
||||
/// The reverse delta of a RemoveSource restores the prior source body, and applying op-then-reverse
|
||||
/// round-trips the source chain.
|
||||
/// Undo puts back exactly what an op overwrote, stamps, tombstones and placeholders included, for every kind of
|
||||
/// op and wherever it lands: on a live entity, a removed one, or one never seen.
|
||||
#[test]
|
||||
fn remove_source_reverse_restores_prior() {
|
||||
fn restoring_what_an_op_overwrote_gives_back_the_registry_exactly() {
|
||||
use crate::{AttributeDelta, Implementation, Network, NodeInput, ROOT_NETWORK};
|
||||
let attribute = |key: &str, value: i64| AttributeDelta {
|
||||
key: key.into(),
|
||||
value: Some(Value::Int(value.into())),
|
||||
};
|
||||
let reference = |id: u64| NodeInput::Node { id: NodeId(id), index: 0 };
|
||||
let (live, removed, unseen, network, resource) = (NodeId(1), NodeId(2), NodeId(3), NetworkId(7), ResourceId::new());
|
||||
let node = || Node::new(ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(1)), 2);
|
||||
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
let id = ResourceId::new();
|
||||
let key = source_key(0.5, 1);
|
||||
|
||||
commit_op(
|
||||
&mut document,
|
||||
RD::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: Value::Str("kept".into()),
|
||||
},
|
||||
);
|
||||
|
||||
// Compute the reverse while the body is still present, then apply the removal.
|
||||
let reverse = document.compute_reverse_delta(RegistryTarget::Working, &RD::RemoveSource { id, key }).unwrap();
|
||||
match &reverse {
|
||||
RD::AddSource { source, .. } => assert_eq!(*source, Value::Str("kept".into()), "reverse of removal re-adds the body"),
|
||||
other => panic!("expected AddSource reverse, got {other:?}"),
|
||||
for (op, at) in [
|
||||
(
|
||||
RD::AddNetwork {
|
||||
id: ROOT_NETWORK,
|
||||
network: Network::default(),
|
||||
},
|
||||
1,
|
||||
),
|
||||
(
|
||||
RD::AddNetwork {
|
||||
id: network,
|
||||
network: Network::default(),
|
||||
},
|
||||
1,
|
||||
),
|
||||
(RD::AddNode { id: live, node: node() }, 2),
|
||||
(RD::AddNode { id: removed, node: node() }, 2),
|
||||
(RD::RemoveNode { id: removed, snapshot: node() }, 3),
|
||||
(
|
||||
RD::ChangeNodeAttribute {
|
||||
id: live,
|
||||
delta: attribute("kept", 1),
|
||||
},
|
||||
4,
|
||||
),
|
||||
(
|
||||
RD::AddSource {
|
||||
id: resource,
|
||||
key: source_key(0.5, 1),
|
||||
source: Value::Str("kept".into()),
|
||||
},
|
||||
4,
|
||||
),
|
||||
(RD::ChangeDocumentAttribute { delta: attribute("kept", 1) }, 4),
|
||||
(
|
||||
RD::SetNetworkExport {
|
||||
id: network,
|
||||
index: 0,
|
||||
export: Some(reference(1)),
|
||||
},
|
||||
4,
|
||||
),
|
||||
] {
|
||||
document.apply_op_idempotent(op, ts(at, 2)).unwrap();
|
||||
}
|
||||
|
||||
document.apply_op(RD::RemoveSource { id, key }, ts(5, 1)).unwrap();
|
||||
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();
|
||||
assert_eq!(document.working_registry.resources.get(&id).unwrap().source(&key).unwrap().source, Value::Str("kept".into()));
|
||||
}
|
||||
|
||||
/// AddSource on a fresh slot reverses to a RemoveSource; on an occupied slot it restores the prior body.
|
||||
#[test]
|
||||
fn add_source_reverse_depends_on_prior_state() {
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
let id = ResourceId::new();
|
||||
let key = source_key(0.5, 1);
|
||||
|
||||
// Fresh slot: reverse removes.
|
||||
let reverse_fresh = document
|
||||
.compute_reverse_delta(
|
||||
RegistryTarget::Working,
|
||||
&RD::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: Value::Str("first".into()),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(reverse_fresh, RD::RemoveSource { .. }), "reverse of add-to-empty is remove, got {reverse_fresh:?}");
|
||||
|
||||
// Occupy the slot, then reverse of a new add restores the existing body.
|
||||
document
|
||||
.apply_op(
|
||||
RD::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: Value::Str("existing".into()),
|
||||
},
|
||||
ts(1, 1),
|
||||
)
|
||||
.unwrap();
|
||||
let reverse_overwrite = document
|
||||
.compute_reverse_delta(
|
||||
RegistryTarget::Working,
|
||||
&RD::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: Value::Str("overwrite".into()),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
match reverse_overwrite {
|
||||
RD::AddSource { source, .. } => assert_eq!(source, Value::Str("existing".into()), "reverse restores prior body"),
|
||||
other => panic!("expected AddSource reverse, got {other:?}"),
|
||||
let ops = [
|
||||
RD::AddNode { id: live, node: node() },
|
||||
RD::AddNode { id: unseen, node: node() },
|
||||
RD::RemoveNode { id: live, snapshot: node() },
|
||||
RD::ChangeNodeAttribute {
|
||||
id: live,
|
||||
delta: attribute("kept", 2),
|
||||
},
|
||||
RD::ChangeNodeAttribute { id: live, delta: attribute("new", 2) },
|
||||
RD::ChangeNodeAttribute {
|
||||
id: removed,
|
||||
delta: attribute("new", 2),
|
||||
},
|
||||
RD::ChangeNodeAttribute {
|
||||
id: unseen,
|
||||
delta: attribute("new", 2),
|
||||
},
|
||||
RD::ChangeNodeInput {
|
||||
id: live,
|
||||
index: 1,
|
||||
new_input: reference(2),
|
||||
},
|
||||
RD::ChangeNodeInput {
|
||||
id: live,
|
||||
index: 5,
|
||||
new_input: reference(3),
|
||||
},
|
||||
RD::ChangeNodeInputAttribute {
|
||||
id: live,
|
||||
index: 0,
|
||||
delta: attribute("name", 2),
|
||||
},
|
||||
RD::SetNodeInputs {
|
||||
id: live,
|
||||
inputs: vec![crate::InputSlot::unset(TimeStamp::ORIGIN); 3],
|
||||
},
|
||||
RD::SetNodeImplementation {
|
||||
id: live,
|
||||
implementation: Implementation::Network(NetworkId(8)),
|
||||
},
|
||||
RD::SetNetworkExport {
|
||||
id: network,
|
||||
index: 3,
|
||||
export: Some(reference(3)),
|
||||
},
|
||||
RD::ChangeNetworkAttribute {
|
||||
id: network,
|
||||
delta: attribute("new", 2),
|
||||
},
|
||||
RD::RemoveNetwork {
|
||||
id: network,
|
||||
snapshot: Network::default(),
|
||||
},
|
||||
RD::AddSource {
|
||||
id: resource,
|
||||
key: source_key(0.5, 1),
|
||||
source: Value::Str("new".into()),
|
||||
},
|
||||
RD::RemoveSource {
|
||||
id: resource,
|
||||
key: source_key(0.5, 1),
|
||||
},
|
||||
RD::SetResourceHash { id: ResourceId::new(), hash: None },
|
||||
RD::RemoveResource {
|
||||
id: resource,
|
||||
snapshot: Default::default(),
|
||||
},
|
||||
RD::ChangeDocumentAttribute { delta: attribute("kept", 2) },
|
||||
RD::RegisterPeer {
|
||||
peer: PeerId(5),
|
||||
user: crate::UserId(5),
|
||||
},
|
||||
];
|
||||
for op in ops {
|
||||
let before = document.working_registry.clone();
|
||||
let priors = crate::prior::capture(&before, &op);
|
||||
let mut after = document.clone();
|
||||
after.apply_op_idempotent(op.clone(), ts(10, 2)).unwrap();
|
||||
assert_ne!(after.working_registry, before, "{op:?} should change something for this to check anything");
|
||||
crate::prior::restore(&mut after.working_registry, &priors);
|
||||
assert_eq!(after.working_registry, before, "restoring {op:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -742,15 +743,6 @@ 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
|
||||
@@ -816,7 +808,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, Implementation};
|
||||
use crate::{AttributeValue, AttributesWrite, Implementation};
|
||||
|
||||
let keys = ["ui::position", "ui::display_name", "ui::locked", "ui::pinned", "call_argument", "context_features"];
|
||||
|
||||
@@ -838,16 +830,18 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
||||
input: crate::NodeInput::Import { index: 0 },
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
attributes: input_attributes,
|
||||
attributes_timestamp: TimeStamp::ORIGIN,
|
||||
}];
|
||||
|
||||
Node {
|
||||
presence: Default::default(),
|
||||
network_timestamp: Default::default(),
|
||||
added: Default::default(),
|
||||
inputs_timestamp: Default::default(),
|
||||
implementation: implementation.clone(),
|
||||
implementation_timestamp: Default::default(),
|
||||
inputs,
|
||||
attributes,
|
||||
attributes_timestamp: Default::default(),
|
||||
network: ROOT_NETWORK,
|
||||
}
|
||||
};
|
||||
@@ -867,10 +861,7 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
||||
id: NodeId(9),
|
||||
node: make_node(&forward),
|
||||
},
|
||||
RegistryDelta::AddNode {
|
||||
id: NodeId(9),
|
||||
node: make_node(&forward),
|
||||
},
|
||||
Vec::new(),
|
||||
);
|
||||
let delta_reversed = Delta::new(
|
||||
parent,
|
||||
@@ -880,21 +871,29 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
||||
id: NodeId(9),
|
||||
node: make_node(&reversed),
|
||||
},
|
||||
RegistryDelta::AddNode {
|
||||
id: NodeId(9),
|
||||
node: make_node(&reversed),
|
||||
},
|
||||
Vec::new(),
|
||||
);
|
||||
|
||||
assert_eq!(delta_forward.id, delta_reversed.id, "Rev must not depend on attribute insertion order");
|
||||
}
|
||||
|
||||
/// Commit a retired delta and mirror it onto the working registry; `commit_op_for_test` alone only
|
||||
/// advances the snapshot zone.
|
||||
pub(super) fn commit_retired(session: &mut Session, op: RegistryDelta) {
|
||||
let before = session.history().count();
|
||||
session.commit_op_for_test(op).expect("commit failed");
|
||||
|
||||
for delta in session.cloned_deltas().into_iter().skip(before) {
|
||||
session.document.apply_op_idempotent(delta.kind, delta.timestamp).expect("mirroring onto the working registry");
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
pub(super) 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)),
|
||||
@@ -911,7 +910,8 @@ fn hot_op(op: RegistryDelta, counter: u64, peer: u64, sequence: u64) -> HotOp {
|
||||
}
|
||||
}
|
||||
|
||||
/// An op past a gap is covered without the gap, a filled gap joins the prefix, and absorbing is a union.
|
||||
/// Settled marks are a per-author prefix plus runs past gaps: an op past a gap is covered without claiming
|
||||
/// the gap, a filled gap folds into the prefix, a gap that never fills stays one run, and absorbing is a union.
|
||||
#[test]
|
||||
fn retired_marks_keep_a_prefix_and_runs_past_gaps() {
|
||||
let author = PeerId(1);
|
||||
@@ -920,7 +920,7 @@ fn retired_marks_keep_a_prefix_and_runs_past_gaps() {
|
||||
sequence: crate::HotSequence(sequence),
|
||||
};
|
||||
let marks_of = |batches: &[&[u64]]| {
|
||||
let mut marks = crate::RetiredMarks::default();
|
||||
let mut marks = crate::SettledHotOps::default();
|
||||
batches.iter().for_each(|batch| marks.extend(batch.iter().map(|&sequence| id(sequence))));
|
||||
marks
|
||||
};
|
||||
@@ -939,9 +939,9 @@ fn retired_marks_keep_a_prefix_and_runs_past_gaps() {
|
||||
for (batches, absorbed, prefix, runs) in cases {
|
||||
let mut marks = marks_of(batches);
|
||||
marks.absorb(&marks_of(absorbed));
|
||||
let up_to = marks.retired_up_to.get(&author).copied().unwrap_or(crate::HotSequence::NONE);
|
||||
let up_to = marks.settled_up_to.get(&author).copied().unwrap_or(crate::HotSequence::NONE);
|
||||
assert_eq!(up_to, crate::HotSequence(prefix), "{batches:?}");
|
||||
assert_eq!(marks.retired_runs.get(&author).map(Vec::len), runs, "{batches:?}");
|
||||
assert_eq!(marks.settled_beyond.get(&author).map(Vec::len), runs, "{batches:?}");
|
||||
for sequence in 1..=21 {
|
||||
let retired = batches.iter().chain(absorbed).any(|batch| batch.contains(&sequence));
|
||||
assert_eq!(marks.covers(id(sequence)), retired, "{batches:?}: sequence {sequence}");
|
||||
@@ -949,32 +949,60 @@ fn retired_marks_keep_a_prefix_and_runs_past_gaps() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A retirer that never received an author's earlier op still retires the later one, past the author's prefix.
|
||||
/// Retirement drains the hot log, so a retirer that never received an author's earlier op still retires the
|
||||
/// later one, past the author's prefix.
|
||||
#[test]
|
||||
fn retiring_over_a_gap_lands_beyond_the_prefix() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
// Sequence 1 was lost with the link that carried it.
|
||||
let second = hot_op(set_document_attribute("late", 1), 9, 2, 2);
|
||||
host.replay_hot_op(second.clone()).expect("apply");
|
||||
host.apply_hot_op(second.clone()).expect("apply");
|
||||
host.retire(second.timestamp).expect("retire");
|
||||
|
||||
let marks = host.retired_marks();
|
||||
assert_eq!(marks.retired_up_to.get(&PeerId(2)).copied().unwrap_or(crate::HotSequence::NONE), crate::HotSequence::NONE);
|
||||
assert_eq!(marks.retired_runs.get(&PeerId(2)).map(Vec::len), Some(1));
|
||||
let marks = host.settled_marks();
|
||||
assert_eq!(marks.settled_up_to.get(&PeerId(2)).copied().unwrap_or(crate::HotSequence::NONE), crate::HotSequence::NONE);
|
||||
assert_eq!(marks.settled_beyond.get(&PeerId(2)).map(Vec::len), Some(1));
|
||||
assert!(marks.covers(second.id()));
|
||||
}
|
||||
|
||||
/// So the snapshot and a replay keep the LWW winner the live view did, whether the straggler retires with it or after.
|
||||
/// Undo and redo move only the retired zone and never promote the hot tail into it, a fold skips the undone
|
||||
/// delta kept in the DAG for redo, and a published commit is not silently rewound since peers hold it.
|
||||
#[test]
|
||||
fn undo_and_redo_move_only_unpublished_retired_history() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
commit_retired(&mut session, set_document_attribute("first", 1));
|
||||
let boundary = session.history().last().expect("a committed delta").id;
|
||||
session.mark_interaction_end(boundary);
|
||||
commit_retired(&mut session, set_document_attribute("second", 2));
|
||||
session.stage_ops([set_document_attribute("hot", 3)]).expect("stage");
|
||||
|
||||
let mut published = session.clone();
|
||||
published.publish_up_to(published.head_rev().expect("a head"));
|
||||
assert!(session.can_undo() && !published.can_undo());
|
||||
|
||||
let retired = |session: &Session, key| holds(&session.retired_registry().attributes, key);
|
||||
session.undo().expect("undo");
|
||||
assert!(!retired(&session, "second") && !retired(&session, "hot"));
|
||||
let folded = session.snapshot_from_history().expect("fold");
|
||||
assert!(holds(&folded.attributes, "first") && !holds(&folded.attributes, "second"));
|
||||
|
||||
session.redo().expect("redo");
|
||||
assert!(retired(&session, "second") && !retired(&session, "hot"));
|
||||
assert!(holds(&session.registry().attributes, "hot"));
|
||||
}
|
||||
|
||||
/// A retired delta keeps its op's authoring stamp, so the snapshot and a replay of history keep the LWW winner
|
||||
/// the live view did, whether the losing straggler retires with the winner or after it.
|
||||
#[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, 1);
|
||||
host.replay_hot_op(winner.clone()).expect("apply winner");
|
||||
host.apply_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, 1)).expect("apply straggler");
|
||||
host.apply_hot_op(hot_op(set_document_attribute("k", 2), 5, 3, 1)).expect("apply straggler");
|
||||
host.retire(winner.timestamp).expect("retire");
|
||||
|
||||
let value = |registry: &crate::Registry| registry.attributes.get("k").map(|attribute| attribute.value.clone());
|
||||
@@ -984,8 +1012,11 @@ fn retirement_preserves_the_live_lww_winner() {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// Every registry field, entity existence included, is last-writer-wins on a timestamp, so a set of ops
|
||||
/// folds to one registry in any order. Random structural and field ops, attribute deletions included, over
|
||||
/// a few ids so they collide, folded in random orders.
|
||||
/// Removal snapshots are either constant or, as a remover would send them, a fold of some of the ops before.
|
||||
/// Along the way, restoring what each op overwrote gives back the registry it applied to.
|
||||
#[test]
|
||||
fn a_set_of_ops_folds_to_one_registry_in_any_order() {
|
||||
use crate::{Implementation, Priority, ResourceEntry, SourceKey, SourceValue, UserId};
|
||||
@@ -999,11 +1030,18 @@ fn a_set_of_ops_folds_to_one_registry_in_any_order() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Folds the ops in order.
|
||||
fn fold(ops: &[(RegistryDelta, TimeStamp)]) -> crate::Registry {
|
||||
/// Folds the ops in the order given; an op naming an entity not yet seen lands on a placeholder, so every op lands.
|
||||
/// `check_restore` also restores each op's priors on a copy and compares it with the registry the op applied to.
|
||||
fn fold(ops: &[(RegistryDelta, TimeStamp)], check_restore: bool) -> crate::Registry {
|
||||
let mut document = fresh_document(PeerId(9));
|
||||
for (op, at) in ops {
|
||||
let before = check_restore.then(|| (document.working_registry.clone(), crate::prior::capture(&document.working_registry, op)));
|
||||
document.apply_op_idempotent(op.clone(), *at).unwrap_or_else(|error| panic!("{op:?} at {at:?}: {error}"));
|
||||
if let Some((registry, priors)) = before {
|
||||
let mut restored = document.working_registry.clone();
|
||||
crate::prior::restore(&mut restored, &priors);
|
||||
assert_eq!(restored, registry, "restoring what {op:?} overwrote");
|
||||
}
|
||||
}
|
||||
document.working_registry
|
||||
}
|
||||
@@ -1033,24 +1071,15 @@ fn a_set_of_ops_folds_to_one_registry_in_any_order() {
|
||||
};
|
||||
// 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<_>>());
|
||||
let saw = |rng: &mut Lcg| fold(&seen.iter().filter(|_| rng.below(2) == 0).cloned().collect::<Vec<_>>(), false);
|
||||
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() },
|
||||
}
|
||||
}
|
||||
0 => RegistryDelta::AddNetwork {
|
||||
id: network_id,
|
||||
network: Network::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 })
|
||||
snapshot.map_or(RegistryDelta::EndTransaction, |snapshot| RegistryDelta::RemoveNetwork { id: network_id, snapshot })
|
||||
}
|
||||
2 | 3 => RegistryDelta::AddNode {
|
||||
id: node_id,
|
||||
@@ -1059,7 +1088,7 @@ fn a_set_of_ops_folds_to_one_registry_in_any_order() {
|
||||
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 })
|
||||
snapshot.map_or(RegistryDelta::EndTransaction, |snapshot| RegistryDelta::RemoveNode { id: node_id, snapshot })
|
||||
}
|
||||
5 | 6 => RegistryDelta::ChangeNodeInput {
|
||||
id: node_id,
|
||||
@@ -1069,27 +1098,11 @@ fn a_set_of_ops_folds_to_one_registry_in_any_order() {
|
||||
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
|
||||
.map(|_| InputSlot {
|
||||
input: input(rng),
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
attributes: Default::default(),
|
||||
attributes_timestamp: TimeStamp::ORIGIN,
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
@@ -1125,7 +1138,7 @@ fn a_set_of_ops_folds_to_one_registry_in_any_order() {
|
||||
} else {
|
||||
Some(ResourceEntry::default())
|
||||
};
|
||||
snapshot.map_or(RegistryDelta::Other(Value::None), |snapshot| RegistryDelta::RemoveResource { id: resource_id, snapshot })
|
||||
snapshot.map_or(RegistryDelta::EndTransaction, |snapshot| RegistryDelta::RemoveResource { id: resource_id, snapshot })
|
||||
}
|
||||
13 => RegistryDelta::SetResourceHash {
|
||||
id: resource_id,
|
||||
@@ -1181,22 +1194,29 @@ fn a_set_of_ops_folds_to_one_registry_in_any_order() {
|
||||
ops.push((op, at));
|
||||
}
|
||||
|
||||
let reference = fold(&ops);
|
||||
let reference = fold(&ops, true);
|
||||
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:?}");
|
||||
assert_eq!(
|
||||
fold(&shuffled, false),
|
||||
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.
|
||||
/// A removal's snapshot carries the addition's stamps, and an entry stamped at its map's floor was written by
|
||||
/// the op that set the floor, so folding the snapshot keeps it. Pins a revived node losing `reflection_metadata`.
|
||||
#[test]
|
||||
fn a_removal_snapshot_keeps_the_attributes_the_addition_wrote() {
|
||||
use crate::{AttributesRead, AttributesWrite};
|
||||
|
||||
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);
|
||||
@@ -1225,8 +1245,10 @@ fn a_removal_snapshot_keeps_the_attributes_the_addition_wrote() {
|
||||
assert_eq!(replayed.working_registry, document.working_registry);
|
||||
}
|
||||
|
||||
/// An op rejected partway leaves the registry as it was, including the nodes it references, which a landed op
|
||||
/// would bring back.
|
||||
#[test]
|
||||
fn a_refused_replayed_op_changes_nothing() {
|
||||
fn a_rejected_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);
|
||||
@@ -1248,137 +1270,3 @@ fn a_refused_replayed_op_changes_nothing() {
|
||||
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,6 +650,7 @@ 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;
|
||||
|
||||
@@ -716,6 +717,7 @@ 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;
|
||||
|
||||
@@ -756,12 +758,13 @@ fn cyclic_network_reference_is_rejected() {
|
||||
crate::NodeId(0),
|
||||
Node {
|
||||
presence: Default::default(),
|
||||
network_timestamp: Default::default(),
|
||||
added: Default::default(),
|
||||
inputs_timestamp: Default::default(),
|
||||
implementation: Implementation::Network(child_network_id),
|
||||
implementation_timestamp: Default::default(),
|
||||
inputs: Vec::new(),
|
||||
attributes: crate::Attributes::default(),
|
||||
attributes_timestamp: Default::default(),
|
||||
network: crate::ROOT_NETWORK,
|
||||
},
|
||||
);
|
||||
@@ -769,12 +772,13 @@ fn cyclic_network_reference_is_rejected() {
|
||||
crate::NodeId(1),
|
||||
Node {
|
||||
presence: Default::default(),
|
||||
network_timestamp: Default::default(),
|
||||
added: Default::default(),
|
||||
inputs_timestamp: Default::default(),
|
||||
implementation: Implementation::Network(crate::ROOT_NETWORK),
|
||||
implementation_timestamp: Default::default(),
|
||||
inputs: Vec::new(),
|
||||
attributes: crate::Attributes::default(),
|
||||
attributes_timestamp: Default::default(),
|
||||
network: child_network_id,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -10,7 +10,7 @@ use rustc_hash::{FxHashMap, FxHashSet};
|
||||
|
||||
use crate::attr::*;
|
||||
use crate::metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry};
|
||||
use crate::{Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId, Value, from_value};
|
||||
use crate::{AttributesRead, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId, Value, from_value};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ConversionError {
|
||||
@@ -255,7 +255,6 @@ fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[R
|
||||
let locked = node.attributes.get_or(node::ui::LOCKED, false);
|
||||
let pinned = node.attributes.get_or(node::ui::PINNED, false);
|
||||
let output_names: Vec<String> = node.attributes.get_or_default(node::ui::OUTPUT_NAMES);
|
||||
let output_descriptions: Vec<String> = node.attributes.get_or_default(node::ui::OUTPUT_DESCRIPTIONS);
|
||||
|
||||
let input_metadata: Vec<InputMetadataEntry> = node.inputs.iter().map(|slot| &slot.attributes).map(extract_input_metadata).collect();
|
||||
|
||||
@@ -270,7 +269,6 @@ fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[R
|
||||
pinned,
|
||||
input_metadata,
|
||||
output_names,
|
||||
output_descriptions,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -300,8 +298,7 @@ fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes,
|
||||
|
||||
/// Reassembles `input_data` by scanning every attribute under `ui::input_data::` and stripping the prefix.
|
||||
fn extract_input_metadata(attributes: &crate::Attributes) -> InputMetadataEntry {
|
||||
let input_data: HashMap<String, Value> = attributes
|
||||
.live()
|
||||
let input_data: HashMap<String, Value> = crate::attributes::live(attributes)
|
||||
.filter_map(|(key, value)| key.strip_prefix(node::input::ui::DATA_PREFIX).map(|sub_key| (sub_key.to_owned(), value.value.clone())))
|
||||
.collect();
|
||||
|
||||
@@ -343,14 +340,13 @@ 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 } => {
|
||||
// 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.
|
||||
// A node removed concurrently keeps its id, as the editor holds a dangling input; only a node
|
||||
// never seen has no id to map to.
|
||||
let referenced = registry.node_or_removed(*node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
|
||||
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 !placeholder && referenced.network != network_id {
|
||||
if referenced.network != network_id {
|
||||
return Err(ConversionError::CrossNetworkReference {
|
||||
network: network_id,
|
||||
referenced: *node_id,
|
||||
|
||||
@@ -30,7 +30,6 @@ interpreted-executor = { workspace = true }
|
||||
graphene-std = { workspace = true } # NOTE: `core-types` should not be added here because `graphene-std` re-exports its contents
|
||||
preprocessor = { workspace = true }
|
||||
math-parser = { workspace = true }
|
||||
snapping = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
js-sys = { workspace = true }
|
||||
|
||||
+6
-10
@@ -37,11 +37,15 @@ 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 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.;
|
||||
/// These are layers whose bounding boxes are used for alignment.
|
||||
pub const MAX_ALIGNMENT_CANDIDATES: usize = 100;
|
||||
/// These are layers that are used for the layer snapper.
|
||||
pub const MAX_SNAP_CANDIDATES: usize = 10;
|
||||
/// These are points (anchors and bounding box corners etc.) in the layer snapper.
|
||||
pub const MAX_LAYER_SNAP_POINTS: usize = 100;
|
||||
|
||||
pub const DRAG_THRESHOLD: f64 = 1.;
|
||||
|
||||
@@ -183,14 +187,6 @@ 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;
|
||||
|
||||
// FONTS
|
||||
/// How long a font catalog request may go unanswered before another can be sent.
|
||||
pub const FONT_CATALOG_REQUEST_TIMEOUT_MILLISECONDS: u64 = 60_000;
|
||||
/// How long to wait after a failed font catalog request before sending another.
|
||||
pub const FONT_CATALOG_RETRY_DELAY_MILLISECONDS: u64 = 10_000;
|
||||
|
||||
// UI
|
||||
pub const UI_SCALE_DEFAULT: f64 = 1.;
|
||||
|
||||
+14
-76
@@ -2,7 +2,6 @@ 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::*;
|
||||
@@ -57,35 +56,24 @@ impl DispatcherMessageHandlers {
|
||||
}
|
||||
}
|
||||
|
||||
/// For optimization, these messages are deferred to the end of the outermost queue, where equal copies are dropped.
|
||||
/// Each must only refresh a cache, a layout, the frontend, or a render from the current state, so one run at the end matches running every copy.
|
||||
/// For optimization, these are messages guaranteed to be redundant when repeated.
|
||||
/// The last occurrence of the message in the message queue is sufficient to ensure correct behavior.
|
||||
/// In addition, these messages do not change any state in the backend (aside from caches).
|
||||
const SIDE_EFFECT_FREE_MESSAGES: &[MessageDiscriminant] = &[
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::DocumentStructureChanged)),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
|
||||
NodeGraphMessageDiscriminant::RunDocumentGraph,
|
||||
))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
|
||||
NodeGraphMessageDiscriminant::UpdateLayerPanel,
|
||||
))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(NodeGraphMessageDiscriminant::SendWires))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
|
||||
NodeGraphMessageDiscriminant::UpdateVisibleNodes,
|
||||
))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
|
||||
NodeGraphMessageDiscriminant::SendSelectedNodes,
|
||||
))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
|
||||
NodeGraphMessageDiscriminant::UpdateGraphBarRight,
|
||||
))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::SubmitActiveGraphRender),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::SubmitEyedropperPreviewRender),
|
||||
MessageDiscriminant::MenuBar(MenuBarMessageDiscriminant::SendLayout),
|
||||
MessageDiscriminant::Frontend(FrontendMessageDiscriminant::UpdateUIScale),
|
||||
];
|
||||
/// Since we don't need to update the frontend multiple times per frame,
|
||||
/// we have a set of messages which we will buffer until the next frame is requested.
|
||||
const FRONTEND_UPDATE_MESSAGES: &[MessageDiscriminant] = &[
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::Inspector(InspectorMessageDiscriminant::Refresh))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::PropertiesPanel(
|
||||
PropertiesPanelMessageDiscriminant::Refresh,
|
||||
))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::UpdateDocumentWidgets),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::Overlays(OverlaysMessageDiscriminant::Draw))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::RenderRulers)),
|
||||
@@ -96,7 +84,6 @@ const DEBUG_MESSAGE_BLOCK_LIST: &[MessageDiscriminant] = &[
|
||||
MessageDiscriminant::Broadcast(BroadcastMessageDiscriminant::TriggerEvent(EventMessageDiscriminant::AnimationFrame)),
|
||||
MessageDiscriminant::Animation(AnimationMessageDiscriminant::IncrementFrameCounter),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::AutoSaveAllDocuments),
|
||||
MessageDiscriminant::Tool(ToolMessageDiscriminant::SnappingTick),
|
||||
];
|
||||
// TODO: Find a way to combine these with the list above. We use strings for now since these are the standard variant names used by multiple messages. But having these also type-checked would be best.
|
||||
const DEBUG_MESSAGE_ENDING_BLOCK_LIST: &[&str] = &["PointerMove", "PointerOutsideViewport", "Overlays", "Draw", "CurrentTime", "Time"];
|
||||
@@ -271,7 +258,6 @@ 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,
|
||||
@@ -287,7 +273,7 @@ impl Dispatcher {
|
||||
let layout = &self.message_handlers.portfolio_message_handler.workspace.panel_layout;
|
||||
menu_bar_message_handler.data_panel_open = layout.is_panel_present(PanelType::Data);
|
||||
menu_bar_message_handler.layers_panel_open = layout.is_panel_present(PanelType::Layers);
|
||||
menu_bar_message_handler.inspector_open = layout.is_panel_present(PanelType::Inspector);
|
||||
menu_bar_message_handler.properties_panel_open = layout.is_panel_present(PanelType::Properties);
|
||||
menu_bar_message_handler.message_logging_verbosity = self.message_handlers.debug_message_handler.message_logging_verbosity;
|
||||
menu_bar_message_handler.reset_node_definitions_on_open = self.message_handlers.portfolio_message_handler.reset_node_definitions_on_open;
|
||||
menu_bar_message_handler.show_storage_preferences = self.message_handlers.preferences_message_handler.show_storage_preferences;
|
||||
@@ -298,45 +284,26 @@ 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_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();
|
||||
let selected_nodes = document.network_interface.selected_nodes();
|
||||
let metadata = &document.network_interface.document_network_metadata().persistent_metadata;
|
||||
|
||||
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 = 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_selected_layers = selected_nodes.selected_visible_layers(&document.network_interface).next().is_some();
|
||||
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 = in_document_network && make_path_editable_is_allowed(&mut document.network_interface).is_some();
|
||||
menu_bar_message_handler.make_path_editable_is_allowed = 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;
|
||||
}
|
||||
@@ -353,13 +320,11 @@ impl Dispatcher {
|
||||
Message::Tool(message) => {
|
||||
let Some(document_id) = self.message_handlers.portfolio_message_handler.active_document_id() else {
|
||||
warn!("Called ToolMessage without an active document.\nGot {message:?}");
|
||||
self.cleanup_queues(false);
|
||||
continue;
|
||||
return;
|
||||
};
|
||||
let Some(document) = self.message_handlers.portfolio_message_handler.documents.get_mut(&document_id) else {
|
||||
warn!("Called ToolMessage with an invalid active document.\nGot {message:?}");
|
||||
self.cleanup_queues(false);
|
||||
continue;
|
||||
return;
|
||||
};
|
||||
|
||||
let context = ToolMessageContext {
|
||||
@@ -468,33 +433,6 @@ mod test {
|
||||
use crate::messages::portfolio::ingest::utility_types::IngestAction;
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn switching_documents_and_tools_does_not_add_event_listeners() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let first_document = editor.portfolio_message_handler().active_document_id().unwrap();
|
||||
editor.new_document().await;
|
||||
let second_document = editor.portfolio_message_handler().active_document_id().unwrap();
|
||||
editor.select_tool(ToolType::Select).await;
|
||||
|
||||
let listener_count = |editor: &EditorTestUtils| editor.editor.dispatcher.message_handlers.broadcast_message_handler.listener_count();
|
||||
let initial_listener_count = listener_count(&editor);
|
||||
|
||||
for _ in 0..3 {
|
||||
for document_id in [first_document, second_document] {
|
||||
editor.handle_message(PortfolioMessage::SelectDocument { document_id }).await;
|
||||
}
|
||||
editor.select_tool(ToolType::Path).await;
|
||||
editor.select_tool(ToolType::Select).await;
|
||||
|
||||
// Last, since a document switch would restore anything the graph's opening and closing drop
|
||||
editor.handle_message(DocumentMessage::GraphViewOverlayToggle).await;
|
||||
editor.handle_message(DocumentMessage::GraphViewOverlayToggle).await;
|
||||
}
|
||||
|
||||
assert_eq!(listener_count(&editor), initial_listener_count);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
/// This test will fail when you make changes to the underlying serialization format for a document.
|
||||
async fn check_if_demo_art_opens() {
|
||||
@@ -552,7 +490,7 @@ mod test {
|
||||
});
|
||||
|
||||
// Check if the graph renders
|
||||
if let Err(e) = editor.eval_graph_until_finished().await {
|
||||
if let Err(e) = editor.eval_graph().await {
|
||||
print_problem_to_terminal_on_failure(&format!("Failed to evaluate the graph for document '{document_name}':\n{e}"));
|
||||
}
|
||||
|
||||
|
||||
@@ -14,13 +14,7 @@ impl MessageHandler<BroadcastMessage, ()> for BroadcastMessageHandler {
|
||||
BroadcastMessage::TriggerEvent(message) => self.event.process_message(message, responses, EventMessageContext { listeners: &mut self.listeners }),
|
||||
|
||||
// Messages
|
||||
BroadcastMessage::SubscribeEvent { on, send } => {
|
||||
// Skip an existing listener, since some are subscribed again on every document switch
|
||||
let listeners = self.listeners.entry(on).or_default();
|
||||
if !listeners.contains(&send) {
|
||||
listeners.push(*send);
|
||||
}
|
||||
}
|
||||
BroadcastMessage::SubscribeEvent { on, send } => self.listeners.entry(on).or_default().push(*send),
|
||||
BroadcastMessage::UnsubscribeEvent { on, send } => self.listeners.entry(on).or_default().retain(|msg| *msg != *send),
|
||||
}
|
||||
}
|
||||
@@ -29,10 +23,3 @@ impl MessageHandler<BroadcastMessage, ()> for BroadcastMessageHandler {
|
||||
actions!(EventMessageDiscriminant;)
|
||||
}
|
||||
}
|
||||
|
||||
impl BroadcastMessageHandler {
|
||||
#[cfg(test)]
|
||||
pub fn listener_count(&self) -> usize {
|
||||
self.listeners.values().map(Vec::len).sum()
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
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;
|
||||
@@ -80,18 +79,23 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
}
|
||||
|
||||
ClipboardMessage::CopyLayers => {
|
||||
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() {
|
||||
if current_tool == &ToolType::Path {
|
||||
responses.add(PathToolMessage::Copy);
|
||||
return;
|
||||
}
|
||||
|
||||
let SelectionParts { layers, chain_nodes, other_nodes } = active_document.partition_selection();
|
||||
let mut items = Vec::new();
|
||||
let Some(active_document) = portfolio.active_document_id.and_then(|id| portfolio.documents.get_mut(&id)) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let mut ordered_last_elements = layers;
|
||||
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<_>>();
|
||||
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)
|
||||
@@ -119,69 +123,38 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
.collect::<Vec<_>>();
|
||||
tree_path.reverse();
|
||||
|
||||
items.push(ClipboardItem::Layer(ClipboardLayer {
|
||||
buffer.push(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),
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
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 });
|
||||
responses.add(ClipboardMessage::WriteItems {
|
||||
items: buffer.into_iter().map(ClipboardItem::Layer).collect(),
|
||||
});
|
||||
}
|
||||
ClipboardMessage::CutLayers => {
|
||||
let Some(active_document) = portfolio.active_document() else { return };
|
||||
|
||||
if current_tool == &ToolType::Path && !active_document.graph_view_overlay_open() {
|
||||
if current_tool == &ToolType::Path {
|
||||
responses.add(PathToolMessage::Cut);
|
||||
return;
|
||||
}
|
||||
|
||||
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() {
|
||||
if let Some(active_document) = portfolio.active_document()
|
||||
&& active_document.graph_view_overlay_open()
|
||||
{
|
||||
responses.add(NodeGraphMessage::Cut);
|
||||
return;
|
||||
}
|
||||
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);
|
||||
|
||||
responses.add(ClipboardMessage::CopyLayers);
|
||||
responses.add(DocumentMessage::DeleteSelectedLayers);
|
||||
}
|
||||
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,
|
||||
});
|
||||
@@ -194,7 +167,6 @@ 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(_) => {}
|
||||
}
|
||||
}
|
||||
@@ -255,7 +227,6 @@ 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 {
|
||||
@@ -273,12 +244,6 @@ 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),
|
||||
}
|
||||
@@ -314,10 +279,7 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
responses.add(ClipboardMessage::PasteLayers { entries: layers });
|
||||
}
|
||||
for nodes in node_groups {
|
||||
responses.add(DocumentMessage::PasteNodes { nodes });
|
||||
}
|
||||
for copies in chain_node_groups {
|
||||
responses.add(DocumentMessage::PasteChainNodes { copies });
|
||||
responses.add(NodeGraphMessage::InsertNodes { nodes });
|
||||
}
|
||||
for paths in vectors {
|
||||
responses.add(ClipboardMessage::PasteVectors { paths });
|
||||
@@ -340,6 +302,7 @@ 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;
|
||||
@@ -358,6 +321,8 @@ 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 });
|
||||
|
||||
@@ -386,24 +351,22 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet {
|
||||
nodes: layers.iter().map(|layer| layer.to_node()).collect(),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: all_new_ids });
|
||||
responses.add(DeferMessage::AfterGraphRun {
|
||||
messages: vec![PortfolioMessage::CenterLayers { layers }.into()],
|
||||
});
|
||||
}
|
||||
}
|
||||
ClipboardMessage::PasteVectors { paths } => {
|
||||
// The Path tool pastes points into the path it's editing in the viewport
|
||||
// If using Path tool then send the operation to Path tool
|
||||
// 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 && portfolio.active_document().is_some_and(|document| !document.graph_view_overlay_open()) {
|
||||
if *current_tool == ToolType::Path {
|
||||
responses.add(PathToolMessage::Paste { paths });
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, create new layers and add paths into those
|
||||
// If not using Path tool, 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::{ChainNodeCopy, NodeTemplate};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64;
|
||||
use glam::DAffine2;
|
||||
@@ -27,8 +27,6 @@ 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,11 +107,7 @@ 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 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 gradient = Gradient::from(ramp);
|
||||
let first_color = gradient.color(0).unwrap_or(Color::BLACK);
|
||||
self.gradient = Some(gradient);
|
||||
self.adopt_color(first_color);
|
||||
@@ -827,6 +823,7 @@ fn rgb_input(channel: RgbChannel, value: Option<f64>, tooltip_label: &'static st
|
||||
.disabled(disabled)
|
||||
.min(0.)
|
||||
.max(255.)
|
||||
.min_width(1)
|
||||
.display_decimal_places(0)
|
||||
.tooltip_label(tooltip_label)
|
||||
.tooltip_description("Integers 0–255.")
|
||||
@@ -840,6 +837,7 @@ fn hsv_input(channel: HsvChannel, value: Option<f64>, max: f64, unit: &'static s
|
||||
.disabled(disabled)
|
||||
.min(0.)
|
||||
.max(max)
|
||||
.min_width(1)
|
||||
.unit(unit)
|
||||
.display_decimal_places(1)
|
||||
.tooltip_label(tooltip_label)
|
||||
|
||||
@@ -123,16 +123,13 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
||||
.collect();
|
||||
|
||||
let export_type = vec![
|
||||
TextLabel::new("File Type").table_align(true).sizing(WidgetSizing::fixed(100)).widget_instance(),
|
||||
TextLabel::new("File Type").table_align(true).min_width(100).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
DropdownInput::new(entries)
|
||||
.selected_index(selected_index.map(|index| index as u32))
|
||||
.sizing(WidgetSizing::default().min_width(200))
|
||||
.widget_instance(),
|
||||
DropdownInput::new(entries).selected_index(selected_index.map(|index| index as u32)).min_width(200).widget_instance(),
|
||||
];
|
||||
|
||||
let resolution = vec![
|
||||
TextLabel::new("Scale Factor").table_align(true).sizing(WidgetSizing::fixed(100)).widget_instance(),
|
||||
TextLabel::new("Scale Factor").table_align(true).min_width(100).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(self.scale_factor))
|
||||
.unit("")
|
||||
@@ -141,7 +138,7 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
||||
.increment_step(0.5)
|
||||
.disabled(self.file_type == FileType::Svg)
|
||||
.on_update(|number_input: &NumberInput| ExportDialogMessage::ScaleFactor { factor: number_input.value.unwrap() }.into())
|
||||
.sizing(WidgetSizing::default().min_width(200))
|
||||
.min_width(200)
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
@@ -180,7 +177,7 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
||||
}
|
||||
|
||||
let export_area = vec![
|
||||
TextLabel::new("Bounds").table_align(true).sizing(WidgetSizing::fixed(100)).widget_instance(),
|
||||
TextLabel::new("Bounds").table_align(true).min_width(100).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
DropdownInput::new(entries).selected_index(Some(index as u32)).widget_instance(),
|
||||
];
|
||||
|
||||
+24
-13
@@ -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,7 +26,23 @@ impl MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHa
|
||||
|
||||
if self.infinite {
|
||||
// Infinite canvas: add a locked white background layer
|
||||
graph_modification_utils::new_background_layer(0, responses);
|
||||
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,
|
||||
});
|
||||
} else if self.dimensions.x > 0 && self.dimensions.y > 0 {
|
||||
// Finite canvas: create an artboard with the specified dimensions
|
||||
responses.add(GraphOperationMessage::NewArtboard {
|
||||
@@ -84,22 +100,17 @@ impl DialogLayoutHolder for NewDocumentDialogMessageHandler {
|
||||
impl LayoutHolder for NewDocumentDialogMessageHandler {
|
||||
fn layout(&self) -> Layout {
|
||||
let name = vec![
|
||||
TextLabel::new("Name").table_align(true).sizing(WidgetSizing::fixed(90)).widget_instance(),
|
||||
TextLabel::new("Name").table_align(true).min_width(90).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextInput::new(&self.name)
|
||||
.on_update(|text_input: &TextInput| NewDocumentDialogMessage::Name { name: text_input.value.clone() }.into())
|
||||
// Matches the 100px of both NumberInputs below plus the 4px of the Related-type separator between them
|
||||
.sizing(WidgetSizing::default().min_width(204))
|
||||
.min_width(204) // Matches the 100px of both NumberInputs below + the 4px of the Unrelated-type separator
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let checkbox_id = CheckboxId::new();
|
||||
let infinite = vec![
|
||||
TextLabel::new("Infinite Canvas")
|
||||
.table_align(true)
|
||||
.sizing(WidgetSizing::fixed(90))
|
||||
.for_checkbox(checkbox_id)
|
||||
.widget_instance(),
|
||||
TextLabel::new("Infinite Canvas").table_align(true).min_width(90).for_checkbox(checkbox_id).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
CheckboxInput::new(self.infinite)
|
||||
.on_update(|checkbox_input: &CheckboxInput| NewDocumentDialogMessage::Infinite { infinite: checkbox_input.checked }.into())
|
||||
@@ -108,7 +119,7 @@ impl LayoutHolder for NewDocumentDialogMessageHandler {
|
||||
];
|
||||
|
||||
let scale = vec![
|
||||
TextLabel::new("Dimensions").table_align(true).sizing(WidgetSizing::fixed(90)).widget_instance(),
|
||||
TextLabel::new("Dimensions").table_align(true).min_width(90).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(self.dimensions.x as f64))
|
||||
.label("W")
|
||||
@@ -117,7 +128,7 @@ impl LayoutHolder for NewDocumentDialogMessageHandler {
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.is_integer(true)
|
||||
.disabled(self.infinite)
|
||||
.sizing(WidgetSizing::default().min_width(100))
|
||||
.min_width(100)
|
||||
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsX { width: number_input.value.unwrap() }.into())
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
@@ -128,7 +139,7 @@ impl LayoutHolder for NewDocumentDialogMessageHandler {
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.is_integer(true)
|
||||
.disabled(self.infinite)
|
||||
.sizing(WidgetSizing::default().min_width(100))
|
||||
.min_width(100)
|
||||
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsY { height: number_input.value.unwrap() }.into())
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
@@ -177,7 +177,6 @@ impl PreferencesDialogMessageHandler {
|
||||
}),
|
||||
])
|
||||
.selected_index(Some(preferences.selection_mode as u32))
|
||||
.sizing(WidgetSizing::default().shrink(false))
|
||||
.widget_instance();
|
||||
let selection_mode = vec![
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
@@ -267,7 +266,6 @@ impl PreferencesDialogMessageHandler {
|
||||
.on_update(move |_| PreferencesMessage::GraphWireStyle { style: GraphWireStyle::GridAligned }.into()),
|
||||
])
|
||||
.selected_index(Some(preferences.graph_wire_style as u32))
|
||||
.sizing(WidgetSizing::default().shrink(false))
|
||||
.widget_instance();
|
||||
let graph_wire_style = vec![
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
|
||||
@@ -51,13 +51,7 @@ impl LayoutHolder for DemoArtworkDialog {
|
||||
|
||||
let buttons = chunk
|
||||
.iter()
|
||||
.map(|(name, _, filename)| {
|
||||
TextButton::new(*name)
|
||||
.sizing(WidgetSizing::default().min_width(256))
|
||||
.flush(true)
|
||||
.on_update(|_| make_dialog(name, filename))
|
||||
.widget_instance()
|
||||
})
|
||||
.map(|(name, _, filename)| TextButton::new(*name).min_width(256).flush(true).on_update(|_| make_dialog(name, filename)).widget_instance())
|
||||
.collect();
|
||||
|
||||
vec![LayoutGroup::row(images), LayoutGroup::row(buttons), LayoutGroup::row(vec![])]
|
||||
|
||||
@@ -3,7 +3,6 @@ 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,
|
||||
@@ -68,8 +67,6 @@ 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>,
|
||||
},
|
||||
@@ -210,23 +207,6 @@ 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,8 +16,6 @@ pub enum InputMapperMessage {
|
||||
KeyUpNoRepeat(Key),
|
||||
#[child]
|
||||
DoubleClick(MouseButton),
|
||||
#[child]
|
||||
DoubleTap(Key),
|
||||
|
||||
// Messages
|
||||
PointerMove,
|
||||
|
||||
@@ -40,7 +40,6 @@ 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());
|
||||
@@ -70,7 +69,6 @@ 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]),
|
||||
_ => (),
|
||||
}
|
||||
|
||||
|
||||
@@ -105,10 +105,10 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
entry!(KeyDown(Minus); action_dispatch=TransformLayerMessage::TypeNegate),
|
||||
entry!(KeyDown(Comma); action_dispatch=TransformLayerMessage::TypeDecimalPoint),
|
||||
entry!(KeyDown(Period); action_dispatch=TransformLayerMessage::TypeDecimalPoint),
|
||||
entry!(PointerMove; refresh_keys=[Control, Shift, Alt, KeyQ, KeyW], action_dispatch=TransformLayerMessage::PointerMove { slow_key: Shift, increments_key: Control }),
|
||||
entry!(PointerMove; refresh_keys=[Control, Shift], action_dispatch=TransformLayerMessage::PointerMove { slow_key: Shift, increments_key: Control }),
|
||||
//
|
||||
// SelectToolMessage
|
||||
entry!(PointerMove; refresh_keys=[Control, Alt, Shift, KeyQ, KeyW], action_dispatch=SelectToolMessage::PointerMove { modifier_keys: SelectToolPointerKeys { axis_align: Shift, snap_angle: Shift, center: Alt, duplicate: Alt } }),
|
||||
entry!(PointerMove; refresh_keys=[Control, Alt, Shift], action_dispatch=SelectToolMessage::PointerMove { modifier_keys: SelectToolPointerKeys { axis_align: Shift, snap_angle: Shift, center: Alt, duplicate: Alt } }),
|
||||
entry!(KeyDown(MouseLeft); action_dispatch=SelectToolMessage::DragStart { extend_selection: Shift, remove_from_selection: Alt, select_deepest: Accel, lasso_select: Control, skew: Control }),
|
||||
entry!(KeyUp(MouseLeft); action_dispatch=SelectToolMessage::DragStop { remove_from_selection: Alt }),
|
||||
entry!(KeyDown(Enter); action_dispatch=SelectToolMessage::Enter),
|
||||
@@ -118,7 +118,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
//
|
||||
// ArtboardToolMessage
|
||||
entry!(KeyDown(MouseLeft); action_dispatch=ArtboardToolMessage::PointerDown),
|
||||
entry!(PointerMove; refresh_keys=[Shift, Alt, KeyQ, KeyW], action_dispatch=ArtboardToolMessage::PointerMove { constrain_axis_or_aspect: Shift, center: Alt }),
|
||||
entry!(PointerMove; refresh_keys=[Shift, Alt], action_dispatch=ArtboardToolMessage::PointerMove { constrain_axis_or_aspect: Shift, center: Alt }),
|
||||
entry!(KeyUp(MouseLeft); action_dispatch=ArtboardToolMessage::PointerUp),
|
||||
entry!(KeyDown(Delete); action_dispatch=ArtboardToolMessage::DeleteSelected),
|
||||
entry!(KeyDown(Backspace); action_dispatch=ArtboardToolMessage::DeleteSelected),
|
||||
@@ -166,7 +166,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
entry!(KeyDown(Escape); action_dispatch=EyedropperToolMessage::Abort),
|
||||
//
|
||||
// TextToolMessage
|
||||
entry!(PointerMove; refresh_keys=[Alt, Shift, KeyQ, KeyW], action_dispatch=TextToolMessage::PointerMove { center: Alt, lock_ratio: Shift }),
|
||||
entry!(PointerMove; refresh_keys=[Alt, Shift], action_dispatch=TextToolMessage::PointerMove { center: Alt, lock_ratio: Shift }),
|
||||
entry!(KeyDown(MouseLeft); action_dispatch=TextToolMessage::DragStart),
|
||||
entry!(KeyUp(MouseLeft); action_dispatch=TextToolMessage::DragStop),
|
||||
entry!(KeyDown(MouseRight); action_dispatch=TextToolMessage::Abort),
|
||||
@@ -176,7 +176,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
// GradientToolMessage
|
||||
entry!(DoubleClick(MouseButton::Left); action_dispatch=GradientToolMessage::DoubleClick),
|
||||
entry!(KeyDown(MouseLeft); action_dispatch=GradientToolMessage::PointerDown),
|
||||
entry!(PointerMove; refresh_keys=[Shift, Control, KeyQ, KeyW], action_dispatch=GradientToolMessage::PointerMove { constrain_axis: Shift, lock_angle: Control }),
|
||||
entry!(PointerMove; refresh_keys=[Shift, Control], action_dispatch=GradientToolMessage::PointerMove { constrain_axis: Shift, lock_angle: Control }),
|
||||
entry!(KeyUp(MouseLeft); action_dispatch=GradientToolMessage::PointerUp),
|
||||
entry!(KeyDown(Delete); action_dispatch=GradientToolMessage::DeleteStop),
|
||||
entry!(KeyDown(Backspace); action_dispatch=GradientToolMessage::DeleteStop),
|
||||
@@ -190,7 +190,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
entry!(KeyDown(Escape); action_dispatch=ShapeToolMessage::Abort),
|
||||
entry!(KeyDown(BracketLeft); action_dispatch=ShapeToolMessage::DecreaseSides),
|
||||
entry!(KeyDown(BracketRight); action_dispatch=ShapeToolMessage::IncreaseSides),
|
||||
entry!(PointerMove; refresh_keys=[Alt, Shift, Control, KeyQ, KeyW], action_dispatch=ShapeToolMessage::PointerMove { modifier: [Alt, Shift, Control] }),
|
||||
entry!(PointerMove; refresh_keys=[Alt, Shift, Control], action_dispatch=ShapeToolMessage::PointerMove { modifier: [Alt, Shift, Control] }),
|
||||
entry!(KeyDown(ArrowUp); modifiers=[Shift, ArrowLeft], action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: -BIG_NUDGE_AMOUNT, delta_y: -BIG_NUDGE_AMOUNT, resize: Alt, resize_opposite: Control }),
|
||||
entry!(KeyDown(ArrowUp); modifiers=[Shift, ArrowRight], action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: BIG_NUDGE_AMOUNT, delta_y: -BIG_NUDGE_AMOUNT, resize: Alt, resize_opposite: Control }),
|
||||
entry!(KeyDown(ArrowUp); modifiers=[Shift], action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: 0., delta_y: -BIG_NUDGE_AMOUNT, resize: Alt, resize_opposite: Control }),
|
||||
@@ -233,7 +233,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
entry!(KeyDown(KeyG); action_dispatch=PathToolMessage::GRS { key: KeyG }),
|
||||
entry!(KeyDown(KeyR); action_dispatch=PathToolMessage::GRS { key: KeyR }),
|
||||
entry!(KeyDown(KeyS); action_dispatch=PathToolMessage::GRS { key: KeyS }),
|
||||
entry!(PointerMove; refresh_keys=[KeyC, Space, Control, Shift, Alt, KeyQ, KeyW], action_dispatch=PathToolMessage::PointerMove { toggle_colinear: KeyC, equidistant: Alt, move_anchor_with_handles: Space, snap_angle: Shift, lock_angle: Control, delete_segment: Alt, break_colinear_molding: Alt, segment_editing_modifier: Control }),
|
||||
entry!(PointerMove; refresh_keys=[KeyC, Space, Control, Shift, Alt], action_dispatch=PathToolMessage::PointerMove { toggle_colinear: KeyC, equidistant: Alt, move_anchor_with_handles: Space, snap_angle: Shift, lock_angle: Control, delete_segment: Alt, break_colinear_molding: Alt, segment_editing_modifier: Control }),
|
||||
entry!(KeyDown(Delete); action_dispatch=PathToolMessage::Delete),
|
||||
entry!(KeyDown(KeyA); modifiers=[Accel], action_dispatch=PathToolMessage::SelectAll),
|
||||
entry!(KeyDown(KeyA); modifiers=[Accel, Shift], canonical, action_dispatch=PathToolMessage::DeselectAllSelected),
|
||||
@@ -269,7 +269,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
entry!(KeyDown(KeyJ); modifiers=[Accel], action_dispatch=ToolMessage::Path(PathToolMessage::ClosePath)),
|
||||
//
|
||||
// PenToolMessage
|
||||
entry!(PointerMove; refresh_keys=[Control, Alt, Shift, KeyC, KeyQ, KeyW], action_dispatch=PenToolMessage::PointerMove { snap_angle: Shift, break_handle: Alt, lock_angle: Control, colinear: KeyC, move_anchor_with_handles: Space }),
|
||||
entry!(PointerMove; refresh_keys=[Control, Alt, Shift, KeyC], action_dispatch=PenToolMessage::PointerMove { snap_angle: Shift, break_handle: Alt, lock_angle: Control, colinear: KeyC, move_anchor_with_handles: Space }),
|
||||
entry!(KeyDownNoRepeat(Tab); action_dispatch=PenToolMessage::SwapHandles),
|
||||
entry!(KeyDown(MouseLeft); action_dispatch=PenToolMessage::DragStart { append_to_selected: Shift }),
|
||||
entry!(KeyUp(MouseLeft); action_dispatch=PenToolMessage::DragStop),
|
||||
@@ -290,7 +290,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
entry!(KeyDown(Escape); action_dispatch=FreehandToolMessage::Abort),
|
||||
//
|
||||
// SplineToolMessage
|
||||
entry!(PointerMove; refresh_keys=[KeyQ, KeyW], action_dispatch=SplineToolMessage::PointerMove),
|
||||
entry!(PointerMove; action_dispatch=SplineToolMessage::PointerMove),
|
||||
entry!(KeyDown(MouseLeft); action_dispatch=SplineToolMessage::DragStart { append_to_selected: Shift }),
|
||||
entry!(KeyUp(MouseLeft); action_dispatch=SplineToolMessage::DragStop),
|
||||
entry!(KeyDown(MouseRight); action_dispatch=SplineToolMessage::Confirm),
|
||||
@@ -337,7 +337,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
entry!(KeyDown(Tab); action_dispatch=ToolMessage::ToggleSelectVsPath),
|
||||
//
|
||||
// DocumentMessage
|
||||
entry!(DoubleTap(Space); action_dispatch=DocumentMessage::GraphViewOverlayToggle),
|
||||
entry!(KeyDown(Space); modifiers=[Control], 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,7 +354,8 @@ 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], action_dispatch=DocumentMessage::DuplicateSelectedLayers),
|
||||
entry!(KeyDown(KeyD); modifiers=[Accel], canonical, action_dispatch=DocumentMessage::DuplicateSelectedLayers),
|
||||
entry!(KeyDown(KeyJ); 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 }),
|
||||
@@ -415,32 +416,23 @@ 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, 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(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(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, 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 }),
|
||||
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 }),
|
||||
// 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, 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!(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!(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.) }),
|
||||
@@ -471,7 +463,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 double_tap, 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 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`
|
||||
@@ -484,10 +476,6 @@ 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`
|
||||
@@ -501,7 +489,6 @@ 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,7 +119,6 @@ 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();
|
||||
@@ -139,7 +138,6 @@ 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,
|
||||
@@ -150,7 +148,7 @@ macro_rules! mapping {
|
||||
}
|
||||
)*
|
||||
|
||||
(key_up, key_down, key_up_no_repeat, key_down_no_repeat, double_click, double_tap, wheel_scroll, pointer_move, pointer_shake)
|
||||
(key_up, key_down, key_up_no_repeat, key_down_no_repeat, double_click, wheel_scroll, pointer_move, pointer_shake)
|
||||
}};
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ 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,
|
||||
@@ -37,7 +36,6 @@ 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,5 +1,4 @@
|
||||
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};
|
||||
@@ -18,18 +17,6 @@ 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]
|
||||
@@ -39,7 +26,6 @@ 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);
|
||||
@@ -59,22 +45,7 @@ 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));
|
||||
@@ -85,22 +56,9 @@ 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);
|
||||
@@ -120,7 +78,6 @@ 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);
|
||||
@@ -142,7 +99,6 @@ 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);
|
||||
@@ -237,10 +193,8 @@ 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, MouseKeys};
|
||||
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[test]
|
||||
@@ -345,310 +299,4 @@ 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,19 +35,4 @@ 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,7 +1,4 @@
|
||||
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::*;
|
||||
@@ -94,41 +91,6 @@ 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 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,7 +127,7 @@ impl LayoutMessageHandler {
|
||||
}
|
||||
}
|
||||
// A section contains more LayoutGroups which we add to the stack.
|
||||
LayoutGroup::NodeSection(NodeSection { layout, .. }) => {
|
||||
LayoutGroup::Section(WidgetSection { layout, .. }) => {
|
||||
stack.extend(layout.0.iter().enumerate().map(|(index, val)| ([widget_path.as_slice(), &[index]].concat(), val)));
|
||||
}
|
||||
LayoutGroup::Table(WidgetTable { rows, .. }) => {
|
||||
@@ -358,29 +320,6 @@ 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 {
|
||||
@@ -435,14 +374,6 @@ impl LayoutMessageHandler {
|
||||
_ => {}
|
||||
},
|
||||
},
|
||||
Widget::ParameterChainToggle(parameter_chain_toggle) => {
|
||||
let callback_message = match action {
|
||||
WidgetValueAction::Commit => (parameter_chain_toggle.on_commit.callback)(&()),
|
||||
WidgetValueAction::Update => (parameter_chain_toggle.on_update.callback)(parameter_chain_toggle),
|
||||
};
|
||||
|
||||
responses.add(callback_message);
|
||||
}
|
||||
Widget::ParameterExposeButton(parameter_expose_button) => {
|
||||
let callback_message = match action {
|
||||
WidgetValueAction::Commit => (parameter_expose_button.on_commit.callback)(&()),
|
||||
|
||||
@@ -2,9 +2,7 @@ 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;
|
||||
@@ -60,18 +58,18 @@ define_layout_target!(
|
||||
DialogColumn2,
|
||||
/// Contains the widgets located directly above the canvas to the right, for example the zoom in and out buttons.
|
||||
DocumentBar,
|
||||
/// 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,
|
||||
/// Controls for adding, grouping, and deleting layers at the bottom of the Layers panel.
|
||||
LayersPanelBottomBar,
|
||||
/// 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.
|
||||
NodeGraphControlBar,
|
||||
/// The body of the Inspector containing many collapsable sections.
|
||||
Inspector,
|
||||
/// The body of the Properties panel containing many collapsable sections.
|
||||
PropertiesPanel,
|
||||
/// The contextual input key/mouse combination shortcuts shown in the status bar at the bottom of the window.
|
||||
StatusBarHints,
|
||||
/// The version information shown in the status bar at the bottom right of the window.
|
||||
@@ -149,23 +147,6 @@ 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();
|
||||
@@ -295,7 +276,7 @@ impl<'a> Iterator for WidgetIter<'a> {
|
||||
self.table.extend(rows.iter().flatten().flatten().rev());
|
||||
self.next()
|
||||
}
|
||||
Some(LayoutGroup::NodeSection(NodeSection { layout, .. })) => {
|
||||
Some(LayoutGroup::Section(WidgetSection { layout, .. })) => {
|
||||
for layout_row in &layout.0 {
|
||||
self.stack.push(layout_row);
|
||||
}
|
||||
@@ -347,7 +328,7 @@ impl<'a> Iterator for WidgetIterMut<'a> {
|
||||
self.table.extend(rows.iter_mut().flatten().flatten().rev());
|
||||
self.next()
|
||||
}
|
||||
Some(LayoutGroup::NodeSection(NodeSection { layout, .. })) => {
|
||||
Some(LayoutGroup::Section(WidgetSection { layout, .. })) => {
|
||||
for layout_row in &mut layout.0 {
|
||||
self.stack.push(layout_row);
|
||||
}
|
||||
@@ -364,7 +345,7 @@ pub enum LayoutGroup {
|
||||
Column(WidgetColumn),
|
||||
Row(WidgetRow),
|
||||
Table(WidgetTable),
|
||||
NodeSection(NodeSection),
|
||||
Section(WidgetSection),
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -390,47 +371,25 @@ pub struct WidgetTable {
|
||||
pub unstyled: bool,
|
||||
}
|
||||
|
||||
/// A wire drawn between Inspector 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 Inspector section for a single node: a header with its name and pin, delete, and visibility controls, above its input parameter widgets.
|
||||
/// 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 NodeSection {
|
||||
/// The node's name shown in the section header: its implementation name, followed in parentheses by its given alias if it has one.
|
||||
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).
|
||||
pub visible: bool,
|
||||
/// Whether the node is pinned, keeping its section shown in the Inspector when nothing is selected (shown as the pin icon).
|
||||
/// Whether the node is pinned, keeping its section shown in the Properties panel when nothing is selected (shown as the pin icon).
|
||||
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 section showing the chain feeding one of its inputs, the wire drawn up into that input from the chain's sections within it (none when it shows no chain).
|
||||
#[serde(rename = "chainWire")]
|
||||
pub chain_wire: Option<SectionWire>,
|
||||
/// For a section in the chain feeding another section's input, 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 only refers to its node with a row like the Data panel's, in place of its header and parameters (for the layer whose stack feeds the bottom of a chain).
|
||||
#[serde(rename = "nodeReference")]
|
||||
pub node_reference: bool,
|
||||
/// 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 Inspector section this is.
|
||||
/// The ID of the node whose properties this section displays.
|
||||
pub id: u64,
|
||||
/// The node's Inspector content, rendered as the section's body when expanded, followed by the sections of any chain it shows (those with an `output_wire`).
|
||||
/// The node's properties content, rendered as the section's body when expanded.
|
||||
pub layout: Layout,
|
||||
}
|
||||
|
||||
@@ -465,18 +424,13 @@ impl LayoutGroup {
|
||||
Self::Table(WidgetTable { rows, unstyled })
|
||||
}
|
||||
|
||||
#[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::NodeSection(NodeSection {
|
||||
pub fn section(name: impl Into<String>, 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,
|
||||
node_reference: false,
|
||||
expanded,
|
||||
id,
|
||||
layout,
|
||||
@@ -500,9 +454,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::ParameterChainToggle(x) => &mut x.tooltip_description,
|
||||
Widget::PopoverButton(x) => &mut x.tooltip_description,
|
||||
Widget::TextAreaInput(x) => &mut x.tooltip_description,
|
||||
Widget::TextButton(x) => &mut x.tooltip_description,
|
||||
@@ -572,30 +524,22 @@ impl Diffable for LayoutGroup {
|
||||
}
|
||||
}
|
||||
(
|
||||
Self::NodeSection(NodeSection {
|
||||
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,
|
||||
node_reference: current_node_reference,
|
||||
expanded: current_expanded,
|
||||
id: current_id,
|
||||
layout: current_layout,
|
||||
}),
|
||||
Self::NodeSection(NodeSection {
|
||||
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,
|
||||
node_reference: new_node_reference,
|
||||
expanded: new_expanded,
|
||||
id: new_id,
|
||||
layout: new_layout,
|
||||
@@ -605,42 +549,30 @@ 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_node_reference != new_node_reference
|
||||
|| *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_node_reference = new_node_reference;
|
||||
*current_expanded = new_expanded;
|
||||
*current_id = new_id;
|
||||
current_layout.clone_from(&new_layout);
|
||||
|
||||
// Push an update layout group to the diff
|
||||
let new_value = Self::NodeSection(NodeSection {
|
||||
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,
|
||||
node_reference: new_node_reference,
|
||||
expanded: new_expanded,
|
||||
id: new_id,
|
||||
layout: new_layout,
|
||||
@@ -691,7 +623,7 @@ impl Diffable for LayoutGroup {
|
||||
}
|
||||
}
|
||||
}
|
||||
Self::NodeSection(NodeSection { layout, .. }) => {
|
||||
Self::Section(WidgetSection { layout, .. }) => {
|
||||
layout.collect_checkbox_ids(layout_target, widget_path, checkbox_map);
|
||||
}
|
||||
}
|
||||
@@ -721,7 +653,7 @@ impl Diffable for LayoutGroup {
|
||||
}
|
||||
}
|
||||
}
|
||||
Self::NodeSection(NodeSection { layout, .. }) => {
|
||||
Self::Section(WidgetSection { layout, .. }) => {
|
||||
layout.replace_widget_ids(layout_target, widget_path, checkbox_map);
|
||||
}
|
||||
}
|
||||
@@ -883,11 +815,9 @@ pub enum Widget {
|
||||
IconLabel(IconLabel),
|
||||
ImageButton(ImageButton),
|
||||
ImageLabel(ImageLabel),
|
||||
MathExpressionInput(MathExpressionInput),
|
||||
ShortcutLabel(ShortcutLabel),
|
||||
NodeCatalog(NodeCatalog),
|
||||
NumberInput(NumberInput),
|
||||
ParameterChainToggle(ParameterChainToggle),
|
||||
ParameterExposeButton(ParameterExposeButton),
|
||||
ReferencePointInput(ReferencePointInput),
|
||||
PopoverButton(PopoverButton),
|
||||
@@ -902,78 +832,12 @@ pub enum Widget {
|
||||
WorkingColorsInput(WorkingColorsInput),
|
||||
}
|
||||
|
||||
/// How a widget claims width within its row, borrowing the model of flexbox. Parts left unset follow the defaults of the layout it appears in.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WidgetSizing {
|
||||
/// The width in pixels before growing or shrinking.
|
||||
pub basis: Option<u32>,
|
||||
/// Whether it widens into spare room in its row.
|
||||
pub grow: Option<bool>,
|
||||
/// Whether it narrows below its starting width when its row runs out of room.
|
||||
pub shrink: Option<bool>,
|
||||
/// The narrowest it can be, in pixels.
|
||||
pub min_width: Option<u32>,
|
||||
/// The widest it can be, in pixels.
|
||||
pub max_width: Option<u32>,
|
||||
}
|
||||
|
||||
impl WidgetSizing {
|
||||
/// Exactly this many pixels wide, neither growing nor shrinking.
|
||||
pub const fn fixed(width: u32) -> Self {
|
||||
Self {
|
||||
basis: Some(width),
|
||||
grow: Some(false),
|
||||
shrink: Some(false),
|
||||
min_width: Some(width),
|
||||
max_width: Some(width),
|
||||
}
|
||||
}
|
||||
|
||||
/// As wide as its content, neither growing nor shrinking.
|
||||
pub const fn hug() -> Self {
|
||||
Self {
|
||||
basis: None,
|
||||
grow: Some(false),
|
||||
shrink: Some(false),
|
||||
min_width: None,
|
||||
max_width: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn basis(mut self, width: u32) -> Self {
|
||||
self.basis = Some(width);
|
||||
self
|
||||
}
|
||||
|
||||
pub const fn grow(mut self, grow: bool) -> Self {
|
||||
self.grow = Some(grow);
|
||||
self
|
||||
}
|
||||
|
||||
pub const fn shrink(mut self, shrink: bool) -> Self {
|
||||
self.shrink = Some(shrink);
|
||||
self
|
||||
}
|
||||
|
||||
pub const fn min_width(mut self, width: u32) -> Self {
|
||||
self.min_width = Some(width);
|
||||
self
|
||||
}
|
||||
|
||||
pub const fn max_width(mut self, width: u32) -> Self {
|
||||
self.max_width = Some(width);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// A single change to part of the UI, containing the location of the change and the new value.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct WidgetDiff {
|
||||
/// A path to the change
|
||||
/// e.g. [0, 1, 2] in the Inspector is the first section, second row and third widget.
|
||||
/// e.g. [0, 1, 2] in the Properties panel is the first section, second row and third widget.
|
||||
/// An empty path [] shows that the entire panel has changed and is sent when the UI is first created.
|
||||
#[serde(rename = "widgetPath")]
|
||||
pub widget_path: Vec<usize>,
|
||||
@@ -1007,7 +871,6 @@ impl DiffUpdate {
|
||||
Widget::DropdownInput(widget) => widget.tooltip_shortcut.as_mut(),
|
||||
Widget::IconButton(widget) => widget.tooltip_shortcut.as_mut(),
|
||||
Widget::NumberInput(widget) => widget.tooltip_shortcut.as_mut(),
|
||||
Widget::ParameterChainToggle(widget) => widget.tooltip_shortcut.as_mut(),
|
||||
Widget::ParameterExposeButton(widget) => widget.tooltip_shortcut.as_mut(),
|
||||
Widget::PopoverButton(widget) => widget.tooltip_shortcut.as_mut(),
|
||||
Widget::TextButton(widget) => widget.tooltip_shortcut.as_mut(),
|
||||
@@ -1015,7 +878,6 @@ impl DiffUpdate {
|
||||
Widget::ShortcutLabel(widget) => widget.shortcut.as_mut(),
|
||||
Widget::IconLabel(_)
|
||||
| Widget::ImageLabel(_)
|
||||
| Widget::MathExpressionInput(_)
|
||||
| Widget::NodeCatalog(_)
|
||||
| Widget::ReferencePointInput(_)
|
||||
| Widget::RadioInput(_)
|
||||
@@ -1062,6 +924,28 @@ 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) => {
|
||||
|
||||
@@ -1,266 +0,0 @@
|
||||
//! 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,5 +1,4 @@
|
||||
pub mod layout_widget;
|
||||
pub mod math_expression;
|
||||
pub mod tooltip_markdown;
|
||||
pub mod widgets;
|
||||
|
||||
|
||||
@@ -33,10 +33,6 @@ 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")]
|
||||
@@ -49,19 +45,6 @@ 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)]
|
||||
@@ -130,33 +113,6 @@ pub struct ParameterExposeButton {
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
}
|
||||
|
||||
/// A parameter's name, for an input fed by a chain of nodes, that shows or hides that chain's sections within its node's Inspector section.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Default, WidgetBuilder)]
|
||||
#[derivative(Debug, PartialEq)]
|
||||
pub struct ParameterChainToggle {
|
||||
// Content
|
||||
#[widget_builder(constructor)]
|
||||
pub name: String,
|
||||
pub expanded: 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<ParameterChainToggle>,
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Default, WidgetBuilder)]
|
||||
#[derivative(Debug, PartialEq)]
|
||||
@@ -181,7 +137,10 @@ pub struct TextButton {
|
||||
pub emphasized: bool,
|
||||
pub flush: bool,
|
||||
pub narrow: bool,
|
||||
pub sizing: WidgetSizing,
|
||||
|
||||
// Sizing
|
||||
#[serde(rename = "minWidth")]
|
||||
pub min_width: u32,
|
||||
|
||||
// Tooltips
|
||||
#[serde(rename = "tooltipLabel")]
|
||||
@@ -248,9 +207,14 @@ pub struct ColorInput {
|
||||
pub disabled: bool,
|
||||
pub mixed: bool,
|
||||
|
||||
// Sizing
|
||||
#[serde(rename = "minWidth")]
|
||||
pub min_width: u32,
|
||||
#[serde(rename = "maxWidth")]
|
||||
pub max_width: u32,
|
||||
|
||||
// Styling
|
||||
pub narrow: bool,
|
||||
pub sizing: WidgetSizing,
|
||||
|
||||
// Tooltips
|
||||
#[serde(rename = "tooltipLabel")]
|
||||
|
||||
@@ -77,19 +77,23 @@ pub struct DropdownInput {
|
||||
|
||||
// Styling
|
||||
pub narrow: bool,
|
||||
pub sizing: WidgetSizing,
|
||||
// Sized to the selected entry, rather than the widest, so its width changes with the selection
|
||||
#[serde(rename = "sizedToSelection")]
|
||||
pub sized_to_selection: bool,
|
||||
|
||||
// Behavior
|
||||
#[serde(rename = "virtualScrolling")]
|
||||
pub virtual_scrolling: bool,
|
||||
#[derivative(Default(value = "true"))]
|
||||
pub interactive: bool,
|
||||
// Set along with the `on_file_drop` callback
|
||||
#[serde(rename = "takesFileDrop")]
|
||||
#[widget_builder(skip)]
|
||||
pub takes_file_drop: bool,
|
||||
|
||||
// Sizing
|
||||
#[serde(rename = "minWidth")]
|
||||
pub min_width: u32,
|
||||
#[serde(rename = "maxWidth")]
|
||||
pub max_width: u32,
|
||||
|
||||
// Tooltips
|
||||
#[serde(rename = "tooltipLabel")]
|
||||
pub tooltip_label: String,
|
||||
@@ -134,8 +138,6 @@ 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
|
||||
@@ -154,9 +156,6 @@ 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)]
|
||||
@@ -172,7 +171,6 @@ 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);
|
||||
}
|
||||
}
|
||||
@@ -218,7 +216,6 @@ pub struct NumberInput {
|
||||
|
||||
// Styling
|
||||
pub narrow: bool,
|
||||
pub sizing: WidgetSizing,
|
||||
|
||||
// Behavior
|
||||
pub mode: NumberInputMode,
|
||||
@@ -245,6 +242,12 @@ pub struct NumberInput {
|
||||
#[derivative(Default(value = "true"))]
|
||||
pub unit_is_hidden_when_editing: bool,
|
||||
|
||||
// Sizing
|
||||
#[serde(rename = "minWidth")]
|
||||
pub min_width: u32,
|
||||
#[serde(rename = "maxWidth")]
|
||||
pub max_width: u32,
|
||||
|
||||
// Tooltips
|
||||
#[serde(rename = "tooltipLabel")]
|
||||
pub tooltip_label: String,
|
||||
@@ -358,7 +361,10 @@ pub struct RadioInput {
|
||||
|
||||
// Styling
|
||||
pub narrow: bool,
|
||||
pub sizing: WidgetSizing,
|
||||
|
||||
// Sizing
|
||||
#[serde(rename = "minWidth")]
|
||||
pub min_width: u32,
|
||||
//
|
||||
// Callbacks exists on the `RadioEntryData` children, not this parent `RadioInput`
|
||||
}
|
||||
@@ -469,7 +475,12 @@ pub struct TextInput {
|
||||
// Styling
|
||||
pub narrow: bool,
|
||||
pub centered: bool,
|
||||
pub sizing: WidgetSizing,
|
||||
|
||||
// Sizing
|
||||
#[serde(rename = "minWidth")]
|
||||
pub min_width: u32,
|
||||
#[serde(rename = "maxWidth")]
|
||||
pub max_width: u32,
|
||||
|
||||
// Tooltips
|
||||
#[serde(rename = "tooltipLabel")]
|
||||
@@ -488,153 +499,6 @@ 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)]
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use super::input_widgets::CheckboxId;
|
||||
use crate::messages::layout::utility_types::layout_widget::WidgetSizing;
|
||||
use crate::messages::{frontend::IconName, input_mapper::utility_types::misc::ActionShortcut};
|
||||
use derivative::*;
|
||||
use graphite_proc_macros::WidgetBuilder;
|
||||
@@ -71,7 +70,12 @@ pub struct TextLabel {
|
||||
pub center_align: bool,
|
||||
#[serde(rename = "tableAlign")]
|
||||
pub table_align: bool,
|
||||
pub sizing: WidgetSizing,
|
||||
|
||||
// Sizing
|
||||
#[serde(rename = "minWidth")]
|
||||
pub min_width: u32,
|
||||
#[serde(rename = "maxWidth")]
|
||||
pub max_width: u32,
|
||||
#[serde(rename = "minWidthCharacters")]
|
||||
pub min_width_characters: u32,
|
||||
|
||||
|
||||
@@ -12,12 +12,8 @@ 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,
|
||||
@@ -25,7 +21,7 @@ pub struct MenuBarMessageHandler {
|
||||
pub make_path_editable_is_allowed: bool,
|
||||
pub data_panel_open: bool,
|
||||
pub layers_panel_open: bool,
|
||||
pub inspector_open: bool,
|
||||
pub properties_panel_open: bool,
|
||||
pub focus_document: bool,
|
||||
}
|
||||
|
||||
@@ -48,12 +44,8 @@ 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;
|
||||
@@ -209,13 +201,13 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon("Cut")
|
||||
.tooltip_shortcut(action_shortcut!(ClipboardMessageDiscriminant::Cut))
|
||||
.on_commit(|_| ClipboardMessage::Cut.into())
|
||||
.disabled(no_active_document || !has_selected_nodes),
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
MenuListEntry::new("Copy")
|
||||
.label("Copy")
|
||||
.icon("Copy")
|
||||
.tooltip_shortcut(action_shortcut!(ClipboardMessageDiscriminant::Copy))
|
||||
.on_commit(|_| ClipboardMessage::Copy.into())
|
||||
.disabled(no_active_document || !has_selected_nodes),
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
MenuListEntry::new("Paste")
|
||||
.label("Paste")
|
||||
.icon("Paste")
|
||||
@@ -242,7 +234,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.label("Convert to Infinite Canvas")
|
||||
.icon("Artboard")
|
||||
.on_commit(|_| DocumentMessage::RemoveArtboards.into())
|
||||
.disabled(no_active_document || !has_artboards),
|
||||
.disabled(no_active_document),
|
||||
],
|
||||
])
|
||||
.widget_instance(),
|
||||
@@ -275,7 +267,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon("FolderOpen")
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::UngroupSelectedLayers))
|
||||
.on_commit(|_| DocumentMessage::UngroupSelectedLayers.into())
|
||||
.disabled(no_active_document || !has_selected_groups),
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Hide/Show")
|
||||
@@ -283,7 +275,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon("EyeHide")
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::ToggleSelectedVisibility))
|
||||
.on_commit(|_| DocumentMessage::ToggleSelectedVisibility.into())
|
||||
.disabled(no_active_document || !has_selected_nodes),
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
MenuListEntry::new("Lock/Unlock")
|
||||
.label("Lock/Unlock")
|
||||
.icon("PadlockLocked")
|
||||
@@ -297,19 +289,19 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon("TransformationGrab")
|
||||
.tooltip_shortcut(action_shortcut!(TransformLayerMessageDiscriminant::BeginGrab))
|
||||
.on_commit(|_| TransformLayerMessage::BeginGrab.into())
|
||||
.disabled(no_active_document || node_graph_open || !has_selected_visible_and_unlocked_layers),
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
MenuListEntry::new("Rotate")
|
||||
.label("Rotate")
|
||||
.icon("TransformationRotate")
|
||||
.tooltip_shortcut(action_shortcut!(TransformLayerMessageDiscriminant::BeginRotate))
|
||||
.on_commit(|_| TransformLayerMessage::BeginRotate.into())
|
||||
.disabled(no_active_document || node_graph_open || !has_selected_visible_and_unlocked_layers),
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
MenuListEntry::new("Scale")
|
||||
.label("Scale")
|
||||
.icon("TransformationScale")
|
||||
.tooltip_shortcut(action_shortcut!(TransformLayerMessageDiscriminant::BeginScale))
|
||||
.on_commit(|_| TransformLayerMessage::BeginScale.into())
|
||||
.disabled(no_active_document || node_graph_open || !has_selected_visible_and_unlocked_layers),
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Arrange")
|
||||
@@ -354,7 +346,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
MenuListEntry::new("Align")
|
||||
.label("Align")
|
||||
.icon("AlignVerticalCenter")
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers)
|
||||
.disabled(no_active_document || !has_selected_layers)
|
||||
.children(vec![
|
||||
vec![
|
||||
MenuListEntry::new("Align Left")
|
||||
@@ -367,7 +359,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
MenuListEntry::new("Align Horizontal Center")
|
||||
.label("Align Horizontal Center")
|
||||
.icon("AlignHorizontalCenter")
|
||||
@@ -378,7 +370,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
MenuListEntry::new("Align Right")
|
||||
.label("Align Right")
|
||||
.icon("AlignRight")
|
||||
@@ -389,7 +381,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Align Top")
|
||||
@@ -402,7 +394,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
MenuListEntry::new("Align Vertical Center")
|
||||
.label("Align Vertical Center")
|
||||
.icon("AlignVerticalCenter")
|
||||
@@ -413,7 +405,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
MenuListEntry::new("Align Bottom")
|
||||
.label("Align Bottom")
|
||||
.icon("AlignBottom")
|
||||
@@ -424,40 +416,40 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
],
|
||||
]),
|
||||
MenuListEntry::new("Flip")
|
||||
.label("Flip")
|
||||
.icon("FlipVertical")
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers)
|
||||
.disabled(no_active_document || !has_selected_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_visible_and_unlocked_layers),
|
||||
.disabled(no_active_document || !has_selected_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_visible_and_unlocked_layers),
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
]]),
|
||||
MenuListEntry::new("Turn")
|
||||
.label("Turn")
|
||||
.icon("TurnPositive90")
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers)
|
||||
.disabled(no_active_document || !has_selected_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_visible_and_unlocked_layers),
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
MenuListEntry::new("Turn 90°")
|
||||
.label("Turn 90°")
|
||||
.icon("TurnPositive90")
|
||||
.on_commit(|_| DocumentMessage::RotateSelectedLayers { degrees: 90. }.into())
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
]]),
|
||||
MenuListEntry::new("Boolean")
|
||||
.label("Boolean")
|
||||
@@ -521,7 +513,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
vec![
|
||||
MenuListEntry::new("Make Path Editable")
|
||||
.label("Make Path Editable")
|
||||
.icon("Path")
|
||||
.icon("NodeShape")
|
||||
.on_commit(|_| NodeGraphMessage::AddPathNode.into())
|
||||
.disabled(!make_path_editable_is_allowed),
|
||||
MenuListEntry::new("Expand Fill/Stroke")
|
||||
@@ -554,7 +546,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon("SelectParent")
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::SelectParentLayer))
|
||||
.on_commit(|_| DocumentMessage::SelectParentLayer.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_nodes),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Previous Selection")
|
||||
@@ -608,7 +600,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon("FrameSelected")
|
||||
.tooltip_shortcut(action_shortcut!(NavigationMessageDiscriminant::FitViewportToSelection))
|
||||
.on_commit(|_| NavigationMessage::FitViewportToSelection.into())
|
||||
.disabled(no_active_document || if node_graph_open { !has_selected_nodes } else { !has_selected_visible_layers }),
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
MenuListEntry::new("Zoom to Fit")
|
||||
.label("Zoom to Fit")
|
||||
.icon("FrameAll")
|
||||
@@ -669,11 +661,11 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.on_commit(|_| WorkspaceMessage::ResetWorkspaceLayout.into()),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Inspector")
|
||||
.label("Inspector")
|
||||
.icon(if self.inspector_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.tooltip_shortcut(action_shortcut!(WorkspaceMessageDiscriminant::ToggleInspectorOpen))
|
||||
.on_commit(|_| WorkspaceMessage::ToggleInspectorOpen.into())
|
||||
MenuListEntry::new("Properties")
|
||||
.label("Properties")
|
||||
.icon(if self.properties_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.tooltip_shortcut(action_shortcut!(WorkspaceMessageDiscriminant::TogglePropertiesPanelOpen))
|
||||
.on_commit(|_| WorkspaceMessage::TogglePropertiesPanelOpen.into())
|
||||
.disabled(self.focus_document),
|
||||
MenuListEntry::new("Layers")
|
||||
.label("Layers")
|
||||
|
||||
@@ -11,12 +11,13 @@ 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, RelativeAbsolute,
|
||||
AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RedGreenBlueAlpha, RelativeAbsolute,
|
||||
SelectiveColorChoice, TonalRange,
|
||||
};
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
@@ -39,7 +40,6 @@ 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,17 +100,12 @@ impl MessageHandler<DataPanelMessage, DataPanelMessageContext<'_>> for DataPanel
|
||||
|
||||
impl DataPanelMessageHandler {
|
||||
fn update_layout(&mut self, responses: &mut VecDeque<Message>, context: DataPanelMessageContext<'_>) {
|
||||
let DataPanelMessageContext {
|
||||
network_interface,
|
||||
selection_network_path,
|
||||
..
|
||||
} = context;
|
||||
let DataPanelMessageContext { network_interface, .. } = 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(),
|
||||
@@ -127,13 +122,32 @@ impl DataPanelMessageHandler {
|
||||
|
||||
let mut widgets = Vec::new();
|
||||
|
||||
// The selected layer or node, by its icon and name
|
||||
// Selected layer/node name
|
||||
if let Some((node_id, parent_path)) = self.introspected_node_path.split_last() {
|
||||
let node_id = *node_id;
|
||||
let is_layer = network_interface.is_layer(&node_id, parent_path);
|
||||
let parent_path_owned = parent_path.to_vec();
|
||||
|
||||
widgets.extend([
|
||||
IconLabel::new(network_interface.node_icon(node_id, parent_path)).widget_instance(),
|
||||
if is_layer {
|
||||
IconLabel::new("Layer").tooltip_description("Name of the selected layer.").widget_instance()
|
||||
} else {
|
||||
IconLabel::new("Node").tooltip_description("Name of the selected node.").widget_instance()
|
||||
},
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
TextLabel::new(network_interface.display_name(node_id, parent_path)).widget_instance(),
|
||||
TextInput::new(network_interface.display_name(&node_id, parent_path))
|
||||
.tooltip_description(if is_layer { "Name of the selected layer." } else { "Name of the selected node." })
|
||||
.on_update(move |text_input| {
|
||||
NodeGraphMessage::SetDisplayName {
|
||||
node_id,
|
||||
network_path: parent_path_owned.clone(),
|
||||
alias: text_input.value.clone(),
|
||||
skip_adding_history_step: false,
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.max_width(200)
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
]);
|
||||
}
|
||||
@@ -162,8 +176,6 @@ 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.
|
||||
@@ -226,11 +238,13 @@ 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>,
|
||||
@@ -280,11 +294,13 @@ 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>,
|
||||
@@ -387,7 +403,7 @@ impl<T: TableItemLayout> TableItemLayout for Item<T> {
|
||||
let target = PathStep::Attribute { row: 0, key: key.clone() };
|
||||
let cell = self.attributes().get_any(key).and_then(|any| dispatch_value_widgets(any, target, data)).unwrap_or_else(|| {
|
||||
let text = self.attributes().display_value(key, display_value_override).unwrap_or_else(|| "-".to_string());
|
||||
vec![text_preview_label(text)]
|
||||
vec![TextLabel::new(text).narrow(true).widget_instance()]
|
||||
});
|
||||
values.push(cell);
|
||||
}
|
||||
@@ -451,7 +467,7 @@ impl<T: TableItemLayout> TableItemLayout for List<T> {
|
||||
let target = PathStep::Attribute { row: index, key: key.clone() };
|
||||
let cell = self.attribute_any(key, index).and_then(|any| dispatch_value_widgets(any, target, data)).unwrap_or_else(|| {
|
||||
let text = self.attribute_display_value(key, index, display_value_override).unwrap_or_else(|| "-".to_string());
|
||||
vec![text_preview_label(text)]
|
||||
vec![TextLabel::new(text).narrow(true).widget_instance()]
|
||||
});
|
||||
values.push(cell);
|
||||
}
|
||||
@@ -919,14 +935,6 @@ fn string_preview(value: &str) -> String {
|
||||
first_line.chars().take(MAX_CHARACTERS - 1).chain(['…']).collect()
|
||||
}
|
||||
|
||||
/// Shows text in a table cell as a string preview, with the full text as its tooltip when the preview cuts it short.
|
||||
fn text_preview_label(text: String) -> WidgetInstance {
|
||||
let preview = string_preview(&text);
|
||||
let tooltip = if preview == text { String::new() } else { text };
|
||||
|
||||
TextLabel::new(preview).narrow(true).tooltip_label(tooltip).widget_instance()
|
||||
}
|
||||
|
||||
impl TableItemLayout for DVec2 {
|
||||
fn type_name() -> &'static str {
|
||||
"Vec2"
|
||||
@@ -1026,11 +1034,13 @@ impl_table_item_layout_for_choice_enum!(
|
||||
TextDenomination,
|
||||
DesaturateMethod,
|
||||
RedGreenBlue,
|
||||
RedGreenBlueAlpha,
|
||||
RelativeAbsolute,
|
||||
SelectiveColorChoice,
|
||||
TonalRange,
|
||||
AdjustmentChannel,
|
||||
HueSaturationRange,
|
||||
XY,
|
||||
ScaleType,
|
||||
CentroidType,
|
||||
BooleanOperation,
|
||||
@@ -1075,35 +1085,6 @@ fn node_id_display_label(node_id: NodeId, network_interface: &NodeNetworkInterfa
|
||||
}
|
||||
}
|
||||
|
||||
/// A reference to a node, as a button with its icon and name that selects it with the message from `select`.
|
||||
pub fn node_reference_button(
|
||||
node_id: NodeId,
|
||||
network_interface: &NodeNetworkInterface,
|
||||
network_path: &[NodeId],
|
||||
selection_network_path: &[NodeId],
|
||||
select: impl Fn() -> Message + Send + Sync + 'static,
|
||||
) -> WidgetInstance {
|
||||
let is_layer = network_interface.is_layer(&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 == selection_network_path;
|
||||
let already_selected = network_interface.selected_nodes_in_nested_network(network_path).is_some_and(|selected| selected.0 == [node_id]);
|
||||
|
||||
TextButton::new(name)
|
||||
.icon(icon)
|
||||
.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, _) => "",
|
||||
})
|
||||
.on_update(move |_| select())
|
||||
.widget_instance()
|
||||
}
|
||||
|
||||
impl TableItemLayout for NodeId {
|
||||
fn type_name() -> &'static str {
|
||||
"NodeId"
|
||||
@@ -1111,34 +1092,108 @@ impl TableItemLayout for NodeId {
|
||||
fn identifier(&self) -> String {
|
||||
format!("Node {self}")
|
||||
}
|
||||
// Override so the breadcrumb uses the node's resolved display name instead of the bare-ID fallback `identifier()` returns
|
||||
// Override so the breadcrumb uses the same resolved display name as the value button, 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)
|
||||
}
|
||||
// Shown inline as a button with the node's icon and name that selects it. 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> {
|
||||
// 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> {
|
||||
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 {
|
||||
node_id,
|
||||
network_path: path_for_rename.clone(),
|
||||
alias: text_input.value.clone(),
|
||||
skip_adding_history_step: false,
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.max_width(200)
|
||||
.widget_instance()
|
||||
} else {
|
||||
TextLabel::new(name).widget_instance()
|
||||
};
|
||||
|
||||
// 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 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(),
|
||||
);
|
||||
}
|
||||
|
||||
// Selecting starts from the root of the newly selected node's data, since the current drill-down path means nothing there
|
||||
let select = move || Message::Batched {
|
||||
messages: Box::new([
|
||||
DataPanelMessage::TruncateElementPath { len: 0 }.into(),
|
||||
NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] }.into(),
|
||||
]),
|
||||
};
|
||||
vec![node_reference_button(node_id, network_interface, &network_path, data.selection_network_path, select)]
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(self.value_widgets(PathStep::Element(0), data))]
|
||||
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)]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1196,11 +1251,13 @@ 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,7 +7,6 @@ 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};
|
||||
@@ -34,7 +33,7 @@ pub enum DocumentMessage {
|
||||
#[child]
|
||||
Overlays(OverlaysMessage),
|
||||
#[child]
|
||||
Inspector(InspectorMessage),
|
||||
PropertiesPanel(PropertiesPanelMessage),
|
||||
#[child]
|
||||
DataPanel(DataPanelMessage),
|
||||
#[child]
|
||||
@@ -90,9 +89,6 @@ pub enum DocumentMessage {
|
||||
GridVisibility {
|
||||
visible: bool,
|
||||
},
|
||||
LayersPanelHoverOverlays {
|
||||
context: OverlayContext,
|
||||
},
|
||||
BlendSelectedLayers,
|
||||
MorphSelectedLayers,
|
||||
ExpandFillStrokeOnSelectedLayers,
|
||||
@@ -104,27 +100,9 @@ pub enum DocumentMessage {
|
||||
parent: LayerNodeIdentifier,
|
||||
insert_index: usize,
|
||||
},
|
||||
ReorderInspectorSection {
|
||||
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,
|
||||
@@ -184,12 +162,6 @@ pub enum DocumentMessage {
|
||||
ctrl: bool,
|
||||
shift: bool,
|
||||
},
|
||||
SelectChainNode {
|
||||
layer: NodeId,
|
||||
node_id: NodeId,
|
||||
ctrl: bool,
|
||||
shift: bool,
|
||||
},
|
||||
SetActivePanel {
|
||||
active_panel: PanelType,
|
||||
},
|
||||
@@ -199,9 +171,6 @@ pub enum DocumentMessage {
|
||||
SetGraphFadeArtwork {
|
||||
percentage: f64,
|
||||
},
|
||||
SetLayersPanelHoveredLayer {
|
||||
id: Option<NodeId>,
|
||||
},
|
||||
SetNodePinned {
|
||||
node_id: NodeId,
|
||||
pinned: bool,
|
||||
@@ -232,10 +201,6 @@ pub enum DocumentMessage {
|
||||
SetRenderMode {
|
||||
render_mode: RenderMode,
|
||||
},
|
||||
ShowNodeInGraph {
|
||||
node_id: NodeId,
|
||||
},
|
||||
ShowSelectionInGraph,
|
||||
AddTransaction,
|
||||
StartTransaction,
|
||||
EndTransaction,
|
||||
@@ -249,16 +214,8 @@ pub enum DocumentMessage {
|
||||
tree_path: Vec<NodeId>,
|
||||
recursive: bool,
|
||||
},
|
||||
ToggleNodeInspectorSectionExpanded {
|
||||
ToggleNodePropertiesSectionExpanded {
|
||||
node_id: NodeId,
|
||||
recursive: bool,
|
||||
},
|
||||
ToggleNodeInspectorInputChain {
|
||||
node_id: NodeId,
|
||||
input_index: usize,
|
||||
},
|
||||
ToggleLayerChainExpanded {
|
||||
layer_id: NodeId,
|
||||
},
|
||||
ToggleSelectedVisibility,
|
||||
ToggleSelectedLocked,
|
||||
@@ -269,7 +226,6 @@ pub enum DocumentMessage {
|
||||
upstream_footprints: HashMap<NodeId, Footprint>,
|
||||
local_transforms: HashMap<NodeId, DAffine2>,
|
||||
first_element_source_id: HashMap<NodeId, Option<NodeId>>,
|
||||
document_to_viewport: DAffine2,
|
||||
},
|
||||
UpdateClickTargets {
|
||||
click_targets: HashMap<NodeId, Vec<Arc<ClickTarget>>>,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+2
-54
@@ -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, new_background_layer};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_clip_mode;
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
@@ -138,7 +138,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
return;
|
||||
};
|
||||
if set_stroke_paint_order(network_interface, &[], stroke_node_id, paint_order) {
|
||||
responses.add(InspectorMessage::Refresh);
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
@@ -413,9 +413,6 @@ 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(),
|
||||
@@ -493,9 +490,6 @@ 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);
|
||||
@@ -1111,52 +1105,6 @@ mod tests {
|
||||
assert_eq!(paint_order, PaintOrder::StrokeAbove, "the rewrite should move the stroke back upstream of the fill");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stroke_order_set_keeps_the_layer_chain_in_place() {
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graphene_std::vector::style::PaintOrder;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
|
||||
let layer = editor.active_document().metadata().all_layers().next().unwrap();
|
||||
|
||||
// Each node of the layer's chain from the layer outward, with its offset from the layer if it is chain-positioned
|
||||
let chain_layout = |editor: &EditorTestUtils| {
|
||||
let interface = &editor.active_document().network_interface;
|
||||
let layer_position = interface.position(&layer.to_node(), &[]).unwrap_or_default();
|
||||
interface
|
||||
.layer_chain_nodes(layer.to_node(), &[])
|
||||
.into_iter()
|
||||
.map(|node_id| {
|
||||
let offset = interface.is_chain(&node_id, &[]).then(|| interface.position(&node_id, &[]).unwrap_or_default() - layer_position);
|
||||
(interface.display_name(&node_id, &[]), offset)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let original = chain_layout(&editor);
|
||||
assert!(
|
||||
original.iter().all(|(_, offset)| offset.is_some()),
|
||||
"a fresh shape's nodes should all be chain-positioned: {original:?}"
|
||||
);
|
||||
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::StrokeOrderSet {
|
||||
layer,
|
||||
paint_order: PaintOrder::StrokeBelow,
|
||||
})
|
||||
.await;
|
||||
|
||||
// Only the Fill and Stroke nodes trade places, so the chain keeps every slot
|
||||
let swap_name = |name: &str| match name {
|
||||
"Fill" => "Stroke".to_string(),
|
||||
"Stroke" => "Fill".to_string(),
|
||||
other => other.to_string(),
|
||||
};
|
||||
let expected = original.iter().map(|(name, offset)| (swap_name(name), *offset)).collect::<Vec<_>>();
|
||||
assert_eq!(chain_layout(&editor), expected, "the swap should leave the layer's chain intact");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_node_inserted_between_the_fill_and_stroke_makes_the_order_swap_inapplicable() {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
|
||||
|
||||
@@ -752,7 +752,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
};
|
||||
|
||||
transform_utils::update_transform(self.network_interface, &transform_node_id, last_transform_value);
|
||||
self.responses.add(InspectorMessage::Refresh);
|
||||
self.responses.add(PropertiesPanelMessage::Refresh);
|
||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
@@ -959,7 +959,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
transform_utils::update_transform(self.network_interface, &transform_node_id, transform);
|
||||
|
||||
// Refresh the render and editor UI
|
||||
self.responses.add(InspectorMessage::Refresh);
|
||||
self.responses.add(PropertiesPanelMessage::Refresh);
|
||||
if !skip_rerender {
|
||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
@@ -970,7 +970,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
return;
|
||||
};
|
||||
self.network_interface.vector_modify(&path_node_id, modification_type);
|
||||
self.responses.add(InspectorMessage::Refresh);
|
||||
self.responses.add(PropertiesPanelMessage::Refresh);
|
||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
@@ -1002,10 +1002,10 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
);
|
||||
}
|
||||
|
||||
/// Set the input, refresh the Inspector, and run the document graph if skip_rerender is false
|
||||
/// Set the input, refresh the Properties panel, and run the document graph if skip_rerender is false
|
||||
pub fn set_input_with_refresh(&mut self, input_connector: InputConnector, input: NodeInput, skip_rerender: bool) {
|
||||
self.network_interface.set_input(&input_connector, input, &[]);
|
||||
self.responses.add(InspectorMessage::Refresh);
|
||||
self.responses.add(PropertiesPanelMessage::Refresh);
|
||||
if !skip_rerender {
|
||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
@@ -1057,14 +1057,6 @@ pub fn set_stroke_paint_order(network_interface: &mut NodeNetworkInterface, netw
|
||||
};
|
||||
let downstream_consumers = primary_output_consumers(network_interface, network_path, downstream);
|
||||
|
||||
// The rewiring knocks chain nodes out to absolute positions, so record how the pair and the chain feeding it were placed
|
||||
let original_placements = network_interface
|
||||
.upstream_flow_back_from_nodes(vec![downstream], network_path, FlowType::HorizontalFlow)
|
||||
.enumerate()
|
||||
.take_while(|(index, node_id)| *index < 2 || network_interface.is_chain(node_id, network_path))
|
||||
.map(|(_, node_id)| (node_id, network_interface.is_chain(&node_id, network_path), network_interface.position(&node_id, network_path)))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
network_interface.set_input(&InputConnector::node_at_index(downstream, 0), upstream_source, network_path);
|
||||
network_interface.set_input(&InputConnector::node_at_index(upstream, 0), NodeInput::node(downstream, 0), network_path);
|
||||
for consumer in &downstream_consumers {
|
||||
@@ -1074,15 +1066,5 @@ pub fn set_stroke_paint_order(network_interface: &mut NodeNetworkInterface, netw
|
||||
network_interface.set_input(consumer, NodeInput::node(upstream, 0), network_path);
|
||||
}
|
||||
|
||||
// Each node of the pair takes over the other's place, and the chain feeding the pair is restored as it was
|
||||
let swapped_nodes = [upstream, downstream].into_iter().chain(original_placements.iter().skip(2).map(|(node_id, _, _)| *node_id));
|
||||
for (node_id, (_, was_chain, position)) in swapped_nodes.zip(&original_placements) {
|
||||
if *was_chain {
|
||||
network_interface.set_chain_position(&node_id, network_path);
|
||||
} else if let Some(position) = position {
|
||||
network_interface.set_absolute_position(&node_id, *position, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
use graphene_std::uuid::NodeId;
|
||||
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::NodeInspectorContext;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct InspectorMessageContext<'a> {
|
||||
pub executor: &'a mut NodeGraphExecutor,
|
||||
pub document_id: DocumentId,
|
||||
pub network_interface: &'a mut NodeNetworkInterface,
|
||||
pub resources: &'a ResourceMessageHandler,
|
||||
pub selection_network_path: &'a [NodeId],
|
||||
pub fonts: &'a FontsMessageHandler,
|
||||
pub inspector_open: bool,
|
||||
pub inspector_collapsed_sections: &'a [NodeId],
|
||||
pub inspector_expanded_input_chains: &'a [(NodeId, Option<usize>)],
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, ExtractField)]
|
||||
pub struct InspectorMessageHandler {}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<InspectorMessage, InspectorMessageContext<'_>> for InspectorMessageHandler {
|
||||
fn process_message(&mut self, message: InspectorMessage, responses: &mut VecDeque<Message>, context: InspectorMessageContext) {
|
||||
let InspectorMessageContext {
|
||||
executor,
|
||||
document_id,
|
||||
network_interface,
|
||||
resources,
|
||||
selection_network_path,
|
||||
fonts,
|
||||
inspector_open,
|
||||
inspector_collapsed_sections,
|
||||
inspector_expanded_input_chains,
|
||||
} = context;
|
||||
|
||||
match message {
|
||||
InspectorMessage::Clear => {
|
||||
responses.add(LayoutMessage::SendLayout {
|
||||
layout: Layout::default(),
|
||||
layout_target: LayoutTarget::Inspector,
|
||||
});
|
||||
}
|
||||
InspectorMessage::Refresh => {
|
||||
if !inspector_open {
|
||||
responses.add(InspectorMessage::Clear);
|
||||
return;
|
||||
}
|
||||
|
||||
let mut node_inspector_context = NodeInspectorContext {
|
||||
responses,
|
||||
executor,
|
||||
document_id,
|
||||
network_interface,
|
||||
resources,
|
||||
selection_network_path,
|
||||
fonts,
|
||||
inspector_collapsed_sections,
|
||||
inspector_expanded_input_chains,
|
||||
};
|
||||
let layout = Layout(NodeGraphMessageHandler::collate_inspector_sections(&mut node_inspector_context));
|
||||
|
||||
node_inspector_context.responses.add(LayoutMessage::SendLayout {
|
||||
layout,
|
||||
layout_target: LayoutTarget::Inspector,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn actions(&self) -> ActionList {
|
||||
actions!(InspectorMessageDiscriminant;)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
mod inspector_message;
|
||||
pub mod inspector_message_handler;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use inspector_message::{InspectorMessage, InspectorMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use inspector_message_handler::InspectorMessageHandler;
|
||||
@@ -7,10 +7,10 @@ pub(crate) mod storage_tests;
|
||||
|
||||
pub mod data_panel;
|
||||
pub mod graph_operation;
|
||||
pub mod inspector;
|
||||
pub mod navigation;
|
||||
pub mod node_graph;
|
||||
pub mod overlays;
|
||||
pub mod properties_panel;
|
||||
pub mod resource;
|
||||
pub mod utility_types;
|
||||
|
||||
@@ -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, SelectionParts};
|
||||
pub use document_message_handler::{DocumentMessageContext, DocumentMessageHandler};
|
||||
@@ -6,21 +6,21 @@ use glam::DVec2;
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum NavigationMessage {
|
||||
// Messages
|
||||
BeginCanvasPan { artwork_behind_graph: bool },
|
||||
BeginCanvasPan,
|
||||
BeginCanvasTilt { was_dispatched_from_menu: bool },
|
||||
BeginCanvasZoom { artwork_behind_graph: bool },
|
||||
BeginCanvasZoom,
|
||||
CanvasPan { delta: DVec2 },
|
||||
CanvasPanAbortPrepare { x_not_y_axis: bool },
|
||||
CanvasPanAbort { x_not_y_axis: bool },
|
||||
CanvasPanByViewportFraction { delta: DVec2 },
|
||||
CanvasPanMouseWheel { use_y_as_x: bool, artwork_behind_graph: bool },
|
||||
CanvasPanMouseWheel { use_y_as_x: bool },
|
||||
CanvasTiltResetAndZoomTo100Percent,
|
||||
CanvasTiltSet { angle_radians: f64 },
|
||||
CanvasZoomDecrease { center_on_mouse: bool },
|
||||
CanvasZoomIncrease { center_on_mouse: bool },
|
||||
CanvasZoomMouseWheel { artwork_behind_graph: bool },
|
||||
CanvasZoomMouseWheel,
|
||||
CanvasZoomSet { zoom_factor: f64 },
|
||||
CanvasFlip,
|
||||
EndArtworkBehindGraph,
|
||||
EndCanvasPTZ { abort_transform: bool },
|
||||
EndCanvasPTZWithClick { commit_key: Key },
|
||||
FitViewportToBounds { bounds: [DVec2; 2], prevent_zoom_past_100: bool },
|
||||
|
||||
@@ -31,8 +31,6 @@ 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]
|
||||
@@ -48,17 +46,6 @@ 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)
|
||||
@@ -87,7 +74,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);
|
||||
@@ -102,9 +89,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;
|
||||
};
|
||||
// The node graph can't be tilted, so the tilt shortcut pans the artwork behind it instead
|
||||
// If the node graph is open, prevent tilt and instead start panning
|
||||
if graph_view_overlay_open {
|
||||
responses.add(NavigationMessage::BeginCanvasPan { artwork_behind_graph: true });
|
||||
responses.add(NavigationMessage::BeginCanvasPan);
|
||||
} else {
|
||||
responses.add(FrontendMessage::UpdateMouseCursor { cursor: MouseCursorIcon::Default });
|
||||
HintData(vec![
|
||||
@@ -123,7 +110,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;
|
||||
};
|
||||
@@ -187,7 +174,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()
|
||||
@@ -196,6 +183,20 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
} * -VIEWPORT_SCROLL_RATE;
|
||||
responses.add(NavigationMessage::CanvasPan { delta });
|
||||
}
|
||||
NavigationMessage::CanvasTiltResetAndZoomTo100Percent => {
|
||||
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 CanvasTiltResetAndZoomTo100Percent");
|
||||
return;
|
||||
};
|
||||
ptz.set_tilt(0.);
|
||||
ptz.set_zoom(1.);
|
||||
if graph_view_overlay_open {
|
||||
responses.add(NodeGraphMessage::UpdateGraphBarRight);
|
||||
} else {
|
||||
responses.add(PortfolioMessage::UpdateDocumentWidgets);
|
||||
}
|
||||
responses.add(DocumentMessage::PTZUpdate);
|
||||
}
|
||||
NavigationMessage::CanvasTiltSet { angle_radians } => {
|
||||
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 CanvasTiltSet");
|
||||
@@ -230,7 +231,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. {
|
||||
@@ -290,9 +291,6 @@ 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");
|
||||
@@ -325,7 +323,6 @@ 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);
|
||||
@@ -485,11 +482,6 @@ 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 {
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
mod document_node_derive;
|
||||
|
||||
use super::node_inspector::choice::enum_choice;
|
||||
use super::node_inspector::{self, ParameterWidgetsInfo, SliderRange};
|
||||
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,
|
||||
@@ -16,14 +15,16 @@ use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::value::*;
|
||||
use graph_craft::document::*;
|
||||
use graph_craft::{concrete, list};
|
||||
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType};
|
||||
use graphene_std::extract_xy::XY;
|
||||
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType, RedGreenBlueAlpha};
|
||||
use graphene_std::raster_types::{CPU, Raster};
|
||||
#[allow(unused_imports)]
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::*;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
pub struct NodeInspectorContext<'a> {
|
||||
pub struct NodePropertiesContext<'a> {
|
||||
pub responses: &'a mut VecDeque<Message>,
|
||||
pub executor: &'a mut NodeGraphExecutor,
|
||||
pub document_id: DocumentId,
|
||||
@@ -31,19 +32,18 @@ pub struct NodeInspectorContext<'a> {
|
||||
pub resources: &'a ResourceMessageHandler,
|
||||
pub fonts: &'a FontsMessageHandler,
|
||||
pub selection_network_path: &'a [NodeId],
|
||||
/// The node IDs whose Inspector sections the user has collapsed.
|
||||
pub inspector_collapsed_sections: &'a [NodeId],
|
||||
/// The input (if any) whose feeding chain a node's section shows, for each node where that differs from the default.
|
||||
pub inspector_expanded_input_chains: &'a [(NodeId, Option<usize>)],
|
||||
pub document_name: &'a str,
|
||||
/// The node IDs whose Properties panel sections the user has collapsed.
|
||||
pub properties_panel_collapsed_sections: &'a [NodeId],
|
||||
}
|
||||
|
||||
impl NodeInspectorContext<'_> {
|
||||
impl NodePropertiesContext<'_> {
|
||||
pub fn call_widget_override(&mut self, node_id: &NodeId, index: usize) -> Option<Vec<LayoutGroup>> {
|
||||
let input_inspector_row = self.network_interface.persistent_input_metadata(node_id, index, self.selection_network_path)?;
|
||||
let input_properties_row = self.network_interface.persistent_input_metadata(node_id, index, self.selection_network_path)?;
|
||||
|
||||
// The stored override wins, falling back to the definition's own so documents saved before it gained one still
|
||||
// pick it up. Only `Custom` is recovered, since the other kinds also need input data stored at insertion time.
|
||||
let widget_override = input_inspector_row.widget_override.clone().or_else(|| {
|
||||
let widget_override = input_properties_row.widget_override.clone().or_else(|| {
|
||||
let implementation = self.network_interface.implementation(node_id, self.selection_network_path)?;
|
||||
let DocumentNodeImplementation::ProtoNode(proto_node_identifier) = implementation else {
|
||||
return None;
|
||||
@@ -130,16 +130,13 @@ 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>,
|
||||
|
||||
/// Node level overrides are stored based on the reference, not the instance. If the node is modified such that it becomes a local version
|
||||
/// (for example an input is added), the reference is no longer to the definition, and the overrides are lost.
|
||||
/// Most nodes should not use a node-level Inspector override, since it is less flexible than an input-level override.
|
||||
pub inspector: Option<&'static str>,
|
||||
/// Most nodes should not use node based properties, since they are less flexible than input level properties.
|
||||
pub properties: Option<&'static str>,
|
||||
}
|
||||
|
||||
// We use the once_cell to use the document node definitions throughout the editor without passing a reference
|
||||
@@ -155,18 +152,16 @@ 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()
|
||||
},
|
||||
description: Cow::Borrowed("An empty node network you can use to create your own custom nodes."),
|
||||
inspector: None,
|
||||
properties: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Merge",
|
||||
category: "General",
|
||||
icon: Some("NodeMerge"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(5), 0)],
|
||||
@@ -227,22 +222,17 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::type_default(list!(Graphic), true), NodeInput::type_default(list!(Graphic), true)],
|
||||
input_metadata: vec![
|
||||
("Base", "The stack of layers below this one, which the content is placed above.").into(),
|
||||
("Content", "The artwork this layer adds to the stack as a single item.").into(),
|
||||
],
|
||||
input_metadata: vec![("Base", "TODO").into(), ("Content", "TODO").into()],
|
||||
output_names: vec!["Out".to_string()],
|
||||
output_descriptions: vec!["The stack of layers with this layer's content placed on top.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Merges the provided content as a new item in the layer's compositing stack."),
|
||||
inspector: None,
|
||||
properties: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Artboard",
|
||||
category: "General",
|
||||
icon: Some("NodeArtboard"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(4), 0)],
|
||||
@@ -313,11 +303,11 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
NodeInput::value(TaggedValue::Bool(true), false),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("Base", "The stack of artboards below this one, which this artboard is placed above.").into(),
|
||||
("Content", "Graphics to include within the artboard.").into(),
|
||||
("Base", "TODO").into(),
|
||||
InputMetadata::with_name_description_override("Content", "TODO", WidgetOverride::Hidden),
|
||||
InputMetadata::with_name_description_override(
|
||||
"Location",
|
||||
"Coordinate of the top-left corner of the artboard within the document.",
|
||||
"TODO",
|
||||
WidgetOverride::Vec2(Vec2InputSettings {
|
||||
x: "X".to_string(),
|
||||
y: "Y".to_string(),
|
||||
@@ -328,7 +318,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
),
|
||||
InputMetadata::with_name_description_override(
|
||||
"Dimensions",
|
||||
"Width and height of the artboard within the document.",
|
||||
"TODO",
|
||||
WidgetOverride::Vec2(Vec2InputSettings {
|
||||
x: "W".to_string(),
|
||||
y: "H".to_string(),
|
||||
@@ -337,21 +327,19 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
..Default::default()
|
||||
}),
|
||||
),
|
||||
InputMetadata::with_name_description_override("Background", "Color of the artboard background.", WidgetOverride::Custom("artboard_background".to_string())),
|
||||
("Clip", "Whether to cut off the contained content that extends outside the artboard, or keep it visible.").into(),
|
||||
InputMetadata::with_name_description_override("Background", "TODO", WidgetOverride::Custom("artboard_background".to_string())),
|
||||
("Clip", "TODO").into(),
|
||||
],
|
||||
output_names: vec!["Out".to_string()],
|
||||
output_descriptions: vec!["The stack of artboards with this artboard placed on top.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Creates a new Artboard which can be used as a working surface."),
|
||||
inspector: None,
|
||||
properties: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Blend",
|
||||
category: "Vector",
|
||||
icon: Some("NodeBlend"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(16), 0)],
|
||||
@@ -510,32 +498,22 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
NodeInput::type_default(item!(Vector), false),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("Content", "The vector objects to create intermediate shapes between.").into(),
|
||||
(
|
||||
"Count",
|
||||
"The number of shapes spanning from the first object to the last, repeated for each subpath of the control path.",
|
||||
)
|
||||
.into(),
|
||||
("Reverse", "Flip the stacking order of the shapes, so the ones nearest the first object are on top.").into(),
|
||||
("Distribution", "What changes evenly from one shape to the next, which sets how the intermediate shapes are spaced.").into(),
|
||||
(
|
||||
"Path",
|
||||
"An optional control path with one anchor point per object. Curved segments shape the trajectory of the blend instead of traveling straight.",
|
||||
)
|
||||
.into(),
|
||||
("Content", "TODO").into(),
|
||||
("Count", "TODO").into(),
|
||||
("Reverse", "TODO").into(),
|
||||
("Distribution", "TODO").into(),
|
||||
("Path", "TODO").into(),
|
||||
],
|
||||
output_names: vec!["Out".to_string()],
|
||||
output_descriptions: vec!["The blended shapes, from the first object to the last.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Creates a series of intermediate shapes that gradually transition between vector objects, optionally along a control path."),
|
||||
inspector: None,
|
||||
description: Cow::Borrowed("TODO"),
|
||||
properties: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Origins to Polyline",
|
||||
category: "Vector",
|
||||
icon: Some("NodeOriginsToPolyline"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(7), 0)],
|
||||
@@ -604,19 +582,17 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::type_default(list!(Vector), true)],
|
||||
input_metadata: vec![("Vector", "The vector objects to connect in order by their origins.").into()],
|
||||
input_metadata: vec![("Vector", "TODO").into()],
|
||||
output_names: vec!["Vector".to_string()],
|
||||
output_descriptions: vec!["An open polyline with an anchor point at the origin of each object.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Connects the origins of vector objects in order with an open polyline, such as to make a control path for the **Blend** and **Morph** nodes."),
|
||||
inspector: None,
|
||||
description: Cow::Borrowed("TODO"),
|
||||
properties: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Load Image",
|
||||
category: "Web Request",
|
||||
icon: Some("NodeLoadImage"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
@@ -641,22 +617,17 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::String("graphite:null".to_string()), false)],
|
||||
input_metadata: vec![
|
||||
("Empty", "Has no effect, since the image is loaded from the URL.").into(),
|
||||
("URL", "The web address or local asset path of the image to load.").into(),
|
||||
],
|
||||
input_metadata: vec![("Empty", "TODO").into(), ("URL", "TODO").into()],
|
||||
output_names: vec!["Image".to_string()],
|
||||
output_descriptions: vec!["The loaded image, which is empty if it fails to load or decode.".to_string()],
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Loads an image from a given URL."),
|
||||
inspector: None,
|
||||
properties: None,
|
||||
},
|
||||
#[cfg(all(feature = "gpu", target_family = "wasm"))]
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Rasterize",
|
||||
category: "Raster",
|
||||
icon: Some("NodeRasterize"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(2), 0)],
|
||||
@@ -698,36 +669,137 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
false,
|
||||
),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("Artwork", "The graphics to render as an image.").into(),
|
||||
("Footprint", "The area of the document to render, and the resolution to render it at.").into(),
|
||||
],
|
||||
input_metadata: vec![("Artwork", "TODO").into(), ("Footprint", "TODO").into()],
|
||||
output_names: vec!["Canvas".to_string()],
|
||||
output_descriptions: vec!["The rendered image.".to_string()],
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Renders a view of the input graphics within an area defined by the *Footprint*, producing a raster image."),
|
||||
inspector: None,
|
||||
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)],
|
||||
input_metadata: vec![("Node", "The node to output as data rather than evaluating it.").into()],
|
||||
input_metadata: vec![("Node", "TODO").into()],
|
||||
output_names: vec!["Document Node".to_string()],
|
||||
output_descriptions: vec!["The connected node itself, as data.".to_string()],
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Outputs the connected node itself as data, rather than the result of evaluating it."),
|
||||
inspector: None,
|
||||
description: Cow::Borrowed("TODO"),
|
||||
properties: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Regex Find",
|
||||
category: "Text: Regex",
|
||||
icon: Some("NodeRegexFind"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![
|
||||
@@ -790,21 +862,16 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
("Multiline", "Make `^` and `$` match the start and end of each line, not just the whole string.").into(),
|
||||
],
|
||||
output_names: vec!["Match".to_string(), "Captures".to_string()],
|
||||
output_descriptions: vec![
|
||||
"The whole portion of the string matching the pattern, or empty if there is no match.".to_string(),
|
||||
"The text matched by each capture group in the pattern, in order.".to_string(),
|
||||
],
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed(
|
||||
r#"Finds a portion of the string matching a regular expression pattern. With "Match Index" at its default 0, it selects the first non-overlapping occurrence, but others may be selected. Capture groups, if any, are produced as a list in the "Captures" output."#,
|
||||
),
|
||||
inspector: None,
|
||||
properties: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Path",
|
||||
category: "Vector",
|
||||
icon: Some("NodePath"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
@@ -839,88 +906,72 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
NodeInput::type_default(item!(Vector), true),
|
||||
NodeInput::value(TaggedValue::VectorModification(Default::default()), false),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("Content", "The original shape that edits made with the Pen and Path tools are applied to.").into(),
|
||||
("Modification", "The edits made with the Pen and Path tools, stored as changes to points and segments.").into(),
|
||||
],
|
||||
input_metadata: vec![("Content", "TODO").into(), ("Modification", "TODO").into()],
|
||||
output_names: vec!["Modified".to_string()],
|
||||
output_descriptions: vec!["The shape with the Pen and Path tool edits applied.".to_string()],
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Holds the edits made with the Pen and Path tools, applying them to the incoming shape."),
|
||||
inspector: None,
|
||||
description: Cow::Borrowed("TODO"),
|
||||
properties: None,
|
||||
},
|
||||
];
|
||||
|
||||
document_node_derive::post_process_nodes(custom)
|
||||
}
|
||||
|
||||
type NodeInspector = HashMap<String, Box<dyn Fn(NodeId, &mut NodeInspectorContext) -> Vec<LayoutGroup> + Send + Sync>>;
|
||||
type NodeProperties = HashMap<String, Box<dyn Fn(NodeId, &mut NodePropertiesContext) -> Vec<LayoutGroup> + Send + Sync>>;
|
||||
|
||||
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
|
||||
pub static NODE_OVERRIDES: once_cell::sync::Lazy<NodeInspector> = once_cell::sync::Lazy::new(static_node_inspector);
|
||||
pub static NODE_OVERRIDES: once_cell::sync::Lazy<NodeProperties> = once_cell::sync::Lazy::new(static_node_properties);
|
||||
|
||||
/// Defines the logic for inputs to display a custom Inspector widget.
|
||||
fn static_node_inspector() -> NodeInspector {
|
||||
let mut map: NodeInspector = HashMap::new();
|
||||
map.insert("brightness_contrast_inspector".to_string(), Box::new(node_inspector::brightness_contrast_inspector));
|
||||
map.insert("channel_mixer_inspector".to_string(), Box::new(node_inspector::channel_mixer_inspector));
|
||||
map.insert("levels_inspector".to_string(), Box::new(node_inspector::levels_inspector));
|
||||
map.insert("transfer_curves_inspector".to_string(), Box::new(node_inspector::transfer_curves_inspector));
|
||||
map.insert("hue_saturation_inspector".to_string(), Box::new(node_inspector::hue_saturation_inspector));
|
||||
map.insert("black_and_white_inspector".to_string(), Box::new(node_inspector::black_and_white_inspector));
|
||||
map.insert("threshold_inspector".to_string(), Box::new(node_inspector::threshold_inspector));
|
||||
map.insert("vibrance_inspector".to_string(), Box::new(node_inspector::vibrance_inspector));
|
||||
map.insert("color_balance_inspector".to_string(), Box::new(node_inspector::color_balance_inspector));
|
||||
map.insert("fill_inspector".to_string(), Box::new(node_inspector::fill_inspector));
|
||||
map.insert("stroke_inspector".to_string(), Box::new(node_inspector::stroke_inspector));
|
||||
map.insert("offset_path_inspector".to_string(), Box::new(node_inspector::offset_path_inspector));
|
||||
map.insert("selective_color_inspector".to_string(), Box::new(node_inspector::selective_color_inspector));
|
||||
map.insert("exposure_inspector".to_string(), Box::new(node_inspector::exposure_inspector));
|
||||
map.insert("format_number_inspector".to_string(), Box::new(node_inspector::format_number_inspector));
|
||||
map.insert("string_capitalization_inspector".to_string(), Box::new(node_inspector::string_capitalization_inspector));
|
||||
map.insert("rectangle_inspector".to_string(), Box::new(node_inspector::rectangle_inspector));
|
||||
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
|
||||
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
|
||||
map.insert("sample_polyline_inspector".to_string(), Box::new(node_inspector::sample_polyline_inspector));
|
||||
/// Defines the logic for inputs to display a custom Properties panel widget.
|
||||
fn static_node_properties() -> NodeProperties {
|
||||
let mut map: NodeProperties = HashMap::new();
|
||||
map.insert("brightness_contrast_properties".to_string(), Box::new(node_properties::brightness_contrast_properties));
|
||||
map.insert("channel_mixer_properties".to_string(), Box::new(node_properties::channel_mixer_properties));
|
||||
map.insert("levels_properties".to_string(), Box::new(node_properties::levels_properties));
|
||||
map.insert("transfer_curves_properties".to_string(), Box::new(node_properties::transfer_curves_properties));
|
||||
map.insert("hue_saturation_properties".to_string(), Box::new(node_properties::hue_saturation_properties));
|
||||
map.insert("black_and_white_properties".to_string(), Box::new(node_properties::black_and_white_properties));
|
||||
map.insert("threshold_properties".to_string(), Box::new(node_properties::threshold_properties));
|
||||
map.insert("vibrance_properties".to_string(), Box::new(node_properties::vibrance_properties));
|
||||
map.insert("color_balance_properties".to_string(), Box::new(node_properties::color_balance_properties));
|
||||
map.insert("fill_properties".to_string(), Box::new(node_properties::fill_properties));
|
||||
map.insert("stroke_properties".to_string(), Box::new(node_properties::stroke_properties));
|
||||
map.insert("offset_path_properties".to_string(), Box::new(node_properties::offset_path_properties));
|
||||
map.insert("selective_color_properties".to_string(), Box::new(node_properties::selective_color_properties));
|
||||
map.insert("exposure_properties".to_string(), Box::new(node_properties::exposure_properties));
|
||||
map.insert("format_number_properties".to_string(), Box::new(node_properties::format_number_properties));
|
||||
map.insert("string_capitalization_properties".to_string(), Box::new(node_properties::string_capitalization_properties));
|
||||
map.insert("rectangle_properties".to_string(), Box::new(node_properties::rectangle_properties));
|
||||
map.insert("grid_properties".to_string(), Box::new(node_properties::grid_properties));
|
||||
map.insert("spiral_properties".to_string(), Box::new(node_properties::spiral_properties));
|
||||
map.insert("sample_polyline_properties".to_string(), Box::new(node_properties::sample_polyline_properties));
|
||||
map.insert(
|
||||
"monitor_inspector".to_string(),
|
||||
Box::new(|_node_id, _context| node_inspector::string_inspector("Used internally by the editor to obtain a layer thumbnail.")),
|
||||
"monitor_properties".to_string(),
|
||||
Box::new(|_node_id, _context| node_properties::string_properties("Used internally by the editor to obtain a layer thumbnail.")),
|
||||
);
|
||||
map
|
||||
}
|
||||
|
||||
type InputInspector = HashMap<String, Box<dyn Fn(NodeId, usize, &mut NodeInspectorContext) -> Result<Vec<LayoutGroup>, String> + Send + Sync>>;
|
||||
type InputProperties = HashMap<String, Box<dyn Fn(NodeId, usize, &mut NodePropertiesContext) -> Result<Vec<LayoutGroup>, String> + Send + Sync>>;
|
||||
|
||||
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
|
||||
static INPUT_OVERRIDES: once_cell::sync::Lazy<InputInspector> = once_cell::sync::Lazy::new(static_input_inspector);
|
||||
static INPUT_OVERRIDES: once_cell::sync::Lazy<InputProperties> = once_cell::sync::Lazy::new(static_input_properties);
|
||||
|
||||
/// Defines the logic for inputs to display a custom Inspector widget.
|
||||
fn static_input_inspector() -> InputInspector {
|
||||
let mut map: InputInspector = HashMap::new();
|
||||
map.insert(
|
||||
"hidden".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
Ok(node_inspector::exposed_parameter_row(&ParameterWidgetsInfo::at_index(node_id, index, true, context))
|
||||
.into_iter()
|
||||
.collect())
|
||||
}),
|
||||
);
|
||||
/// Defines the logic for inputs to display a custom Properties panel widget.
|
||||
fn static_input_properties() -> InputProperties {
|
||||
let mut map: InputProperties = HashMap::new();
|
||||
map.insert("hidden".to_string(), Box::new(|_node_id, _index, _context| Ok(Vec::new())));
|
||||
map.insert(
|
||||
"string".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
// Falls back to the legacy key
|
||||
let network_interface = &context.network_interface;
|
||||
let Some(value) = network_interface
|
||||
.input_data(&node_id, index, "string_inspector", context.selection_network_path)
|
||||
.or_else(|| network_interface.input_data(&node_id, index, "string_properties", context.selection_network_path))
|
||||
else {
|
||||
return Err(format!("Could not get string Inspector input data for node {node_id}"));
|
||||
let Some(value) = context.network_interface.input_data(&node_id, index, "string_properties", context.selection_network_path) else {
|
||||
return Err(format!("Could not get string properties for node {node_id}"));
|
||||
};
|
||||
let Some(string) = value.as_str() else {
|
||||
return Err(format!("Could not downcast string Inspector input data for node {node_id}"));
|
||||
return Err(format!("Could not downcast string properties for node {node_id}"));
|
||||
};
|
||||
Ok(node_inspector::string_inspector(string))
|
||||
Ok(node_properties::string_properties(string))
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
@@ -991,7 +1042,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
true
|
||||
});
|
||||
|
||||
Ok(vec![LayoutGroup::row(node_inspector::number_widget(
|
||||
Ok(vec![LayoutGroup::row(node_properties::number_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, blank_assist, context),
|
||||
number_input,
|
||||
))])
|
||||
@@ -1013,7 +1064,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
if let Some(unit) = field.unit {
|
||||
number_input = number_input.unit(unit);
|
||||
}
|
||||
// Typing is clamped only by the hard bounds; the slider extent prefers the soft bounds (see `inspector_row_from_type`)
|
||||
// Typing is clamped only by the hard bounds; the slider extent prefers the soft bounds (see `property_from_type`)
|
||||
if let Some(hard_min) = field.number_hard_min {
|
||||
number_input = number_input.min(hard_min);
|
||||
}
|
||||
@@ -1032,7 +1083,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
}
|
||||
};
|
||||
// NOTE: The bool input MUST be at the input index directly before the f64 input!
|
||||
Ok(vec![LayoutGroup::row(node_inspector::optional_f64_widget(
|
||||
Ok(vec![LayoutGroup::row(node_properties::optional_f64_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, false, context),
|
||||
index - 1,
|
||||
number_input,
|
||||
@@ -1051,7 +1102,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
max: 100.,
|
||||
default: Some(100.),
|
||||
};
|
||||
Ok(vec![LayoutGroup::row(node_inspector::optional_f64_widget(
|
||||
Ok(vec![LayoutGroup::row(node_properties::optional_f64_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, false, context),
|
||||
index - 1,
|
||||
number_input,
|
||||
@@ -1062,7 +1113,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
map.insert(
|
||||
// A type-witness input, whose stored value's type selects the node's row: the dropdown lists the types the rows accept there
|
||||
"type_choice".to_string(),
|
||||
Box::new(|node_id, index, context| Ok(vec![node_inspector::type_choice_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context))])),
|
||||
Box::new(|node_id, index, context| Ok(vec![node_properties::type_choice_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context))])),
|
||||
);
|
||||
map.insert(
|
||||
"vec2".to_string(),
|
||||
@@ -1104,7 +1155,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
.and_then(|value| value.as_bool())
|
||||
.unwrap_or_default();
|
||||
|
||||
Ok(vec![node_inspector::vec2_widget(
|
||||
Ok(vec![node_properties::vec2_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
&x,
|
||||
&y,
|
||||
@@ -1115,10 +1166,10 @@ fn static_input_inspector() -> InputInspector {
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"noise_inspector_scale".to_string(),
|
||||
"noise_properties_scale".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let (_, coherent_noise_active, _, _, _, _) = node_inspector::query_noise_pattern_state(node_id, context)?;
|
||||
let scale = node_inspector::number_widget(
|
||||
let (_, coherent_noise_active, _, _, _, _) = node_properties::query_noise_pattern_state(node_id, context)?;
|
||||
let scale = node_properties::number_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
NumberInput::default().min(0.).disabled(!coherent_noise_active),
|
||||
);
|
||||
@@ -1126,28 +1177,28 @@ fn static_input_inspector() -> InputInspector {
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"noise_inspector_noise_type".to_string(),
|
||||
"noise_properties_noise_type".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let noise_type_row = enum_choice::<NoiseType>().for_socket(ParameterWidgetsInfo::at_index(node_id, index, true, context)).inspector_row();
|
||||
let noise_type_row = enum_choice::<NoiseType>().for_socket(ParameterWidgetsInfo::at_index(node_id, index, true, context)).property_row();
|
||||
Ok(vec![noise_type_row, LayoutGroup::row(Vec::new())])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"noise_inspector_domain_warp_type".to_string(),
|
||||
"noise_properties_domain_warp_type".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let (_, coherent_noise_active, _, _, _, _) = node_inspector::query_noise_pattern_state(node_id, context)?;
|
||||
let (_, coherent_noise_active, _, _, _, _) = node_properties::query_noise_pattern_state(node_id, context)?;
|
||||
let domain_warp_type = enum_choice::<DomainWarpType>()
|
||||
.for_socket(ParameterWidgetsInfo::at_index(node_id, index, true, context))
|
||||
.disabled(!coherent_noise_active)
|
||||
.inspector_row();
|
||||
.property_row();
|
||||
Ok(vec![domain_warp_type])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"noise_inspector_domain_warp_amplitude".to_string(),
|
||||
"noise_properties_domain_warp_amplitude".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let (_, coherent_noise_active, _, _, domain_warp_active, _) = node_inspector::query_noise_pattern_state(node_id, context)?;
|
||||
let domain_warp_amplitude = node_inspector::number_widget(
|
||||
let (_, coherent_noise_active, _, _, domain_warp_active, _) = node_properties::query_noise_pattern_state(node_id, context)?;
|
||||
let domain_warp_amplitude = node_properties::number_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
NumberInput::default().min(0.).disabled(!coherent_noise_active || !domain_warp_active),
|
||||
);
|
||||
@@ -1155,21 +1206,21 @@ fn static_input_inspector() -> InputInspector {
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"noise_inspector_fractal_type".to_string(),
|
||||
"noise_properties_fractal_type".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let (_, coherent_noise_active, _, _, _, _) = node_inspector::query_noise_pattern_state(node_id, context)?;
|
||||
let (_, coherent_noise_active, _, _, _, _) = node_properties::query_noise_pattern_state(node_id, context)?;
|
||||
let fractal_type_row = enum_choice::<FractalType>()
|
||||
.for_socket(ParameterWidgetsInfo::at_index(node_id, index, true, context))
|
||||
.disabled(!coherent_noise_active)
|
||||
.inspector_row();
|
||||
.property_row();
|
||||
Ok(vec![fractal_type_row])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"noise_inspector_fractal_octaves".to_string(),
|
||||
"noise_properties_fractal_octaves".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let (fractal_active, coherent_noise_active, _, _, _, domain_warp_only_fractal_type_wrongly_active) = node_inspector::query_noise_pattern_state(node_id, context)?;
|
||||
let fractal_octaves = node_inspector::number_widget(
|
||||
let (fractal_active, coherent_noise_active, _, _, _, domain_warp_only_fractal_type_wrongly_active) = node_properties::query_noise_pattern_state(node_id, context)?;
|
||||
let fractal_octaves = node_properties::number_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
NumberInput::default()
|
||||
.mode_range()
|
||||
@@ -1183,10 +1234,10 @@ fn static_input_inspector() -> InputInspector {
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"noise_inspector_fractal_lacunarity".to_string(),
|
||||
"noise_properties_fractal_lacunarity".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let (fractal_active, coherent_noise_active, _, _, _, domain_warp_only_fractal_type_wrongly_active) = node_inspector::query_noise_pattern_state(node_id, context)?;
|
||||
let fractal_lacunarity = node_inspector::number_widget(
|
||||
let (fractal_active, coherent_noise_active, _, _, _, domain_warp_only_fractal_type_wrongly_active) = node_properties::query_noise_pattern_state(node_id, context)?;
|
||||
let fractal_lacunarity = node_properties::number_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
NumberInput::default()
|
||||
.mode_range()
|
||||
@@ -1198,10 +1249,10 @@ fn static_input_inspector() -> InputInspector {
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"noise_inspector_fractal_gain".to_string(),
|
||||
"noise_properties_fractal_gain".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let (fractal_active, coherent_noise_active, _, _, _, domain_warp_only_fractal_type_wrongly_active) = node_inspector::query_noise_pattern_state(node_id, context)?;
|
||||
let fractal_gain = node_inspector::number_widget(
|
||||
let (fractal_active, coherent_noise_active, _, _, _, domain_warp_only_fractal_type_wrongly_active) = node_properties::query_noise_pattern_state(node_id, context)?;
|
||||
let fractal_gain = node_properties::number_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
NumberInput::default()
|
||||
.mode_range()
|
||||
@@ -1213,10 +1264,10 @@ fn static_input_inspector() -> InputInspector {
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"noise_inspector_fractal_weighted_strength".to_string(),
|
||||
"noise_properties_fractal_weighted_strength".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let (fractal_active, coherent_noise_active, _, _, _, domain_warp_only_fractal_type_wrongly_active) = node_inspector::query_noise_pattern_state(node_id, context)?;
|
||||
let fractal_weighted_strength = node_inspector::range_slider_widget(
|
||||
let (fractal_active, coherent_noise_active, _, _, _, domain_warp_only_fractal_type_wrongly_active) = node_properties::query_noise_pattern_state(node_id, context)?;
|
||||
let fractal_weighted_strength = node_properties::range_slider_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
NumberInput::default()
|
||||
.min(0.)
|
||||
@@ -1228,10 +1279,10 @@ fn static_input_inspector() -> InputInspector {
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"noise_inspector_ping_pong_strength".to_string(),
|
||||
"noise_properties_ping_pong_strength".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let (fractal_active, coherent_noise_active, _, ping_pong_active, _, domain_warp_only_fractal_type_wrongly_active) = node_inspector::query_noise_pattern_state(node_id, context)?;
|
||||
let fractal_ping_pong_strength = node_inspector::number_widget(
|
||||
let (fractal_active, coherent_noise_active, _, ping_pong_active, _, domain_warp_only_fractal_type_wrongly_active) = node_properties::query_noise_pattern_state(node_id, context)?;
|
||||
let fractal_ping_pong_strength = node_properties::number_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
NumberInput::default()
|
||||
.mode_range()
|
||||
@@ -1243,32 +1294,32 @@ fn static_input_inspector() -> InputInspector {
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"noise_inspector_cellular_distance_function".to_string(),
|
||||
"noise_properties_cellular_distance_function".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let (_, coherent_noise_active, cellular_noise_active, _, _, _) = node_inspector::query_noise_pattern_state(node_id, context)?;
|
||||
let (_, coherent_noise_active, cellular_noise_active, _, _, _) = node_properties::query_noise_pattern_state(node_id, context)?;
|
||||
let cellular_distance_function_row = enum_choice::<CellularDistanceFunction>()
|
||||
.for_socket(ParameterWidgetsInfo::at_index(node_id, index, true, context))
|
||||
.disabled(!coherent_noise_active || !cellular_noise_active)
|
||||
.inspector_row();
|
||||
.property_row();
|
||||
Ok(vec![cellular_distance_function_row])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"noise_inspector_cellular_return_type".to_string(),
|
||||
"noise_properties_cellular_return_type".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let (_, coherent_noise_active, cellular_noise_active, _, _, _) = node_inspector::query_noise_pattern_state(node_id, context)?;
|
||||
let (_, coherent_noise_active, cellular_noise_active, _, _, _) = node_properties::query_noise_pattern_state(node_id, context)?;
|
||||
let cellular_return_type = enum_choice::<CellularReturnType>()
|
||||
.for_socket(ParameterWidgetsInfo::at_index(node_id, index, true, context))
|
||||
.disabled(!coherent_noise_active || !cellular_noise_active)
|
||||
.inspector_row();
|
||||
.property_row();
|
||||
Ok(vec![cellular_return_type])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"noise_inspector_cellular_jitter".to_string(),
|
||||
"noise_properties_cellular_jitter".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let (_, coherent_noise_active, cellular_noise_active, _, _, _) = node_inspector::query_noise_pattern_state(node_id, context)?;
|
||||
let cellular_jitter = node_inspector::number_widget(
|
||||
let (_, coherent_noise_active, cellular_noise_active, _, _, _) = node_properties::query_noise_pattern_state(node_id, context)?;
|
||||
let cellular_jitter = node_properties::number_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
NumberInput::default()
|
||||
.mode_range()
|
||||
@@ -1282,15 +1333,15 @@ fn static_input_inspector() -> InputInspector {
|
||||
map.insert(
|
||||
"assign_colors_gradient".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let gradient_row = node_inspector::color_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context), ColorInput::default().allow_none(false));
|
||||
let gradient_row = node_properties::color_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context), ColorInput::default().allow_none(false));
|
||||
Ok(vec![gradient_row])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"assign_colors_seed".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let randomize_enabled = node_inspector::query_assign_colors_randomize(node_id, context)?;
|
||||
let seed_row = node_inspector::number_widget(
|
||||
let randomize_enabled = node_properties::query_assign_colors_randomize(node_id, context)?;
|
||||
let seed_row = node_properties::number_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
NumberInput::default().min(0.).int().disabled(!randomize_enabled),
|
||||
);
|
||||
@@ -1300,8 +1351,8 @@ fn static_input_inspector() -> InputInspector {
|
||||
map.insert(
|
||||
"assign_colors_repeat_every".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let randomize_enabled = node_inspector::query_assign_colors_randomize(node_id, context)?;
|
||||
let repeat_every_row = node_inspector::number_widget(
|
||||
let randomize_enabled = node_properties::query_assign_colors_randomize(node_id, context)?;
|
||||
let repeat_every_row = node_properties::number_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
NumberInput::default().min(0.).int().disabled(randomize_enabled),
|
||||
);
|
||||
@@ -1311,9 +1362,9 @@ fn static_input_inspector() -> InputInspector {
|
||||
map.insert(
|
||||
"transform_rotation".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let mut widgets = node_inspector::start_widgets(&ParameterWidgetsInfo::at_index(node_id, index, true, context));
|
||||
let mut widgets = node_properties::start_widgets(&ParameterWidgetsInfo::at_index(node_id, index, true, context));
|
||||
|
||||
let document_node = node_inspector::get_document_node(node_id, context)?;
|
||||
let document_node = node_properties::get_document_node(node_id, context)?;
|
||||
let Some(input) = document_node.inputs.get(index) else {
|
||||
return Err("Input not found in transform rotation input override".to_string());
|
||||
};
|
||||
@@ -1325,12 +1376,12 @@ fn static_input_inspector() -> InputInspector {
|
||||
.mode(NumberInputMode::Range)
|
||||
.range_min(Some(-180.))
|
||||
.range_max(Some(180.))
|
||||
.on_update(node_inspector::update_value_at_index(
|
||||
.on_update(node_properties::update_value_at_index(
|
||||
|number_input: &NumberInput| TaggedValue::Number(number_input.value.unwrap()),
|
||||
node_id,
|
||||
index,
|
||||
))
|
||||
.on_commit(node_inspector::commit_value)
|
||||
.on_commit(node_properties::commit_value)
|
||||
.widget_instance(),
|
||||
]);
|
||||
}
|
||||
@@ -1342,7 +1393,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
map.insert(
|
||||
"transform_translation".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
Ok(vec![node_inspector::vec2_widget(
|
||||
Ok(vec![node_properties::vec2_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
"X",
|
||||
"Y",
|
||||
@@ -1356,7 +1407,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
map.insert(
|
||||
"transform_scale".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
Ok(vec![node_inspector::vec2_widget(
|
||||
Ok(vec![node_properties::vec2_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
"W",
|
||||
"H",
|
||||
@@ -1370,9 +1421,9 @@ fn static_input_inspector() -> InputInspector {
|
||||
map.insert(
|
||||
"transform_skew".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let mut widgets = node_inspector::start_widgets(&ParameterWidgetsInfo::at_index(node_id, index, true, context));
|
||||
let mut widgets = node_properties::start_widgets(&ParameterWidgetsInfo::at_index(node_id, index, true, context));
|
||||
|
||||
let document_node = node_inspector::get_document_node(node_id, context)?;
|
||||
let document_node = node_properties::get_document_node(node_id, context)?;
|
||||
let Some(input) = document_node.inputs.get(index) else {
|
||||
return Err("Input not found in transform skew input override".to_string());
|
||||
};
|
||||
@@ -1384,12 +1435,12 @@ fn static_input_inspector() -> InputInspector {
|
||||
.unit("°")
|
||||
.min(-89.9)
|
||||
.max(89.9)
|
||||
.on_update(node_inspector::update_value_at_index(
|
||||
.on_update(node_properties::update_value_at_index(
|
||||
move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), val.y)),
|
||||
node_id,
|
||||
index,
|
||||
))
|
||||
.on_commit(node_inspector::commit_value)
|
||||
.on_commit(node_properties::commit_value)
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
NumberInput::new(Some(val.y))
|
||||
@@ -1397,12 +1448,12 @@ fn static_input_inspector() -> InputInspector {
|
||||
.unit("°")
|
||||
.min(-89.9)
|
||||
.max(89.9)
|
||||
.on_update(node_inspector::update_value_at_index(
|
||||
.on_update(node_properties::update_value_at_index(
|
||||
move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(val.x, input.value.unwrap())),
|
||||
node_id,
|
||||
index,
|
||||
))
|
||||
.on_commit(node_inspector::commit_value)
|
||||
.on_commit(node_properties::commit_value)
|
||||
.widget_instance(),
|
||||
]);
|
||||
}
|
||||
@@ -1412,14 +1463,14 @@ fn static_input_inspector() -> InputInspector {
|
||||
);
|
||||
map.insert(
|
||||
"text_area".to_string(),
|
||||
Box::new(|node_id, index, context| Ok(vec![LayoutGroup::row(node_inspector::text_area_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context)))])),
|
||||
Box::new(|node_id, index, context| Ok(vec![LayoutGroup::row(node_properties::text_area_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context)))])),
|
||||
);
|
||||
map.insert(
|
||||
// A math expression, flagged with a warning icon while it fails to parse
|
||||
"math_expression".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
Ok(vec![LayoutGroup::row(node_inspector::math_expression_widget(info, false))])
|
||||
Ok(vec![LayoutGroup::row(node_properties::math_expression_widget(info, false))])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
@@ -1427,7 +1478,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"math_expression_or_reducer".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
Ok(vec![LayoutGroup::row(node_inspector::math_expression_widget(info, true))])
|
||||
Ok(vec![LayoutGroup::row(node_properties::math_expression_widget(info, true))])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
@@ -1437,7 +1488,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
if context.fonts.font_catalog.is_empty() {
|
||||
context.responses.add(FontsMessage::LoadCatalog);
|
||||
}
|
||||
let (font, style) = node_inspector::font_inputs(ParameterWidgetsInfo::at_index(node_id, index, true, context));
|
||||
let (font, style) = node_properties::font_inputs(ParameterWidgetsInfo::at_index(node_id, index, true, context));
|
||||
let mut result = vec![LayoutGroup::row(font)];
|
||||
if let Some(style) = style {
|
||||
result.push(LayoutGroup::row(style));
|
||||
@@ -1448,21 +1499,21 @@ fn static_input_inspector() -> InputInspector {
|
||||
map.insert(
|
||||
"image_file".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let widgets = node_inspector::resource_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context), vec![TypeFilter::raster()]);
|
||||
let widgets = node_properties::resource_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context), vec![TypeFilter::raster()]);
|
||||
Ok(vec![LayoutGroup::row(widgets)])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"lut_file".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let widgets = node_inspector::resource_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context), vec![TypeFilter::lut()]);
|
||||
let widgets = node_properties::resource_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context), vec![TypeFilter::lut()]);
|
||||
Ok(vec![LayoutGroup::row(widgets)])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"artboard_background".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
Ok(vec![node_inspector::color_widget(
|
||||
Ok(vec![node_properties::color_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
ColorInput::default().allow_none(false),
|
||||
)])
|
||||
@@ -1473,7 +1524,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
Box::new(|node_id, index, context| {
|
||||
let choices = enum_choice::<text::TextAlign>()
|
||||
.for_socket(ParameterWidgetsInfo::at_index(node_id, index, true, context))
|
||||
.inspector_row();
|
||||
.property_row();
|
||||
Ok(vec![choices])
|
||||
}),
|
||||
);
|
||||
@@ -1620,7 +1671,7 @@ impl InputTypeConstraint {
|
||||
pub fn collect_node_types() -> Vec<FrontendNodeType> {
|
||||
DOCUMENT_NODE_TYPES
|
||||
.iter()
|
||||
.filter(|(_, definition)| !registry::is_hidden_category(definition.category))
|
||||
.filter(|(_, definition)| !definition.category.is_empty())
|
||||
.map(|(identifier, definition)| {
|
||||
let mut name = definition.node_template.display_name.clone();
|
||||
if name.is_empty() {
|
||||
@@ -1639,14 +1690,12 @@ pub fn collect_node_types() -> Vec<FrontendNodeType> {
|
||||
pub fn collect_node_descriptions() -> Vec<(String, String)> {
|
||||
DOCUMENT_NODE_TYPES
|
||||
.iter()
|
||||
.map(|(identifier, definition)| (identifier.serialized(), definition.description.to_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())))
|
||||
.map(|(identifier, definition)| {
|
||||
(
|
||||
identifier.serialized(),
|
||||
if definition.description != "TODO" { definition.description.to_string() } else { String::new() },
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -1665,7 +1714,7 @@ impl DocumentNodeDefinition {
|
||||
}
|
||||
});
|
||||
|
||||
// Ensure that the input metadata is initialized for every input of every node
|
||||
// Ensure that the input properties are initialized for every input of every node
|
||||
template.normalize_input_metadata();
|
||||
|
||||
template
|
||||
@@ -1702,6 +1751,8 @@ 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
|
||||
@@ -1721,6 +1772,8 @@ 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");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-20
@@ -38,12 +38,10 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
let NodeMetadata {
|
||||
display_name,
|
||||
category,
|
||||
icon,
|
||||
fields,
|
||||
description,
|
||||
inspector,
|
||||
properties,
|
||||
context_features,
|
||||
output_fields,
|
||||
..
|
||||
} = metadata;
|
||||
|
||||
@@ -68,20 +66,6 @@ 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 {
|
||||
@@ -101,13 +85,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),
|
||||
inspector: *inspector,
|
||||
properties: *properties,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
pub mod document_node_definitions;
|
||||
mod node_graph_message;
|
||||
mod node_graph_message_handler;
|
||||
pub mod node_inspector;
|
||||
pub mod node_properties;
|
||||
pub mod utility_types;
|
||||
|
||||
#[doc(inline)]
|
||||
|
||||
@@ -2,7 +2,7 @@ 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::{ChainInsertionPoint, ChainNodeCopy, ImportOrExport, InputConnector, NodeTemplate, OutputConnector, RootNode};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{ImportOrExport, InputConnector, NodeTemplate, OutputConnector};
|
||||
use crate::messages::prelude::*;
|
||||
use glam::IVec2;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
@@ -19,16 +19,8 @@ pub enum NodeGraphMessage {
|
||||
},
|
||||
AddPathNode,
|
||||
AddImport,
|
||||
/// Adds the import at `import_index` wired to `input_connector`, from a wire dragged out of a dimmed connector for adding one.
|
||||
/// Index 0 fills the empty primary, and any other is the next secondary import.
|
||||
AddImportAndConnect {
|
||||
import_index: usize,
|
||||
input_connector: InputConnector,
|
||||
},
|
||||
/// Inserts a Passthrough node beside the import that takes over the wires it fed, so nodes can be placed in front of all of them at once.
|
||||
AddImportPassthrough {
|
||||
import_index: usize,
|
||||
},
|
||||
AddPrimaryImport,
|
||||
AddSecondaryImport,
|
||||
AddExport,
|
||||
AddPrimaryExport,
|
||||
AddSecondaryExport,
|
||||
@@ -68,14 +60,7 @@ pub enum NodeGraphMessage {
|
||||
DisconnectInput {
|
||||
input_connector: InputConnector,
|
||||
},
|
||||
/// Disconnects every wire an import feeds, or the wire feeding an export.
|
||||
DisconnectImportExport {
|
||||
index: ImportOrExport,
|
||||
},
|
||||
DisconnectRootNode,
|
||||
SetRootNodeToRestore {
|
||||
root_node_to_restore: RootNode,
|
||||
},
|
||||
EnterNestedNetwork,
|
||||
DuplicateSelectedNodes,
|
||||
ExposeInput {
|
||||
@@ -83,10 +68,7 @@ pub enum NodeGraphMessage {
|
||||
set_to_exposed: bool,
|
||||
start_transaction: bool,
|
||||
},
|
||||
/// Whether the subgraph node shows its input for an import as a connector rather than as a parameter in the Inspector.
|
||||
/// A hidden primary import also disappears from the subgraph.
|
||||
ExposeEncapsulatingInput {
|
||||
input_index: usize,
|
||||
ExposeEncapsulatingPrimaryInput {
|
||||
exposed: bool,
|
||||
},
|
||||
ExposePrimaryExport {
|
||||
@@ -112,23 +94,10 @@ pub enum NodeGraphMessage {
|
||||
node_id: NodeId,
|
||||
parent: LayerNodeIdentifier,
|
||||
},
|
||||
MoveChainNodes {
|
||||
node_ids: Vec<NodeId>,
|
||||
layer: NodeId,
|
||||
ReorderChainNode {
|
||||
node_id: 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,
|
||||
@@ -152,8 +121,6 @@ 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,
|
||||
ShakeNode,
|
||||
UpdateNodeGraphWidth,
|
||||
RemoveImport {
|
||||
@@ -162,10 +129,6 @@ pub enum NodeGraphMessage {
|
||||
RemoveExport {
|
||||
export_index: usize,
|
||||
},
|
||||
/// Removes an import or export, or hides it if it's the primary, since the primary slot always remains.
|
||||
RemoveImportExport {
|
||||
index: ImportOrExport,
|
||||
},
|
||||
ReorderImport {
|
||||
start_index: usize,
|
||||
end_index: usize,
|
||||
@@ -249,14 +212,6 @@ pub enum NodeGraphMessage {
|
||||
name: String,
|
||||
index: ImportOrExport,
|
||||
},
|
||||
SetImportExportDescription {
|
||||
description: String,
|
||||
index: ImportOrExport,
|
||||
},
|
||||
SetImportExportDescriptionImpl {
|
||||
description: String,
|
||||
index: ImportOrExport,
|
||||
},
|
||||
ToggleSelectedAsLayersOrNodes,
|
||||
ToggleSelectedLocked,
|
||||
ToggleLocked {
|
||||
@@ -291,6 +246,7 @@ pub enum NodeGraphMessage {
|
||||
node_ids: Vec<NodeId>,
|
||||
network_path: Vec<NodeId>,
|
||||
},
|
||||
UpdateEdges,
|
||||
UpdateBoxSelection,
|
||||
UpdateImportsExports,
|
||||
UpdateLayerPanel,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+240
-366
File diff suppressed because it is too large.
Load diff
@@ -51,8 +51,9 @@ pub struct FrontendGraphInput {
|
||||
pub resolved_type: String,
|
||||
#[serde(rename = "validTypes")]
|
||||
pub valid_types: Vec<String>,
|
||||
/// Whether a wire feeds this input.
|
||||
pub connected: bool,
|
||||
#[serde(rename = "connectedTo")]
|
||||
/// Either "nothing", "import #{index}", or "{node name} #{output_index}".
|
||||
pub connected_to: String,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -64,11 +65,10 @@ pub struct FrontendGraphOutput {
|
||||
pub description: String,
|
||||
#[serde(rename = "resolvedType")]
|
||||
pub resolved_type: String,
|
||||
/// Every type this output could produce given its node's current inputs, or empty where that isn't known.
|
||||
#[serde(rename = "possibleTypes")]
|
||||
pub possible_types: Vec<String>,
|
||||
/// Whether this output feeds at least one wire.
|
||||
pub connected: bool,
|
||||
/// If connected to an export, it is "export index {index}".
|
||||
/// If connected to a node, it is "{node name} input {input_index}".
|
||||
#[serde(rename = "connectedTo")]
|
||||
pub connected_to: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -161,16 +161,6 @@ pub enum ContextMenuData {
|
||||
#[serde(rename = "compatibleType")]
|
||||
compatible_type: Option<String>,
|
||||
},
|
||||
/// An import or export of the viewed subgraph, by its index among the imports or the exports.
|
||||
ModifyImportExport {
|
||||
#[serde(rename = "isImport")]
|
||||
is_import: bool,
|
||||
index: u32,
|
||||
/// For an import, whether the subgraph node shows its input as a connector rather than as a parameter in the Inspector.
|
||||
exposed: bool,
|
||||
/// Whether any wire is attached to it within the subgraph.
|
||||
connected: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -206,8 +196,8 @@ pub struct FrontendClickTargets {
|
||||
pub icon_click_targets: Vec<String>,
|
||||
#[serde(rename = "allNodesBoundingBox")]
|
||||
pub all_nodes_bounding_box: String,
|
||||
#[serde(rename = "importExportNames")]
|
||||
pub import_export_names: Vec<String>,
|
||||
#[serde(rename = "modifyImportExport")]
|
||||
pub modify_import_export: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
|
||||
@@ -231,7 +231,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
|
||||
widgets.push(LayoutGroup::row(vec![TextLabel::new("Grid").bold(true).widget_instance()]));
|
||||
|
||||
widgets.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("Type").sizing(WidgetSizing::fixed(60)).table_align(true).widget_instance(),
|
||||
TextLabel::new("Type").min_width(60).max_width(60).table_align(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
RadioInput::new(vec![
|
||||
RadioEntryData::new("rectangular").label("Rectangular").on_update(update_val(grid, |grid, _| {
|
||||
@@ -253,7 +253,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
|
||||
};
|
||||
})),
|
||||
])
|
||||
.sizing(WidgetSizing::default().min_width(200))
|
||||
.min_width(200)
|
||||
.selected_index(Some(match grid.grid_type {
|
||||
GridType::Rectangular { .. } => 0,
|
||||
GridType::Isometric { .. } => 1,
|
||||
@@ -262,7 +262,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
|
||||
]));
|
||||
|
||||
let mut color_widgets = vec![
|
||||
TextLabel::new("Display").sizing(WidgetSizing::fixed(60)).table_align(true).widget_instance(),
|
||||
TextLabel::new("Display").min_width(60).max_width(60).table_align(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
];
|
||||
color_widgets.extend([
|
||||
@@ -287,32 +287,32 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
|
||||
widgets.push(LayoutGroup::row(color_widgets));
|
||||
|
||||
widgets.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("Origin").sizing(WidgetSizing::fixed(60)).table_align(true).widget_instance(),
|
||||
TextLabel::new("Origin").min_width(60).max_width(60).table_align(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(grid.origin.x))
|
||||
.label("X")
|
||||
.unit(" px")
|
||||
.sizing(WidgetSizing::default().min_width(98))
|
||||
.min_width(98)
|
||||
.on_update(update_origin(grid, |grid| Some(&mut grid.origin.x)))
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
NumberInput::new(Some(grid.origin.y))
|
||||
.label("Y")
|
||||
.unit(" px")
|
||||
.sizing(WidgetSizing::default().min_width(98))
|
||||
.min_width(98)
|
||||
.on_update(update_origin(grid, |grid| Some(&mut grid.origin.y)))
|
||||
.widget_instance(),
|
||||
]));
|
||||
|
||||
match grid.grid_type {
|
||||
GridType::Rectangular { spacing } => widgets.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("Spacing").sizing(WidgetSizing::fixed(60)).table_align(true).widget_instance(),
|
||||
TextLabel::new("Spacing").min_width(60).max_width(60).table_align(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(spacing.x))
|
||||
.label("X")
|
||||
.unit(" px")
|
||||
.min(0.)
|
||||
.sizing(WidgetSizing::default().min_width(98))
|
||||
.min_width(98)
|
||||
.on_update(update_origin(grid, |grid| grid.grid_type.rectangular_spacing().map(|spacing| &mut spacing.x)))
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
@@ -320,33 +320,33 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
|
||||
.label("Y")
|
||||
.unit(" px")
|
||||
.min(0.)
|
||||
.sizing(WidgetSizing::default().min_width(98))
|
||||
.min_width(98)
|
||||
.on_update(update_origin(grid, |grid| grid.grid_type.rectangular_spacing().map(|spacing| &mut spacing.y)))
|
||||
.widget_instance(),
|
||||
])),
|
||||
GridType::Isometric { y_axis_spacing, angle_a, angle_b } => {
|
||||
widgets.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("Y Spacing").sizing(WidgetSizing::fixed(60)).table_align(true).widget_instance(),
|
||||
TextLabel::new("Y Spacing").min_width(60).max_width(60).table_align(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(y_axis_spacing))
|
||||
.unit(" px")
|
||||
.min(0.)
|
||||
.sizing(WidgetSizing::default().min_width(200))
|
||||
.min_width(200)
|
||||
.on_update(update_origin(grid, |grid| grid.grid_type.isometric_y_spacing()))
|
||||
.widget_instance(),
|
||||
]));
|
||||
widgets.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("Angles").sizing(WidgetSizing::fixed(60)).table_align(true).widget_instance(),
|
||||
TextLabel::new("Angles").min_width(60).max_width(60).table_align(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(angle_a))
|
||||
.unit("°")
|
||||
.sizing(WidgetSizing::default().min_width(98))
|
||||
.min_width(98)
|
||||
.on_update(update_origin(grid, |grid| grid.grid_type.angle_a()))
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
NumberInput::new(Some(angle_b))
|
||||
.unit("°")
|
||||
.sizing(WidgetSizing::default().min_width(98))
|
||||
.min_width(98)
|
||||
.on_update(update_origin(grid, |grid| grid.grid_type.angle_b()))
|
||||
.widget_instance(),
|
||||
]));
|
||||
|
||||
@@ -9,8 +9,7 @@ pub struct OverlaysMessageContext<'a> {
|
||||
|
||||
#[derive(Debug, Clone, Default, ExtractField)]
|
||||
pub struct OverlaysMessageHandler {
|
||||
/// In the order they were added, which is the order they draw in.
|
||||
pub overlay_providers: Vec<OverlayProvider>,
|
||||
pub overlay_providers: HashSet<OverlayProvider>,
|
||||
#[cfg(target_family = "wasm")]
|
||||
canvas: Option<web_sys::HtmlCanvasElement>,
|
||||
#[cfg(target_family = "wasm")]
|
||||
@@ -64,13 +63,6 @@ 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(),
|
||||
@@ -88,7 +80,6 @@ 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()));
|
||||
@@ -101,12 +92,10 @@ impl MessageHandler<OverlaysMessage, OverlaysMessageContext<'_>> for OverlaysMes
|
||||
let _ = (responses, visibility_settings, viewport);
|
||||
}
|
||||
OverlaysMessage::AddProvider { provider: message } => {
|
||||
// A provider added again moves to the end, so it draws on top from then on
|
||||
self.overlay_providers.retain(|provider| !std::ptr::fn_addr_eq(*provider, message));
|
||||
self.overlay_providers.push(message);
|
||||
self.overlay_providers.insert(message);
|
||||
}
|
||||
OverlaysMessage::RemoveProvider { provider: message } => {
|
||||
self.overlay_providers.retain(|provider| !std::ptr::fn_addr_eq(*provider, message));
|
||||
self.overlay_providers.remove(&message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1043,7 +1043,7 @@ impl OverlayContext {
|
||||
};
|
||||
let y = match pivot[1] {
|
||||
Pivot::Start => padding + metrics.font_bounding_box_ascent() - metrics.font_bounding_box_descent(),
|
||||
Pivot::Middle => (metrics.font_bounding_box_ascent() - metrics.font_bounding_box_descent()) / 2.,
|
||||
Pivot::Middle => (metrics.font_bounding_box_ascent() + metrics.font_bounding_box_descent()) / 2.,
|
||||
Pivot::End => -padding,
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
mod properties_panel_message;
|
||||
pub mod properties_panel_message_handler;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use properties_panel_message::{PropertiesPanelMessage, PropertiesPanelMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use properties_panel_message_handler::PropertiesPanelMessageHandler;
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[impl_message(Message, DocumentMessage, Inspector)]
|
||||
#[impl_message(Message, DocumentMessage, PropertiesPanel)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum InspectorMessage {
|
||||
pub enum PropertiesPanelMessage {
|
||||
// Messages
|
||||
Clear,
|
||||
Refresh,
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
use graphene_std::uuid::NodeId;
|
||||
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::NodePropertiesContext;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct PropertiesPanelMessageContext<'a> {
|
||||
pub executor: &'a mut NodeGraphExecutor,
|
||||
pub document_id: DocumentId,
|
||||
pub network_interface: &'a mut NodeNetworkInterface,
|
||||
pub resources: &'a ResourceMessageHandler,
|
||||
pub selection_network_path: &'a [NodeId],
|
||||
pub document_name: &'a str,
|
||||
pub fonts: &'a FontsMessageHandler,
|
||||
pub properties_panel_open: bool,
|
||||
pub properties_panel_collapsed_sections: &'a [NodeId],
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, ExtractField)]
|
||||
pub struct PropertiesPanelMessageHandler {}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<PropertiesPanelMessage, PropertiesPanelMessageContext<'_>> for PropertiesPanelMessageHandler {
|
||||
fn process_message(&mut self, message: PropertiesPanelMessage, responses: &mut VecDeque<Message>, context: PropertiesPanelMessageContext) {
|
||||
let PropertiesPanelMessageContext {
|
||||
executor,
|
||||
document_id,
|
||||
network_interface,
|
||||
resources,
|
||||
selection_network_path,
|
||||
document_name,
|
||||
fonts,
|
||||
properties_panel_open,
|
||||
properties_panel_collapsed_sections,
|
||||
} = context;
|
||||
|
||||
match message {
|
||||
PropertiesPanelMessage::Clear => {
|
||||
responses.add(LayoutMessage::SendLayout {
|
||||
layout: Layout::default(),
|
||||
layout_target: LayoutTarget::PropertiesPanel,
|
||||
});
|
||||
}
|
||||
PropertiesPanelMessage::Refresh => {
|
||||
if !properties_panel_open {
|
||||
responses.add(PropertiesPanelMessage::Clear);
|
||||
return;
|
||||
}
|
||||
|
||||
let mut node_properties_context = NodePropertiesContext {
|
||||
responses,
|
||||
executor,
|
||||
document_id,
|
||||
network_interface,
|
||||
resources,
|
||||
selection_network_path,
|
||||
document_name,
|
||||
fonts,
|
||||
properties_panel_collapsed_sections,
|
||||
};
|
||||
let layout = Layout(NodeGraphMessageHandler::collate_properties(&mut node_properties_context));
|
||||
|
||||
node_properties_context.responses.add(LayoutMessage::SendLayout {
|
||||
layout,
|
||||
layout_target: LayoutTarget::PropertiesPanel,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn actions(&self) -> ActionList {
|
||||
actions!(PropertiesMessageDiscriminant;)
|
||||
}
|
||||
}
|
||||
@@ -8,29 +8,20 @@ use std::collections::{BTreeSet, HashMap};
|
||||
|
||||
use document_graph_storage::{NodeMetadataSource, PeerId, Registry, to_value};
|
||||
|
||||
use super::test_support::{load_demo, load_demo_with_output_descriptions, node_paths, open_demo};
|
||||
use super::test_support::{load_demo, node_paths};
|
||||
use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeLocator;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::{DocumentSettings, StorageMetadataView, build_interface_from_storage};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::CollapsedLayers;
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
|
||||
/// Storage drops output descriptions that are all empty, which means the same as having none.
|
||||
fn normalize_output_descriptions(output_descriptions: Vec<String>) -> Vec<String> {
|
||||
if output_descriptions.iter().all(String::is_empty) { Vec::new() } else { output_descriptions }
|
||||
}
|
||||
|
||||
/// Loads a demo artwork, round-trips its `NodeNetwork + NodeNetworkInterface metadata` through
|
||||
/// `Registry`, and asserts every node's `ui::*` attributes survive unchanged.
|
||||
///
|
||||
/// Uses one demo (rather than the full set) because this is an exhaustive per-node check.
|
||||
#[test]
|
||||
fn editor_metadata_round_trip_against_demo() {
|
||||
let document = load_demo_with_output_descriptions("changing-seasons.graphite");
|
||||
let document = load_demo("changing-seasons.graphite");
|
||||
let interface = &document.network_interface;
|
||||
let source = StorageMetadataView::new(interface);
|
||||
|
||||
@@ -48,7 +39,6 @@ fn editor_metadata_round_trip_against_demo() {
|
||||
let mut checked_any_position = false;
|
||||
let mut checked_any_layer = false;
|
||||
let mut checked_any_input_metadata = false;
|
||||
let mut checked_any_output_description = false;
|
||||
|
||||
for (network_path, local_id) in node_paths(interface) {
|
||||
let expected_position = source.position(&network_path, local_id);
|
||||
@@ -57,7 +47,6 @@ fn editor_metadata_round_trip_against_demo() {
|
||||
let expected_locked = source.locked(&network_path, local_id);
|
||||
let expected_pinned = source.pinned(&network_path, local_id);
|
||||
let expected_output_names = source.output_names(&network_path, local_id);
|
||||
let expected_output_descriptions = normalize_output_descriptions(source.output_descriptions(&network_path, local_id));
|
||||
|
||||
// Use the node's input count as the slot-by-slot iteration bound for the per-input metadata checks.
|
||||
let input_count = interface.document_node(&local_id, &network_path).map(|node| node.inputs.len()).unwrap_or(0);
|
||||
@@ -84,10 +73,6 @@ fn editor_metadata_round_trip_against_demo() {
|
||||
assert_eq!(entry.locked, expected_locked, "locked mismatch for node {local_id:?} in network {network_path:?}");
|
||||
assert_eq!(entry.pinned, expected_pinned, "pinned mismatch for node {local_id:?} in network {network_path:?}");
|
||||
assert_eq!(entry.output_names, expected_output_names, "output_names mismatch for node {local_id:?} in network {network_path:?}");
|
||||
assert_eq!(
|
||||
entry.output_descriptions, expected_output_descriptions,
|
||||
"output_descriptions mismatch for node {local_id:?} in network {network_path:?}"
|
||||
);
|
||||
|
||||
// Per-input metadata: the entry's `input_metadata` has one slot per input, each matching the trait's
|
||||
// per-field view (same "empty string ↔ None" normalization as `display_name`).
|
||||
@@ -130,9 +115,6 @@ fn editor_metadata_round_trip_against_demo() {
|
||||
if any_input_metadata_present {
|
||||
checked_any_input_metadata = true;
|
||||
}
|
||||
if !expected_output_descriptions.is_empty() {
|
||||
checked_any_output_description = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Sanity: a real artwork should exercise at least these two shapes; otherwise the test is
|
||||
@@ -142,7 +124,6 @@ fn editor_metadata_round_trip_against_demo() {
|
||||
// Demo artworks always have some custom widget overrides / input names; if not, the
|
||||
// per-input round-trip isn't actually being exercised here.
|
||||
assert!(checked_any_input_metadata, "demo artwork produced no per-input metadata: fixture is wrong or extraction is broken");
|
||||
assert!(checked_any_output_description, "no output descriptions were round-tripped: fixture is wrong or extraction is broken");
|
||||
}
|
||||
|
||||
/// Full editor-side round-trip: original interface → Registry → (NodeNetwork, Vec<entry>) →
|
||||
@@ -150,7 +131,7 @@ fn editor_metadata_round_trip_against_demo() {
|
||||
/// the original when read through `StorageMetadataView`.
|
||||
#[test]
|
||||
fn editor_interface_rebuild_round_trip() {
|
||||
let document = load_demo_with_output_descriptions("changing-seasons.graphite");
|
||||
let document = load_demo("changing-seasons.graphite");
|
||||
let original = &document.network_interface;
|
||||
let original_view = StorageMetadataView::new(original);
|
||||
|
||||
@@ -232,11 +213,6 @@ fn editor_interface_rebuild_round_trip() {
|
||||
original_view.output_names(&network_path, local_id),
|
||||
"output_names mismatch for node {local_id:?} in network {network_path:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_output_descriptions(rebuilt_view.output_descriptions(&network_path, local_id)),
|
||||
normalize_output_descriptions(original_view.output_descriptions(&network_path, local_id)),
|
||||
"output_descriptions mismatch for node {local_id:?} in network {network_path:?}"
|
||||
);
|
||||
}
|
||||
|
||||
// Symmetric: every node in the original must also exist in the rebuilt interface.
|
||||
@@ -308,57 +284,6 @@ fn migrating_a_document_records_no_changes() {
|
||||
assert!(recorded.is_empty(), "migration left {} recorded changes behind", recorded.len());
|
||||
}
|
||||
|
||||
/// The first Merge node in a document, as its network path and ID.
|
||||
fn first_merge(document: &DocumentMessageHandler) -> (Vec<NodeId>, NodeId) {
|
||||
let merge = Some(DefinitionIdentifier::Network("Merge".into()));
|
||||
node_paths(&document.network_interface)
|
||||
.into_iter()
|
||||
.find(|(network_path, node_id)| document.network_interface.reference(node_id, network_path) == merge)
|
||||
.expect("the demo artwork should have a Merge node")
|
||||
}
|
||||
|
||||
/// Opening a document fills in the output descriptions of a node saved before its definition had any.
|
||||
#[test]
|
||||
fn opening_a_document_fills_output_descriptions_a_node_was_saved_without() {
|
||||
let mut document = open_demo("changing-seasons.graphite");
|
||||
let (network_path, node_id) = first_merge(&document);
|
||||
|
||||
// Saved as it would have been before Merge's definition described its output
|
||||
let mut node = document.network_interface.node_mut(NodeLocator::new(node_id, &network_path)).expect("the Merge node should exist");
|
||||
node.set_output_descriptions(Vec::new());
|
||||
|
||||
let content = document.serialize_document();
|
||||
let reopened = load_legacy_document(content, &HashMapResourceStorage::new(), false).expect("the saved document should open");
|
||||
|
||||
let definition_description = resolve_document_node_type(&DefinitionIdentifier::Network("Merge".into()))
|
||||
.and_then(|definition| definition.node_template.output_descriptions.first().cloned())
|
||||
.filter(|description| !description.is_empty())
|
||||
.expect("Merge's definition should describe its output");
|
||||
assert_eq!(
|
||||
reopened.network_interface.output_description(&node_id, 0, &network_path),
|
||||
definition_description,
|
||||
"the Merge node should be given its definition's output description"
|
||||
);
|
||||
}
|
||||
|
||||
/// An output description that was emptied stays empty when the document is saved and opened again, rather than being filled from the definition.
|
||||
#[test]
|
||||
fn an_emptied_output_description_stays_empty_after_reopening() {
|
||||
let mut document = open_demo("changing-seasons.graphite");
|
||||
let (network_path, node_id) = first_merge(&document);
|
||||
|
||||
let mut node = document.network_interface.node_mut(NodeLocator::new(node_id, &network_path)).expect("the Merge node should exist");
|
||||
node.set_output_descriptions(vec![String::new()]);
|
||||
|
||||
let content = document.serialize_document();
|
||||
let reopened = load_legacy_document(content, &HashMapResourceStorage::new(), false).expect("the saved document should open");
|
||||
assert_eq!(
|
||||
reopened.network_interface.output_description(&node_id, 0, &network_path),
|
||||
"",
|
||||
"the emptied description should stay empty"
|
||||
);
|
||||
}
|
||||
|
||||
/// The pinned display order is document state, so it survives a registry round trip. It names nodes and
|
||||
/// the stored form uses storage IDs, so this also checks the references resolve back to the right
|
||||
/// runtime nodes.
|
||||
|
||||
@@ -546,6 +546,8 @@ 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
|
||||
|
||||
@@ -10,8 +10,8 @@ use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId};
|
||||
|
||||
use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::{DocumentSettings, StorageMetadataView, build_interface_from_storage};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{NodeLocator, NodeNetworkInterface};
|
||||
|
||||
/// Load a demo `.graphite` straight into a `DocumentMessageHandler` for inspection.
|
||||
pub fn load_demo(file_name: &str) -> DocumentMessageHandler {
|
||||
@@ -20,33 +20,6 @@ pub fn load_demo(file_name: &str) -> DocumentMessageHandler {
|
||||
DocumentMessageHandler::deserialize_document(&content).unwrap_or_else(|e| panic!("Failed to deserialize {path}: {e:?}"))
|
||||
}
|
||||
|
||||
/// Open a demo `.graphite` the way the editor does, with its migrations and load-time fix-ups.
|
||||
pub fn open_demo(file_name: &str) -> DocumentMessageHandler {
|
||||
let path = format!("../demo-artwork/{file_name}");
|
||||
let content = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("Failed to read {path}: {e}"));
|
||||
crate::messages::portfolio::document_storage_io::load_legacy_document(content, &HashMapResourceStorage::new(), false).unwrap_or_else(|e| panic!("Failed to open {path}: {e:?}"))
|
||||
}
|
||||
|
||||
/// Load a demo `.graphite` and describe every subgraph node's outputs, which the demos predate, so a round trip has output descriptions to carry.
|
||||
pub fn load_demo_with_output_descriptions(file_name: &str) -> DocumentMessageHandler {
|
||||
let mut document = load_demo(file_name);
|
||||
let interface = &mut document.network_interface;
|
||||
|
||||
for (network_path, node_id) in node_paths(interface) {
|
||||
let node_path = [network_path.as_slice(), &[node_id]].concat();
|
||||
let Some(export_count) = interface.nested_network(&node_path).map(|network| network.exports.len()) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let output_descriptions = (0..export_count).map(|index| format!("Output {index} of node {node_id}.")).collect();
|
||||
if let Some(mut node) = interface.node_mut(NodeLocator::new(node_id, &network_path)) {
|
||||
node.set_output_descriptions(output_descriptions);
|
||||
}
|
||||
}
|
||||
|
||||
document
|
||||
}
|
||||
|
||||
/// Walk every node in every nested network and collect `(network_path, local_id)` pairs, so a test can
|
||||
/// iterate every node addressable from the metadata side.
|
||||
pub fn node_paths(interface: &NodeNetworkInterface) -> Vec<(Vec<NodeId>, NodeId)> {
|
||||
|
||||
@@ -11,11 +11,10 @@ use graphene_std::math::quad::Quad;
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
|
||||
use kurbo::BezPath;
|
||||
use kurbo::{Affine, BezPath};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::num::NonZeroU64;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
// ================
|
||||
// DocumentMetadata
|
||||
@@ -45,11 +44,6 @@ pub struct DocumentMetadata {
|
||||
pub layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>,
|
||||
/// Transform from document space to viewport space.
|
||||
pub document_to_viewport: DAffine2,
|
||||
/// The transform from document space to viewport space that the latest render was made with, which is the one `upstream_footprints` include.
|
||||
pub rendered_document_to_viewport: DAffine2,
|
||||
/// A number that is replaced whenever the layer structure, or the geometry and transforms a render reported, change.
|
||||
/// Anything derived from them is up to date for as long as this is the number it was derived at.
|
||||
pub generation: u64,
|
||||
}
|
||||
|
||||
// =================================
|
||||
@@ -130,30 +124,6 @@ impl DocumentMetadata {
|
||||
self.document_to_viewport.inverse() * self.transform_to_viewport_if_feeds(layer, network_interface)
|
||||
}
|
||||
|
||||
/// The transformation to document space from layer space as the latest render had it.
|
||||
/// Unlike [`Self::transform_to_document`], this stays correct after the view changes and before the next render reports back.
|
||||
pub fn transform_to_document_as_rendered(&self, layer: LayerNodeIdentifier) -> DAffine2 {
|
||||
self.document_to_viewport_placing(layer).inverse() * self.transform_to_viewport(layer)
|
||||
}
|
||||
|
||||
/// The counterpart of [`Self::transform_to_document_as_rendered`] for [`Self::transform_to_document_if_feeds`].
|
||||
pub fn transform_to_document_as_rendered_if_feeds(&self, layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> DAffine2 {
|
||||
self.document_to_viewport_placing(layer).inverse() * self.transform_to_viewport_if_feeds(layer, network_interface)
|
||||
}
|
||||
|
||||
/// The view that [`Self::transform_to_viewport`] places a layer by: the latest render's for a layer it reported a footprint for, and the present one for any other, such as the root.
|
||||
fn document_to_viewport_placing(&self, layer: LayerNodeIdentifier) -> DAffine2 {
|
||||
let reported = layer != LayerNodeIdentifier::ROOT_PARENT && self.upstream_footprints.contains_key(&layer.to_node());
|
||||
if reported { self.rendered_document_to_viewport } else { self.document_to_viewport }
|
||||
}
|
||||
|
||||
/// Notes that the layer structure, or something a render reported, has changed.
|
||||
pub fn mark_changed(&mut self) {
|
||||
// Drawing from one counter for every document keeps a number from ever standing for two states, including across the swaps that undo and redo make
|
||||
static NEXT_GENERATION: AtomicU64 = AtomicU64::new(1);
|
||||
self.generation = NEXT_GENERATION.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn transform_to_viewport_with_first_transform_node_if_group(&self, layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> DAffine2 {
|
||||
let footprint = self.upstream_footprints.get(&layer.to_node()).map(|footprint| footprint.transform).unwrap_or(self.document_to_viewport);
|
||||
let local_transform = self.local_transforms.get(&layer.to_node()).copied();
|
||||
@@ -213,6 +183,23 @@ impl DocumentMetadata {
|
||||
.reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
/// Get the loose bounding box of the click target of the specified layer in the specified transform space
|
||||
pub fn loose_bounding_box_with_transform(&self, layer: LayerNodeIdentifier, transform: DAffine2) -> Option<[DVec2; 2]> {
|
||||
self.visual_targets(layer)?
|
||||
.iter()
|
||||
.filter_map(|click_target| match click_target.target_type() {
|
||||
ClickTargetType::Path(path) => {
|
||||
let mut transformed = path.clone();
|
||||
transformed.apply_affine(Affine::new(transform.to_cols_array()));
|
||||
|
||||
let control_box = transformed.control_box();
|
||||
(!transformed.is_empty()).then(|| [DVec2::new(control_box.min_x(), control_box.min_y()), DVec2::new(control_box.max_x(), control_box.max_y())])
|
||||
}
|
||||
ClickTargetType::FreePoint(_) => click_target.bounding_box_with_transform(transform),
|
||||
})
|
||||
.reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
/// Calculate the corners of the bounding box but with a nonzero size.
|
||||
///
|
||||
/// If the layer bounds are `0` in either axis then they are changed to be `1`.
|
||||
@@ -608,63 +595,6 @@ pub struct NodeRelations {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_transform_as_rendered_stays_put_while_the_view_moves_on() {
|
||||
let layer = LayerNodeIdentifier::new_unchecked(NodeId(3));
|
||||
let rendered_view = DAffine2::from_scale_angle_translation(DVec2::splat(2.), 0.3, DVec2::new(40., -10.));
|
||||
let layer_to_document = DAffine2::from_translation(DVec2::new(100., 50.)) * DAffine2::from_angle(0.5);
|
||||
|
||||
// A render made at one view reports where it drew the layer
|
||||
let mut metadata = DocumentMetadata {
|
||||
document_to_viewport: rendered_view,
|
||||
rendered_document_to_viewport: rendered_view,
|
||||
..Default::default()
|
||||
};
|
||||
let footprint = Footprint {
|
||||
transform: rendered_view * layer_to_document,
|
||||
..Default::default()
|
||||
};
|
||||
metadata.upstream_footprints.insert(layer.to_node(), footprint);
|
||||
assert!(metadata.transform_to_document_as_rendered(layer).abs_diff_eq(layer_to_document, 1e-9));
|
||||
|
||||
// Panning and zooming before the next render reports back leaves the layer where it was in the document
|
||||
metadata.document_to_viewport = DAffine2::from_scale_angle_translation(DVec2::splat(5.), -0.2, DVec2::new(-300., 80.));
|
||||
assert!(metadata.transform_to_document_as_rendered(layer).abs_diff_eq(layer_to_document, 1e-9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_root_and_a_layer_without_a_footprint_stay_put_as_rendered_while_the_view_moves_on() {
|
||||
let unreported_layer = LayerNodeIdentifier::new_unchecked(NodeId(3));
|
||||
let rendered_view = DAffine2::from_scale_angle_translation(DVec2::splat(2.), 0.3, DVec2::new(40., -10.));
|
||||
let mut metadata = DocumentMetadata {
|
||||
document_to_viewport: rendered_view,
|
||||
rendered_document_to_viewport: rendered_view,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Panning and zooming before the next render reports back leaves them lined up with the document
|
||||
metadata.document_to_viewport = DAffine2::from_scale_angle_translation(DVec2::splat(5.), -0.2, DVec2::new(-300., 80.));
|
||||
for layer in [LayerNodeIdentifier::ROOT_PARENT, unreported_layer] {
|
||||
assert!(metadata.transform_to_document_as_rendered(layer).abs_diff_eq(DAffine2::IDENTITY, 1e-9));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_two_states_share_a_generation() {
|
||||
let mut first = DocumentMetadata::default();
|
||||
let mut second = DocumentMetadata::default();
|
||||
|
||||
first.mark_changed();
|
||||
let earlier = first.clone();
|
||||
second.mark_changed();
|
||||
first.mark_changed();
|
||||
|
||||
// A copy kept from before, as undo keeps one, still has the number that stood for its own state alone
|
||||
let generations = [earlier.generation, first.generation, second.generation, DocumentMetadata::default().generation];
|
||||
assert!(generations.iter().enumerate().all(|(index, generation)| !generations[..index].contains(generation)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tree() {
|
||||
let mut metadata = DocumentMetadata::default();
|
||||
|
||||
@@ -64,6 +64,7 @@ pub struct SnappingState {
|
||||
pub snapping_enabled: bool,
|
||||
pub grid_snapping: bool,
|
||||
pub artboards: bool,
|
||||
pub tolerance: f64,
|
||||
pub bounding_box: BoundingBoxSnapping,
|
||||
pub path: PathSnapping,
|
||||
pub grid: GridSnapping,
|
||||
@@ -75,6 +76,7 @@ impl Default for SnappingState {
|
||||
snapping_enabled: true,
|
||||
grid_snapping: false,
|
||||
artboards: true,
|
||||
tolerance: 8.,
|
||||
bounding_box: BoundingBoxSnapping::default(),
|
||||
path: PathSnapping::default(),
|
||||
grid: GridSnapping::default(),
|
||||
@@ -82,6 +84,36 @@ impl Default for SnappingState {
|
||||
}
|
||||
}
|
||||
|
||||
impl SnappingState {
|
||||
pub const fn target_enabled(&self, target: SnapTarget) -> bool {
|
||||
if !self.snapping_enabled {
|
||||
return false;
|
||||
}
|
||||
match target {
|
||||
SnapTarget::BoundingBox(target) => match target {
|
||||
BoundingBoxSnapTarget::CornerPoint => self.bounding_box.corner_point,
|
||||
BoundingBoxSnapTarget::EdgeMidpoint => self.bounding_box.edge_midpoint,
|
||||
BoundingBoxSnapTarget::CenterPoint => self.bounding_box.center_point,
|
||||
},
|
||||
SnapTarget::Path(target) => match target {
|
||||
PathSnapTarget::AnchorPointWithColinearHandles | PathSnapTarget::AnchorPointWithFreeHandles => self.path.anchor_point,
|
||||
PathSnapTarget::LineMidpoint => self.path.line_midpoint,
|
||||
PathSnapTarget::AlongPath => self.path.along_path,
|
||||
PathSnapTarget::NormalToPath => self.path.normal_to_path,
|
||||
PathSnapTarget::TangentToPath => self.path.tangent_to_path,
|
||||
PathSnapTarget::IntersectionPoint => self.path.path_intersection_point,
|
||||
PathSnapTarget::PerpendicularToEndpoint => self.path.perpendicular_from_endpoint,
|
||||
},
|
||||
SnapTarget::Artboard(_) => self.artboards,
|
||||
SnapTarget::Grid(_) => self.grid_snapping,
|
||||
SnapTarget::Alignment(AlignmentSnapTarget::AlignWithAnchorPoint) => self.path.align_with_anchor_point,
|
||||
SnapTarget::Alignment(_) => self.bounding_box.align_with_edges,
|
||||
SnapTarget::DistributeEvenly(_) => self.bounding_box.distribute_evenly,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct BoundingBoxSnapping {
|
||||
@@ -112,7 +144,9 @@ pub struct PathSnapping {
|
||||
pub along_path: bool,
|
||||
pub normal_to_path: bool,
|
||||
pub tangent_to_path: bool,
|
||||
pub path_intersection_point: bool,
|
||||
pub align_with_anchor_point: bool, // TODO: Rename
|
||||
pub perpendicular_from_endpoint: bool,
|
||||
}
|
||||
|
||||
impl Default for PathSnapping {
|
||||
@@ -123,7 +157,9 @@ impl Default for PathSnapping {
|
||||
along_path: true,
|
||||
normal_to_path: true,
|
||||
tangent_to_path: true,
|
||||
path_intersection_point: true,
|
||||
align_with_anchor_point: true,
|
||||
perpendicular_from_endpoint: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -233,6 +269,136 @@ impl GridSnapping {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum BoundingBoxSnapSource {
|
||||
CornerPoint,
|
||||
CenterPoint,
|
||||
EdgeMidpoint,
|
||||
}
|
||||
|
||||
impl fmt::Display for BoundingBoxSnapSource {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
BoundingBoxSnapSource::CornerPoint => write!(f, "Bounding Box: Corner Point"),
|
||||
BoundingBoxSnapSource::CenterPoint => write!(f, "Bounding Box: Center Point"),
|
||||
BoundingBoxSnapSource::EdgeMidpoint => write!(f, "Bounding Box: Edge Midpoint"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ArtboardSnapSource {
|
||||
CornerPoint,
|
||||
CenterPoint,
|
||||
}
|
||||
|
||||
impl fmt::Display for ArtboardSnapSource {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
ArtboardSnapSource::CornerPoint => write!(f, "Artboard: Corner Point"),
|
||||
ArtboardSnapSource::CenterPoint => write!(f, "Artboard: Center Point"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PathSnapSource {
|
||||
AnchorPointWithColinearHandles,
|
||||
AnchorPointWithFreeHandles,
|
||||
HandlePoint,
|
||||
LineMidpoint,
|
||||
IntersectionPoint,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum GradientSnapSource {
|
||||
Endpoint,
|
||||
}
|
||||
|
||||
impl fmt::Display for GradientSnapSource {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
GradientSnapSource::Endpoint => write!(f, "Gradient: Endpoint"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for PathSnapSource {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
PathSnapSource::AnchorPointWithColinearHandles | PathSnapSource::AnchorPointWithFreeHandles => write!(f, "Path: Anchor Point"),
|
||||
PathSnapSource::HandlePoint => write!(f, "Path: Handle Point"),
|
||||
PathSnapSource::LineMidpoint => write!(f, "Path: Line Midpoint"),
|
||||
PathSnapSource::IntersectionPoint => write!(f, "Path: Intersection Point"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AlignmentSnapSource {
|
||||
BoundingBoxCornerPoint,
|
||||
BoundingBoxCenterPoint,
|
||||
BoundingBoxEdgeMidpoint,
|
||||
ArtboardCornerPoint,
|
||||
ArtboardCenterPoint,
|
||||
}
|
||||
|
||||
impl fmt::Display for AlignmentSnapSource {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
AlignmentSnapSource::BoundingBoxCornerPoint => write!(f, "{}", BoundingBoxSnapSource::CornerPoint),
|
||||
AlignmentSnapSource::BoundingBoxCenterPoint => write!(f, "{}", BoundingBoxSnapSource::CenterPoint),
|
||||
AlignmentSnapSource::BoundingBoxEdgeMidpoint => write!(f, "{}", BoundingBoxSnapSource::EdgeMidpoint),
|
||||
AlignmentSnapSource::ArtboardCornerPoint => write!(f, "{}", ArtboardSnapSource::CornerPoint),
|
||||
AlignmentSnapSource::ArtboardCenterPoint => write!(f, "{}", ArtboardSnapSource::CenterPoint),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SnapSource {
|
||||
#[default]
|
||||
None,
|
||||
BoundingBox(BoundingBoxSnapSource),
|
||||
Artboard(ArtboardSnapSource),
|
||||
Path(PathSnapSource),
|
||||
Alignment(AlignmentSnapSource),
|
||||
Gradient(GradientSnapSource),
|
||||
}
|
||||
|
||||
impl SnapSource {
|
||||
pub fn is_some(&self) -> bool {
|
||||
self != &Self::None
|
||||
}
|
||||
pub fn bounding_box(&self) -> bool {
|
||||
matches!(self, Self::BoundingBox(_) | Self::Artboard(_))
|
||||
}
|
||||
pub fn align(&self) -> bool {
|
||||
matches!(self, Self::Alignment(_))
|
||||
}
|
||||
pub fn center(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Alignment(AlignmentSnapSource::ArtboardCenterPoint | AlignmentSnapSource::BoundingBoxCenterPoint)
|
||||
| Self::Artboard(ArtboardSnapSource::CenterPoint)
|
||||
| Self::BoundingBox(BoundingBoxSnapSource::CenterPoint)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for SnapSource {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
SnapSource::None => write!(f, "None"),
|
||||
SnapSource::BoundingBox(bounding_box_snap_source) => write!(f, "{bounding_box_snap_source}"),
|
||||
SnapSource::Artboard(artboard_snap_source) => write!(f, "{artboard_snap_source}"),
|
||||
SnapSource::Path(path_snap_source) => write!(f, "{path_snap_source}"),
|
||||
SnapSource::Alignment(alignment_snap_source) => write!(f, "{alignment_snap_source}"),
|
||||
SnapSource::Gradient(gradient_snap_source) => write!(f, "{gradient_snap_source}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type GetSnapState = for<'a> fn(&'a mut SnappingState) -> &'a mut bool;
|
||||
pub const SNAP_FUNCTIONS_FOR_BOUNDING_BOXES: [(&str, GetSnapState, &str); 5] = [
|
||||
(
|
||||
@@ -261,7 +427,7 @@ pub const SNAP_FUNCTIONS_FOR_BOUNDING_BOXES: [(&str, GetSnapState, &str); 5] = [
|
||||
"Snaps to a consistent distance offset established by the bounding boxes of nearby layers.",
|
||||
),
|
||||
];
|
||||
pub const SNAP_FUNCTIONS_FOR_PATHS: [(&str, GetSnapState, &str); 6] = [
|
||||
pub const SNAP_FUNCTIONS_FOR_PATHS: [(&str, GetSnapState, &str); 7] = [
|
||||
(
|
||||
"Align with Anchor Points",
|
||||
(|snapping_state: &mut SnappingState| &mut snapping_state.path.align_with_anchor_point) as GetSnapState,
|
||||
@@ -278,23 +444,205 @@ pub const SNAP_FUNCTIONS_FOR_PATHS: [(&str, GetSnapState, &str); 6] = [
|
||||
(|snapping_state: &mut SnappingState| &mut snapping_state.path.line_midpoint) as GetSnapState,
|
||||
"Snaps to the point at the middle of any straight line segment of a vector path.",
|
||||
),
|
||||
(
|
||||
"Path Intersection Points",
|
||||
(|snapping_state: &mut SnappingState| &mut snapping_state.path.path_intersection_point) as GetSnapState,
|
||||
"Snaps to any points where vector paths intersect.",
|
||||
),
|
||||
(
|
||||
"Along Paths",
|
||||
(|snapping_state: &mut SnappingState| &mut snapping_state.path.along_path) as GetSnapState,
|
||||
"Snaps along the length of any vector path.",
|
||||
),
|
||||
(
|
||||
// TODO: This works correctly for line segments, but not curved segments.
|
||||
// TODO: Therefore, we should make this use the normal in relation to the incoming curve, not the straight line between the incoming curve's start point and the path.
|
||||
"Normal to Paths",
|
||||
(|snapping_state: &mut SnappingState| &mut snapping_state.path.normal_to_path) as GetSnapState,
|
||||
"Snaps a line to a point perpendicular to a vector path.",
|
||||
// TODO: Fix the bug/limitation that requires 'Intersections of Paths' to be enabled
|
||||
"Snaps a line to a point perpendicular to a vector path.\n(Due to a bug, 'Intersections of Paths' must be enabled.)",
|
||||
),
|
||||
(
|
||||
// TODO: This works correctly for line segments, but not curved segments.
|
||||
// TODO: Therefore, we should make this use the tangent in relation to the incoming curve, not the straight line between the incoming curve's start point and the path.
|
||||
"Tangent to Paths",
|
||||
(|snapping_state: &mut SnappingState| &mut snapping_state.path.tangent_to_path) as GetSnapState,
|
||||
"Snaps a line to a point tangent to a vector path.",
|
||||
// TODO: Fix the bug/limitation that requires 'Intersections of Paths' to be enabled
|
||||
"Snaps a line to a point tangent to a vector path.\n(Due to a bug, 'Intersections of Paths' must be enabled.)",
|
||||
),
|
||||
];
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum BoundingBoxSnapTarget {
|
||||
CornerPoint,
|
||||
CenterPoint,
|
||||
EdgeMidpoint,
|
||||
}
|
||||
|
||||
impl fmt::Display for BoundingBoxSnapTarget {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
BoundingBoxSnapTarget::CornerPoint => write!(f, "Bounding Box: Corner Point"),
|
||||
BoundingBoxSnapTarget::CenterPoint => write!(f, "Bounding Box: Center Point"),
|
||||
BoundingBoxSnapTarget::EdgeMidpoint => write!(f, "Bounding Box: Edge Midpoint"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum PathSnapTarget {
|
||||
AnchorPointWithColinearHandles,
|
||||
AnchorPointWithFreeHandles,
|
||||
LineMidpoint,
|
||||
AlongPath,
|
||||
NormalToPath,
|
||||
TangentToPath,
|
||||
IntersectionPoint,
|
||||
PerpendicularToEndpoint,
|
||||
}
|
||||
|
||||
impl fmt::Display for PathSnapTarget {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
PathSnapTarget::AnchorPointWithColinearHandles | PathSnapTarget::AnchorPointWithFreeHandles => write!(f, "Path: Anchor Point"),
|
||||
PathSnapTarget::LineMidpoint => write!(f, "Path: Line Midpoint"),
|
||||
PathSnapTarget::AlongPath => write!(f, "Path: Along Path"),
|
||||
PathSnapTarget::NormalToPath => write!(f, "Path: Normal to Path"),
|
||||
PathSnapTarget::TangentToPath => write!(f, "Path: Tangent to Path"),
|
||||
PathSnapTarget::IntersectionPoint => write!(f, "Path: Intersection Point"),
|
||||
PathSnapTarget::PerpendicularToEndpoint => write!(f, "Path: Perp. to Endpoint"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ArtboardSnapTarget {
|
||||
CornerPoint,
|
||||
CenterPoint,
|
||||
AlongEdge,
|
||||
}
|
||||
|
||||
impl fmt::Display for ArtboardSnapTarget {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
ArtboardSnapTarget::CornerPoint => write!(f, "Artboard: Corner Point"),
|
||||
ArtboardSnapTarget::CenterPoint => write!(f, "Artboard: Center Point"),
|
||||
ArtboardSnapTarget::AlongEdge => write!(f, "Artboard: Along Edge"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum GridSnapTarget {
|
||||
Line,
|
||||
LineNormal,
|
||||
Intersection,
|
||||
}
|
||||
|
||||
impl fmt::Display for GridSnapTarget {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
GridSnapTarget::Line => write!(f, "Grid: Along Line"),
|
||||
GridSnapTarget::LineNormal => write!(f, "Grid: Normal to Line"),
|
||||
GridSnapTarget::Intersection => write!(f, "Grid: Intersection Point"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AlignmentSnapTarget {
|
||||
BoundingBoxCornerPoint,
|
||||
BoundingBoxCenterPoint,
|
||||
ArtboardCornerPoint,
|
||||
ArtboardCenterPoint,
|
||||
AlignWithAnchorPoint,
|
||||
IntersectionPoint,
|
||||
PerpendicularToEndpoint,
|
||||
}
|
||||
|
||||
impl fmt::Display for AlignmentSnapTarget {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
AlignmentSnapTarget::BoundingBoxCornerPoint => write!(f, "{}", BoundingBoxSnapTarget::CornerPoint),
|
||||
AlignmentSnapTarget::BoundingBoxCenterPoint => write!(f, "{}", BoundingBoxSnapTarget::CenterPoint),
|
||||
AlignmentSnapTarget::ArtboardCornerPoint => write!(f, "{}", ArtboardSnapTarget::CornerPoint),
|
||||
AlignmentSnapTarget::ArtboardCenterPoint => write!(f, "{}", ArtboardSnapTarget::CenterPoint),
|
||||
AlignmentSnapTarget::AlignWithAnchorPoint => write!(f, "{}", PathSnapTarget::AnchorPointWithColinearHandles),
|
||||
AlignmentSnapTarget::IntersectionPoint => write!(f, "{}", PathSnapTarget::IntersectionPoint),
|
||||
AlignmentSnapTarget::PerpendicularToEndpoint => write!(f, "{}", PathSnapTarget::PerpendicularToEndpoint),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DistributionSnapTarget {
|
||||
X,
|
||||
Y,
|
||||
Right,
|
||||
Left,
|
||||
Up,
|
||||
Down,
|
||||
XY,
|
||||
}
|
||||
|
||||
impl fmt::Display for DistributionSnapTarget {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
DistributionSnapTarget::X => write!(f, "Distribute: X"),
|
||||
DistributionSnapTarget::Y => write!(f, "Distribute: Y"),
|
||||
DistributionSnapTarget::Right => write!(f, "Distribute: Right"),
|
||||
DistributionSnapTarget::Left => write!(f, "Distribute: Left"),
|
||||
DistributionSnapTarget::Up => write!(f, "Distribute: Up"),
|
||||
DistributionSnapTarget::Down => write!(f, "Distribute: Down"),
|
||||
DistributionSnapTarget::XY => write!(f, "Distribute: XY"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DistributionSnapTarget {
|
||||
pub const fn is_x(&self) -> bool {
|
||||
matches!(self, Self::Left | Self::Right | Self::X)
|
||||
}
|
||||
pub const fn is_y(&self) -> bool {
|
||||
matches!(self, Self::Up | Self::Down | Self::Y)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SnapTarget {
|
||||
#[default]
|
||||
None,
|
||||
BoundingBox(BoundingBoxSnapTarget),
|
||||
Path(PathSnapTarget),
|
||||
Artboard(ArtboardSnapTarget),
|
||||
Grid(GridSnapTarget),
|
||||
Alignment(AlignmentSnapTarget),
|
||||
DistributeEvenly(DistributionSnapTarget),
|
||||
}
|
||||
|
||||
impl SnapTarget {
|
||||
pub fn is_some(&self) -> bool {
|
||||
self != &Self::None
|
||||
}
|
||||
pub fn bounding_box(&self) -> bool {
|
||||
matches!(self, Self::BoundingBox(_) | Self::Artboard(_))
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for SnapTarget {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
SnapTarget::None => write!(f, "None"),
|
||||
SnapTarget::BoundingBox(bounding_box_snap_target) => write!(f, "{bounding_box_snap_target}"),
|
||||
SnapTarget::Path(path_snap_target) => write!(f, "{path_snap_target}"),
|
||||
SnapTarget::Artboard(artboard_snap_target) => write!(f, "{artboard_snap_target}"),
|
||||
SnapTarget::Grid(grid_snap_target) => write!(f, "{grid_snap_target}"),
|
||||
SnapTarget::Alignment(alignment_snap_target) => write!(f, "{alignment_snap_target}"),
|
||||
SnapTarget::DistributeEvenly(distribution_snap_target) => write!(f, "{distribution_snap_target}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: implement icons for SnappingOptions eventually
|
||||
pub enum SnappingOptions {
|
||||
BoundingBoxes,
|
||||
@@ -318,18 +666,11 @@ 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,7 +25,6 @@ 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::*;
|
||||
@@ -55,7 +54,6 @@ 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};
|
||||
@@ -92,15 +90,6 @@ 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 {
|
||||
@@ -112,9 +101,6 @@ 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ impl NodeNetworkInterface {
|
||||
// A peer can name a slot past the end of this network's exports, which is an insert here
|
||||
// rather than a write to a slot that does not exist yet.
|
||||
Some(input) if *export_index >= self.number_of_exports(network_path) => {
|
||||
self.insert_export_slot(network_path, *export_index, input.clone(), String::new(), String::new());
|
||||
self.insert_export_slot(network_path, *export_index, input.clone(), String::new());
|
||||
}
|
||||
Some(input) => {
|
||||
self.set_input_slot(&InputConnector::Export(*export_index), network_path, input.clone());
|
||||
@@ -107,7 +107,6 @@ impl NodeNetworkInterface {
|
||||
NodeMetadataChange::Locked(locked) => node.set_locked(*locked),
|
||||
NodeMetadataChange::Pinned(pinned) => node.set_pinned(*pinned),
|
||||
NodeMetadataChange::OutputNames(output_names) => node.set_output_names(output_names.clone()),
|
||||
NodeMetadataChange::OutputDescriptions(output_descriptions) => node.set_output_descriptions(output_descriptions.clone()),
|
||||
NodeMetadataChange::InputName { index, name } => node.set_input_name(*index, name.clone()),
|
||||
NodeMetadataChange::WidgetOverride { index, widget_override } => node.set_widget_override(*index, widget_override.clone()),
|
||||
};
|
||||
|
||||
Loaded 100 of 393 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user