mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
33
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3902163e03 | ||
|
|
99824a70a9 | ||
|
|
c25410185c | ||
|
|
93665c5e9d | ||
|
|
ccb02ddf8d | ||
|
|
305cd02332 | ||
|
|
3394695fb9 | ||
|
|
47f56b481c | ||
|
|
bdab64eb29 | ||
|
|
0fe91cc0fd | ||
|
|
06672ddb39 | ||
|
|
e060233d7c | ||
|
|
70e0c51fae | ||
|
|
3e46541ea0 | ||
|
|
526e760792 | ||
|
|
4749e2518f | ||
|
|
07acbfad9f | ||
|
|
aca1805fcf | ||
|
|
35b9153f27 | ||
|
|
93ca25ebe5 | ||
|
|
6ef640c288 | ||
|
|
0f21bbc337 | ||
|
|
fee15b9048 | ||
|
|
6c52714194 | ||
|
|
f5f1b09eec | ||
|
|
5528af9617 | ||
|
|
1863e9ea67 | ||
|
|
ea17f690a2 | ||
|
|
6d3951b26f | ||
|
|
225c2cde98 | ||
|
|
3799e55491 | ||
|
|
74a80b61bd | ||
|
|
951005e5cf |
No files matched your search
@@ -1,2 +1,2 @@
|
|||||||
https://github.com/Keavon/graphite-branded-assets/archive/ca7dd793caba8999ec33fde99bb721a69c3d221f.tar.gz
|
https://github.com/Keavon/graphite-branded-assets/archive/6687dc6d3d8552948458d00d35e2bee3a40ab66b.tar.gz
|
||||||
77e8a6b68d67a8d5fcfd6268a6b7938ac9322d877378c6563e933a57df6da821
|
7663b4a35f377a5d3363430a725a1d5f634fbdc56adca5e43167786b8fe1b253
|
||||||
@@ -7,15 +7,9 @@ on:
|
|||||||
- master
|
- master
|
||||||
paths:
|
paths:
|
||||||
- website/**
|
- website/**
|
||||||
- frontend/eslint.config.js
|
|
||||||
- frontend/eslint-require-data-selectors.js
|
|
||||||
- frontend/package-lock.json
|
|
||||||
pull_request:
|
pull_request:
|
||||||
paths:
|
paths:
|
||||||
- website/**
|
- website/**
|
||||||
- frontend/eslint.config.js
|
|
||||||
- frontend/eslint-require-data-selectors.js
|
|
||||||
- frontend/package-lock.json
|
|
||||||
env:
|
env:
|
||||||
CARGO_TERM_COLOR: always
|
CARGO_TERM_COLOR: always
|
||||||
INDEX_HTML_HEAD_INCLUSION: <script defer data-domain="graphite.art" data-api="/visit/event" src="/visit/script.hash.js"></script>
|
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
|
uses: actions/setup-node@v6
|
||||||
with:
|
with:
|
||||||
node-version-file: .nvmrc
|
node-version-file: .nvmrc
|
||||||
cache: npm
|
|
||||||
cache-dependency-path: |
|
|
||||||
frontend/package-lock.json
|
|
||||||
website/package-lock.json
|
|
||||||
|
|
||||||
- name: 🕸 Install Zola
|
- name: 🕸 Install Zola
|
||||||
uses: taiki-e/install-action@v2
|
uses: taiki-e/install-action@v2
|
||||||
@@ -65,12 +55,9 @@ jobs:
|
|||||||
cargo run -p crate-hierarchy-viz -- website/generated
|
cargo run -p crate-hierarchy-viz -- website/generated
|
||||||
cargo run -p editor-message-tree -- website/generated
|
cargo run -p editor-message-tree -- website/generated
|
||||||
|
|
||||||
- name: 🔧 Install website and frontend npm dependencies
|
- name: 🔧 Install website npm dependencies
|
||||||
run: |
|
run: |
|
||||||
# The website is linted by the frontend's ESLint config and the tools it installs
|
cd website
|
||||||
cd frontend
|
|
||||||
npm ci
|
|
||||||
cd ../website
|
|
||||||
npm ci
|
npm ci
|
||||||
|
|
||||||
- name: 📃 Generate node catalog documentation
|
- name: 📃 Generate node catalog documentation
|
||||||
|
|||||||
+2
-22
@@ -61,9 +61,7 @@ in
|
|||||||
graphite-bundle = (lib.call ./pkgs/graphite-bundle.nix) { };
|
graphite-bundle = (lib.call ./pkgs/graphite-bundle.nix) { };
|
||||||
graphite-bundle-dev = (lib.call ./pkgs/graphite-bundle.nix) { graphite = graphite-dev; };
|
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 = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { };
|
||||||
graphite-flatpak-manifest-dev = (lib.call ./pkgs/graphite-flatpak-manifest.nix) {
|
graphite-flatpak-manifest-dev = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { graphite-bundle = graphite-bundle-dev; };
|
||||||
graphite-bundle = graphite-bundle-dev;
|
|
||||||
};
|
|
||||||
graphite-cef = lib.call ./pkgs/graphite-cef.nix;
|
graphite-cef = lib.call ./pkgs/graphite-cef.nix;
|
||||||
|
|
||||||
# TODO: graphene-cli = lib.call ./pkgs/graphene-cli.nix;
|
# TODO: graphene-cli = lib.call ./pkgs/graphene-cli.nix;
|
||||||
@@ -72,26 +70,8 @@ in
|
|||||||
|
|
||||||
devShells = withArgs (
|
devShells = withArgs (
|
||||||
{ lib, ... }:
|
{ lib, ... }:
|
||||||
let
|
|
||||||
shell = lib.makeOverridable (lib.call ./dev.nix);
|
|
||||||
in
|
|
||||||
{
|
{
|
||||||
default = shell {
|
default = lib.call ./dev.nix;
|
||||||
desktop = true;
|
|
||||||
};
|
|
||||||
full = shell {
|
|
||||||
desktop = true;
|
|
||||||
x11 = true;
|
|
||||||
playwright = true;
|
|
||||||
};
|
|
||||||
minimal = shell { };
|
|
||||||
x11 = shell {
|
|
||||||
desktop = true;
|
|
||||||
x11 = true;
|
|
||||||
};
|
|
||||||
playwright = shell {
|
|
||||||
playwright = true;
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{ pkgs, ... }:
|
{ pkgs, ... }:
|
||||||
|
|
||||||
let
|
let
|
||||||
toolchain = pkgs.rust-bin.nightly."2026-07-03".default.override {
|
toolchain = pkgs.rust-bin.nightly."2026-04-11".default.override {
|
||||||
extensions = [
|
extensions = [
|
||||||
"rust-src"
|
"rust-src"
|
||||||
"rust-analyzer"
|
"rust-analyzer"
|
||||||
@@ -31,12 +31,12 @@ let
|
|||||||
}).buildRustPackage
|
}).buildRustPackage
|
||||||
(finalAttrs: {
|
(finalAttrs: {
|
||||||
pname = "rustc_codegen_spirv";
|
pname = "rustc_codegen_spirv";
|
||||||
version = "0.10.0";
|
version = "0.10.0-alpha.1";
|
||||||
src = pkgs.fetchCrate {
|
src = pkgs.fetchCrate {
|
||||||
inherit (finalAttrs) pname version;
|
inherit (finalAttrs) pname version;
|
||||||
sha256 = "sha256-QluNI2TdJI0j2CBOeAbB9DfOv+8LqzWk7siZyT1WWLU=";
|
sha256 = "sha256-zJEpExkPgYzwo7fR4ge4GxJNj7H5yo4bJ4eTOw36+7c=";
|
||||||
};
|
};
|
||||||
cargoHash = "sha256-vvviUccnip+j60Ml1vqLNJ49KyEF40VLUoV1TMALHMs=";
|
cargoHash = "sha256-J1rtbfGqrL2NJ7Bu2pYfDwCdUmnECB/kzxrpYluA0kY=";
|
||||||
cargoBuildFlags = [
|
cargoBuildFlags = [
|
||||||
"-p"
|
"-p"
|
||||||
"rustc_codegen_spirv"
|
"rustc_codegen_spirv"
|
||||||
|
|||||||
+52
-80
@@ -3,90 +3,62 @@
|
|||||||
deps,
|
deps,
|
||||||
self,
|
self,
|
||||||
system,
|
system,
|
||||||
lib,
|
|
||||||
...
|
...
|
||||||
}:
|
}:
|
||||||
|
|
||||||
{
|
|
||||||
desktop ? false,
|
|
||||||
x11 ? false,
|
|
||||||
playwright ? false,
|
|
||||||
}:
|
|
||||||
|
|
||||||
let
|
let
|
||||||
features = [
|
libs = [
|
||||||
{
|
pkgs.wayland
|
||||||
packages = [
|
pkgs.vulkan-loader
|
||||||
pkgs.pkg-config
|
pkgs.libGL
|
||||||
|
pkgs.openssl
|
||||||
|
pkgs.libraw
|
||||||
|
|
||||||
pkgs.lld
|
# X11 Support
|
||||||
pkgs.nodejs
|
pkgs.libxkbcommon
|
||||||
pkgs.binaryen
|
pkgs.libXcursor
|
||||||
pkgs.wasm-bindgen-cli_0_2_121
|
pkgs.libxcb
|
||||||
pkgs.cargo-about
|
pkgs.libX11
|
||||||
|
|
||||||
pkgs.rustc
|
|
||||||
pkgs.cargo
|
|
||||||
pkgs.rust-analyzer
|
|
||||||
pkgs.clippy
|
|
||||||
pkgs.rustfmt
|
|
||||||
|
|
||||||
pkgs.git
|
|
||||||
|
|
||||||
pkgs.cargo-nextest
|
|
||||||
pkgs.cargo-expand
|
|
||||||
|
|
||||||
# Linker
|
|
||||||
pkgs.mold
|
|
||||||
|
|
||||||
# Profiling tools
|
|
||||||
pkgs.gnuplot
|
|
||||||
pkgs.samply
|
|
||||||
pkgs.cargo-flamegraph
|
|
||||||
|
|
||||||
# Plotting tools
|
|
||||||
pkgs.graphviz
|
|
||||||
];
|
|
||||||
}
|
|
||||||
deps.rustGPU
|
|
||||||
(lib.optionalAttrs desktop (
|
|
||||||
{
|
|
||||||
libs = [
|
|
||||||
pkgs.wayland
|
|
||||||
pkgs.vulkan-loader
|
|
||||||
pkgs.libGL
|
|
||||||
pkgs.libxkbcommon
|
|
||||||
self.packages.${system}.graphite-cef
|
|
||||||
];
|
|
||||||
env = {
|
|
||||||
CEF_PATH = "${self.packages.${system}.graphite-cef}/lib";
|
|
||||||
XDG_DATA_DIRS = "${pkgs.gsettings-desktop-schemas}/share/gsettings-schemas/${pkgs.gsettings-desktop-schemas.name}:${pkgs.gtk3}/share/gsettings-schemas/${pkgs.gtk3.name}:$XDG_DATA_DIRS";
|
|
||||||
};
|
|
||||||
}
|
|
||||||
))
|
|
||||||
(lib.optionalAttrs x11 {
|
|
||||||
libs = [
|
|
||||||
pkgs.libXcursor
|
|
||||||
pkgs.libxcb
|
|
||||||
pkgs.libX11
|
|
||||||
];
|
|
||||||
})
|
|
||||||
(lib.optionalAttrs playwright (
|
|
||||||
assert pkgs.playwright-driver.version == (lib.importJSON ../tools/web-editor-driver/playwright/package-lock.json).packages."node_modules/playwright-core".version;
|
|
||||||
{
|
|
||||||
env = {
|
|
||||||
PLAYWRIGHT_BROWSERS_PATH = pkgs.playwright-driver.browsers-chromium;
|
|
||||||
PLAYWRIGHT_SKIP_VALIDATE_HOST_REQUIREMENTS = "true";
|
|
||||||
};
|
|
||||||
}
|
|
||||||
))
|
|
||||||
];
|
];
|
||||||
|
|
||||||
libs = lib.concatMap (feature: feature.libs or [ ]) features;
|
|
||||||
in
|
in
|
||||||
pkgs.mkShell {
|
pkgs.mkShell (
|
||||||
packages = libs ++ lib.concatMap (feature: feature.packages or [ ]) features;
|
{
|
||||||
env = lib.mergeAttrsList (map (feature: feature.env or { }) features) // {
|
packages = libs ++ [
|
||||||
LD_LIBRARY_PATH = lib.makeLibraryPath 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 = ''
|
postInstall = ''
|
||||||
rm -r $out/* $out/.* || true
|
rm -r $out/* $out/.* || true
|
||||||
strip ./Release/*.so*
|
strip ./Release/*.so*
|
||||||
mkdir $out/lib
|
mv ./Release/* $out/
|
||||||
mv ./Release/* $out/lib/
|
|
||||||
find "./Resources/locales" -maxdepth 1 -type f ! -name 'en-US.pak' -delete
|
find "./Resources/locales" -maxdepth 1 -type f ! -name 'en-US.pak' -delete
|
||||||
mv ./Resources/* $out/lib/
|
mv ./Resources/* $out/
|
||||||
mv ./include $out/lib/
|
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 '${
|
echo '${
|
||||||
builtins.toJSON {
|
builtins.toJSON {
|
||||||
@@ -44,6 +43,6 @@ pkgs.cef-binary.overrideAttrs {
|
|||||||
name = builtins.baseNameOf url;
|
name = builtins.baseNameOf url;
|
||||||
sha1 = "";
|
sha1 = "";
|
||||||
}
|
}
|
||||||
}' > $out/lib/archive.json
|
}' > $out/archive.json
|
||||||
'';
|
'';
|
||||||
}
|
}
|
||||||
@@ -20,7 +20,6 @@ let
|
|||||||
pkgs.libGL
|
pkgs.libGL
|
||||||
pkgs.openssl
|
pkgs.openssl
|
||||||
pkgs.libraw
|
pkgs.libraw
|
||||||
self.packages.${system}.graphite-cef
|
|
||||||
# X11 Support
|
# X11 Support
|
||||||
pkgs.libxkbcommon
|
pkgs.libxkbcommon
|
||||||
pkgs.libXcursor
|
pkgs.libXcursor
|
||||||
@@ -51,7 +50,7 @@ let
|
|||||||
pkgs.pkg-config
|
pkgs.pkg-config
|
||||||
pkgs.lld
|
pkgs.lld
|
||||||
];
|
];
|
||||||
env.CEF_PATH = "${self.packages.${system}.graphite-cef}/lib";
|
env.CEF_PATH = self.packages.${system}.graphite-cef;
|
||||||
buildPhase =
|
buildPhase =
|
||||||
let
|
let
|
||||||
profile = if dev then "dev" else "release";
|
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;
|
RASTER_NODES_SHADER_PATH = self.packages.${system}.graphite-raster-nodes-shaders;
|
||||||
GRAPHITE_GIT_COMMIT_HASH = self.rev or "unknown";
|
GRAPHITE_GIT_COMMIT_HASH = self.rev or "unknown";
|
||||||
GRAPHITE_GIT_COMMIT_DATE = self.lastModified 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 = ''
|
postPatch = ''
|
||||||
@@ -149,7 +148,7 @@ deps.crane.lib.buildPackage (
|
|||||||
remove-references-to -t "${common.cargoVendorDir}" $out/bin/graphite
|
remove-references-to -t "${common.cargoVendorDir}" $out/bin/graphite
|
||||||
|
|
||||||
patchelf \
|
patchelf \
|
||||||
--set-rpath "${pkgs.lib.makeLibraryPath libs}" \
|
--set-rpath "${pkgs.lib.makeLibraryPath libs}:${self.packages.${system}.graphite-cef}" \
|
||||||
--add-needed libGL.so \
|
--add-needed libGL.so \
|
||||||
--add-needed libEGL.so \
|
--add-needed libEGL.so \
|
||||||
$out/bin/graphite
|
$out/bin/graphite
|
||||||
|
|||||||
Generated
+158
-273
File diff suppressed because it is too large.
Load diff
+7
-20
@@ -16,9 +16,7 @@ members = [
|
|||||||
"libraries/dyn-any",
|
"libraries/dyn-any",
|
||||||
"libraries/math-parser",
|
"libraries/math-parser",
|
||||||
"libraries/ipsum",
|
"libraries/ipsum",
|
||||||
"libraries/snapping",
|
|
||||||
"libraries/wgpu-sync",
|
"libraries/wgpu-sync",
|
||||||
"libraries/control-protocol",
|
|
||||||
"node-graph/libraries/graphene-hash",
|
"node-graph/libraries/graphene-hash",
|
||||||
"node-graph/libraries/*",
|
"node-graph/libraries/*",
|
||||||
"node-graph/nodes/*",
|
"node-graph/nodes/*",
|
||||||
@@ -37,7 +35,6 @@ members = [
|
|||||||
"tools/third-party-licenses",
|
"tools/third-party-licenses",
|
||||||
"tools/editor-message-tree",
|
"tools/editor-message-tree",
|
||||||
"tools/node-docs",
|
"tools/node-docs",
|
||||||
"tools/web-editor-driver",
|
|
||||||
]
|
]
|
||||||
default-members = [
|
default-members = [
|
||||||
"editor",
|
"editor",
|
||||||
@@ -45,7 +42,6 @@ default-members = [
|
|||||||
"libraries/dyn-any",
|
"libraries/dyn-any",
|
||||||
"libraries/math-parser",
|
"libraries/math-parser",
|
||||||
"libraries/ipsum",
|
"libraries/ipsum",
|
||||||
"libraries/snapping",
|
|
||||||
"node-graph/graph-craft",
|
"node-graph/graph-craft",
|
||||||
"node-graph/interpreted-executor",
|
"node-graph/interpreted-executor",
|
||||||
"node-graph/node-macro",
|
"node-graph/node-macro",
|
||||||
@@ -57,7 +53,7 @@ default-members = [
|
|||||||
resolver = "2"
|
resolver = "2"
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
rust-version = "1.98"
|
rust-version = "1.88"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
authors = ["Graphite Authors <[email protected]>"]
|
authors = ["Graphite Authors <[email protected]>"]
|
||||||
homepage = "https://graphite.art"
|
homepage = "https://graphite.art"
|
||||||
@@ -81,7 +77,6 @@ preprocessor = { path = "node-graph/preprocessor" }
|
|||||||
math-parser = { path = "libraries/math-parser" }
|
math-parser = { path = "libraries/math-parser" }
|
||||||
graphene-application-io = { path = "node-graph/libraries/application-io" }
|
graphene-application-io = { path = "node-graph/libraries/application-io" }
|
||||||
graphene-resource = { path = "node-graph/libraries/resources" }
|
graphene-resource = { path = "node-graph/libraries/resources" }
|
||||||
graphene-animation = { path = "node-graph/libraries/animation" }
|
|
||||||
core-types = { path = "node-graph/libraries/core-types" }
|
core-types = { path = "node-graph/libraries/core-types" }
|
||||||
no-std-types = { path = "node-graph/libraries/no-std-types" }
|
no-std-types = { path = "node-graph/libraries/no-std-types" }
|
||||||
raster-types = { path = "node-graph/libraries/raster-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" }
|
transform-nodes = { path = "node-graph/nodes/transform" }
|
||||||
vector-nodes = { path = "node-graph/nodes/vector" }
|
vector-nodes = { path = "node-graph/nodes/vector" }
|
||||||
repeat-nodes = { path = "node-graph/nodes/repeat" }
|
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" }
|
math-nodes = { path = "node-graph/nodes/math" }
|
||||||
path-bool-nodes = { path = "node-graph/nodes/path-bool" }
|
path-bool-nodes = { path = "node-graph/nodes/path-bool" }
|
||||||
graph-craft = { path = "node-graph/graph-craft" }
|
graph-craft = { path = "node-graph/graph-craft" }
|
||||||
@@ -113,17 +106,15 @@ wgpu-executor = { path = "node-graph/libraries/wgpu-executor" }
|
|||||||
wgpu-sync = { path = "libraries/wgpu-sync" }
|
wgpu-sync = { path = "libraries/wgpu-sync" }
|
||||||
graphite-proc-macros = { path = "proc-macros" }
|
graphite-proc-macros = { path = "proc-macros" }
|
||||||
graphite-editor = { path = "editor" }
|
graphite-editor = { path = "editor" }
|
||||||
control-protocol = { path = "libraries/control-protocol" }
|
|
||||||
graphene-canvas-utils = { path = "node-graph/libraries/canvas-utils" }
|
graphene-canvas-utils = { path = "node-graph/libraries/canvas-utils" }
|
||||||
ipsum = { path = "libraries/ipsum" }
|
ipsum = { path = "libraries/ipsum" }
|
||||||
snapping = { path = "libraries/snapping" }
|
|
||||||
|
|
||||||
# Workspace dependencies
|
# Workspace dependencies
|
||||||
rustc-hash = "2.0"
|
rustc-hash = "2.0"
|
||||||
bytemuck = { version = "1.13", features = ["derive", "min_const_generics"] }
|
bytemuck = { version = "1.13", features = ["derive", "min_const_generics"] }
|
||||||
serde = { version = "1.0", features = ["derive", "rc"] }
|
serde = { version = "1.0", features = ["derive", "rc"] }
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
postcard = { version = "1.1", default-features = false, features = ["use-std"] }
|
rmp-serde = "1.3"
|
||||||
serde_bytes = "0.11"
|
serde_bytes = "0.11"
|
||||||
serde-wasm-bindgen = "0.6"
|
serde-wasm-bindgen = "0.6"
|
||||||
reqwest = { version = "0.13", features = ["blocking", "json"] }
|
reqwest = { version = "0.13", features = ["blocking", "json"] }
|
||||||
@@ -132,7 +123,7 @@ env_logger = "0.11"
|
|||||||
log = "0.4"
|
log = "0.4"
|
||||||
bitflags = { version = "2.4", features = ["serde"] }
|
bitflags = { version = "2.4", features = ["serde"] }
|
||||||
ctor = "0.2"
|
ctor = "0.2"
|
||||||
convert_case = "0.12"
|
convert_case = "0.8"
|
||||||
titlecase = "3.6"
|
titlecase = "3.6"
|
||||||
fancy-regex = "0.18.0"
|
fancy-regex = "0.18.0"
|
||||||
unicode-segmentation = "1.13.2"
|
unicode-segmentation = "1.13.2"
|
||||||
@@ -181,6 +172,7 @@ tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-mult
|
|||||||
kurbo = { version = "0.13", features = ["serde"] }
|
kurbo = { version = "0.13", features = ["serde"] }
|
||||||
vello = "0.10"
|
vello = "0.10"
|
||||||
vello_encoding = "0.10"
|
vello_encoding = "0.10"
|
||||||
|
resvg = "0.47"
|
||||||
usvg = "0.47"
|
usvg = "0.47"
|
||||||
simplecss = "0.2"
|
simplecss = "0.2"
|
||||||
parley = { version = "0.9", default-features = false, features = ["std"] }
|
parley = { version = "0.9", default-features = false, features = ["std"] }
|
||||||
@@ -190,12 +182,10 @@ color = "0.3"
|
|||||||
# Linebender ecosystem (END)
|
# Linebender ecosystem (END)
|
||||||
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
|
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
|
||||||
rand_chacha = "0.9"
|
rand_chacha = "0.9"
|
||||||
glam = { version = "0.33", default-features = false, features = [
|
glam = { version = "0.32.1", default-features = false, features = [
|
||||||
"nostd-libm",
|
"nostd-libm",
|
||||||
"scalar-math",
|
"scalar-math",
|
||||||
"bytemuck",
|
"bytemuck",
|
||||||
"debug-glam-assert",
|
|
||||||
"all-types",
|
|
||||||
] }
|
] }
|
||||||
base64 = "0.22"
|
base64 = "0.22"
|
||||||
blake3 = "1.5"
|
blake3 = "1.5"
|
||||||
@@ -249,11 +239,8 @@ rfd = "0.17"
|
|||||||
open = "5.3"
|
open = "5.3"
|
||||||
spin = "0.10"
|
spin = "0.10"
|
||||||
clap = "4.5"
|
clap = "4.5"
|
||||||
|
spirv-std = { version = "0.10.0-alpha.1", features = ["bytemuck"] }
|
||||||
# Ensure these are kept in sync with .nix/deps/rust-gpu.nix
|
cargo-gpu-install = { version = "0.10.0-alpha.1", default-features = false }
|
||||||
spirv-std = { version = "0.10.0", features = ["bytemuck"] }
|
|
||||||
cargo-gpu-install = { version = "0.10.0", default-features = false }
|
|
||||||
|
|
||||||
qrcodegen = "1.8"
|
qrcodegen = "1.8"
|
||||||
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
|
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
|
||||||
scraper = "0.25"
|
scraper = "0.25"
|
||||||
|
|||||||
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::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_Line truncated
|
||||||
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]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2Line truncated
|
||||||
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
|
||||||
@@ -5,15 +5,9 @@ version.workspace = true
|
|||||||
license.workspace = true
|
license.workspace = true
|
||||||
authors.workspace = true
|
authors.workspace = true
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
repository.workspace = true
|
|
||||||
readme.workspace = true
|
|
||||||
homepage.workspace = true
|
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
publish.workspace = true
|
publish.workspace = true
|
||||||
|
|
||||||
[lints]
|
|
||||||
workspace = true
|
|
||||||
|
|
||||||
[[bin]]
|
[[bin]]
|
||||||
name = "graphite"
|
name = "graphite"
|
||||||
path = "src/main.rs"
|
path = "src/main.rs"
|
||||||
|
|||||||
@@ -5,15 +5,9 @@ version.workspace = true
|
|||||||
license.workspace = true
|
license.workspace = true
|
||||||
authors.workspace = true
|
authors.workspace = true
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
repository.workspace = true
|
|
||||||
readme.workspace = true
|
|
||||||
homepage.workspace = true
|
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
publish.workspace = true
|
publish.workspace = true
|
||||||
|
|
||||||
[lints]
|
|
||||||
workspace = true
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
cef-dll-sys = { workspace = true }
|
cef-dll-sys = { workspace = true }
|
||||||
|
|
||||||
|
|||||||
@@ -7,9 +7,6 @@ mod mac;
|
|||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
mod win;
|
mod win;
|
||||||
|
|
||||||
// Avoid incorrect warnings about an unused dependency (this crate sets `DEP_CEF_DLL_WRAPPER_CEF_DIR` which is used in `build.rs`)
|
|
||||||
use cef_dll_sys as _;
|
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
linux::main().unwrap();
|
linux::main().unwrap();
|
||||||
|
|||||||
@@ -5,9 +5,6 @@ version.workspace = true
|
|||||||
license.workspace = true
|
license.workspace = true
|
||||||
authors.workspace = true
|
authors.workspace = true
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
repository.workspace = true
|
|
||||||
readme.workspace = true
|
|
||||||
homepage.workspace = true
|
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
publish.workspace = true
|
publish.workspace = true
|
||||||
|
|
||||||
|
|||||||
@@ -5,15 +5,9 @@ version.workspace = true
|
|||||||
license.workspace = true
|
license.workspace = true
|
||||||
authors.workspace = true
|
authors.workspace = true
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
repository.workspace = true
|
|
||||||
readme.workspace = true
|
|
||||||
homepage.workspace = true
|
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
publish.workspace = true
|
publish.workspace = true
|
||||||
|
|
||||||
[lints]
|
|
||||||
workspace = true
|
|
||||||
|
|
||||||
[[bin]]
|
[[bin]]
|
||||||
name = "graphite"
|
name = "graphite"
|
||||||
path = "src/main.rs"
|
path = "src/main.rs"
|
||||||
|
|||||||
@@ -5,15 +5,9 @@ version.workspace = true
|
|||||||
license.workspace = true
|
license.workspace = true
|
||||||
authors.workspace = true
|
authors.workspace = true
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
repository.workspace = true
|
|
||||||
readme.workspace = true
|
|
||||||
homepage.workspace = true
|
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
publish.workspace = true
|
publish.workspace = true
|
||||||
|
|
||||||
[lints]
|
|
||||||
workspace = true
|
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
main = ["dep:graphite-desktop"]
|
main = ["dep:graphite-desktop"]
|
||||||
helper = ["dep:graphite-desktop-ui"]
|
helper = ["dep:graphite-desktop-ui"]
|
||||||
|
|||||||
@@ -5,15 +5,9 @@ version.workspace = true
|
|||||||
license.workspace = true
|
license.workspace = true
|
||||||
authors.workspace = true
|
authors.workspace = true
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
repository.workspace = true
|
|
||||||
readme.workspace = true
|
|
||||||
homepage.workspace = true
|
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
publish.workspace = true
|
publish.workspace = true
|
||||||
|
|
||||||
[lints]
|
|
||||||
workspace = true
|
|
||||||
|
|
||||||
[[bin]]
|
[[bin]]
|
||||||
name = "graphite"
|
name = "graphite"
|
||||||
path = "src/main.rs"
|
path = "src/main.rs"
|
||||||
|
|||||||
+15
-8
@@ -25,7 +25,7 @@ use crate::render::{RenderError, RenderState};
|
|||||||
use crate::ui::{InputEvent, UiCommand, UiInstance};
|
use crate::ui::{InputEvent, UiCommand, UiInstance};
|
||||||
use crate::window::Window;
|
use crate::window::Window;
|
||||||
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, IngestAction, Preferences};
|
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, IngestAction, Preferences};
|
||||||
use crate::wrapper::{DesktopWrapper, FolderStore, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
|
use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
|
||||||
|
|
||||||
pub(crate) struct App {
|
pub(crate) struct App {
|
||||||
render_state: Option<RenderState>,
|
render_state: Option<RenderState>,
|
||||||
@@ -99,13 +99,7 @@ impl App {
|
|||||||
let wake = Arc::new(move || {
|
let wake = Arc::new(move || {
|
||||||
wake_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Wake));
|
wake_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Wake));
|
||||||
});
|
});
|
||||||
let desktop_wrapper = DesktopWrapper::new(
|
let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), dirs::app_autosave_documents_dir(), wgpu_context.clone(), wake);
|
||||||
rand::rng().random(),
|
|
||||||
Arc::new(resource_storage),
|
|
||||||
Arc::new(FolderStore::new(dirs::app_autosave_documents_dir())),
|
|
||||||
wgpu_context.clone(),
|
|
||||||
wake,
|
|
||||||
);
|
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
render_state: None,
|
render_state: None,
|
||||||
@@ -313,6 +307,19 @@ impl App {
|
|||||||
DesktopFrontendMessage::PersistenceReadState => {
|
DesktopFrontendMessage::PersistenceReadState => {
|
||||||
responses.push(DesktopWrapperMessage::LoadPersistedState { state: persist::read_state() });
|
responses.push(DesktopWrapperMessage::LoadPersistedState { state: persist::read_state() });
|
||||||
}
|
}
|
||||||
|
DesktopFrontendMessage::PersistenceReadDocument { id } => {
|
||||||
|
if let Some(document) = persist::read_document_content(&id) {
|
||||||
|
responses.push(DesktopWrapperMessage::LoadDocumentContent { id, document });
|
||||||
|
} else {
|
||||||
|
tracing::error!("Failed to read document content for {id:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
DesktopFrontendMessage::PersistenceWriteDocument { id, document_serialized_content } => {
|
||||||
|
persist::write_document_content(id, document_serialized_content);
|
||||||
|
}
|
||||||
|
DesktopFrontendMessage::PersistenceDeleteDocument { id } => {
|
||||||
|
persist::delete_document(&id);
|
||||||
|
}
|
||||||
DesktopFrontendMessage::PersistenceWritePreferences { preferences } => {
|
DesktopFrontendMessage::PersistenceWritePreferences { preferences } => {
|
||||||
preferences::write(preferences);
|
preferences::write(preferences);
|
||||||
}
|
}
|
||||||
|
|||||||
+52
-50
@@ -1,9 +1,6 @@
|
|||||||
use crate::wrapper::messages::PersistedState;
|
use crate::wrapper::messages::{DocumentId, PersistedState};
|
||||||
|
|
||||||
pub(crate) fn read_state() -> PersistedState {
|
pub(crate) fn read_state() -> PersistedState {
|
||||||
if let Err(error) = migrate_documents() {
|
|
||||||
tracing::error!("Autosave migration failed: {error}");
|
|
||||||
}
|
|
||||||
let path = state_file_path();
|
let path = state_file_path();
|
||||||
let data = match std::fs::read_to_string(&path) {
|
let data = match std::fs::read_to_string(&path) {
|
||||||
Ok(d) => d,
|
Ok(d) => d,
|
||||||
@@ -16,13 +13,16 @@ pub(crate) fn read_state() -> PersistedState {
|
|||||||
return PersistedState::default();
|
return PersistedState::default();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
match ron::from_str(&data) {
|
let loaded = match ron::from_str(&data) {
|
||||||
Ok(d) => d,
|
Ok(d) => d,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
tracing::error!("Failed to deserialize persistent data: {e}");
|
tracing::error!("Failed to deserialize persistent data: {e}");
|
||||||
PersistedState::default()
|
return PersistedState::default();
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
|
garbage_collect_document_files(&loaded);
|
||||||
|
loaded
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn write_state(state: PersistedState) {
|
pub(crate) fn write_state(state: PersistedState) {
|
||||||
@@ -37,6 +37,47 @@ pub(crate) fn write_state(state: PersistedState) {
|
|||||||
if let Err(e) = std::fs::write(state_file_path(), data) {
|
if let Err(e) = std::fs::write(state_file_path(), data) {
|
||||||
tracing::error!("Failed to write persistent data to disk: {e}");
|
tracing::error!("Failed to write persistent data to disk: {e}");
|
||||||
}
|
}
|
||||||
|
garbage_collect_document_files(state);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn write_document_content(id: DocumentId, document_content: String) {
|
||||||
|
if let Err(e) = std::fs::write(document_content_path(&id), document_content) {
|
||||||
|
tracing::error!("Failed to write document {id:?} to disk: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn read_document_content(id: &DocumentId) -> Option<String> {
|
||||||
|
std::fs::read_to_string(document_content_path(id)).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn delete_document(id: &DocumentId) {
|
||||||
|
if let Err(e) = std::fs::remove_file(document_content_path(id)) {
|
||||||
|
tracing::error!("Failed to delete document {id:?} from disk: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn garbage_collect_document_files(state: &PersistedState) {
|
||||||
|
let valid_paths: std::collections::HashSet<_> = state.documents.iter().map(|doc| document_content_path(&doc.id)).collect();
|
||||||
|
|
||||||
|
let directory = crate::dirs::app_autosave_documents_dir();
|
||||||
|
let entries = match std::fs::read_dir(&directory) {
|
||||||
|
Ok(entries) => entries,
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Failed to read autosave documents directory: {e}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let path = entry.path();
|
||||||
|
if path.is_file()
|
||||||
|
&& !valid_paths.contains(&path)
|
||||||
|
&& let Err(e) = std::fs::remove_file(&path)
|
||||||
|
{
|
||||||
|
tracing::error!("Failed to remove orphaned document file {path:?}: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn state_file_path() -> std::path::PathBuf {
|
fn state_file_path() -> std::path::PathBuf {
|
||||||
@@ -45,47 +86,8 @@ fn state_file_path() -> std::path::PathBuf {
|
|||||||
path
|
path
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Remove this migration code
|
fn document_content_path(id: &DocumentId) -> std::path::PathBuf {
|
||||||
fn migrate_documents() -> std::io::Result<()> {
|
let mut path = crate::dirs::app_autosave_documents_dir();
|
||||||
let root = crate::dirs::app_autosave_documents_dir();
|
path.push(format!("{:x}.{}", id.0, graphite_desktop_wrapper::FILE_EXTENSION));
|
||||||
let entries = match std::fs::read_dir(&root) {
|
path
|
||||||
Ok(entries) => entries,
|
|
||||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
|
||||||
Err(error) => return Err(error),
|
|
||||||
};
|
|
||||||
for entry in entries {
|
|
||||||
let entry = match entry {
|
|
||||||
Ok(entry) => entry,
|
|
||||||
Err(error) => {
|
|
||||||
tracing::error!("Skipping an unreadable autosave entry: {error}");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if let Err(error) = migrate_document(&root, &entry) {
|
|
||||||
tracing::error!("Autosave migration of {} failed: {error}", entry.path().display());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn migrate_document(root: &std::path::Path, entry: &std::fs::DirEntry) -> std::io::Result<()> {
|
|
||||||
let path = entry.path();
|
|
||||||
if !entry.file_type()?.is_file() || path.extension().and_then(|s| s.to_str()) != Some(graphite_desktop_wrapper::FILE_EXTENSION) {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
let Some(id) = path.file_stem().and_then(|s| s.to_str()).and_then(|s| u64::from_str_radix(s, 16).ok()) else {
|
|
||||||
return Ok(());
|
|
||||||
};
|
|
||||||
let destination = root.join(format!("{id:016x}"));
|
|
||||||
if !destination.join("legacy.graphite").exists() && !destination.join("manifest.json").exists() {
|
|
||||||
std::fs::create_dir_all(&destination)?;
|
|
||||||
let staging = destination.join("legacy.graphite.migrating");
|
|
||||||
std::fs::copy(&path, &staging)?;
|
|
||||||
std::fs::rename(staging, destination.join("legacy.graphite"))?;
|
|
||||||
}
|
|
||||||
let backup = path.with_extension(format!("{}.migrated", graphite_desktop_wrapper::FILE_EXTENSION));
|
|
||||||
if backup.exists() {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
std::fs::rename(path, backup)
|
|
||||||
}
|
}
|
||||||
@@ -5,15 +5,9 @@ version.workspace = true
|
|||||||
license.workspace = true
|
license.workspace = true
|
||||||
authors.workspace = true
|
authors.workspace = true
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
repository.workspace = true
|
|
||||||
readme.workspace = true
|
|
||||||
homepage.workspace = true
|
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
publish.workspace = true
|
publish.workspace = true
|
||||||
|
|
||||||
[lints]
|
|
||||||
workspace = true
|
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = []
|
default = []
|
||||||
embedded_resources = ["dep:graphite-desktop-embedded-resources"]
|
embedded_resources = ["dep:graphite-desktop-embedded-resources"]
|
||||||
|
|||||||
@@ -5,15 +5,9 @@ version.workspace = true
|
|||||||
license.workspace = true
|
license.workspace = true
|
||||||
authors.workspace = true
|
authors.workspace = true
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
repository.workspace = true
|
|
||||||
readme.workspace = true
|
|
||||||
homepage.workspace = true
|
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
publish.workspace = true
|
publish.workspace = true
|
||||||
|
|
||||||
[lints]
|
|
||||||
workspace = true
|
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
|
gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
|
||||||
|
|
||||||
|
|||||||
@@ -44,6 +44,10 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
|||||||
let message = FrontendMessage::UpdateFullscreen { fullscreen };
|
let message = FrontendMessage::UpdateFullscreen { fullscreen };
|
||||||
dispatcher.queue_editor_message(message);
|
dispatcher.queue_editor_message(message);
|
||||||
}
|
}
|
||||||
|
DesktopWrapperMessage::LoadDocumentContent { id, document } => {
|
||||||
|
let message = PersistentStateMessage::LoadDocument { document_id: id, document };
|
||||||
|
dispatcher.queue_editor_message(message);
|
||||||
|
}
|
||||||
DesktopWrapperMessage::LoadPersistedState { state } => {
|
DesktopWrapperMessage::LoadPersistedState { state } => {
|
||||||
let message = PersistentStateMessage::LoadState { state };
|
let message = PersistentStateMessage::LoadState { state };
|
||||||
dispatcher.queue_editor_message(message);
|
dispatcher.queue_editor_message(message);
|
||||||
|
|||||||
@@ -69,6 +69,18 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
|||||||
FrontendMessage::TriggerPersistenceWriteState { state } => {
|
FrontendMessage::TriggerPersistenceWriteState { state } => {
|
||||||
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteState { state });
|
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteState { state });
|
||||||
}
|
}
|
||||||
|
FrontendMessage::TriggerPersistenceReadDocument { document_id } => {
|
||||||
|
dispatcher.respond(DesktopFrontendMessage::PersistenceReadDocument { id: document_id });
|
||||||
|
}
|
||||||
|
FrontendMessage::TriggerPersistenceDeleteDocument { document_id } => {
|
||||||
|
dispatcher.respond(DesktopFrontendMessage::PersistenceDeleteDocument { id: document_id });
|
||||||
|
}
|
||||||
|
FrontendMessage::TriggerPersistenceWriteDocument { document_id, document } => {
|
||||||
|
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteDocument {
|
||||||
|
id: document_id,
|
||||||
|
document_serialized_content: document,
|
||||||
|
});
|
||||||
|
}
|
||||||
FrontendMessage::TriggerOpenLaunchDocuments => {
|
FrontendMessage::TriggerOpenLaunchDocuments => {
|
||||||
dispatcher.respond(DesktopFrontendMessage::OpenLaunchDocuments);
|
dispatcher.respond(DesktopFrontendMessage::OpenLaunchDocuments);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ use std::sync::Arc;
|
|||||||
|
|
||||||
pub use graph_craft::application_io::resource::MmapResourceStorage;
|
pub use graph_craft::application_io::resource::MmapResourceStorage;
|
||||||
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
|
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
|
||||||
pub use graphite_editor::document_store::{DocumentStore, FolderStore};
|
|
||||||
pub use wgpu_executor::Texture;
|
pub use wgpu_executor::Texture;
|
||||||
pub use wgpu_executor::WgpuBackends;
|
pub use wgpu_executor::WgpuBackends;
|
||||||
pub use wgpu_executor::WgpuContext;
|
pub use wgpu_executor::WgpuContext;
|
||||||
@@ -33,7 +32,7 @@ pub struct DesktopWrapper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl DesktopWrapper {
|
impl DesktopWrapper {
|
||||||
pub fn new(uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, document_store: Arc<dyn DocumentStore>, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self {
|
pub fn new(uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, working_copy_root: std::path::PathBuf, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self {
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
let host = Host::Windows;
|
let host = Host::Windows;
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
@@ -44,7 +43,7 @@ impl DesktopWrapper {
|
|||||||
let application_io = PlatformApplicationIo::new_with_context(wgpu_context);
|
let application_io = PlatformApplicationIo::new_with_context(wgpu_context);
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
editor: Editor::new(env, uuid_random_seed, resource_storage, document_store, application_io, schedule_wake),
|
editor: Editor::new(env, uuid_random_seed, resource_storage, Some(working_copy_root), application_io, schedule_wake),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ impl<'a> DesktopWrapperMessageDispatcher<'a> {
|
|||||||
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses)
|
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses)
|
||||||
&& e != "No active document"
|
&& e != "No active document"
|
||||||
{
|
{
|
||||||
tracing::error!("Error polling node graph: {}", e);
|
tracing::error!("Error poling node graph: {}", e);
|
||||||
}
|
}
|
||||||
while let Some(message) = responses.pop_front() {
|
while let Some(message) = responses.pop_front() {
|
||||||
self.queue_editor_message(message);
|
self.queue_editor_message(message);
|
||||||
|
|||||||
@@ -44,6 +44,13 @@ pub enum DesktopFrontendMessage {
|
|||||||
enabled: bool,
|
enabled: bool,
|
||||||
},
|
},
|
||||||
UpdateOverlays(vello::Scene),
|
UpdateOverlays(vello::Scene),
|
||||||
|
PersistenceWriteDocument {
|
||||||
|
id: DocumentId,
|
||||||
|
document_serialized_content: String,
|
||||||
|
},
|
||||||
|
PersistenceDeleteDocument {
|
||||||
|
id: DocumentId,
|
||||||
|
},
|
||||||
PersistenceWritePreferences {
|
PersistenceWritePreferences {
|
||||||
preferences: Preferences,
|
preferences: Preferences,
|
||||||
},
|
},
|
||||||
@@ -52,6 +59,9 @@ pub enum DesktopFrontendMessage {
|
|||||||
state: PersistedState,
|
state: PersistedState,
|
||||||
},
|
},
|
||||||
PersistenceReadState,
|
PersistenceReadState,
|
||||||
|
PersistenceReadDocument {
|
||||||
|
id: DocumentId,
|
||||||
|
},
|
||||||
UpdateMenu {
|
UpdateMenu {
|
||||||
entries: Vec<MenuItem>,
|
entries: Vec<MenuItem>,
|
||||||
},
|
},
|
||||||
@@ -82,6 +92,7 @@ pub enum DesktopWrapperMessage {
|
|||||||
PollNodeGraphEvaluation,
|
PollNodeGraphEvaluation,
|
||||||
UpdateMaximized { maximized: bool },
|
UpdateMaximized { maximized: bool },
|
||||||
UpdateFullscreen { fullscreen: bool },
|
UpdateFullscreen { fullscreen: bool },
|
||||||
|
LoadDocumentContent { id: DocumentId, document: String },
|
||||||
LoadPersistedState { state: PersistedState },
|
LoadPersistedState { state: PersistedState },
|
||||||
LoadPreferences { preferences: Preferences },
|
LoadPreferences { preferences: Preferences },
|
||||||
MenuEvent { id: String },
|
MenuEvent { id: String },
|
||||||
|
|||||||
@@ -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 for shortcuts that include mouse motion because we can't show them in native menu
|
||||||
return None;
|
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() {
|
match labeled_key.key() {
|
||||||
Key::Shift => modifiers |= Modifiers::SHIFT,
|
Key::Shift => modifiers |= Modifiers::SHIFT,
|
||||||
Key::Control => modifiers |= Modifiers::CONTROL,
|
Key::Control => modifiers |= Modifiers::CONTROL,
|
||||||
|
|||||||
@@ -5,15 +5,9 @@ version.workspace = true
|
|||||||
license.workspace = true
|
license.workspace = true
|
||||||
authors.workspace = true
|
authors.workspace = true
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
repository.workspace = true
|
|
||||||
readme.workspace = true
|
|
||||||
homepage.workspace = true
|
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
publish.workspace = true
|
publish.workspace = true
|
||||||
|
|
||||||
[lints]
|
|
||||||
workspace = true
|
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = []
|
default = []
|
||||||
zip = ["dep:zip"]
|
zip = ["dep:zip"]
|
||||||
@@ -40,7 +34,6 @@ web-sys = { workspace = true, features = [
|
|||||||
"FileSystemFileHandle",
|
"FileSystemFileHandle",
|
||||||
"FileSystemGetFileOptions",
|
"FileSystemGetFileOptions",
|
||||||
"FileSystemGetDirectoryOptions",
|
"FileSystemGetDirectoryOptions",
|
||||||
"FileSystemRemoveOptions",
|
|
||||||
"FileSystemHandle",
|
"FileSystemHandle",
|
||||||
"FileSystemHandleKind",
|
"FileSystemHandleKind",
|
||||||
"FileSystemWritableFileStream",
|
"FileSystemWritableFileStream",
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ use std::fs::{self, OpenOptions};
|
|||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct FolderBackend {
|
pub struct FolderBackend {
|
||||||
root: PathBuf,
|
root: PathBuf,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,11 +2,11 @@
|
|||||||
|
|
||||||
use crate::{ByteHolder, Container, ContainerError, Result, validate_path, validate_prefix, with_trailing_slash};
|
use crate::{ByteHolder, Container, ContainerError, Result, validate_path, validate_prefix, with_trailing_slash};
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::{HashMap, HashSet};
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::Mutex;
|
||||||
|
|
||||||
#[derive(Clone, Default)]
|
#[derive(Default)]
|
||||||
pub struct MemoryBackend {
|
pub struct MemoryBackend {
|
||||||
files: Arc<Mutex<HashMap<String, Vec<u8>>>>,
|
files: Mutex<HashMap<String, Vec<u8>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MemoryBackend {
|
impl MemoryBackend {
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
use crate::{AsyncContainer, ByteHolder, ContainerError, Result, validate_path, validate_prefix, with_trailing_slash};
|
use crate::{AsyncContainer, ByteHolder, ContainerError, Result, validate_path, validate_prefix, with_trailing_slash};
|
||||||
use futures::channel::oneshot;
|
use futures::channel::oneshot;
|
||||||
use js_sys::Uint8Array;
|
use js_sys::Uint8Array;
|
||||||
use std::cell::Cell;
|
|
||||||
use std::collections::{HashSet, VecDeque};
|
use std::collections::{HashSet, VecDeque};
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
use wasm_bindgen::JsCast;
|
use wasm_bindgen::JsCast;
|
||||||
@@ -41,33 +40,6 @@ struct Inner {
|
|||||||
worker_active: bool,
|
worker_active: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
thread_local! {
|
|
||||||
static LAST_WRITE_FAILURE_ALERT: Cell<Option<f64>> = const { Cell::new(None) };
|
|
||||||
}
|
|
||||||
|
|
||||||
fn report_write_error(operation: &str, path: &str, error: &JsValue) {
|
|
||||||
if is_not_found(error) {
|
|
||||||
log::warn!("OPFS {operation} on {path} dropped: the container no longer exists");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
log::error!("OPFS {operation} failure on {path}:\n{error:?}");
|
|
||||||
let now = js_sys::Date::now();
|
|
||||||
// Debounce alerts to avoid spamming the user
|
|
||||||
if LAST_WRITE_FAILURE_ALERT.get().is_some_and(|last| now - last < 60. * 1000.) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
LAST_WRITE_FAILURE_ALERT.set(Some(now));
|
|
||||||
if let Some(window) = web_sys::window() {
|
|
||||||
let message = format!(
|
|
||||||
"Autosave is not working. Save your documents manually to avoid losing changes.\n\n\
|
|
||||||
Please report it at https://github.com/GraphiteEditor/Graphite/issues/new and include this error:\n\n\
|
|
||||||
{operation} {path}: {error:?}"
|
|
||||||
);
|
|
||||||
let _ = window.alert_with_message(&message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct OpfsBackend {
|
pub struct OpfsBackend {
|
||||||
inner: Arc<Mutex<Inner>>,
|
inner: Arc<Mutex<Inner>>,
|
||||||
}
|
}
|
||||||
@@ -105,6 +77,8 @@ impl OpfsBackend {
|
|||||||
guard.queue.push_back(Mutation::Barrier(sender));
|
guard.queue.push_back(Mutation::Barrier(sender));
|
||||||
kick_worker(&self.inner, &mut guard);
|
kick_worker(&self.inner, &mut guard);
|
||||||
}
|
}
|
||||||
|
// The sender is only dropped without sending if the worker is torn down mid-drain; either way
|
||||||
|
// there is nothing left to wait for, so a receive error is treated as "already flushed".
|
||||||
let _ = receiver.await;
|
let _ = receiver.await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -265,12 +239,12 @@ async fn drain_queue(inner: Arc<Mutex<Inner>>) {
|
|||||||
match mutation {
|
match mutation {
|
||||||
Mutation::Write { path, bytes } => {
|
Mutation::Write { path, bytes } => {
|
||||||
if let Err(error) = write_file(&directory, &path, &bytes).await {
|
if let Err(error) = write_file(&directory, &path, &bytes).await {
|
||||||
report_write_error("write", &path, &error);
|
log::error!("OPFS background write for {path} failed: {error:?}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Mutation::Append { path, bytes } => {
|
Mutation::Append { path, bytes } => {
|
||||||
if let Err(error) = append_file(&directory, &path, &bytes).await {
|
if let Err(error) = append_file(&directory, &path, &bytes).await {
|
||||||
report_write_error("append", &path, &error);
|
log::error!("OPFS background append for {path} failed: {error:?}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Mutation::Delete { path } => {
|
Mutation::Delete { path } => {
|
||||||
@@ -278,7 +252,7 @@ async fn drain_queue(inner: Arc<Mutex<Inner>>) {
|
|||||||
if let Err(error) = remove_file(&directory, &path).await
|
if let Err(error) = remove_file(&directory, &path).await
|
||||||
&& !is_not_found(&error)
|
&& !is_not_found(&error)
|
||||||
{
|
{
|
||||||
report_write_error("delete", &path, &error);
|
log::error!("OPFS background delete for {path} failed: {error:?}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// A receive error on the waiter side just means the reader gave up; nothing to apply.
|
// A receive error on the waiter side just means the reader gave up; nothing to apply.
|
||||||
@@ -289,11 +263,16 @@ async fn drain_queue(inner: Arc<Mutex<Inner>>) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn js_err(error: JsValue) -> ContainerError {
|
||||||
|
ContainerError::Backend(format!("{error:?}"))
|
||||||
|
}
|
||||||
|
|
||||||
/// Resolve `directory_path` (a `/`-separated relative path) under the OPFS root, creating each
|
/// Resolve `directory_path` (a `/`-separated relative path) under the OPFS root, creating each
|
||||||
/// segment. OPFS rejects directory names containing `/`, so a multi-segment path like
|
/// segment. OPFS rejects directory names containing `/`, so a multi-segment path like
|
||||||
/// `documents/<id>` must be descended one segment at a time rather than passed whole.
|
/// `documents/<id>` must be descended one segment at a time rather than passed whole.
|
||||||
async fn open_directory(directory_path: &str) -> std::result::Result<FileSystemDirectoryHandle, JsValue> {
|
async fn open_directory(directory_path: &str) -> std::result::Result<FileSystemDirectoryHandle, JsValue> {
|
||||||
let mut current = opfs_root().await?;
|
let storage = web_sys::window().ok_or_else(|| JsValue::from_str("no window"))?.navigator().storage();
|
||||||
|
let mut current: FileSystemDirectoryHandle = JsFuture::from(storage.get_directory()).await?.dyn_into()?;
|
||||||
|
|
||||||
for segment in directory_path.split('/').filter(|segment| !segment.is_empty()) {
|
for segment in directory_path.split('/').filter(|segment| !segment.is_empty()) {
|
||||||
let options = FileSystemGetDirectoryOptions::new();
|
let options = FileSystemGetDirectoryOptions::new();
|
||||||
@@ -304,37 +283,6 @@ async fn open_directory(directory_path: &str) -> std::result::Result<FileSystemD
|
|||||||
Ok(current)
|
Ok(current)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// List the subdirectories directly under `directory_path`.
|
|
||||||
pub async fn list_directories(directory_path: &str) -> Result<Vec<String>> {
|
|
||||||
crate::validate_prefix(directory_path)?;
|
|
||||||
let root = opfs_root().await.map_err(js_err)?;
|
|
||||||
list_entries(&root, directory_path, EntryKind::Directory).await.map_err(|error| list_error(directory_path, error))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Remove `directory_path` recursively.
|
|
||||||
pub async fn remove_directory(directory_path: &str) -> Result<()> {
|
|
||||||
validate_path(directory_path)?;
|
|
||||||
let root = opfs_root().await.map_err(js_err)?;
|
|
||||||
let removed = async {
|
|
||||||
let (parent, name) = descend(&root, directory_path, false).await?;
|
|
||||||
let options = web_sys::FileSystemRemoveOptions::new();
|
|
||||||
options.set_recursive(true);
|
|
||||||
JsFuture::from(parent.remove_entry_with_options(name, &options)).await
|
|
||||||
}
|
|
||||||
.await;
|
|
||||||
|
|
||||||
match removed {
|
|
||||||
Ok(_) => Ok(()),
|
|
||||||
Err(error) if is_not_found(&error) => Ok(()),
|
|
||||||
Err(error) => Err(js_err(error)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn opfs_root() -> std::result::Result<FileSystemDirectoryHandle, JsValue> {
|
|
||||||
let storage = web_sys::window().ok_or_else(|| JsValue::from_str("no window"))?.navigator().storage();
|
|
||||||
JsFuture::from(storage.get_directory()).await?.dyn_into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Descend the `/`-separated path against `root` and return the directory handle plus the final segment.
|
/// Descend the `/`-separated path against `root` and return the directory handle plus the final segment.
|
||||||
async fn descend<'a>(root: &FileSystemDirectoryHandle, relative: &'a str, create_dirs: bool) -> std::result::Result<(FileSystemDirectoryHandle, &'a str), JsValue> {
|
async fn descend<'a>(root: &FileSystemDirectoryHandle, relative: &'a str, create_dirs: bool) -> std::result::Result<(FileSystemDirectoryHandle, &'a str), JsValue> {
|
||||||
let mut current = root.clone();
|
let mut current = root.clone();
|
||||||
@@ -525,7 +473,3 @@ fn list_error(prefix: &str, error: JsValue) -> ContainerError {
|
|||||||
js_err(error)
|
js_err(error)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn js_err(error: JsValue) -> ContainerError {
|
|
||||||
ContainerError::Backend(format!("{error:?}"))
|
|
||||||
}
|
|
||||||
@@ -12,7 +12,6 @@
|
|||||||
|
|
||||||
pub mod archive;
|
pub mod archive;
|
||||||
pub mod backends;
|
pub mod backends;
|
||||||
pub mod store;
|
|
||||||
|
|
||||||
pub enum ByteHolder {
|
pub enum ByteHolder {
|
||||||
/// Bytes synthesized in memory (decompressed from an archive, produced by serialization).
|
/// Bytes synthesized in memory (decompressed from an archive, produced by serialization).
|
||||||
@@ -351,7 +350,6 @@ impl<C: Container + ?Sized> AsyncContainer for C {
|
|||||||
/// `AsyncContainer::read` returns `impl Future`, so `dyn AsyncContainer` is not object-safe.
|
/// `AsyncContainer::read` returns `impl Future`, so `dyn AsyncContainer` is not object-safe.
|
||||||
/// `AnyContainer` is the workaround: `Gdd` holds one of these by value, and the `AsyncContainer`
|
/// `AnyContainer` is the workaround: `Gdd` holds one of these by value, and the `AsyncContainer`
|
||||||
/// impl forwards to the active variant.
|
/// impl forwards to the active variant.
|
||||||
#[derive(Clone)]
|
|
||||||
pub enum AnyContainer {
|
pub enum AnyContainer {
|
||||||
Memory(backends::memory::MemoryBackend),
|
Memory(backends::memory::MemoryBackend),
|
||||||
#[cfg(not(target_family = "wasm"))]
|
#[cfg(not(target_family = "wasm"))]
|
||||||
|
|||||||
@@ -1,145 +0,0 @@
|
|||||||
use crate::backends::memory::MemoryBackend;
|
|
||||||
use crate::{AnyContainer, Result};
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::future::Future;
|
|
||||||
use std::pin::Pin;
|
|
||||||
use std::sync::Mutex;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
|
||||||
pub struct DocumentKey(pub u64);
|
|
||||||
|
|
||||||
#[cfg(not(target_family = "wasm"))]
|
|
||||||
pub type StoreFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T>> + Send + 'a>>;
|
|
||||||
#[cfg(target_family = "wasm")]
|
|
||||||
pub type StoreFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T>> + 'a>>;
|
|
||||||
|
|
||||||
pub trait DocumentStore: Send + Sync {
|
|
||||||
fn list(&self) -> StoreFuture<'_, Vec<DocumentKey>>;
|
|
||||||
fn open(&self, key: DocumentKey) -> StoreFuture<'_, AnyContainer>;
|
|
||||||
fn remove(&self, key: DocumentKey) -> StoreFuture<'_, ()>;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn directory_name(key: DocumentKey) -> String {
|
|
||||||
format!("{:016x}", key.0)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_directory_name(name: &str) -> Option<DocumentKey> {
|
|
||||||
(name.len() == 16 && name.bytes().all(|byte| byte.is_ascii_hexdigit()))
|
|
||||||
.then(|| u64::from_str_radix(name, 16).ok().map(DocumentKey))
|
|
||||||
.flatten()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
pub struct MemoryStore {
|
|
||||||
documents: Mutex<HashMap<DocumentKey, MemoryBackend>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DocumentStore for MemoryStore {
|
|
||||||
fn list(&self) -> StoreFuture<'_, Vec<DocumentKey>> {
|
|
||||||
let mut keys: Vec<_> = self.documents.lock().unwrap().keys().copied().collect();
|
|
||||||
keys.sort();
|
|
||||||
Box::pin(async move { Ok(keys) })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn open(&self, key: DocumentKey) -> StoreFuture<'_, AnyContainer> {
|
|
||||||
let backend = self.documents.lock().unwrap().entry(key).or_default().clone();
|
|
||||||
Box::pin(async move { Ok(AnyContainer::Memory(backend)) })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn remove(&self, key: DocumentKey) -> StoreFuture<'_, ()> {
|
|
||||||
self.documents.lock().unwrap().remove(&key);
|
|
||||||
Box::pin(async { Ok(()) })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(target_family = "wasm"))]
|
|
||||||
pub struct FolderStore {
|
|
||||||
root: std::path::PathBuf,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(target_family = "wasm"))]
|
|
||||||
impl FolderStore {
|
|
||||||
pub fn new(root: impl Into<std::path::PathBuf>) -> Self {
|
|
||||||
Self { root: root.into() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(target_family = "wasm"))]
|
|
||||||
impl DocumentStore for FolderStore {
|
|
||||||
fn list(&self) -> StoreFuture<'_, Vec<DocumentKey>> {
|
|
||||||
Box::pin(async {
|
|
||||||
let entries = match std::fs::read_dir(&self.root) {
|
|
||||||
Ok(entries) => entries,
|
|
||||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
|
|
||||||
Err(error) => return Err(error.into()),
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut keys: Vec<_> = entries
|
|
||||||
.filter_map(|entry| entry.ok())
|
|
||||||
.filter(|entry| entry.file_type().is_ok_and(|file_type| file_type.is_dir()))
|
|
||||||
.filter_map(|entry| parse_directory_name(&entry.file_name().to_string_lossy()))
|
|
||||||
.collect();
|
|
||||||
keys.sort();
|
|
||||||
Ok(keys)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn open(&self, key: DocumentKey) -> StoreFuture<'_, AnyContainer> {
|
|
||||||
Box::pin(async move {
|
|
||||||
let backend = crate::backends::folder::FolderBackend::create(self.root.join(directory_name(key)))?;
|
|
||||||
Ok(AnyContainer::Folder(backend))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn remove(&self, key: DocumentKey) -> StoreFuture<'_, ()> {
|
|
||||||
Box::pin(async move {
|
|
||||||
match std::fs::remove_dir_all(self.root.join(directory_name(key))) {
|
|
||||||
Ok(()) => Ok(()),
|
|
||||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
|
||||||
Err(error) => Err(error.into()),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_family = "wasm")]
|
|
||||||
pub struct OpfsStore {
|
|
||||||
root: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_family = "wasm")]
|
|
||||||
impl OpfsStore {
|
|
||||||
pub fn new(root: impl Into<String>) -> Self {
|
|
||||||
Self {
|
|
||||||
root: root.into().trim_matches('/').to_string(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn document_path(&self, key: DocumentKey) -> String {
|
|
||||||
let name = directory_name(key);
|
|
||||||
if self.root.is_empty() { name } else { format!("{}/{name}", self.root) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_family = "wasm")]
|
|
||||||
impl DocumentStore for OpfsStore {
|
|
||||||
fn list(&self) -> StoreFuture<'_, Vec<DocumentKey>> {
|
|
||||||
Box::pin(async {
|
|
||||||
let paths = crate::backends::opfs::list_directories(&self.root).await?;
|
|
||||||
let mut keys: Vec<_> = paths.iter().filter_map(|path| parse_directory_name(path.rsplit('/').next()?)).collect();
|
|
||||||
keys.sort();
|
|
||||||
Ok(keys)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn open(&self, key: DocumentKey) -> StoreFuture<'_, AnyContainer> {
|
|
||||||
Box::pin(async move {
|
|
||||||
let backend = crate::backends::opfs::OpfsBackend::open(&self.document_path(key)).await?;
|
|
||||||
Ok(AnyContainer::Opfs(backend))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn remove(&self, key: DocumentKey) -> StoreFuture<'_, ()> {
|
|
||||||
Box::pin(async move { crate::backends::opfs::remove_directory(&self.document_path(key)).await })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -176,15 +176,3 @@ fn folder_backend_write_sized_fills_via_mmap() {
|
|||||||
let read_back = backend.read("resources/sized").unwrap();
|
let read_back = backend.read("resources/sized").unwrap();
|
||||||
assert_eq!(read_back.as_slice(), payload);
|
assert_eq!(read_back.as_slice(), payload);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn memory_backend_clones_share_the_store() {
|
|
||||||
let backend = MemoryBackend::new();
|
|
||||||
let clone = backend.clone();
|
|
||||||
|
|
||||||
backend.write("file", b"through the original").unwrap();
|
|
||||||
assert_eq!(clone.read("file").unwrap().as_slice(), b"through the original");
|
|
||||||
|
|
||||||
clone.remove("file").unwrap();
|
|
||||||
assert!(!backend.exists("file"));
|
|
||||||
}
|
|
||||||
@@ -5,15 +5,9 @@ version.workspace = true
|
|||||||
license.workspace = true
|
license.workspace = true
|
||||||
authors.workspace = true
|
authors.workspace = true
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
repository.workspace = true
|
|
||||||
readme.workspace = true
|
|
||||||
homepage.workspace = true
|
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
publish.workspace = true
|
publish.workspace = true
|
||||||
|
|
||||||
[lints]
|
|
||||||
workspace = true
|
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
# Runtime bridge: the editor <-> storage conversion methods (stage/commit from a `NodeNetwork`,
|
# Runtime bridge: the editor <-> storage conversion methods (stage/commit from a `NodeNetwork`,
|
||||||
# `network_ids`, `declarations`). Off lets a standalone migration tool build without `graph-craft`
|
# `network_ids`, `declarations`). Off lets a standalone migration tool build without `graph-craft`
|
||||||
@@ -33,7 +27,7 @@ graphene-resource = { workspace = true }
|
|||||||
core-types = { workspace = true, optional = true }
|
core-types = { workspace = true, optional = true }
|
||||||
serde = { workspace = true }
|
serde = { workspace = true }
|
||||||
serde_json = { workspace = true }
|
serde_json = { workspace = true }
|
||||||
postcard = { workspace = true }
|
rmp-serde = { workspace = true }
|
||||||
futures = { workspace = true }
|
futures = { workspace = true }
|
||||||
thiserror = "2.0"
|
thiserror = "2.0"
|
||||||
log = { workspace = true }
|
log = { workspace = true }
|
||||||
|
|||||||
@@ -8,16 +8,18 @@ pub enum Codec {
|
|||||||
Json,
|
Json,
|
||||||
/// Newline-delimited compact JSON, one value per line.
|
/// Newline-delimited compact JSON, one value per line.
|
||||||
JsonLines,
|
JsonLines,
|
||||||
/// A single postcard blob. `append` to a non-empty buffer errors.
|
/// A single MessagePack blob. `append` to a non-empty buffer errors.
|
||||||
Postcard,
|
MessagePack,
|
||||||
/// Length-prefixed postcard frames: `[u32 big-endian length][postcard bytes]` per value.
|
/// Length-prefixed MessagePack frames: `[u32 big-endian length][MessagePack bytes]` per value.
|
||||||
PostcardFrames,
|
MessagePackFrames,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
pub enum CodecError {
|
pub enum CodecError {
|
||||||
#[error("postcard error: {0}")]
|
#[error("MessagePack encode error: {0}")]
|
||||||
Postcard(#[from] postcard::Error),
|
MessagePackEncode(#[from] rmp_serde::encode::Error),
|
||||||
|
#[error("MessagePack decode error: {0}")]
|
||||||
|
MessagePackDecode(#[from] rmp_serde::decode::Error),
|
||||||
#[error("JSON error: {0}")]
|
#[error("JSON error: {0}")]
|
||||||
Json(#[from] serde_json::Error),
|
Json(#[from] serde_json::Error),
|
||||||
#[error("frame length {0} exceeds u32")]
|
#[error("frame length {0} exceeds u32")]
|
||||||
@@ -39,8 +41,8 @@ impl Codec {
|
|||||||
match self {
|
match self {
|
||||||
Codec::Json => "json",
|
Codec::Json => "json",
|
||||||
Codec::JsonLines => "jsonl",
|
Codec::JsonLines => "jsonl",
|
||||||
Codec::Postcard => "bin",
|
Codec::MessagePack => "bin",
|
||||||
Codec::PostcardFrames => "frames",
|
Codec::MessagePackFrames => "frames",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,15 +62,15 @@ impl Codec {
|
|||||||
output.push(b'\n');
|
output.push(b'\n');
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
Codec::Postcard => {
|
Codec::MessagePack => {
|
||||||
if !output.is_empty() {
|
if !output.is_empty() {
|
||||||
return Err(CodecError::SingleValueAlreadyWritten);
|
return Err(CodecError::SingleValueAlreadyWritten);
|
||||||
}
|
}
|
||||||
postcard::to_io(value, &mut *output)?;
|
rmp_serde::encode::write(output, value)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
Codec::PostcardFrames => {
|
Codec::MessagePackFrames => {
|
||||||
let payload = postcard::to_stdvec(value)?;
|
let payload = rmp_serde::to_vec(value)?;
|
||||||
let length = u32::try_from(payload.len()).map_err(|_| CodecError::FrameTooLarge(payload.len()))?;
|
let length = u32::try_from(payload.len()).map_err(|_| CodecError::FrameTooLarge(payload.len()))?;
|
||||||
output.extend_from_slice(&length.to_be_bytes());
|
output.extend_from_slice(&length.to_be_bytes());
|
||||||
output.extend_from_slice(&payload);
|
output.extend_from_slice(&payload);
|
||||||
@@ -89,11 +91,11 @@ impl Codec {
|
|||||||
remaining: bytes,
|
remaining: bytes,
|
||||||
_marker: std::marker::PhantomData,
|
_marker: std::marker::PhantomData,
|
||||||
}),
|
}),
|
||||||
Codec::Postcard => {
|
Codec::MessagePack => {
|
||||||
let single = postcard::from_bytes::<T>(bytes).map_err(CodecError::from);
|
let single = rmp_serde::from_slice::<T>(bytes).map_err(CodecError::from);
|
||||||
Box::new(std::iter::once(single))
|
Box::new(std::iter::once(single))
|
||||||
}
|
}
|
||||||
Codec::PostcardFrames => Box::new(PostcardFrameIter {
|
Codec::MessagePackFrames => Box::new(MessagePackFrameIter {
|
||||||
remaining: bytes,
|
remaining: bytes,
|
||||||
_marker: std::marker::PhantomData,
|
_marker: std::marker::PhantomData,
|
||||||
}),
|
}),
|
||||||
@@ -151,12 +153,12 @@ impl<T: DeserializeOwned> Iterator for JsonLineIter<'_, T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct PostcardFrameIter<'a, T> {
|
struct MessagePackFrameIter<'a, T> {
|
||||||
remaining: &'a [u8],
|
remaining: &'a [u8],
|
||||||
_marker: std::marker::PhantomData<fn() -> T>,
|
_marker: std::marker::PhantomData<fn() -> T>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: DeserializeOwned> Iterator for PostcardFrameIter<'_, T> {
|
impl<T: DeserializeOwned> Iterator for MessagePackFrameIter<'_, T> {
|
||||||
type Item = Result<T, CodecError>;
|
type Item = Result<T, CodecError>;
|
||||||
|
|
||||||
fn next(&mut self) -> Option<Self::Item> {
|
fn next(&mut self) -> Option<Self::Item> {
|
||||||
@@ -181,7 +183,7 @@ impl<T: DeserializeOwned> Iterator for PostcardFrameIter<'_, T> {
|
|||||||
let (frame, after) = tail.split_at(length);
|
let (frame, after) = tail.split_at(length);
|
||||||
self.remaining = after;
|
self.remaining = after;
|
||||||
|
|
||||||
Some(postcard::from_bytes(frame).map_err(CodecError::from))
|
Some(rmp_serde::from_slice(frame).map_err(CodecError::from))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -222,20 +224,31 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn postcard_round_trip_single() {
|
fn message_pack_round_trip_single() {
|
||||||
let frame = Frame { id: 99, label: "blob".into() };
|
let frame = Frame { id: 99, label: "blob".into() };
|
||||||
let bytes = Codec::Postcard.write_single(&frame).unwrap();
|
let bytes = Codec::MessagePack.write_single(&frame).unwrap();
|
||||||
let decoded: Frame = Codec::Postcard.read_single(&bytes).unwrap();
|
let decoded: Frame = Codec::MessagePack.read_single(&bytes).unwrap();
|
||||||
assert_eq!(decoded, frame);
|
assert_eq!(decoded, frame);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn postcard_append_to_non_empty_errors() {
|
fn message_pack_append_to_non_empty_errors() {
|
||||||
let mut buffer = vec![0xAB];
|
let mut buffer = vec![0xAB];
|
||||||
let result = Codec::Postcard.append(&mut buffer, &Frame { id: 1, label: "x".into() });
|
let result = Codec::MessagePack.append(&mut buffer, &Frame { id: 1, label: "x".into() });
|
||||||
assert!(matches!(result, Err(CodecError::SingleValueAlreadyWritten)), "got {result:?}");
|
assert!(matches!(result, Err(CodecError::SingleValueAlreadyWritten)), "got {result:?}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A type-erased `serde_json::Value` round-trips through the binary codec: the property postcard
|
||||||
|
/// could not satisfy (it raises `WontImplement` on self-describing values), which is why the
|
||||||
|
/// resource/attribute deltas that carry `serde_json::Value` bodies need a self-describing codec.
|
||||||
|
#[test]
|
||||||
|
fn message_pack_round_trips_serde_json_value() {
|
||||||
|
let value = serde_json::json!({ "kind": "embedded", "priority": 1.5, "tags": ["a", "b"] });
|
||||||
|
let bytes = Codec::MessagePack.write_single(&value).unwrap();
|
||||||
|
let decoded: serde_json::Value = Codec::MessagePack.read_single(&bytes).unwrap();
|
||||||
|
assert_eq!(decoded, value);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn json_lines_round_trip_and_skip_blanks() {
|
fn json_lines_round_trip_and_skip_blanks() {
|
||||||
let frames = [Frame { id: 1, label: "alpha".into() }, Frame { id: 2, label: "beta".into() }];
|
let frames = [Frame { id: 1, label: "alpha".into() }, Frame { id: 2, label: "beta".into() }];
|
||||||
@@ -250,13 +263,13 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn postcard_frames_round_trip() {
|
fn message_pack_frames_round_trip() {
|
||||||
let frames = frames();
|
let frames = frames();
|
||||||
let mut buffer = Vec::new();
|
let mut buffer = Vec::new();
|
||||||
for frame in &frames {
|
for frame in &frames {
|
||||||
Codec::PostcardFrames.append(&mut buffer, frame).unwrap();
|
Codec::MessagePackFrames.append(&mut buffer, frame).unwrap();
|
||||||
}
|
}
|
||||||
let decoded: Vec<Frame> = Codec::PostcardFrames.iter(&buffer).collect::<Result<_, _>>().unwrap();
|
let decoded: Vec<Frame> = Codec::MessagePackFrames.iter(&buffer).collect::<Result<_, _>>().unwrap();
|
||||||
assert_eq!(decoded, frames);
|
assert_eq!(decoded, frames);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -264,27 +277,27 @@ mod tests {
|
|||||||
/// deterministically (declared length exceeds the bytes that actually made it to disk) rather
|
/// deterministically (declared length exceeds the bytes that actually made it to disk) rather
|
||||||
/// than decoding a partial value into a plausible-but-wrong one.
|
/// than decoding a partial value into a plausible-but-wrong one.
|
||||||
#[test]
|
#[test]
|
||||||
fn postcard_frames_detect_truncation() {
|
fn message_pack_frames_detect_truncation() {
|
||||||
let mut buffer = Vec::new();
|
let mut buffer = Vec::new();
|
||||||
Codec::PostcardFrames.append(&mut buffer, &Frame { id: 7, label: "ok".into() }).unwrap();
|
Codec::MessagePackFrames.append(&mut buffer, &Frame { id: 7, label: "ok".into() }).unwrap();
|
||||||
buffer.truncate(buffer.len() - 1);
|
buffer.truncate(buffer.len() - 1);
|
||||||
let last = Codec::PostcardFrames.iter::<Frame>(&buffer).last().unwrap();
|
let last = Codec::MessagePackFrames.iter::<Frame>(&buffer).last().unwrap();
|
||||||
assert!(matches!(last, Err(CodecError::TruncatedFrame { .. })), "got {last:?}");
|
assert!(matches!(last, Err(CodecError::TruncatedFrame { .. })), "got {last:?}");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A buffer whose first record's length prefix itself is incomplete (fewer than 4 bytes) is
|
/// A buffer whose first record's length prefix itself is incomplete (fewer than 4 bytes) is
|
||||||
/// reported as a truncated prefix rather than mis-read as a zero-length frame.
|
/// reported as a truncated prefix rather than mis-read as a zero-length frame.
|
||||||
#[test]
|
#[test]
|
||||||
fn postcard_frames_detect_truncated_length_prefix() {
|
fn message_pack_frames_detect_truncated_length_prefix() {
|
||||||
let buffer = vec![0x00, 0x00];
|
let buffer = vec![0x00, 0x00];
|
||||||
let last = Codec::PostcardFrames.iter::<Frame>(&buffer).last().unwrap();
|
let last = Codec::MessagePackFrames.iter::<Frame>(&buffer).last().unwrap();
|
||||||
assert!(matches!(last, Err(CodecError::TruncatedLengthPrefix(2))), "got {last:?}");
|
assert!(matches!(last, Err(CodecError::TruncatedLengthPrefix(2))), "got {last:?}");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn write_single_then_read_with_iter_yields_one() {
|
fn write_single_then_read_with_iter_yields_one() {
|
||||||
let frame = Frame { id: 5, label: "one".into() };
|
let frame = Frame { id: 5, label: "one".into() };
|
||||||
for codec in [Codec::Json, Codec::JsonLines, Codec::Postcard, Codec::PostcardFrames] {
|
for codec in [Codec::Json, Codec::JsonLines, Codec::MessagePack, Codec::MessagePackFrames] {
|
||||||
let bytes = codec.write_single(&frame).unwrap();
|
let bytes = codec.write_single(&frame).unwrap();
|
||||||
let collected: Vec<Frame> = codec.iter(&bytes).collect::<Result<_, _>>().unwrap();
|
let collected: Vec<Frame> = codec.iter(&bytes).collect::<Result<_, _>>().unwrap();
|
||||||
assert_eq!(collected, vec![Frame { id: 5, label: "one".into() }], "codec {codec:?}");
|
assert_eq!(collected, vec![Frame { id: 5, label: "one".into() }], "codec {codec:?}");
|
||||||
@@ -302,7 +315,12 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn extensions_are_distinct() {
|
fn extensions_are_distinct() {
|
||||||
let exts = [Codec::Json.extension(), Codec::JsonLines.extension(), Codec::Postcard.extension(), Codec::PostcardFrames.extension()];
|
let exts = [
|
||||||
|
Codec::Json.extension(),
|
||||||
|
Codec::JsonLines.extension(),
|
||||||
|
Codec::MessagePack.extension(),
|
||||||
|
Codec::MessagePackFrames.extension(),
|
||||||
|
];
|
||||||
let unique: std::collections::HashSet<_> = exts.iter().collect();
|
let unique: std::collections::HashSet<_> = exts.iter().collect();
|
||||||
assert_eq!(unique.len(), exts.len(), "extensions collide: {exts:?}");
|
assert_eq!(unique.len(), exts.len(), "extensions collide: {exts:?}");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,9 +35,6 @@ pub enum Error {
|
|||||||
#[cfg(feature = "conversion")]
|
#[cfg(feature = "conversion")]
|
||||||
#[error("commit error: {0}")]
|
#[error("commit error: {0}")]
|
||||||
Commit(#[from] CommitError),
|
Commit(#[from] CommitError),
|
||||||
/// The container has no manifest, cannot be opened.
|
|
||||||
#[error("container has no manifest")]
|
|
||||||
MissingManifest,
|
|
||||||
/// The manifest's `format` field is not the `.gdd` magic, so this is not a `.gdd` document.
|
/// The manifest's `format` field is not the `.gdd` magic, so this is not a `.gdd` document.
|
||||||
#[error("not a .gdd document (manifest format = {found:?}, expected {expected:?})")]
|
#[error("not a .gdd document (manifest format = {found:?}, expected {expected:?})")]
|
||||||
WrongFormat { found: String, expected: &'static str },
|
WrongFormat { found: String, expected: &'static str },
|
||||||
|
|||||||
@@ -146,14 +146,10 @@ impl<L: Layout> Gdd<L> {
|
|||||||
// Carry the per-peer cursor + view settings so a `.gdd` reopened elsewhere restores the viewport.
|
// Carry the per-peer cursor + view settings so a `.gdd` reopened elsewhere restores the viewport.
|
||||||
let session_state = SessionState {
|
let session_state = SessionState {
|
||||||
peer_id: self.session.peer(),
|
peer_id: self.session.peer(),
|
||||||
user_id: self.session.user(),
|
|
||||||
head_rev: self.session.head_rev(),
|
head_rev: self.session.head_rev(),
|
||||||
last_broadcast_rev: self.session.last_broadcast_rev(),
|
last_broadcast_rev: self.session.last_broadcast_rev(),
|
||||||
redo_stack: self.session.redo_stack().to_vec(),
|
redo_stack: self.session.redo_stack().to_vec(),
|
||||||
next_node_counter: self.session.next_node_counter(),
|
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(),
|
|
||||||
view_settings: self.view_settings.clone(),
|
view_settings: self.view_settings.clone(),
|
||||||
network_view_settings: self.network_view_settings.clone(),
|
network_view_settings: self.network_view_settings.clone(),
|
||||||
};
|
};
|
||||||
@@ -198,15 +194,8 @@ impl<L: Layout> Gdd<L> {
|
|||||||
if options.include_registry {
|
if options.include_registry {
|
||||||
// With history, the persisted snapshot is the retired registry and the hot log layers on top
|
// 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
|
// (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
|
// `bootstrap_from_registry` reconstructs the whole document from it alone.
|
||||||
// its own, so the tombstones go.
|
let snapshot = if options.include_history { export_session.retired_registry() } else { export_session.registry() };
|
||||||
let live;
|
|
||||||
let snapshot = if options.include_history {
|
|
||||||
export_session.retired_registry()
|
|
||||||
} else {
|
|
||||||
live = export_session.registry().without_tombstones();
|
|
||||||
&live
|
|
||||||
};
|
|
||||||
sink.write_entry(&io::path_for(self.layout.registry_basename(), codecs.registry), &codecs.registry.write_single(snapshot)?)?;
|
sink.write_entry(&io::path_for(self.layout.registry_basename(), codecs.registry), &codecs.registry.write_single(snapshot)?)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+59
-49
@@ -6,6 +6,7 @@
|
|||||||
//!
|
//!
|
||||||
//! See the "On-disk container" section of `node-graph/rfcs/document-format.md` for the format spec.
|
//! See the "On-disk container" section of `node-graph/rfcs/document-format.md` for the format spec.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
// `Path` and `FolderBackend` are only used by the native-only path-based open/create, so they're
|
// `Path` and `FolderBackend` are only used by the native-only path-based open/create, so they're
|
||||||
// gated off wasm to avoid unused-import warnings.
|
// gated off wasm to avoid unused-import warnings.
|
||||||
#[cfg(not(target_family = "wasm"))]
|
#[cfg(not(target_family = "wasm"))]
|
||||||
@@ -13,10 +14,10 @@ use std::path::Path;
|
|||||||
|
|
||||||
#[cfg(not(target_family = "wasm"))]
|
#[cfg(not(target_family = "wasm"))]
|
||||||
use document_container::backends::folder::FolderBackend;
|
use document_container::backends::folder::FolderBackend;
|
||||||
use document_container::{AnyContainer, AsyncContainer, ByteHolder};
|
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
|
||||||
#[cfg(feature = "conversion")]
|
#[cfg(feature = "conversion")]
|
||||||
use document_graph_storage::{CommitError, NodeMetadataSource};
|
use document_graph_storage::{CommitError, NodeMetadataSource};
|
||||||
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session, UserId};
|
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session};
|
||||||
#[cfg(feature = "conversion")]
|
#[cfg(feature = "conversion")]
|
||||||
use graphene_resource::LoadResource;
|
use graphene_resource::LoadResource;
|
||||||
use graphene_resource::ResourceHash;
|
use graphene_resource::ResourceHash;
|
||||||
@@ -48,28 +49,30 @@ pub type GddV1 = Gdd<GddV1Layout>;
|
|||||||
pub const MANIFEST_CODEC: Codec = Codec::Json;
|
pub const MANIFEST_CODEC: Codec = Codec::Json;
|
||||||
|
|
||||||
/// Working-copy codecs. The working copy lives in appdata, not under VCS — these defaults
|
/// Working-copy codecs. The working copy lives in appdata, not under VCS — these defaults
|
||||||
/// optimize for size and write cost. JSON/JSONL is opt-in via `ExportFormat::Folder` for users who
|
/// optimize for size and write cost. MessagePack is self-describing, so it round-trips the
|
||||||
/// want a diffable on-disk representation. Recorded in the manifest at create time and read back on
|
/// type-erased `serde_json::Value` bodies that resource and attribute deltas carry (a non-self-
|
||||||
/// open (see [`manifest::PayloadCodecs`]), so the persist path never probes the filesystem.
|
/// describing format like postcard cannot). JSON/JSONL is opt-in via `ExportFormat::Folder` for
|
||||||
|
/// users who want a diffable on-disk representation. Recorded in the manifest at create time and
|
||||||
|
/// read back on open (see [`manifest::PayloadCodecs`]), so the persist path never probes the filesystem.
|
||||||
pub const DEFAULT_SESSION_CODEC: Codec = Codec::Json;
|
pub const DEFAULT_SESSION_CODEC: Codec = Codec::Json;
|
||||||
pub const DEFAULT_REGISTRY_CODEC: Codec = Codec::Postcard;
|
pub const DEFAULT_REGISTRY_CODEC: Codec = Codec::MessagePack;
|
||||||
pub const DEFAULT_HISTORY_CODEC: Codec = Codec::PostcardFrames;
|
pub const DEFAULT_HISTORY_CODEC: Codec = Codec::MessagePackFrames;
|
||||||
pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::PostcardFrames;
|
pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::MessagePackFrames;
|
||||||
|
|
||||||
/// Editor-facing handle. Owns the `Session` and the working-copy container; mutations are mirrored
|
/// Editor-facing handle. Owns the `Session` and the working-copy container; mutations are mirrored
|
||||||
/// to disk continuously (every retirement appends to the history file and re-snapshots the registry).
|
/// to disk continuously (every retirement appends to the history file and re-snapshots the registry).
|
||||||
///
|
///
|
||||||
/// The per-edit persist path (`commit_from_runtime`, `apply_hot_op`, `retire`) is synchronous and
|
/// The per-edit persist path (`commit_from_runtime`, `apply_hot_op`, `retire`) is synchronous and
|
||||||
/// read-free: the manifest is cached in memory (so payload codecs need no disk read), and writes go
|
/// read-free: the manifest is cached in memory (so payload codecs need no disk read), and writes go
|
||||||
/// through the container's sync write surface. Only `open` / `export` are async, since they
|
/// through the container's sync write surface. Only `open` / `create` / `export` are async, since they
|
||||||
/// read.
|
/// read.
|
||||||
/// `Clone` shares the working-copy container (`AnyContainer` is a handle) so a cloned handle reads and writes
|
/// `Clone` shares the working-copy container (`Arc<AnyContainer>`) so a cloned handle reads and writes
|
||||||
/// the *same* on-disk/OPFS working copy — including any writes still queued on the OPFS backend. The
|
/// the *same* on-disk/OPFS working copy — including any writes still queued on the OPFS backend. The
|
||||||
/// `Session` is cloned (a snapshot copy); the container is shared.
|
/// `Session` is cloned (a snapshot copy); the container is shared.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Gdd<L: Layout = GddV1Layout> {
|
pub struct Gdd<L: Layout = GddV1Layout> {
|
||||||
pub(crate) session: Session,
|
pub(crate) session: Session,
|
||||||
pub(crate) working: AnyContainer,
|
pub(crate) working: Arc<AnyContainer>,
|
||||||
pub(crate) layout: L,
|
pub(crate) layout: L,
|
||||||
/// In-memory copy of the manifest, kept authoritative since `Gdd` is its sole writer. Holds the
|
/// In-memory copy of the manifest, kept authoritative since `Gdd` is its sole writer. Holds the
|
||||||
/// per-payload codecs so the persist path never probes the filesystem, keeping it fully read-free
|
/// per-payload codecs so the persist path never probes the filesystem, keeping it fully read-free
|
||||||
@@ -77,10 +80,10 @@ pub struct Gdd<L: Layout = GddV1Layout> {
|
|||||||
pub(crate) manifest: Manifest,
|
pub(crate) manifest: Manifest,
|
||||||
/// Per-peer view settings (PTZ, rulers, etc.), persisted in `session.json` not the registry, so
|
/// Per-peer view settings (PTZ, rulers, etc.), persisted in `session.json` not the registry, so
|
||||||
/// they stay out of the CRDT/history. Opaque to the storage layer; the editor owns the keys/values.
|
/// they stay out of the CRDT/history. Opaque to the storage layer; the editor owns the keys/values.
|
||||||
pub(crate) view_settings: std::collections::BTreeMap<String, document_graph_storage::Value>,
|
pub(crate) view_settings: std::collections::BTreeMap<String, serde_json::Value>,
|
||||||
/// Per-network view settings (node-graph nav + previewing), keyed by stable [`NetworkId`]. Same per-peer
|
/// Per-network view settings (node-graph nav + previewing), keyed by stable [`NetworkId`]. Same per-peer
|
||||||
/// `session.json` treatment as [`view_settings`](Self::view_settings), but scoped per network.
|
/// `session.json` treatment as [`view_settings`](Self::view_settings), but scoped per network.
|
||||||
pub(crate) network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, document_graph_storage::Value>>,
|
pub(crate) network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Native folder-backed convenience constructors. On wasm the editor builds an OPFS-backed
|
/// Native folder-backed convenience constructors. On wasm the editor builds an OPFS-backed
|
||||||
@@ -98,10 +101,10 @@ impl<L: Layout + Default> Gdd<L> {
|
|||||||
|
|
||||||
/// Create a fresh, empty working copy at `path` bound to `peer`. Writes a default manifest
|
/// Create a fresh, empty working copy at `path` bound to `peer`. Writes a default manifest
|
||||||
/// and session state; the caller fills in editor metadata via [`Gdd::update_manifest`].
|
/// and session state; the caller fills in editor metadata via [`Gdd::update_manifest`].
|
||||||
pub fn create(path: &Path, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
pub async fn create(path: &Path, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
||||||
let working = AnyContainer::Folder(FolderBackend::create(path)?);
|
let working = AnyContainer::Folder(FolderBackend::create(path)?);
|
||||||
let layout = L::default();
|
let layout = L::default();
|
||||||
Self::create_in(working, layout, peer, document_uuid, editor_version, stdlib_version)
|
Self::create_in(working, layout, peer, document_uuid, editor_version, stdlib_version).await
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,14 +124,10 @@ impl<L: Layout> Gdd<L> {
|
|||||||
/// Backend-agnostic open. Splits out so tests can supply a [`document_container::backends::memory::MemoryBackend`].
|
/// Backend-agnostic open. Splits out so tests can supply a [`document_container::backends::memory::MemoryBackend`].
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`Error::MissingManifest`] if the container holds no manifest, [`Error::WrongFormat`] / [`Error::UnsupportedVersion`]
|
/// [`Error::WrongFormat`] / [`Error::UnsupportedVersion`] if the manifest fails validation, plus
|
||||||
/// if it fails validation, plus the usual [`Error::Read`] / [`Error::Codec`] / [`Error::Crdt`] if a payload is malformed.
|
/// the usual [`Error::Read`] / [`Error::Codec`] / [`Error::Crdt`] if a payload is malformed.
|
||||||
pub async fn open_in(working: AnyContainer, layout: L) -> Result<Self, Error> {
|
pub async fn open_in(working: AnyContainer, layout: L) -> Result<Self, Error> {
|
||||||
let manifest: Manifest = match io::read_single(&working, layout.manifest_basename(), MANIFEST_CODEC).await {
|
let manifest: Manifest = io::read_single(&working, layout.manifest_basename(), MANIFEST_CODEC).await?;
|
||||||
Ok(manifest) => manifest,
|
|
||||||
Err(io::ReadError::NotFound { .. }) => return Err(Error::MissingManifest),
|
|
||||||
Err(error) => return Err(error.into()),
|
|
||||||
};
|
|
||||||
validate_manifest(&manifest)?;
|
validate_manifest(&manifest)?;
|
||||||
let codecs = manifest.codecs;
|
let codecs = manifest.codecs;
|
||||||
|
|
||||||
@@ -141,19 +140,18 @@ impl<L: Layout> Gdd<L> {
|
|||||||
let has_history = io::exists(&working, layout.history_basename(), codecs.history).await;
|
let has_history = io::exists(&working, layout.history_basename(), codecs.history).await;
|
||||||
|
|
||||||
let peer = session_state.peer_id;
|
let peer = session_state.peer_id;
|
||||||
let user = session_state.user_id;
|
|
||||||
let mut session = match (has_registry, has_history) {
|
let mut session = match (has_registry, has_history) {
|
||||||
(true, true) => {
|
(true, true) => {
|
||||||
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
|
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
|
||||||
let history = load_history(&working, &layout, codecs.history).await?;
|
let history = load_history(&working, &layout, codecs.history).await?;
|
||||||
Session::load(peer, user, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
|
Session::load(peer, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
|
||||||
}
|
}
|
||||||
(true, false) => {
|
(true, false) => {
|
||||||
// Registry-only export: synthesize a history that reproduces this state.
|
// Registry-only export: synthesize a history that reproduces this state.
|
||||||
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
|
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
|
||||||
Session::bootstrap_from_registry(peer, user, registry)?
|
Session::bootstrap_from_registry(peer, registry)?
|
||||||
}
|
}
|
||||||
(false, _) => Session::replay_from_history(peer, user, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
|
(false, _) => Session::replay_from_history(peer, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Restore the published frontier (silent/published undo boundary) regardless of which load arm ran.
|
// Restore the published frontier (silent/published undo boundary) regardless of which load arm ran.
|
||||||
@@ -161,15 +159,11 @@ impl<L: Layout> Gdd<L> {
|
|||||||
session.publish_up_to(rev);
|
session.publish_up_to(rev);
|
||||||
}
|
}
|
||||||
|
|
||||||
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);
|
|
||||||
replay_hot_log(&working, &layout, codecs.hot_log, &mut session).await?;
|
replay_hot_log(&working, &layout, codecs.hot_log, &mut session).await?;
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
session,
|
session,
|
||||||
working,
|
working: Arc::new(working),
|
||||||
layout,
|
layout,
|
||||||
manifest,
|
manifest,
|
||||||
view_settings: session_state.view_settings,
|
view_settings: session_state.view_settings,
|
||||||
@@ -179,15 +173,11 @@ impl<L: Layout> Gdd<L> {
|
|||||||
|
|
||||||
/// Backend-agnostic create. Records the working-copy default codecs (see `DEFAULT_*_CODEC`) in
|
/// Backend-agnostic create. Records the working-copy default codecs (see `DEFAULT_*_CODEC`) in
|
||||||
/// the manifest and writes each payload with its recorded codec.
|
/// the manifest and writes each payload with its recorded codec.
|
||||||
pub fn create_in(working: AnyContainer, layout: L, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
pub async fn create_in(working: AnyContainer, layout: L, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
||||||
let manifest = Manifest::new(document_uuid, editor_version, stdlib_version);
|
let manifest = Manifest::new(document_uuid, editor_version, stdlib_version);
|
||||||
let codecs = manifest.codecs;
|
let codecs = manifest.codecs;
|
||||||
io::write_single(&working, layout.manifest_basename(), MANIFEST_CODEC, &manifest)?;
|
io::write_single(&working, layout.manifest_basename(), MANIFEST_CODEC, &manifest)?;
|
||||||
let session_state = SessionState {
|
let session_state = SessionState { peer_id: peer, ..Default::default() };
|
||||||
peer_id: peer,
|
|
||||||
user_id: UserId(peer.0),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
io::write_single(&working, layout.session_basename(), codecs.session, &session_state)?;
|
io::write_single(&working, layout.session_basename(), codecs.session, &session_state)?;
|
||||||
|
|
||||||
let session = Session::with_peer(peer);
|
let session = Session::with_peer(peer);
|
||||||
@@ -195,7 +185,7 @@ impl<L: Layout> Gdd<L> {
|
|||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
session,
|
session,
|
||||||
working,
|
working: Arc::new(working),
|
||||||
layout,
|
layout,
|
||||||
manifest,
|
manifest,
|
||||||
view_settings: std::collections::BTreeMap::new(),
|
view_settings: std::collections::BTreeMap::new(),
|
||||||
@@ -266,13 +256,13 @@ impl<L: Layout> Gdd<L> {
|
|||||||
|
|
||||||
/// The per-peer view settings read from `session.json` (PTZ, rulers, overlays, snapping, collapse).
|
/// The per-peer view settings read from `session.json` (PTZ, rulers, overlays, snapping, collapse).
|
||||||
/// Opaque `ui::doc::*` blobs; the editor decodes them. Empty for a fresh document.
|
/// Opaque `ui::doc::*` blobs; the editor decodes them. Empty for a fresh document.
|
||||||
pub fn view_settings(&self) -> &std::collections::BTreeMap<String, document_graph_storage::Value> {
|
pub fn view_settings(&self) -> &std::collections::BTreeMap<String, serde_json::Value> {
|
||||||
&self.view_settings
|
&self.view_settings
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The per-network view settings read from `session.json` (node-graph nav + previewing), keyed by
|
/// The per-network view settings read from `session.json` (node-graph nav + previewing), keyed by
|
||||||
/// [`NetworkId`](document_graph_storage::NetworkId). Opaque `ui::nav::*` / `ui::previewing` blobs the editor decodes.
|
/// [`NetworkId`](document_graph_storage::NetworkId). Opaque `ui::nav::*` / `ui::previewing` blobs the editor decodes.
|
||||||
pub fn network_view_settings(&self) -> &std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, document_graph_storage::Value>> {
|
pub fn network_view_settings(&self) -> &std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>> {
|
||||||
&self.network_view_settings
|
&self.network_view_settings
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -295,20 +285,31 @@ impl<L: Layout> Gdd<L> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Drop the session and return the working-copy container + layout.
|
/// Drop the session and return the working-copy container + layout.
|
||||||
|
/// Intended for test code that needs to reopen against the same container; panics if the container
|
||||||
|
/// is still shared by a `Gdd` clone (tests don't clone before calling this).
|
||||||
pub fn into_storage(self) -> (AnyContainer, L) {
|
pub fn into_storage(self) -> (AnyContainer, L) {
|
||||||
(self.working, self.layout)
|
let working = Arc::try_unwrap(self.working).unwrap_or_else(|_| panic!("into_storage called while the working-copy container is still shared by a Gdd clone"));
|
||||||
|
(working, self.layout)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Resolve every proto-node declaration referenced by the registry or its history into a
|
/// Resolve the proto-node declarations referenced by the registry into a [`document_graph_storage::Declarations`]
|
||||||
/// [`document_graph_storage::Declarations`] map, loading each `ProtoNode`'s bytes from `byte_store`
|
/// map, loading each `ProtoNode`'s bytes from `byte_store` (the global cache in the editor, the
|
||||||
/// (the global cache in the editor, the working-copy container for standalone). Covers history so
|
/// working-copy container for standalone). Only resources referenced by `Implementation::ProtoNode`
|
||||||
/// the map can serve any undo/redo target. Cold-path (mount / open); async because resource loads are.
|
/// are visited, so image/font resources are skipped. Cold-path (open / `to_runtime`); async
|
||||||
|
/// because resource loads are.
|
||||||
#[cfg(feature = "conversion")]
|
#[cfg(feature = "conversion")]
|
||||||
pub async fn declarations(&self, byte_store: &dyn LoadResource) -> document_graph_storage::Declarations {
|
pub async fn declarations(&self, byte_store: &dyn LoadResource) -> document_graph_storage::Declarations {
|
||||||
|
use document_graph_storage::Implementation;
|
||||||
|
|
||||||
|
let registry = self.session.registry();
|
||||||
let mut declarations = document_graph_storage::Declarations::new();
|
let mut declarations = document_graph_storage::Declarations::new();
|
||||||
|
|
||||||
for (id, hash) in self.session.all_declaration_resources() {
|
for node in registry.node_instances.values() {
|
||||||
let Some(hash) = hash else {
|
let Implementation::ProtoNode(id) = node.implementation() else { continue };
|
||||||
|
if declarations.contains_key(id) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(hash) = registry.resources.get(id).and_then(|entry| entry.hash) else {
|
||||||
log::error!("Declaration resource {id} has no resolved hash; cannot load ProtoNode");
|
log::error!("Declaration resource {id} has no resolved hash; cannot load ProtoNode");
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
@@ -318,7 +319,7 @@ impl<L: Layout> Gdd<L> {
|
|||||||
};
|
};
|
||||||
match document_graph_storage::decode_declaration(resource.as_ref()) {
|
match document_graph_storage::decode_declaration(resource.as_ref()) {
|
||||||
Ok(proto) => {
|
Ok(proto) => {
|
||||||
declarations.insert(id, proto);
|
declarations.insert(*id, proto);
|
||||||
}
|
}
|
||||||
Err(error) => log::error!("Failed to deserialize ProtoNode for {id}: {error}"),
|
Err(error) => log::error!("Failed to deserialize ProtoNode for {id}: {error}"),
|
||||||
}
|
}
|
||||||
@@ -327,7 +328,16 @@ impl<L: Layout> Gdd<L> {
|
|||||||
declarations
|
declarations
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Read the embedded legacy `.graphite` document, if present.
|
/// Store the legacy `.graphite` document bytes verbatim inside the working copy (dual-write soak).
|
||||||
|
/// Synchronous (hot-path safe via `write_non_blocking`): called at the autosave boundary alongside
|
||||||
|
/// the registry snapshot. The bytes are opaque to `Gdd` — it never deserializes them.
|
||||||
|
// TODO: Add feature gate for legacy embedding
|
||||||
|
pub fn store_legacy_document(&self, bytes: &[u8]) -> Result<(), ContainerError> {
|
||||||
|
self.working.write_non_blocking(self.layout.legacy_path(), bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read back the embedded legacy `.graphite` document, if present. The compare-on-open oracle and
|
||||||
|
/// the recovery fallback both go through here. `None` when no legacy blob was ever written.
|
||||||
pub async fn read_legacy_document(&self) -> Option<ByteHolder> {
|
pub async fn read_legacy_document(&self) -> Option<ByteHolder> {
|
||||||
self.working.read(self.layout.legacy_path()).await.ok()
|
self.working.read(self.layout.legacy_path()).await.ok()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
use document_container::AsyncContainer;
|
use document_container::AsyncContainer;
|
||||||
#[cfg(feature = "conversion")]
|
#[cfg(feature = "conversion")]
|
||||||
use document_graph_storage::NodeMetadataSource;
|
use document_graph_storage::NodeMetadataSource;
|
||||||
use document_graph_storage::{HotOp, Rev, TimeStamp, Value};
|
use document_graph_storage::{HotOp, Rev, TimeStamp};
|
||||||
#[cfg(feature = "conversion")]
|
#[cfg(feature = "conversion")]
|
||||||
use graphene_resource::ResourceStorage;
|
use graphene_resource::ResourceStorage;
|
||||||
|
|
||||||
@@ -47,7 +47,7 @@ impl<L: Layout> Gdd<L> {
|
|||||||
/// declaration bytes. The working registry reflects the edit immediately, but nothing enters durable
|
/// declaration bytes. The working registry reflects the edit immediately, but nothing enters durable
|
||||||
/// retired history until [`retire_pending_interaction`](Self::retire_pending_interaction). Staging on
|
/// retired history until [`retire_pending_interaction`](Self::retire_pending_interaction). Staging on
|
||||||
/// every edit while retiring only at interaction boundaries lets several edits coalesce into one retired
|
/// every edit while retiring only at interaction boundaries lets several edits coalesce into one retired
|
||||||
/// interaction. Returns the decoded declarations the snapshot references, for the caller's cache.
|
/// interaction.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`Error::Commit`] if the runtime diff is rejected by the session. On an [`Error::Container`] /
|
/// [`Error::Commit`] if the runtime diff is rejected by the session. On an [`Error::Container`] /
|
||||||
@@ -60,8 +60,8 @@ impl<L: Layout> Gdd<L> {
|
|||||||
metadata: &M,
|
metadata: &M,
|
||||||
resources: &graphene_resource::ResourceRegistry,
|
resources: &graphene_resource::ResourceRegistry,
|
||||||
byte_store: &dyn ResourceStorage,
|
byte_store: &dyn ResourceStorage,
|
||||||
) -> Result<document_graph_storage::Declarations, Error> {
|
) -> Result<(), Error> {
|
||||||
let (hot_ops, conversion) = self.session.stage_from_runtime(network, metadata, resources)?;
|
let (hot_ops, declaration_bytes) = self.session.stage_from_runtime(network, metadata, resources)?;
|
||||||
|
|
||||||
for hot_op in &hot_ops {
|
for hot_op in &hot_ops {
|
||||||
self.append_hot_frame(hot_op)?;
|
self.append_hot_frame(hot_op)?;
|
||||||
@@ -70,10 +70,10 @@ impl<L: Layout> Gdd<L> {
|
|||||||
// Persist proto-node declaration content to the byte store (the global cache in the editor,
|
// Persist proto-node declaration content to the byte store (the global cache in the editor,
|
||||||
// the working-copy container for standalone export). Content-addressed, so re-storing
|
// the working-copy container for standalone export). Content-addressed, so re-storing
|
||||||
// identical bytes on every commit is an idempotent no-op.
|
// identical bytes on every commit is an idempotent no-op.
|
||||||
for bytes in conversion.declaration_bytes.values() {
|
for bytes in declaration_bytes.values() {
|
||||||
byte_store.store(bytes);
|
byte_store.store(bytes);
|
||||||
}
|
}
|
||||||
Ok(conversion.declarations)
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Stage ops the caller built from what the editor recorded, rather than deriving them by converting
|
/// Stage ops the caller built from what the editor recorded, rather than deriving them by converting
|
||||||
@@ -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
|
/// 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)).
|
/// re-persist (mirrors [`stage_runtime_snapshot`](Self::stage_runtime_snapshot)).
|
||||||
pub fn apply_hot_op(&mut self, op: HotOp) -> Result<(), Error> {
|
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)?;
|
self.append_hot_frame(&op)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -173,11 +173,9 @@ impl<L: Layout> Gdd<L> {
|
|||||||
/// Unlike the per-interaction marker written inline at retire, this targets an already-written delta, so
|
/// Unlike the per-interaction marker written inline at retire, this targets an already-written delta, so
|
||||||
/// the whole history file is rewritten in topological order. O(history) — fine for occasional user
|
/// the whole history file is rewritten in topological order. O(history) — fine for occasional user
|
||||||
/// labeling, not for per-interaction marking (which uses the inline path). No-op if `rev` is unknown.
|
/// labeling, not for per-interaction marking (which uses the inline path). No-op if `rev` is unknown.
|
||||||
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: Value) -> Result<(), Error> {
|
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: serde_json::Value) -> Result<(), Error> {
|
||||||
if self.session.annotate_delta(rev, key, value) {
|
if self.session.annotate_delta(rev, key, value) {
|
||||||
self.rewrite_history()?;
|
self.rewrite_history()?;
|
||||||
// The annotation ticked the clock, which a reopen must not hand out again.
|
|
||||||
self.persist_session_state()?;
|
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -196,14 +194,10 @@ impl<L: Layout> Gdd<L> {
|
|||||||
fn persist_session_state(&mut self) -> Result<(), Error> {
|
fn persist_session_state(&mut self) -> Result<(), Error> {
|
||||||
let state = SessionState {
|
let state = SessionState {
|
||||||
peer_id: self.session.peer(),
|
peer_id: self.session.peer(),
|
||||||
user_id: self.session.user(),
|
|
||||||
head_rev: self.session.head_rev(),
|
head_rev: self.session.head_rev(),
|
||||||
last_broadcast_rev: self.session.last_broadcast_rev(),
|
last_broadcast_rev: self.session.last_broadcast_rev(),
|
||||||
redo_stack: self.session.redo_stack().to_vec(),
|
redo_stack: self.session.redo_stack().to_vec(),
|
||||||
next_node_counter: self.session.next_node_counter(),
|
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(),
|
|
||||||
view_settings: self.view_settings.clone(),
|
view_settings: self.view_settings.clone(),
|
||||||
network_view_settings: self.network_view_settings.clone(),
|
network_view_settings: self.network_view_settings.clone(),
|
||||||
};
|
};
|
||||||
@@ -211,16 +205,18 @@ impl<L: Layout> Gdd<L> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Re-snapshot the retired registry to `registry.bin`. `Session::load` trusts it to match the persisted `head`
|
/// Re-snapshot the materialized working registry to `registry.bin`. `Session::load` trusts the stored
|
||||||
/// and replays the hot log on top, so it must hold no hot op, and any cursor move must re-persist it.
|
/// registry to match the persisted `head`, so any cursor move (undo/redo) that rewinds the working
|
||||||
|
/// registry without retiring must re-persist it or a reopen would read a registry inconsistent with
|
||||||
|
/// `head`. Synchronous and hot-path-safe (`write_non_blocking`).
|
||||||
fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
|
fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
|
||||||
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.retired_registry())?;
|
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.registry())?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Replace the per-peer view settings and persist them to `session.json`. Called by the editor when
|
/// Replace the per-peer view settings and persist them to `session.json`. Called by the editor when
|
||||||
/// the viewport or a document-level toggle changes; never enters the registry, history, or CRDT.
|
/// the viewport or a document-level toggle changes; never enters the registry, history, or CRDT.
|
||||||
pub fn set_view_settings(&mut self, view_settings: std::collections::BTreeMap<String, document_graph_storage::Value>) -> Result<(), Error> {
|
pub fn set_view_settings(&mut self, view_settings: std::collections::BTreeMap<String, serde_json::Value>) -> Result<(), Error> {
|
||||||
self.view_settings = view_settings;
|
self.view_settings = view_settings;
|
||||||
self.persist_session_state()
|
self.persist_session_state()
|
||||||
}
|
}
|
||||||
@@ -236,7 +232,7 @@ impl<L: Layout> Gdd<L> {
|
|||||||
/// enters the registry, history, or CRDT.
|
/// enters the registry, history, or CRDT.
|
||||||
pub fn set_network_view_settings(
|
pub fn set_network_view_settings(
|
||||||
&mut self,
|
&mut self,
|
||||||
network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, document_graph_storage::Value>>,
|
network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>>,
|
||||||
) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
self.network_view_settings = network_view_settings;
|
self.network_view_settings = network_view_settings;
|
||||||
self.persist_session_state()
|
self.persist_session_state()
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
#[cfg(not(target_family = "wasm"))]
|
#[cfg(not(target_family = "wasm"))]
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
|
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
|
||||||
use graphene_resource::ResourceFuture;
|
use graphene_resource::ResourceFuture;
|
||||||
@@ -38,7 +39,7 @@ impl<L: Layout> Gdd<L> {
|
|||||||
#[cfg(not(target_family = "wasm"))]
|
#[cfg(not(target_family = "wasm"))]
|
||||||
pub fn add_resource_from_path(&mut self, id: document_graph_storage::ResourceId, hash: ResourceHash, src: &Path) -> Result<(), Error> {
|
pub fn add_resource_from_path(&mut self, id: document_graph_storage::ResourceId, hash: ResourceHash, src: &Path) -> Result<(), Error> {
|
||||||
let dest_path = self.layout.resource_path(&hash);
|
let dest_path = self.layout.resource_path(&hash);
|
||||||
if let AnyContainer::Folder(folder) = &self.working {
|
if let AnyContainer::Folder(folder) = self.working.as_ref() {
|
||||||
let full = folder.root().join(&dest_path);
|
let full = folder.root().join(&dest_path);
|
||||||
if let Some(parent) = full.parent() {
|
if let Some(parent) = full.parent() {
|
||||||
std::fs::create_dir_all(parent).map_err(ContainerError::Io)?;
|
std::fs::create_dir_all(parent).map_err(ContainerError::Io)?;
|
||||||
@@ -101,7 +102,7 @@ impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct ResourceProxy<T: Layout>(AnyContainer, T);
|
pub struct ResourceProxy<T: Layout>(Arc<AnyContainer>, T);
|
||||||
|
|
||||||
impl<L: Layout + Send + Sync> LoadResource for ResourceProxy<L> {
|
impl<L: Layout + Send + Sync> LoadResource for ResourceProxy<L> {
|
||||||
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
|
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
//!
|
//!
|
||||||
//! Lives in `session.json`. Rewritten on retirement.
|
//! Lives in `session.json`. Rewritten on retirement.
|
||||||
|
|
||||||
use document_graph_storage::{HotSequence, NetworkId, PeerId, RetiredMarks, Rev, UserId, Value};
|
use document_graph_storage::{NetworkId, PeerId, Rev};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
@@ -15,16 +15,13 @@ pub struct SessionState {
|
|||||||
/// tiebreaking and minting peer-scoped IDs.
|
/// tiebreaking and minting peer-scoped IDs.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub peer_id: PeerId,
|
pub peer_id: PeerId,
|
||||||
/// The person using this device, registered in the CRDT so undo and authorship follow them across peer ids.
|
|
||||||
#[serde(default)]
|
|
||||||
pub user_id: UserId,
|
|
||||||
/// Local-chain cursor. Points at the most recently applied retired delta, or `None` on an empty
|
/// Local-chain cursor. Points at the most recently applied retired delta, or `None` on an empty
|
||||||
/// document (no commits yet).
|
/// document (no commits yet).
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub head_rev: Option<Rev>,
|
pub head_rev: Option<Rev>,
|
||||||
/// Published frontier: the latest retired commit broadcast to a peer. Commits after it are silently
|
/// Published frontier: the latest retired commit broadcast to a peer. Commits after it are silently
|
||||||
/// rewritable on undo; commits at or before it are published. `None` until broadcast transport lands.
|
/// rewritable on undo; commits at or before it are published. `None` until broadcast transport lands.
|
||||||
#[serde(default)]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
pub last_broadcast_rev: Option<Rev>,
|
pub last_broadcast_rev: Option<Rev>,
|
||||||
/// Revs the user has undone past, so redo survives a reopen. (The legacy `VecDeque` redo history
|
/// Revs the user has undone past, so redo survives a reopen. (The legacy `VecDeque` redo history
|
||||||
/// is not persisted, so within the shadow phase this is strictly more capable than the live editor.)
|
/// is not persisted, so within the shadow phase this is strictly more capable than the live editor.)
|
||||||
@@ -34,21 +31,12 @@ pub struct SessionState {
|
|||||||
/// collide on minted IDs.
|
/// collide on minted IDs.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub next_node_counter: u64,
|
pub next_node_counter: u64,
|
||||||
/// The last hot op sequence this peer authored, so a reopen never reuses one.
|
|
||||||
#[serde(default)]
|
|
||||||
pub last_hot_sequence: HotSequence,
|
|
||||||
/// Per-peer view settings (PTZ, rulers, overlays, snapping, panel collapse). Local to the viewer,
|
/// Per-peer view settings (PTZ, rulers, overlays, snapping, panel collapse). Local to the viewer,
|
||||||
/// so kept out of the CRDT/history. Editor owns the keys/values (opaque `ui::doc::*` blobs).
|
/// so kept out of the CRDT/history. Editor owns the keys/values (opaque `ui::doc::*` blobs).
|
||||||
#[serde(default)]
|
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||||
pub view_settings: BTreeMap<String, Value>,
|
pub view_settings: BTreeMap<String, serde_json::Value>,
|
||||||
/// Per-network view settings (node-graph nav + previewing), keyed by the stable storage [`NetworkId`].
|
/// Per-network view settings (node-graph nav + previewing), keyed by the stable storage [`NetworkId`].
|
||||||
/// Per-peer like [`view_settings`](Self::view_settings); opaque `ui::nav::*` / `ui::previewing` blobs.
|
/// Per-peer like [`view_settings`](Self::view_settings); opaque `ui::nav::*` / `ui::previewing` blobs.
|
||||||
#[serde(default)]
|
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||||
pub network_view_settings: BTreeMap<NetworkId, BTreeMap<String, Value>>,
|
pub network_view_settings: BTreeMap<NetworkId, BTreeMap<String, serde_json::Value>>,
|
||||||
/// The retired hot op marks, so a late copy re-sent after a reopen is dropped rather than retired again.
|
|
||||||
#[serde(default)]
|
|
||||||
pub retired_marks: RetiredMarks,
|
|
||||||
/// The Lamport counter, so a reopen never mints a spent stamp.
|
|
||||||
#[serde(default)]
|
|
||||||
pub clock_counter: u64,
|
|
||||||
}
|
}
|
||||||
@@ -5,7 +5,7 @@
|
|||||||
use document_container::AnyContainer;
|
use document_container::AnyContainer;
|
||||||
use document_container::backends::memory::MemoryBackend;
|
use document_container::backends::memory::MemoryBackend;
|
||||||
use document_format::{Codec, Error, GddV1, GddV1Layout, Layout, Manifest, io, manifest};
|
use document_format::{Codec, Error, GddV1, GddV1Layout, Layout, Manifest, io, manifest};
|
||||||
use document_graph_storage::{HotOp, HotSequence, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
|
use document_graph_storage::{HotOp, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
|
||||||
|
|
||||||
fn empty_container() -> AnyContainer {
|
fn empty_container() -> AnyContainer {
|
||||||
AnyContainer::Memory(MemoryBackend::new())
|
AnyContainer::Memory(MemoryBackend::new())
|
||||||
@@ -44,7 +44,7 @@ fn create_in_round_trips_empty_document() {
|
|||||||
futures::executor::block_on(async {
|
futures::executor::block_on(async {
|
||||||
let container = empty_container();
|
let container = empty_container();
|
||||||
|
|
||||||
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()) {
|
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()).await {
|
||||||
Ok(gdd) => gdd,
|
Ok(gdd) => gdd,
|
||||||
Err(error) => panic!("create_in failed: {error:?}"),
|
Err(error) => panic!("create_in failed: {error:?}"),
|
||||||
};
|
};
|
||||||
@@ -82,7 +82,9 @@ fn open_in_rejects_wrong_format_magic() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn manifest_returns_what_create_in_wrote() {
|
fn manifest_returns_what_create_in_wrote() {
|
||||||
futures::executor::block_on(async {
|
futures::executor::block_on(async {
|
||||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into())
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||||
|
|
||||||
assert_eq!(gdd.session().peer(), PeerId(13));
|
assert_eq!(gdd.session().peer(), PeerId(13));
|
||||||
|
|
||||||
@@ -97,7 +99,9 @@ fn manifest_returns_what_create_in_wrote() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn update_manifest_changes_visible_after_reopen() {
|
fn update_manifest_changes_visible_after_reopen() {
|
||||||
futures::executor::block_on(async {
|
futures::executor::block_on(async {
|
||||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||||
|
|
||||||
gdd.update_manifest(|m| m.editor_version = "ed-NEW".into())
|
gdd.update_manifest(|m| m.editor_version = "ed-NEW".into())
|
||||||
.unwrap_or_else(|error| panic!("update_manifest failed: {error:?}"));
|
.unwrap_or_else(|error| panic!("update_manifest failed: {error:?}"));
|
||||||
@@ -112,7 +116,9 @@ fn update_manifest_changes_visible_after_reopen() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
|
fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
|
||||||
futures::executor::block_on(async {
|
futures::executor::block_on(async {
|
||||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||||
|
|
||||||
// AddNetwork on the root network. Idempotent at apply, so two hot ops applied in sequence
|
// AddNetwork on the root network. Idempotent at apply, so two hot ops applied in sequence
|
||||||
// produces one network in the registry.
|
// produces one network in the registry.
|
||||||
@@ -122,7 +128,6 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
|
|||||||
network: Network::default(),
|
network: Network::default(),
|
||||||
},
|
},
|
||||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||||
sequence: HotSequence(1),
|
|
||||||
};
|
};
|
||||||
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
|
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
|
||||||
|
|
||||||
@@ -138,7 +143,9 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||||
futures::executor::block_on(async {
|
futures::executor::block_on(async {
|
||||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||||
|
|
||||||
// Two hot ops: one with low timestamp (will retire), one with high (will stay).
|
// Two hot ops: one with low timestamp (will retire), one with high (will stay).
|
||||||
let early = HotOp {
|
let early = HotOp {
|
||||||
@@ -147,7 +154,6 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
|||||||
network: Network::default(),
|
network: Network::default(),
|
||||||
},
|
},
|
||||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||||
sequence: HotSequence(1),
|
|
||||||
};
|
};
|
||||||
let late = HotOp {
|
let late = HotOp {
|
||||||
op: RegistryDelta::AddNetwork {
|
op: RegistryDelta::AddNetwork {
|
||||||
@@ -155,7 +161,6 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
|||||||
network: Network::default(),
|
network: Network::default(),
|
||||||
},
|
},
|
||||||
timestamp: TimeStamp { counter: 10, peer: PeerId(5) },
|
timestamp: TimeStamp { counter: 10, peer: PeerId(5) },
|
||||||
sequence: HotSequence(2),
|
|
||||||
};
|
};
|
||||||
gdd.apply_hot_op(early).unwrap();
|
gdd.apply_hot_op(early).unwrap();
|
||||||
gdd.apply_hot_op(late).unwrap();
|
gdd.apply_hot_op(late).unwrap();
|
||||||
@@ -184,7 +189,9 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn last_broadcast_rev_persists_across_reopen() {
|
fn last_broadcast_rev_persists_across_reopen() {
|
||||||
futures::executor::block_on(async {
|
futures::executor::block_on(async {
|
||||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||||
|
|
||||||
// Retire one op so there is a real retired rev to mark as published.
|
// Retire one op so there is a real retired rev to mark as published.
|
||||||
let op = HotOp {
|
let op = HotOp {
|
||||||
@@ -193,7 +200,6 @@ fn last_broadcast_rev_persists_across_reopen() {
|
|||||||
network: Network::default(),
|
network: Network::default(),
|
||||||
},
|
},
|
||||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||||
sequence: HotSequence(1),
|
|
||||||
};
|
};
|
||||||
gdd.apply_hot_op(op).unwrap();
|
gdd.apply_hot_op(op).unwrap();
|
||||||
let retired = gdd.retire(TimeStamp { counter: 1, peer: PeerId(5) }).unwrap_or_else(|error| panic!("retire failed: {error:?}"));
|
let retired = gdd.retire(TimeStamp { counter: 1, peer: PeerId(5) }).unwrap_or_else(|error| panic!("retire failed: {error:?}"));
|
||||||
@@ -214,7 +220,9 @@ fn export_folder_round_trips_through_open() {
|
|||||||
use document_format::{ExportFormat, ExportOptions};
|
use document_format::{ExportFormat, ExportOptions};
|
||||||
|
|
||||||
futures::executor::block_on(async {
|
futures::executor::block_on(async {
|
||||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xAB, "ed".into(), "std".into())
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||||
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
let dest = dir.path().join("export");
|
let dest = dir.path().join("export");
|
||||||
@@ -223,7 +231,7 @@ fn export_folder_round_trips_through_open() {
|
|||||||
.await
|
.await
|
||||||
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
|
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
|
||||||
|
|
||||||
// Payloads keep the working-copy codecs: registry is postcard (`.bin`), manifest is JSON.
|
// Payloads keep the working-copy codecs: registry is MessagePack (`.bin`), manifest is JSON.
|
||||||
assert!(dest.join("registry.bin").exists());
|
assert!(dest.join("registry.bin").exists());
|
||||||
assert!(dest.join("manifest.json").exists());
|
assert!(dest.join("manifest.json").exists());
|
||||||
assert!(dest.join("session.json").exists());
|
assert!(dest.join("session.json").exists());
|
||||||
@@ -242,7 +250,9 @@ fn export_zip_round_trips_via_deserialize() {
|
|||||||
use document_format::{ExportFormat, ExportOptions};
|
use document_format::{ExportFormat, ExportOptions};
|
||||||
|
|
||||||
futures::executor::block_on(async {
|
futures::executor::block_on(async {
|
||||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), 0xCD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), 0xCD, "ed".into(), "std".into())
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||||
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
let dest = dir.path().join("doc.gdd.zip");
|
let dest = dir.path().join("doc.gdd.zip");
|
||||||
@@ -267,7 +277,9 @@ fn export_rejects_invalid_options() {
|
|||||||
use document_format::{ExportFormat, ExportOptions};
|
use document_format::{ExportFormat, ExportOptions};
|
||||||
|
|
||||||
futures::executor::block_on(async {
|
futures::executor::block_on(async {
|
||||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xEF, "ed".into(), "std".into())
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||||
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
let dest = dir.path().join("nope");
|
let dest = dir.path().join("nope");
|
||||||
@@ -290,7 +302,9 @@ fn resource_round_trip_add_read_remove() {
|
|||||||
use graphene_resource::{ResourceHash, ResourceId};
|
use graphene_resource::{ResourceHash, ResourceId};
|
||||||
|
|
||||||
futures::executor::block_on(async {
|
futures::executor::block_on(async {
|
||||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), 0xCAFE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), 0xCAFE, "ed".into(), "std".into())
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||||
|
|
||||||
let payload = b"deadbeef cafe babe";
|
let payload = b"deadbeef cafe babe";
|
||||||
let hash = ResourceHash::from(&payload[..]);
|
let hash = ResourceHash::from(&payload[..]);
|
||||||
@@ -320,7 +334,9 @@ fn resource_survives_reopen() {
|
|||||||
use graphene_resource::{ResourceHash, ResourceId};
|
use graphene_resource::{ResourceHash, ResourceId};
|
||||||
|
|
||||||
futures::executor::block_on(async {
|
futures::executor::block_on(async {
|
||||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), 0xC0DE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), 0xC0DE, "ed".into(), "std".into())
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||||
|
|
||||||
let payload = b"persistent bytes";
|
let payload = b"persistent bytes";
|
||||||
let hash = ResourceHash::from(&payload[..]);
|
let hash = ResourceHash::from(&payload[..]);
|
||||||
@@ -349,7 +365,9 @@ fn resource_from_path_uses_fs_copy_on_folder_backend() {
|
|||||||
// Need a folder-backed working copy to exercise the fs::copy path.
|
// Need a folder-backed working copy to exercise the fs::copy path.
|
||||||
let working_dir = tempfile::tempdir().unwrap();
|
let working_dir = tempfile::tempdir().unwrap();
|
||||||
let working = AnyContainer::Folder(FolderBackend::create(working_dir.path()).unwrap());
|
let working = AnyContainer::Folder(FolderBackend::create(working_dir.path()).unwrap());
|
||||||
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||||
|
|
||||||
// Source file outside the working copy.
|
// Source file outside the working copy.
|
||||||
let payload = b"external resource bytes";
|
let payload = b"external resource bytes";
|
||||||
@@ -373,7 +391,9 @@ fn export_carries_resources() {
|
|||||||
use graphene_resource::{ResourceHash, ResourceId};
|
use graphene_resource::{ResourceHash, ResourceId};
|
||||||
|
|
||||||
futures::executor::block_on(async {
|
futures::executor::block_on(async {
|
||||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), 0xBC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), 0xBC, "ed".into(), "std".into())
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||||
|
|
||||||
let payload = b"exported resource";
|
let payload = b"exported resource";
|
||||||
let hash = ResourceHash::from(&payload[..]);
|
let hash = ResourceHash::from(&payload[..]);
|
||||||
@@ -396,12 +416,14 @@ fn export_carries_resources() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn embed_all_resources_materializes_link_only_resource() {
|
fn embed_all_resources_materializes_link_only_resource() {
|
||||||
use document_format::{ExportFormat, ExportOptions};
|
use document_format::{ExportFormat, ExportOptions};
|
||||||
use document_graph_storage::{NoMetadata, to_value};
|
use document_graph_storage::NoMetadata;
|
||||||
use graph_craft::application_io::resource::ResourceStorage;
|
use graph_craft::application_io::resource::ResourceStorage;
|
||||||
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
|
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
|
||||||
|
|
||||||
futures::executor::block_on(async {
|
futures::executor::block_on(async {
|
||||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), 0xF00D, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), 0xF00D, "ed".into(), "std".into())
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||||
|
|
||||||
// A resource whose only source is a URL, resolved to a hash. The bytes live solely in the
|
// A resource whose only source is a URL, resolved to a hash. The bytes live solely in the
|
||||||
// byte store; the working copy never holds them.
|
// byte store; the working copy never holds them.
|
||||||
@@ -448,8 +470,8 @@ fn embed_all_resources_materializes_link_only_resource() {
|
|||||||
|
|
||||||
let entry = reopened.registry().resources.get(&id).expect("resource entry survived export");
|
let entry = reopened.registry().resources.get(&id).expect("resource entry survived export");
|
||||||
assert_eq!(entry.hash, Some(hash));
|
assert_eq!(entry.hash, Some(hash));
|
||||||
let embedded = to_value(&DataSource::Embedded).unwrap();
|
let embedded = serde_json::to_value(DataSource::Embedded).unwrap();
|
||||||
let url = to_value(&DataSource::Url("https://example.com/r.bin".parse().unwrap())).unwrap();
|
let url = serde_json::to_value(DataSource::Url("https://example.com/r.bin".parse().unwrap())).unwrap();
|
||||||
let chain: Vec<_> = entry.sources.iter().map(|(_, value)| value.source.clone()).collect();
|
let chain: Vec<_> = entry.sources.iter().map(|(_, value)| value.source.clone()).collect();
|
||||||
assert_eq!(chain, vec![embedded, url], "Embedded leads the chain, URL kept as fallback");
|
assert_eq!(chain, vec![embedded, url], "Embedded leads the chain, URL kept as fallback");
|
||||||
});
|
});
|
||||||
@@ -466,7 +488,9 @@ fn export_materializes_embedded_resource_from_byte_store() {
|
|||||||
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
|
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
|
||||||
|
|
||||||
futures::executor::block_on(async {
|
futures::executor::block_on(async {
|
||||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), 0xBEEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), 0xBEEF, "ed".into(), "std".into())
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||||
|
|
||||||
// An Embedded resource whose bytes live only in the byte store, not the working copy.
|
// An Embedded resource whose bytes live only in the byte store, not the working copy.
|
||||||
let payload = b"embedded bytes in the cache";
|
let payload = b"embedded bytes in the cache";
|
||||||
@@ -507,7 +531,9 @@ fn export_round_trips_unretired_hot_ops() {
|
|||||||
use graphene_resource::{DataSource, ResourceId, ResourceRegistry};
|
use graphene_resource::{DataSource, ResourceId, ResourceRegistry};
|
||||||
|
|
||||||
futures::executor::block_on(async {
|
futures::executor::block_on(async {
|
||||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xF15E, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xF15E, "ed".into(), "std".into())
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||||
|
|
||||||
let payload = b"hot resource bytes";
|
let payload = b"hot resource bytes";
|
||||||
let hash = graphene_resource::ResourceHash::from(&payload[..]);
|
let hash = graphene_resource::ResourceHash::from(&payload[..]);
|
||||||
@@ -560,12 +586,14 @@ fn open_in_rejects_future_format_version() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn create_in_records_default_codecs_in_manifest() {
|
fn create_in_records_default_codecs_in_manifest() {
|
||||||
futures::executor::block_on(async {
|
futures::executor::block_on(async {
|
||||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||||
|
|
||||||
let codecs = gdd.manifest().codecs;
|
let codecs = gdd.manifest().codecs;
|
||||||
assert_eq!(codecs.registry, Codec::Postcard);
|
assert_eq!(codecs.registry, Codec::MessagePack);
|
||||||
assert_eq!(codecs.history, Codec::PostcardFrames);
|
assert_eq!(codecs.history, Codec::MessagePackFrames);
|
||||||
assert_eq!(codecs.hot_log, Codec::PostcardFrames);
|
assert_eq!(codecs.hot_log, Codec::MessagePackFrames);
|
||||||
assert_eq!(codecs.session, Codec::Json);
|
assert_eq!(codecs.session, Codec::Json);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -581,7 +609,9 @@ fn first_commit_registers_peer_and_survives_reopen() {
|
|||||||
use graphene_resource::ResourceRegistry;
|
use graphene_resource::ResourceRegistry;
|
||||||
|
|
||||||
futures::executor::block_on(async {
|
futures::executor::block_on(async {
|
||||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), 0xAB, "ed".into(), "std".into())
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||||
|
|
||||||
let network = NodeNetwork {
|
let network = NodeNetwork {
|
||||||
exports: vec![NodeInput::node(core_types::uuid::NodeId(0), 0)],
|
exports: vec![NodeInput::node(core_types::uuid::NodeId(0), 0)],
|
||||||
@@ -600,19 +630,11 @@ fn first_commit_registers_peer_and_survives_reopen() {
|
|||||||
|
|
||||||
gdd.commit_from_runtime(&network, &NoMetadata, &ResourceRegistry::new(), &HashMapResourceStorage::new())
|
gdd.commit_from_runtime(&network, &NoMetadata, &ResourceRegistry::new(), &HashMapResourceStorage::new())
|
||||||
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
|
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
|
||||||
assert_eq!(
|
assert_eq!(gdd.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "first commit registers the peer");
|
||||||
gdd.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
|
|
||||||
Some(UserId(21)),
|
|
||||||
"first commit registers the peer"
|
|
||||||
);
|
|
||||||
|
|
||||||
let (working, layout) = gdd.into_storage();
|
let (working, layout) = gdd.into_storage();
|
||||||
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
|
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
|
||||||
assert_eq!(
|
assert_eq!(reopened.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "registration survives reopen");
|
||||||
reopened.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
|
|
||||||
Some(UserId(21)),
|
|
||||||
"registration survives reopen"
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -623,7 +645,9 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
|
|||||||
futures::executor::block_on(async {
|
futures::executor::block_on(async {
|
||||||
use document_container::AsyncContainer;
|
use document_container::AsyncContainer;
|
||||||
|
|
||||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||||
|
|
||||||
let hot_op = HotOp {
|
let hot_op = HotOp {
|
||||||
op: RegistryDelta::AddNetwork {
|
op: RegistryDelta::AddNetwork {
|
||||||
@@ -631,13 +655,12 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
|
|||||||
network: Network::default(),
|
network: Network::default(),
|
||||||
},
|
},
|
||||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||||
sequence: HotSequence(1),
|
|
||||||
};
|
};
|
||||||
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
|
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
|
||||||
|
|
||||||
let (working, layout) = gdd.into_storage();
|
let (working, layout) = gdd.into_storage();
|
||||||
// Defaults: hot log is PostcardFrames (.frames), manifest is always JSON.
|
// Defaults: hot log is MessagePackFrames (.frames), manifest is always JSON.
|
||||||
assert!(working.exists(&io::path_for(layout.hot_log_basename(), Codec::PostcardFrames)).await);
|
assert!(working.exists(&io::path_for(layout.hot_log_basename(), Codec::MessagePackFrames)).await);
|
||||||
assert!(working.exists(&io::path_for(layout.manifest_basename(), Codec::Json)).await);
|
assert!(working.exists(&io::path_for(layout.manifest_basename(), Codec::Json)).await);
|
||||||
|
|
||||||
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
|
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
|
||||||
@@ -675,7 +698,9 @@ fn declarations_round_trip_through_byte_store() {
|
|||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||||
|
|
||||||
// Commit: declaration bytes flow into the byte store, not the Gdd container.
|
// Commit: declaration bytes flow into the byte store, not the Gdd container.
|
||||||
let byte_store = HashMapResourceStorage::new();
|
let byte_store = HashMapResourceStorage::new();
|
||||||
@@ -695,33 +720,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");
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,106 +0,0 @@
|
|||||||
// Staging a whole document after a recorded batch, and what a reopen must carry over.
|
|
||||||
#![cfg(feature = "conversion")]
|
|
||||||
|
|
||||||
use document_container::AnyContainer;
|
|
||||||
use document_container::backends::memory::MemoryBackend;
|
|
||||||
use document_format::{GddV1, GddV1Layout};
|
|
||||||
use document_graph_storage::{NoMetadata, PeerId, Registry};
|
|
||||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
|
||||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
|
|
||||||
use graph_craft::{ProtoNodeIdentifier, concrete};
|
|
||||||
use graphene_resource::ResourceRegistry;
|
|
||||||
|
|
||||||
fn network_with_one_node() -> NodeNetwork {
|
|
||||||
let node = DocumentNode {
|
|
||||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
|
|
||||||
call_argument: concrete!(()),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
NodeNetwork {
|
|
||||||
nodes: [(NodeId(1), node)].into_iter().collect(),
|
|
||||||
..Default::default()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A whole-document stage after a recorded batch stages nothing new: restating the batch would fail on the node it added.
|
|
||||||
#[test]
|
|
||||||
fn restaging_the_whole_document_after_a_batch_stages_nothing() {
|
|
||||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(21), 1, "ed".into(), "std".into()).unwrap();
|
|
||||||
let store = HashMapResourceStorage::new();
|
|
||||||
let resources = ResourceRegistry::new();
|
|
||||||
gdd.stage_runtime_snapshot(&NodeNetwork::default(), &NoMetadata, &resources, &store)
|
|
||||||
.expect("first whole-document stage");
|
|
||||||
|
|
||||||
let target = Registry::convert_from_runtime(&network_with_one_node(), &NoMetadata, &resources, PeerId(21)).unwrap();
|
|
||||||
let ops = document_graph_storage::delta::compute_deltas(gdd.registry(), &target.registry);
|
|
||||||
gdd.stage_constructed_ops(ops, &target.declaration_bytes, &store).expect("recorded batch");
|
|
||||||
let hot_before = gdd.session().hot_log().len();
|
|
||||||
|
|
||||||
gdd.stage_runtime_snapshot(&network_with_one_node(), &NoMetadata, &resources, &store)
|
|
||||||
.expect("the runtime already matches what was staged");
|
|
||||||
assert_eq!(gdd.session().hot_log().len(), hot_before, "nothing new to stage");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `registry.bin` is the retired snapshot the hot log replays onto, so an op still hot at save time must stay out of it.
|
|
||||||
#[test]
|
|
||||||
fn a_reopen_keeps_unretired_hot_ops_out_of_the_retired_snapshot() {
|
|
||||||
use document_graph_storage::{AttributeDelta, HotOp, HotSequence, RegistryDelta, TimeStamp, Value};
|
|
||||||
let set = |value: u32, counter: u64| HotOp {
|
|
||||||
op: RegistryDelta::ChangeDocumentAttribute {
|
|
||||||
delta: AttributeDelta {
|
|
||||||
key: "k".into(),
|
|
||||||
value: Some(Value::from(serde_json::json!(value))),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
timestamp: TimeStamp { counter, peer: PeerId(22) },
|
|
||||||
sequence: HotSequence(counter),
|
|
||||||
};
|
|
||||||
futures::executor::block_on(async {
|
|
||||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(22), 1, "ed".into(), "std".into()).unwrap();
|
|
||||||
gdd.apply_hot_op(set(1, 1)).unwrap();
|
|
||||||
gdd.apply_hot_op(set(2, 2)).unwrap();
|
|
||||||
gdd.retire(TimeStamp { counter: 1, peer: PeerId(22) }).unwrap();
|
|
||||||
|
|
||||||
let retired = gdd.session().retired_registry().clone();
|
|
||||||
let (working, layout) = gdd.into_storage();
|
|
||||||
let reopened = GddV1::open_in(working, layout).await.unwrap();
|
|
||||||
assert!(reopened.session().retired_registry().value_equal(&retired), "the hot op leaked into the retired snapshot");
|
|
||||||
assert_eq!(reopened.session().hot_log().len(), 1);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A reused sequence would let a peer's retired marks drop the new op.
|
|
||||||
#[test]
|
|
||||||
fn a_reopen_continues_the_hot_op_sequence() {
|
|
||||||
use document_graph_storage::{AttributeDelta, RegistryDelta, Value};
|
|
||||||
let set = |value: u32| RegistryDelta::ChangeDocumentAttribute {
|
|
||||||
delta: AttributeDelta {
|
|
||||||
key: "k".into(),
|
|
||||||
value: Some(Value::from(serde_json::json!(value))),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
fn stage(gdd: &mut GddV1, op: RegistryDelta) -> u64 {
|
|
||||||
gdd.stage_constructed_ops(vec![op], &Default::default(), &HashMapResourceStorage::new()).unwrap();
|
|
||||||
gdd.session().hot_log().last().unwrap().sequence.0
|
|
||||||
}
|
|
||||||
futures::executor::block_on(async {
|
|
||||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(23), 1, "ed".into(), "std".into()).unwrap();
|
|
||||||
stage(&mut gdd, set(1));
|
|
||||||
let up_to = gdd.session().hot_log().last().unwrap().timestamp;
|
|
||||||
gdd.retire(up_to).unwrap();
|
|
||||||
let last = stage(&mut gdd, set(2));
|
|
||||||
|
|
||||||
let (working, layout) = gdd.into_storage();
|
|
||||||
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
|
|
||||||
assert_eq!(stage(&mut reopened, set(3)), last + 1);
|
|
||||||
|
|
||||||
let up_to = reopened.session().hot_log().last().unwrap().timestamp;
|
|
||||||
reopened.retire(up_to).unwrap();
|
|
||||||
let last = reopened.session().last_hot_sequence().0;
|
|
||||||
let clock = reopened.session().clock_counter();
|
|
||||||
let (working, layout) = reopened.into_storage();
|
|
||||||
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
|
|
||||||
assert_eq!(reopened.session().clock_counter(), clock, "the clock carries over");
|
|
||||||
assert_eq!(stage(&mut reopened, set(4)), last + 1);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -5,15 +5,9 @@ version.workspace = true
|
|||||||
license.workspace = true
|
license.workspace = true
|
||||||
authors.workspace = true
|
authors.workspace = true
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
repository.workspace = true
|
|
||||||
readme.workspace = true
|
|
||||||
homepage.workspace = true
|
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
publish.workspace = true
|
publish.workspace = true
|
||||||
|
|
||||||
[lints]
|
|
||||||
workspace = true
|
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
conversion = ["dep:graph-craft", "dep:core-types"]
|
conversion = ["dep:graph-craft", "dep:core-types"]
|
||||||
default = ["conversion"]
|
default = ["conversion"]
|
||||||
@@ -28,7 +22,7 @@ serde = { workspace = true }
|
|||||||
serde_json = { workspace = true }
|
serde_json = { workspace = true }
|
||||||
blake3 = { workspace = true }
|
blake3 = { workspace = true }
|
||||||
rustc-hash = { workspace = true }
|
rustc-hash = { workspace = true }
|
||||||
postcard = { workspace = true }
|
rmp-serde = { workspace = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
graph-craft = { workspace = true, features = ["loading"] }
|
graph-craft = { workspace = true, features = ["loading"] }
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use crate::{AttributeDelta, TimeStamp, Value, ValueError, from_value, to_value};
|
use crate::TimeStamp;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::collections::{BTreeMap, btree_map};
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
/// Attribute keys. Glob-import (`use crate::attr::*`) at conversion sites.
|
/// Attribute keys. Glob-import (`use crate::attr::*`) at conversion sites.
|
||||||
///
|
///
|
||||||
@@ -8,214 +8,64 @@ use std::collections::{BTreeMap, btree_map};
|
|||||||
/// keys live on `Node.inputs_attributes[i]`; per-network keys live on `Network.attributes`.
|
/// keys live on `Node.inputs_attributes[i]`; per-network keys live on `Network.attributes`.
|
||||||
pub mod attr;
|
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.
|
||||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
pub struct AttributeValue {
|
pub struct Value {
|
||||||
pub value: Value,
|
pub value: serde_json::Value,
|
||||||
pub timestamp: TimeStamp,
|
pub timestamp: TimeStamp,
|
||||||
// No skipping: the registry is positional on disk.
|
|
||||||
#[serde(default)]
|
|
||||||
pub deleted: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AttributeValue {
|
impl Value {
|
||||||
pub fn new(value: Value, timestamp: TimeStamp) -> Self {
|
pub fn new(value: serde_json::Value, timestamp: TimeStamp) -> Self {
|
||||||
Self { value, timestamp, deleted: false }
|
Self { value, timestamp }
|
||||||
}
|
|
||||||
|
|
||||||
/// The tombstone of a key deleted at `timestamp`.
|
|
||||||
pub fn deleted(timestamp: TimeStamp) -> Self {
|
|
||||||
Self {
|
|
||||||
value: Value::None,
|
|
||||||
timestamp,
|
|
||||||
deleted: true,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Attribute keys and their values, each last-writer-wins on its own timestamp. A key the map lacks is deleted as of
|
pub type Attributes = BTreeMap<String, Value>;
|
||||||
/// its floor, when the map was last written whole.
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
|
||||||
pub struct Attributes {
|
|
||||||
entries: BTreeMap<String, AttributeValue>,
|
|
||||||
#[serde(default)]
|
|
||||||
floor: TimeStamp,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Attributes {
|
/// Write helpers for `Attributes`.
|
||||||
pub fn new() -> Self {
|
pub trait AttributesWrite {
|
||||||
Self::default()
|
/// Inserts a JSON value under `key`.
|
||||||
}
|
fn set(&mut self, key: &str, value: serde_json::Value, timestamp: TimeStamp);
|
||||||
|
|
||||||
/// 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);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Inserts `value` under `key`.
|
|
||||||
pub fn set(&mut self, key: &str, value: Value, timestamp: TimeStamp) {
|
|
||||||
self.insert(key.to_string(), AttributeValue::new(value, timestamp));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Serializes `value` and inserts it under `key`.
|
/// 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<(), serde_json::Error> {
|
||||||
self.set(key, to_value(value)?, timestamp);
|
self.set(key, serde_json::to_value(value)?, timestamp);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Inserts only when `value != default`, so the read side falls back to the same default.
|
/// 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<(), serde_json::Error> {
|
||||||
if value != default {
|
if value != default {
|
||||||
self.set_serialized(key, value, timestamp)?;
|
self.set_serialized(key, value, timestamp)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Deserializes the value under `key`, or `None` if missing, deleted or undecodable.
|
impl AttributesWrite for Attributes {
|
||||||
pub fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
|
fn set(&mut self, key: &str, value: serde_json::Value, timestamp: TimeStamp) {
|
||||||
self.get(key).filter(|v| !v.deleted).and_then(|v| from_value(&v.value).ok())
|
self.insert(key.to_string(), Value { 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`.
|
/// 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)
|
self.get_typed(key).unwrap_or(default)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Same as `get_typed`, falling back to `T::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()
|
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 {
|
impl AttributesRead for Attributes {
|
||||||
fn from_iter<I: IntoIterator<Item = (String, AttributeValue)>>(iter: I) -> Self {
|
fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
|
||||||
Self {
|
self.get(key).and_then(|v| serde_json::from_value(v.value.clone()).ok())
|
||||||
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()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -25,14 +25,12 @@ pub mod node {
|
|||||||
pub const LOCKED: &str = "ui::locked";
|
pub const LOCKED: &str = "ui::locked";
|
||||||
pub const PINNED: &str = "ui::pinned";
|
pub const PINNED: &str = "ui::pinned";
|
||||||
pub const OUTPUT_NAMES: &str = "ui::output_names";
|
pub const OUTPUT_NAMES: &str = "ui::output_names";
|
||||||
pub const OUTPUT_DESCRIPTIONS: &str = "ui::output_descriptions";
|
|
||||||
pub const REFERENCE: &str = "ui::reference"; // TODO: Remove?
|
pub const REFERENCE: &str = "ui::reference"; // TODO: Remove?
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub mod session {
|
pub mod session {
|
||||||
pub mod network {
|
pub mod network {
|
||||||
pub const PREVIEWING: &str = "ui::previewing";
|
|
||||||
// TODO: Remove these graph ui nav-specific attributes
|
// TODO: Remove these graph ui nav-specific attributes
|
||||||
pub const NAV_PTZ: &str = "ui::nav::ptz";
|
pub const NAV_PTZ: &str = "ui::nav::ptz";
|
||||||
pub const NAV_TRANSFORM: &str = "ui::nav::transform";
|
pub const NAV_TRANSFORM: &str = "ui::nav::transform";
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
use crate::{Attributes, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev};
|
use crate::{Attributes, AttributesWrite, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev};
|
||||||
use graphene_resource::ResourceHash;
|
use graphene_resource::ResourceHash;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
/// Content-addressed delta: `id` is `blake3_128(parents, author, timestamp, delta_type)`.
|
/// 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 (it captures pre-state at the moment the forward
|
||||||
|
/// op was applied), so it's serialized for storage but excluded from the identity hash — two peers
|
||||||
|
/// observing the same forward delta against different local states would otherwise compute
|
||||||
|
/// different Revs for the same logical op.
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
pub struct Delta {
|
pub struct Delta {
|
||||||
pub id: Rev,
|
pub id: Rev,
|
||||||
@@ -17,12 +20,8 @@ pub struct Delta {
|
|||||||
/// Local, mutable annotations on this commit (interaction-end marker, future commit messages / labels).
|
/// 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
|
/// 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`.
|
/// identity, and two peers annotating the same op differently must still dedup to one `Rev`.
|
||||||
#[serde(default)]
|
#[serde(default, skip_serializing_if = "Attributes::is_empty")]
|
||||||
pub attributes: Attributes,
|
pub attributes: Attributes,
|
||||||
/// When the delta entered history, in Unix milliseconds by the retiring peer's clock; display only and outside the rev.
|
|
||||||
/// Zero means unrecorded, saving the tag byte of an `Option`. Last, since the history codec is positional.
|
|
||||||
#[serde(default)]
|
|
||||||
pub(crate) retired_at_ms: u64,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Delta {
|
impl Delta {
|
||||||
@@ -36,7 +35,6 @@ impl Delta {
|
|||||||
kind,
|
kind,
|
||||||
reverse,
|
reverse,
|
||||||
attributes: Attributes::default(),
|
attributes: Attributes::default(),
|
||||||
retired_at_ms: 0,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,7 +55,6 @@ impl Delta {
|
|||||||
reverse: kind.clone(),
|
reverse: kind.clone(),
|
||||||
kind,
|
kind,
|
||||||
attributes: Attributes::default(),
|
attributes: Attributes::default(),
|
||||||
retired_at_ms: 0,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,16 +69,11 @@ impl Delta {
|
|||||||
|
|
||||||
/// Mark this delta as the last op of a user interaction, so the undo cursor treats it as a checkpoint.
|
/// Mark this delta as the last op of a user interaction, so the undo cursor treats it as a checkpoint.
|
||||||
pub fn mark_interaction_end(&mut self, timestamp: TimeStamp) {
|
pub fn mark_interaction_end(&mut self, timestamp: TimeStamp) {
|
||||||
self.attributes.set(attr::delta::INTERACTION_END, Value::Bool(true), timestamp);
|
self.attributes.set(attr::delta::INTERACTION_END, serde_json::Value::Bool(true), timestamp);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_interaction_end(&self) -> bool {
|
pub fn is_interaction_end(&self) -> bool {
|
||||||
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == Value::Bool(true))
|
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == serde_json::Value::Bool(true))
|
||||||
}
|
|
||||||
|
|
||||||
/// When the delta entered history in wall-clock milliseconds, if the peer that retired it recorded it.
|
|
||||||
pub fn retired_at(&self) -> Option<u64> {
|
|
||||||
(self.retired_at_ms != 0).then_some(self.retired_at_ms)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The content-addressed `Rev` this delta's identity fields hash to. Equals `id` for a delta built
|
/// The content-addressed `Rev` this delta's identity fields hash to. Equals `id` for a delta built
|
||||||
@@ -106,7 +98,8 @@ pub enum RegistryDelta {
|
|||||||
id: NodeId,
|
id: NodeId,
|
||||||
node: Node,
|
node: Node,
|
||||||
},
|
},
|
||||||
/// `snapshot` is the node as removed, which folds in like any write so a removal of a node never seen still lands.
|
/// `snapshot` lets the reverse `AddNode` rebuild without reading the (already-removed) node from
|
||||||
|
/// the registry, mirroring `RemoveNetwork`.
|
||||||
RemoveNode {
|
RemoveNode {
|
||||||
id: NodeId,
|
id: NodeId,
|
||||||
snapshot: Node,
|
snapshot: Node,
|
||||||
@@ -126,15 +119,6 @@ pub enum RegistryDelta {
|
|||||||
id: NodeId,
|
id: NodeId,
|
||||||
inputs: Vec<InputSlot>,
|
inputs: Vec<InputSlot>,
|
||||||
},
|
},
|
||||||
/// A node's implementation, for swapping what it computes without rebuilding the node.
|
|
||||||
///
|
|
||||||
/// Removing and re-adding the node would express the same change, but would also clear every
|
|
||||||
/// attribute it carries, so restating them would clobber whatever a concurrent peer wrote to the
|
|
||||||
/// node's name, lock or pin.
|
|
||||||
SetNodeImplementation {
|
|
||||||
id: NodeId,
|
|
||||||
implementation: Implementation,
|
|
||||||
},
|
|
||||||
ChangeNodeAttribute {
|
ChangeNodeAttribute {
|
||||||
id: NodeId,
|
id: NodeId,
|
||||||
delta: AttributeDelta,
|
delta: AttributeDelta,
|
||||||
@@ -159,12 +143,13 @@ pub enum RegistryDelta {
|
|||||||
id: NetworkId,
|
id: NetworkId,
|
||||||
network: Network,
|
network: Network,
|
||||||
},
|
},
|
||||||
/// `snapshot` is the network as removed; see [`RemoveNode`](Self::RemoveNode).
|
/// `snapshot` lets the reverse delta rebuild without re-walking history.
|
||||||
RemoveNetwork {
|
RemoveNetwork {
|
||||||
id: NetworkId,
|
id: NetworkId,
|
||||||
snapshot: Network,
|
snapshot: Network,
|
||||||
},
|
},
|
||||||
/// Register a whole resource entry at once, the way `AddNetwork` pairs with `RemoveNetwork`.
|
/// Register a whole resource entry at once. Overwrites any existing entry for `id`; the reverse
|
||||||
|
/// of `RemoveResource`, the way `AddNetwork` pairs with `RemoveNetwork`.
|
||||||
AddResource {
|
AddResource {
|
||||||
id: ResourceId,
|
id: ResourceId,
|
||||||
entry: ResourceEntry,
|
entry: ResourceEntry,
|
||||||
@@ -186,14 +171,16 @@ pub enum RegistryDelta {
|
|||||||
AddSource {
|
AddSource {
|
||||||
id: ResourceId,
|
id: ResourceId,
|
||||||
key: SourceKey,
|
key: SourceKey,
|
||||||
source: Value,
|
source: serde_json::Value,
|
||||||
},
|
},
|
||||||
/// Remove one entry from a resource's source chain. LWW against the entry's timestamp.
|
/// Remove one entry from a resource's source chain. LWW against the entry's timestamp.
|
||||||
RemoveSource {
|
RemoveSource {
|
||||||
id: ResourceId,
|
id: ResourceId,
|
||||||
key: SourceKey,
|
key: SourceKey,
|
||||||
},
|
},
|
||||||
/// Registers a device's `PeerId` to the `UserId` behind it; the newest registration wins.
|
/// Append-only registration of a device's `PeerId` against its owning `UserId`.
|
||||||
|
/// First write wins; conflicting re-registration errors. Duplicate identical registration
|
||||||
|
/// is a no-op. Not LWW — the mapping is forever.
|
||||||
RegisterPeer {
|
RegisterPeer {
|
||||||
peer: PeerId,
|
peer: PeerId,
|
||||||
user: UserId,
|
user: UserId,
|
||||||
@@ -209,47 +196,41 @@ pub enum RegistryDelta {
|
|||||||
extra_parents: Vec<Rev>,
|
extra_parents: Vec<Rev>,
|
||||||
},
|
},
|
||||||
// Allow for future delta types without a model change
|
// Allow for future delta types without a model change
|
||||||
Other(Value),
|
Other(serde_json::Value),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `value: None` means remove. The timestamp comes from the wrapping `Delta`.
|
/// `value: None` means remove. The timestamp comes from the wrapping `Delta`.
|
||||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
pub struct AttributeDelta {
|
pub struct AttributeDelta {
|
||||||
pub key: String,
|
pub key: String,
|
||||||
pub value: Option<Value>,
|
pub value: Option<serde_json::Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn reverse_attribute_delta(delta: &AttributeDelta, attributes: &Attributes) -> AttributeDelta {
|
pub(crate) fn reverse_attribute_delta(delta: &AttributeDelta, attributes: &Attributes) -> AttributeDelta {
|
||||||
AttributeDelta {
|
AttributeDelta {
|
||||||
key: delta.key.clone(),
|
key: delta.key.clone(),
|
||||||
value: attributes.get(&delta.key).filter(|previous| !previous.deleted).map(|previous| previous.value.clone()),
|
value: attributes.get(&delta.key).map(|previous| previous.value.clone()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
pub(crate) fn apply_attribute_delta(delta: AttributeDelta, timestamp: TimeStamp, force: bool, attributes: &mut Attributes) {
|
||||||
mod tests {
|
let AttributeDelta { key, value } = delta;
|
||||||
use super::*;
|
match value {
|
||||||
|
Some(value) => match attributes.entry(key) {
|
||||||
#[test]
|
std::collections::btree_map::Entry::Occupied(mut entry) => {
|
||||||
fn unrecorded_retired_at_costs_one_byte_and_round_trips() {
|
if force || timestamp > entry.get().timestamp {
|
||||||
let base = Delta::new(
|
entry.insert(Value { value, timestamp });
|
||||||
None,
|
}
|
||||||
PeerId(1),
|
}
|
||||||
TimeStamp { counter: 1, peer: PeerId(1) },
|
std::collections::btree_map::Entry::Vacant(entry) => {
|
||||||
RegistryDelta::Other(Value::None),
|
entry.insert(Value { value, timestamp });
|
||||||
RegistryDelta::Other(Value::None),
|
}
|
||||||
);
|
},
|
||||||
let mut stamped = base.clone();
|
None => {
|
||||||
stamped.retired_at_ms = 1_790_000_000_000;
|
let should_remove = force || attributes.get(&key).is_none_or(|existing| timestamp > existing.timestamp);
|
||||||
|
if should_remove {
|
||||||
let bare_base = postcard::to_allocvec(&base).expect("encode");
|
attributes.remove(&key);
|
||||||
let bare_stamped = postcard::to_allocvec(&stamped).expect("encode");
|
}
|
||||||
// Only the integer's varint differs: one byte for zero, six for today's milliseconds, no tag byte in either.
|
}
|
||||||
assert_eq!(bare_stamped.len() - bare_base.len(), postcard::to_allocvec(&1_790_000_000_000u64).unwrap().len() - 1);
|
|
||||||
|
|
||||||
let decoded: Delta = postcard::from_bytes(&bare_stamped).expect("decode");
|
|
||||||
assert_eq!(decoded.retired_at(), Some(1_790_000_000_000));
|
|
||||||
let decoded: Delta = postcard::from_bytes(&bare_base).expect("decode");
|
|
||||||
assert_eq!(decoded.retired_at(), None);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -166,14 +166,14 @@ fn diff_resource_entry(id: ResourceId, from: &ResourceEntry, to: &ResourceEntry,
|
|||||||
deltas.push(RegistryDelta::SetResourceHash { id, hash: to.hash });
|
deltas.push(RegistryDelta::SetResourceHash { id, hash: to.hash });
|
||||||
}
|
}
|
||||||
|
|
||||||
for (key, _) in from.live_sources() {
|
for (key, _) in &from.sources {
|
||||||
if to.source(key).is_none() {
|
if to.source(key).is_none() {
|
||||||
deltas.push(RegistryDelta::RemoveSource { id, key: *key });
|
deltas.push(RegistryDelta::RemoveSource { id, key: *key });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Compare source bodies only; the per-source timestamp is derived from the diff, not part of it.
|
// Compare source bodies only; the per-source timestamp is derived from the diff, not part of it.
|
||||||
for (key, to_source) in to.live_sources() {
|
for (key, to_source) in &to.sources {
|
||||||
if from.source(key).is_none_or(|from_source| from_source.source != to_source.source) {
|
if from.source(key).is_none_or(|from_source| from_source.source != to_source.source) {
|
||||||
deltas.push(RegistryDelta::AddSource {
|
deltas.push(RegistryDelta::AddSource {
|
||||||
id,
|
id,
|
||||||
@@ -196,15 +196,15 @@ fn nodes_have_same_implementation(a: &Node, b: &Node) -> bool {
|
|||||||
fn compute_attribute_deltas(from: &crate::Attributes, to: &crate::Attributes) -> Vec<AttributeDelta> {
|
fn compute_attribute_deltas(from: &crate::Attributes, to: &crate::Attributes) -> Vec<AttributeDelta> {
|
||||||
let mut deltas = Vec::new();
|
let mut deltas = Vec::new();
|
||||||
|
|
||||||
for (key, _) in from.live() {
|
for key in from.keys() {
|
||||||
if to.get(key).is_none_or(|value| value.deleted) {
|
if !to.contains_key(key) {
|
||||||
deltas.push(AttributeDelta { key: key.clone(), value: None });
|
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.
|
// 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 to {
|
||||||
if from.get(key).is_none_or(|from_value| from_value.deleted || from_value.value != to_value.value) {
|
if from.get(key).is_none_or(|from_value| from_value.value != to_value.value) {
|
||||||
deltas.push(AttributeDelta {
|
deltas.push(AttributeDelta {
|
||||||
key: key.clone(),
|
key: key.clone(),
|
||||||
value: Some(to_value.value.clone()),
|
value: Some(to_value.value.clone()),
|
||||||
@@ -218,7 +218,7 @@ fn compute_attribute_deltas(from: &crate::Attributes, to: &crate::Attributes) ->
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::{Attributes, ExportSlot, Network, Node, NodeInput, TimeStamp, Value};
|
use crate::{Attributes, ExportSlot, Network, Node, NodeInput, TimeStamp};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_compute_deltas_empty() {
|
fn test_compute_deltas_empty() {
|
||||||
@@ -298,13 +298,17 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_compute_deltas_change_network_attribute() {
|
fn test_compute_deltas_change_network_attribute() {
|
||||||
use crate::TimeStamp;
|
use crate::{AttributesWrite, TimeStamp};
|
||||||
|
|
||||||
let mut from = Registry::default();
|
let mut from = Registry::default();
|
||||||
from.networks.insert(NetworkId(0), Network::default());
|
from.networks.insert(NetworkId(0), Network::default());
|
||||||
|
|
||||||
let mut to = from.clone();
|
let mut to = from.clone();
|
||||||
to.networks.get_mut(&NetworkId(0)).unwrap().attributes.set("ui::nav::width", Value::Float(640.), TimeStamp::ORIGIN);
|
to.networks
|
||||||
|
.get_mut(&NetworkId(0))
|
||||||
|
.unwrap()
|
||||||
|
.attributes
|
||||||
|
.set("ui::nav::width", serde_json::json!(640.0), TimeStamp::ORIGIN);
|
||||||
|
|
||||||
let deltas = compute_deltas(&from, &to);
|
let deltas = compute_deltas(&from, &to);
|
||||||
assert_eq!(deltas.len(), 1, "a changed per-network attribute must emit one delta");
|
assert_eq!(deltas.len(), 1, "a changed per-network attribute must emit one delta");
|
||||||
@@ -337,10 +341,9 @@ mod tests {
|
|||||||
let stamp = |counter: u64| TimeStamp { counter, peer: crate::PeerId(0) };
|
let stamp = |counter: u64| TimeStamp { counter, peer: crate::PeerId(0) };
|
||||||
node.attributes.insert(
|
node.attributes.insert(
|
||||||
"test".to_string(),
|
"test".to_string(),
|
||||||
crate::AttributeValue {
|
crate::Value {
|
||||||
value: Value::Str("old".into()),
|
value: serde_json::json!("old"),
|
||||||
timestamp: stamp(0),
|
timestamp: stamp(0),
|
||||||
deleted: false,
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
from.node_instances.insert(NodeId(42), node);
|
from.node_instances.insert(NodeId(42), node);
|
||||||
@@ -348,10 +351,9 @@ mod tests {
|
|||||||
let mut to = from.clone();
|
let mut to = from.clone();
|
||||||
to.node_instances.get_mut(&NodeId(42)).unwrap().attributes.insert(
|
to.node_instances.get_mut(&NodeId(42)).unwrap().attributes.insert(
|
||||||
"test".to_string(),
|
"test".to_string(),
|
||||||
crate::AttributeValue {
|
crate::Value {
|
||||||
value: Value::Str("new".into()),
|
value: serde_json::json!("new"),
|
||||||
timestamp: stamp(1),
|
timestamp: stamp(1),
|
||||||
deleted: false,
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -374,10 +376,9 @@ mod tests {
|
|||||||
let mut to = from.clone();
|
let mut to = from.clone();
|
||||||
to.attributes.insert(
|
to.attributes.insert(
|
||||||
"doc::test_attribute".to_string(),
|
"doc::test_attribute".to_string(),
|
||||||
crate::AttributeValue {
|
crate::Value {
|
||||||
value: Value::Str("value".into()),
|
value: serde_json::json!("value"),
|
||||||
timestamp: stamp(1),
|
timestamp: stamp(1),
|
||||||
deleted: false,
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -1,28 +1,23 @@
|
|||||||
use std::collections::{HashMap, HashSet};
|
|
||||||
use std::hash::Hash;
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
Attributes, CrdtError, Delta, ExportSlot, History, HotOp, HotSequence, Implementation, InputSlot, LamportClock, MAX_EXPORT_SLOTS, MAX_INPUT_SLOTS, Network, NetworkId, Node, NodeId, NodeInput,
|
CrdtError, Delta, ExportSlot, History, HotOp, LamportClock, MAX_EXPORT_SLOTS, NetworkId, NodeId, NodeInput, PeerId, Registry, RegistryDelta, ResourceEntry, Rev, SourceValue, TimeStamp,
|
||||||
PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, RetiredMarks, Rev, SourceValue, TimeStamp, Tombstone, UserId, Value, reverse_attribute_delta,
|
apply_attribute_delta, reverse_attribute_delta,
|
||||||
};
|
};
|
||||||
use std::borrow::Cow;
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct Document {
|
pub struct Document {
|
||||||
/// Working registry: retired state with the current hot ops applied on top. This is what live
|
/// Working registry: retired state with the current hot ops applied on top. This is what live
|
||||||
/// reads and `registry()` observe.
|
/// reads and `registry()` observe, and what undo/redo force-apply against.
|
||||||
pub(crate) working_registry: Registry,
|
pub(crate) working_registry: Registry,
|
||||||
/// Live broadcast stream, applied to the `working_registry` on receive, GC'd at retirement.
|
/// Live broadcast stream, applied to the `working_registry` on receive, GC'd at retirement.
|
||||||
/// Persisted for crash recovery so in-flight unretired work survives editor restarts.
|
/// Persisted for crash recovery so in-flight unretired work survives editor restarts.
|
||||||
pub(crate) hot_log: Vec<HotOp>,
|
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,
|
|
||||||
/// The registry as of the last retirement, with no un-retired hot ops applied. Retirement computes
|
/// 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
|
/// 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
|
/// hot-polluted working state) and advances it, stamping fields at the fresh `T_retire`. Kept equal
|
||||||
/// empty.
|
/// to `registry` *by value* whenever the hot log is empty (undo/redo resync it after moving the
|
||||||
|
/// cursor), but field timestamps can differ: retirement bumps the snapshot's to `T_retire` while the
|
||||||
|
/// working registry keeps the staging-time timestamps. Benign while the local monotonic clock makes
|
||||||
|
/// new edits win
|
||||||
pub(crate) retired_snapshot: Registry,
|
pub(crate) retired_snapshot: Registry,
|
||||||
/// User's cursor in their local history chain. `None` on an empty document (no commits yet).
|
/// User's cursor in their local history chain. `None` on an empty document (no commits yet).
|
||||||
pub(crate) head: Option<Rev>,
|
pub(crate) head: Option<Rev>,
|
||||||
@@ -33,49 +28,64 @@ pub struct Document {
|
|||||||
pub(crate) redo_stack: Vec<Rev>,
|
pub(crate) redo_stack: Vec<Rev>,
|
||||||
pub(crate) clock: LamportClock,
|
pub(crate) clock: LamportClock,
|
||||||
pub(crate) peer: PeerId,
|
pub(crate) peer: PeerId,
|
||||||
pub(crate) user: UserId,
|
/// Latest retired commit on the local chain that has been broadcast to at least one peer.
|
||||||
/// The latest retired commit a peer holds: commits after it undo silently, commits up to it stay.
|
/// Commits after this can be rewritten silently; commits at or before this are published
|
||||||
|
/// and require forward reverse-delta ops to undo. `None` means nothing broadcast yet.
|
||||||
pub(crate) last_broadcast_rev: Option<Rev>,
|
pub(crate) last_broadcast_rev: Option<Rev>,
|
||||||
/// Shared-monotonic counter feeding `next_node_id`. Bumped on every mint regardless of which
|
/// 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
|
/// peer is calling; collision avoidance comes from hashing `(self.peer, counter)`, so two peers
|
||||||
/// reading the same counter still produce distinct IDs.
|
/// reading the same counter still produce distinct IDs.
|
||||||
pub(crate) next_node_counter: u64,
|
pub(crate) next_node_counter: u64,
|
||||||
/// Counts this peer's own hot ops, so each carries its position in a gap-free run. See [`HotOp::sequence`].
|
|
||||||
pub(crate) last_hot_sequence: HotSequence,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Document {
|
impl Document {
|
||||||
pub(crate) fn empty(peer: PeerId, user: UserId) -> Self {
|
|
||||||
Self {
|
|
||||||
working_registry: Registry::default(),
|
|
||||||
retired_snapshot: Registry::default(),
|
|
||||||
history: History::new(),
|
|
||||||
hot_log: Vec::new(),
|
|
||||||
hot_timestamps: HashSet::new(),
|
|
||||||
retired: RetiredMarks::default(),
|
|
||||||
head: None,
|
|
||||||
redo_stack: Vec::new(),
|
|
||||||
clock: LamportClock::new(peer),
|
|
||||||
peer,
|
|
||||||
user,
|
|
||||||
last_broadcast_rev: None,
|
|
||||||
next_node_counter: 0,
|
|
||||||
last_hot_sequence: HotSequence::NONE,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Mint a fresh `NodeId` scoped to this document's peer. The 64-bit ID is `blake3(peer, counter)`
|
/// Mint a fresh `NodeId` scoped to this document's peer. The 64-bit ID is `blake3(peer, counter)`
|
||||||
/// truncated; the counter is shared across peers and persisted with the document.
|
/// truncated; the counter is shared across peers and persisted with the document.
|
||||||
pub fn next_node_id(&mut self) -> NodeId {
|
pub fn next_node_id(&mut self) -> NodeId {
|
||||||
self.next_node_counter += 1;
|
self.next_node_counter += 1;
|
||||||
let mut hasher = blake3::Hasher::new();
|
let bytes = rmp_serde::to_vec(&(self.peer, self.next_node_counter)).expect("(PeerId, counter) must serialize");
|
||||||
postcard::to_io(&(self.peer, self.next_node_counter), &mut hasher).expect("(PeerId, counter) must serialize");
|
let digest = blake3::hash(&bytes);
|
||||||
let digest = hasher.finalize();
|
|
||||||
let mut truncated = [0u8; 8];
|
let mut truncated = [0u8; 8];
|
||||||
truncated.copy_from_slice(&digest.as_bytes()[..8]);
|
truncated.copy_from_slice(&digest.as_bytes()[..8]);
|
||||||
NodeId(u64::from_le_bytes(truncated))
|
NodeId(u64::from_le_bytes(truncated))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn restore_node_from_history(&mut self, target: RegistryTarget, node_id: NodeId) -> Result<(), CrdtError> {
|
||||||
|
let delta = self
|
||||||
|
.find_in_ancestry(|d| matches!(d.reverse, RegistryDelta::AddNode { id, .. } if id == node_id))
|
||||||
|
.ok_or(CrdtError::NodeNotInHistory(node_id))?;
|
||||||
|
self.revert_delta(target, delta)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn restore_network_from_history(&mut self, target: RegistryTarget, network_id: NetworkId) -> Result<(), CrdtError> {
|
||||||
|
// Find the Delta whose forward op removed this network. Its `reverse` is `AddNetwork`,
|
||||||
|
// which is what we want to re-apply.
|
||||||
|
let delta = self
|
||||||
|
.find_in_ancestry(|d| matches!(d.reverse, RegistryDelta::AddNetwork { id, .. } if id == network_id))
|
||||||
|
.ok_or(CrdtError::NetworkNotInHistory(network_id))?;
|
||||||
|
self.revert_delta(target, delta)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Search every delta reachable from `head` (following all parents, including a merge's
|
||||||
|
/// `extra_parents`) for the first matching `predicate`, breadth-first. Resurrection needs full
|
||||||
|
/// ancestry reachability, so a node added only on a merged-in branch is still found.
|
||||||
|
fn find_in_ancestry(&self, predicate: impl Fn(&Delta) -> bool) -> Option<Delta> {
|
||||||
|
let mut queue: std::collections::VecDeque<Rev> = self.head.into_iter().collect();
|
||||||
|
let mut seen: std::collections::HashSet<Rev> = self.head.into_iter().collect();
|
||||||
|
while let Some(rev) = queue.pop_front() {
|
||||||
|
let Some(delta) = self.history.get(rev) else { continue };
|
||||||
|
if predicate(delta) {
|
||||||
|
return Some(delta.clone());
|
||||||
|
}
|
||||||
|
for parent in delta.all_parents() {
|
||||||
|
if seen.insert(parent) {
|
||||||
|
queue.push_back(parent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
/// Apply a delta's `reverse` as the new forward op (silent-zone undo). Force-applied: structural
|
/// 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
|
/// ops are idempotent, and LWW arms assign the reverse value unconditionally even though it carries
|
||||||
/// the same timestamp as the forward op it undoes.
|
/// the same timestamp as the forward op it undoes.
|
||||||
@@ -89,70 +99,26 @@ impl Document {
|
|||||||
self.apply_op_with(target, delta.kind, delta.timestamp, ApplyMode::Force)
|
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.
|
/// Apply a live broadcast op. Updates the registry via LWW and appends to the hot log.
|
||||||
pub(crate) fn stage_hot_op(&mut self, hot_op: HotOp, mode: ApplyMode) -> Result<(), CrdtError> {
|
/// Doesn't touch history or `head` — hot ops are transient.
|
||||||
self.apply_op_with(RegistryTarget::Working, hot_op.op.clone(), hot_op.timestamp, mode)?;
|
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
|
||||||
self.hot_timestamps.insert(hot_op.timestamp);
|
self.apply_op(hot_op.op.clone(), hot_op.timestamp)?;
|
||||||
self.hot_log.push(hot_op);
|
self.hot_log.push(hot_op);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Replay a persisted or received hot op. One already retired or held changes nothing.
|
/// Replay a hot op recovered from persisted state. Idempotent on structural ops so that
|
||||||
|
/// re-applying an op whose effect is already reflected in the registry is a no-op rather
|
||||||
|
/// than an error.
|
||||||
pub fn replay_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
|
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()) {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
if self.hot_timestamps.contains(&hot_op.timestamp) {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
self.apply_op_idempotent(hot_op.op.clone(), hot_op.timestamp)?;
|
self.apply_op_idempotent(hot_op.op.clone(), hot_op.timestamp)?;
|
||||||
self.hot_timestamps.insert(hot_op.timestamp);
|
|
||||||
self.hot_log.push(hot_op);
|
self.hot_log.push(hot_op);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Take on a peer's marks as well as this peer's. Returns whether a hot op was dropped.
|
/// Apply a retired commit. Idempotent on structural ops (AddNode/AddNetwork on existing
|
||||||
pub(crate) fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> bool {
|
/// targets, Remove on missing ones) since hot ops already produced the structural state.
|
||||||
self.retired.absorb(remote);
|
/// The point is to bump field timestamps to T_retire via the LWW arms.
|
||||||
self.drop_retired_hot_ops()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Bring the stamp index back in line after the hot log was filtered as a whole.
|
|
||||||
pub(crate) fn resync_hot_timestamps(&mut self) {
|
|
||||||
self.hot_timestamps = self.hot_log.iter().map(|hot_op| hot_op.timestamp).collect();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Re-derive working as the snapshot plus every hot op, for a change that cannot apply in place. O(registry), so rare.
|
|
||||||
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.
|
|
||||||
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 {
|
|
||||||
let before = self.hot_log.len();
|
|
||||||
let retired = &self.retired;
|
|
||||||
self.hot_log.retain(|hot_op| !retired.covers(hot_op.id()));
|
|
||||||
let dropped = self.hot_log.len() != before;
|
|
||||||
if dropped {
|
|
||||||
self.resync_hot_timestamps();
|
|
||||||
self.rebuild_working();
|
|
||||||
}
|
|
||||||
dropped
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Apply a retired commit and record it in history.
|
|
||||||
pub fn apply_delta(&mut self, delta: Delta) -> Result<(), CrdtError> {
|
pub fn apply_delta(&mut self, delta: Delta) -> Result<(), CrdtError> {
|
||||||
for parent in delta.all_parents() {
|
for parent in delta.all_parents() {
|
||||||
if !self.history.contains(parent) {
|
if !self.history.contains(parent) {
|
||||||
@@ -168,24 +134,26 @@ impl Document {
|
|||||||
fn registry_mut(&mut self, target: RegistryTarget) -> &mut Registry {
|
fn registry_mut(&mut self, target: RegistryTarget) -> &mut Registry {
|
||||||
match target {
|
match target {
|
||||||
RegistryTarget::Working => &mut self.working_registry,
|
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 {
|
fn registry_ref(&self, target: RegistryTarget) -> &Registry {
|
||||||
match target {
|
match target {
|
||||||
RegistryTarget::Working => &self.working_registry,
|
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`].
|
/// New local/remote op against the working registry: add ops error on duplicate targets and
|
||||||
#[cfg(test)]
|
/// `Change*` ops error on a missing target, while remove ops no-op when the target is already
|
||||||
|
/// absent; LWW arms keep the newer-timestamp value (strict `>`). The common entry point for edits.
|
||||||
pub(crate) fn apply_op(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
|
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.
|
/// Replay/retire against the working registry: structural ops skip duplicate/missing targets (the
|
||||||
|
/// state is already present from hot ops or a prior snapshot); LWW arms still gate on strict `>`.
|
||||||
pub(crate) fn apply_op_idempotent(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
|
pub(crate) fn apply_op_idempotent(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
|
||||||
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Idempotent)
|
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Idempotent)
|
||||||
}
|
}
|
||||||
@@ -197,180 +165,131 @@ impl Document {
|
|||||||
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Force)
|
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Force)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Applies one op. Every field, existence included, is last-writer-wins on a timestamp, so ops fold alike in any order:
|
|
||||||
/// an addition writes every field, a removal keeps the content as a tombstone, a newer write or reference revives an
|
|
||||||
/// older removal, and a write to an entity never seen lands on a placeholder until its addition arrives.
|
|
||||||
pub(crate) fn apply_op_with(&mut self, target: RegistryTarget, op: RegistryDelta, timestamp: TimeStamp, mode: ApplyMode) -> Result<(), CrdtError> {
|
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
|
// 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.
|
// error. Observation is about causality knowledge, not about whether the op took effect.
|
||||||
self.clock.observe(timestamp);
|
self.clock.observe(timestamp);
|
||||||
|
|
||||||
let strict = mode == ApplyMode::Strict;
|
// Structural ops skip (rather than error) on duplicate/missing targets when not a fresh edit;
|
||||||
|
// LWW arms assign unconditionally only under `Force`.
|
||||||
|
let idempotent = mode != ApplyMode::Live;
|
||||||
let force = mode == ApplyMode::Force;
|
let force = mode == ApplyMode::Force;
|
||||||
|
|
||||||
|
// Resurrect any concurrently-removed targets the op references before binding the registry
|
||||||
|
// (resurrection re-borrows `self` via history), so the mutation below holds one `registry` ref.
|
||||||
|
self.ensure_referenced_exist(target, &op)?;
|
||||||
|
|
||||||
let registry = self.registry_mut(target);
|
let registry = self.registry_mut(target);
|
||||||
match op {
|
match op {
|
||||||
RegistryDelta::AddNode { id, node } => {
|
RegistryDelta::AddNode { id, node } => {
|
||||||
if strict && registry.node_instances.contains_key(&id) {
|
if registry.node_instances.contains_key(&id) {
|
||||||
|
if idempotent {
|
||||||
|
// Hot ops already created this node; skip rather than error.
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
return Err(CrdtError::NodeAlreadyExists(id));
|
return Err(CrdtError::NodeAlreadyExists(id));
|
||||||
}
|
}
|
||||||
write_network(registry, node.network, timestamp, mode, |_| Ok(()))?;
|
registry.node_instances.insert(id, node);
|
||||||
add_entity(&mut registry.node_instances, &mut registry.removed_nodes, id, node, timestamp, force);
|
|
||||||
}
|
}
|
||||||
RegistryDelta::RemoveNode { id, snapshot } => {
|
RegistryDelta::RemoveNode { id, .. } => {
|
||||||
remove_entity(&mut registry.node_instances, &mut registry.removed_nodes, id, snapshot, timestamp, force);
|
registry.node_instances.remove(&id);
|
||||||
}
|
}
|
||||||
RegistryDelta::SetNodeInputs { id, mut inputs } => {
|
RegistryDelta::SetNodeInputs { id, inputs } => {
|
||||||
inputs.iter_mut().for_each(|slot| stamp_listed_slot(slot, timestamp));
|
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||||
let referenced: Vec<NodeId> = inputs
|
node.inputs = inputs;
|
||||||
.iter()
|
|
||||||
.filter_map(|slot| match slot.input {
|
|
||||||
NodeInput::Node { id, .. } => Some(id),
|
|
||||||
_ => None,
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
ensure_seen(registry, &referenced, mode)?;
|
|
||||||
write_node(registry, id, timestamp, mode, |node| {
|
|
||||||
if force {
|
|
||||||
node.inputs = inputs;
|
|
||||||
node.inputs_timestamp = timestamp;
|
|
||||||
} else {
|
|
||||||
merge_inputs(node, inputs, timestamp);
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
})?;
|
|
||||||
for referenced in referenced {
|
|
||||||
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
|
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
|
||||||
let referenced = match new_input {
|
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||||
NodeInput::Node { id, .. } => Some(id),
|
let input = node.inputs.get_mut(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
|
||||||
_ => None,
|
if force || timestamp > input.timestamp {
|
||||||
};
|
input.input = new_input;
|
||||||
ensure_seen(registry, referenced.as_slice(), mode)?;
|
input.timestamp = timestamp;
|
||||||
write_node(registry, id, timestamp, mode, |node| {
|
|
||||||
let Some(input) = slot_for_write(node, index as usize, timestamp, mode)? else { return Ok(()) };
|
|
||||||
if force || timestamp > input.timestamp {
|
|
||||||
input.input = new_input;
|
|
||||||
input.timestamp = timestamp;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
})?;
|
|
||||||
if let Some(referenced) = referenced {
|
|
||||||
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
RegistryDelta::SetNodeImplementation { id, implementation } => {
|
|
||||||
ensure_seen(registry, &[id], mode)?;
|
|
||||||
if let Implementation::Network(network) = implementation {
|
|
||||||
write_network(registry, network, timestamp, mode, |_| Ok(()))?;
|
|
||||||
}
|
|
||||||
write_node(registry, id, timestamp, mode, |node| {
|
|
||||||
if force || timestamp > node.implementation_timestamp {
|
|
||||||
node.implementation = implementation;
|
|
||||||
node.implementation_timestamp = timestamp;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
})?;
|
|
||||||
}
|
|
||||||
RegistryDelta::ChangeNodeAttribute { id, delta } => {
|
RegistryDelta::ChangeNodeAttribute { id, delta } => {
|
||||||
write_node(registry, id, timestamp, mode, |node| {
|
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||||
node.attributes.apply_delta(delta, timestamp, force);
|
apply_attribute_delta(delta, timestamp, force, &mut node.attributes);
|
||||||
Ok(())
|
|
||||||
})?;
|
|
||||||
}
|
}
|
||||||
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => {
|
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => {
|
||||||
write_node(registry, id, timestamp, mode, |node| {
|
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||||
let Some(input) = slot_for_write(node, index as usize, timestamp, mode)? else { return Ok(()) };
|
let input = node.inputs.get_mut(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
|
||||||
input.attributes.apply_delta(delta, timestamp, force);
|
apply_attribute_delta(delta, timestamp, force, &mut input.attributes);
|
||||||
Ok(())
|
|
||||||
})?;
|
|
||||||
}
|
}
|
||||||
RegistryDelta::SetNetworkExport { id, index, export } => {
|
RegistryDelta::SetNetworkExport { id, index, export } => {
|
||||||
let referenced = match export {
|
let net = registry.networks.get_mut(&id).ok_or(CrdtError::NetworkDoesNotExist(id))?;
|
||||||
Some(NodeInput::Node { id, .. }) => Some(id),
|
let slot_idx = index as usize;
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
ensure_seen(registry, referenced.as_slice(), mode)?;
|
|
||||||
write_network(registry, id, timestamp, mode, |net| {
|
|
||||||
let slot_idx = index as usize;
|
|
||||||
if slot_idx >= net.exports.len() {
|
|
||||||
if slot_idx >= MAX_EXPORT_SLOTS {
|
|
||||||
return Err(CrdtError::ExportSlotOutOfBounds(index));
|
|
||||||
}
|
|
||||||
// Past the end of a newer list the slot is gone, as with input slots.
|
|
||||||
if !force && timestamp <= net.exports_timestamp {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
let shape = net.exports_timestamp;
|
|
||||||
net.exports.resize_with(slot_idx + 1, || ExportSlot { target: None, timestamp: shape });
|
|
||||||
}
|
|
||||||
|
|
||||||
let existing = &mut net.exports[slot_idx];
|
if slot_idx >= net.exports.len() {
|
||||||
if force || timestamp > existing.timestamp {
|
if slot_idx >= MAX_EXPORT_SLOTS {
|
||||||
existing.target = export;
|
return Err(CrdtError::ExportSlotOutOfBounds(index));
|
||||||
existing.timestamp = timestamp;
|
|
||||||
}
|
}
|
||||||
Ok(())
|
net.exports.resize(
|
||||||
})?;
|
slot_idx + 1,
|
||||||
if let Some(referenced) = referenced {
|
ExportSlot {
|
||||||
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
|
target: None,
|
||||||
|
timestamp: TimeStamp::ORIGIN,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let existing = &mut net.exports[slot_idx];
|
||||||
|
if force || timestamp > existing.timestamp {
|
||||||
|
existing.target = export;
|
||||||
|
existing.timestamp = timestamp;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
RegistryDelta::AddNetwork { id, network } => {
|
RegistryDelta::AddNetwork { id, network: contents } => {
|
||||||
if strict && registry.networks.contains_key(&id) {
|
if registry.networks.contains_key(&id) {
|
||||||
|
if idempotent {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
return Err(CrdtError::NetworkAlreadyExists(id));
|
return Err(CrdtError::NetworkAlreadyExists(id));
|
||||||
}
|
}
|
||||||
add_entity(&mut registry.networks, &mut registry.removed_networks, id, network, timestamp, force);
|
registry.networks.insert(id, contents);
|
||||||
}
|
}
|
||||||
RegistryDelta::RemoveNetwork { id, snapshot } => {
|
RegistryDelta::RemoveNetwork { id, .. } => {
|
||||||
remove_entity(&mut registry.networks, &mut registry.removed_networks, id, snapshot, timestamp, force);
|
registry.networks.remove(&id);
|
||||||
}
|
}
|
||||||
RegistryDelta::ChangeNetworkAttribute { id, delta } => {
|
RegistryDelta::ChangeNetworkAttribute { id, delta } => {
|
||||||
write_network(registry, id, timestamp, mode, |net| {
|
let net = registry.networks.get_mut(&id).ok_or(CrdtError::NetworkDoesNotExist(id))?;
|
||||||
net.attributes.apply_delta(delta, timestamp, force);
|
apply_attribute_delta(delta, timestamp, force, &mut net.attributes);
|
||||||
Ok(())
|
|
||||||
})?;
|
|
||||||
}
|
}
|
||||||
RegistryDelta::SetResourceHash { id, hash } => {
|
RegistryDelta::SetResourceHash { id, hash } => {
|
||||||
upsert_resource(registry, id, timestamp, |entry| {
|
let entry = registry.resources.entry(id).or_default();
|
||||||
if force || timestamp > entry.hash_timestamp {
|
if force || timestamp > entry.hash_timestamp {
|
||||||
entry.hash = hash;
|
entry.hash = hash;
|
||||||
entry.hash_timestamp = timestamp;
|
entry.hash_timestamp = timestamp;
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
RegistryDelta::AddSource { id, key, source } => {
|
RegistryDelta::AddSource { id, key, source } => {
|
||||||
upsert_resource(registry, id, timestamp, |entry| {
|
let entry = registry.resources.entry(id).or_default();
|
||||||
let value = SourceValue { source, timestamp, deleted: false };
|
let value = SourceValue { source, timestamp };
|
||||||
if force { entry.force_set_source(key, value) } else { entry.set_source(key, value) }
|
if force { entry.force_set_source(key, value) } else { entry.set_source(key, value) }
|
||||||
});
|
|
||||||
}
|
}
|
||||||
RegistryDelta::RemoveSource { id, key } => {
|
RegistryDelta::RemoveSource { id, key } => {
|
||||||
// An upsert, so a removal for an entry never seen leaves a tombstone its addition loses to.
|
if let Some(entry) = registry.resources.get_mut(&id) {
|
||||||
upsert_resource(registry, id, timestamp, |entry| {
|
|
||||||
if force {
|
if force {
|
||||||
entry.force_remove_source(&key);
|
entry.force_remove_source(&key);
|
||||||
} else {
|
} 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);
|
|
||||||
}
|
|
||||||
RegistryDelta::RemoveResource { id, snapshot } => {
|
|
||||||
remove_entity(&mut registry.resources, &mut registry.removed_resources, id, snapshot, timestamp, force);
|
|
||||||
}
|
|
||||||
RegistryDelta::RegisterPeer { peer, user } => {
|
|
||||||
// The newest registration of a device wins, whatever order they land in.
|
|
||||||
if registry.peer_users.get(&peer).is_none_or(|existing| timestamp > existing.timestamp) {
|
|
||||||
registry.peer_users.insert(peer, PeerRegistration { user, timestamp });
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
RegistryDelta::AddResource { id, entry } => {
|
||||||
|
registry.resources.insert(id, entry);
|
||||||
|
}
|
||||||
|
RegistryDelta::RemoveResource { id, .. } => {
|
||||||
|
registry.resources.remove(&id);
|
||||||
|
}
|
||||||
|
RegistryDelta::RegisterPeer { peer, user } => match registry.peer_users.get(&peer) {
|
||||||
|
Some(existing) if *existing != user => return Err(CrdtError::PeerRegistrationConflict(peer)),
|
||||||
|
Some(_) => {}
|
||||||
|
None => {
|
||||||
|
registry.peer_users.insert(peer, user);
|
||||||
|
}
|
||||||
|
},
|
||||||
RegistryDelta::ChangeDocumentAttribute { delta } => {
|
RegistryDelta::ChangeDocumentAttribute { delta } => {
|
||||||
registry.attributes.apply_delta(delta, timestamp, force);
|
apply_attribute_delta(delta, timestamp, force, &mut registry.attributes);
|
||||||
}
|
}
|
||||||
// Merge is a structural sync point only; it mutates no registry state.
|
// Merge is a structural sync point only; it mutates no registry state.
|
||||||
RegistryDelta::Merge { .. } | RegistryDelta::Other(_) => {}
|
RegistryDelta::Merge { .. } | RegistryDelta::Other(_) => {}
|
||||||
@@ -378,42 +297,86 @@ impl Document {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Resurrect (from history) any nodes/networks an op references that were concurrently removed, so
|
||||||
|
/// the op applies against a consistent registry. Cascading: a node's owning network is restored
|
||||||
|
/// before the node. No-op for ops that reference nothing absent.
|
||||||
|
fn ensure_referenced_exist(&mut self, target: RegistryTarget, op: &RegistryDelta) -> Result<(), CrdtError> {
|
||||||
|
match op {
|
||||||
|
RegistryDelta::AddNode { node, .. } => self.ensure_network_exists(target, node.network())?,
|
||||||
|
RegistryDelta::ChangeNodeInput { id, new_input, .. } => {
|
||||||
|
if let NodeInput::Node { id: referenced, .. } = new_input {
|
||||||
|
self.ensure_node_exists(target, *referenced)?;
|
||||||
|
}
|
||||||
|
self.ensure_node_exists(target, *id)?;
|
||||||
|
}
|
||||||
|
RegistryDelta::SetNodeInputs { id, inputs } => {
|
||||||
|
for slot in inputs {
|
||||||
|
if let NodeInput::Node { id: referenced, .. } = slot.input {
|
||||||
|
self.ensure_node_exists(target, referenced)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.ensure_node_exists(target, *id)?;
|
||||||
|
}
|
||||||
|
RegistryDelta::ChangeNodeAttribute { id, .. } | RegistryDelta::ChangeNodeInputAttribute { id, .. } => self.ensure_node_exists(target, *id)?,
|
||||||
|
RegistryDelta::SetNetworkExport {
|
||||||
|
id: network, export: export_target, ..
|
||||||
|
} => {
|
||||||
|
if let Some(NodeInput::Node { id: referenced, .. }) = export_target {
|
||||||
|
self.ensure_node_exists(target, *referenced)?;
|
||||||
|
}
|
||||||
|
self.ensure_network_exists(target, *network)?;
|
||||||
|
}
|
||||||
|
RegistryDelta::ChangeNetworkAttribute { id: network, .. } => self.ensure_network_exists(target, *network)?,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ensure_node_exists(&mut self, target: RegistryTarget, node_id: NodeId) -> Result<(), CrdtError> {
|
||||||
|
if !self.registry_ref(target).node_instances.contains_key(&node_id) {
|
||||||
|
self.restore_node_from_history(target, node_id)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ensure_network_exists(&mut self, target: RegistryTarget, network_id: NetworkId) -> Result<(), CrdtError> {
|
||||||
|
if !self.registry_ref(target).networks.contains_key(&network_id) {
|
||||||
|
self.restore_network_from_history(target, network_id)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Compute the inverse of `delta` against the registry named by `target`. Retirement passes
|
/// Compute the inverse of `delta` against the registry named by `target`. Retirement passes
|
||||||
/// [`RegistryTarget::Retired`] so LWW reverses (export target, inputs, attributes, resource hash)
|
/// [`RegistryTarget::Snapshot`] so LWW reverses (export target, inputs, attributes, resource hash)
|
||||||
/// capture the true pre-op value rather than the hot-polluted working state.
|
/// 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> {
|
pub(crate) fn compute_reverse_delta(&self, target: RegistryTarget, delta: &RegistryDelta) -> Result<RegistryDelta, CrdtError> {
|
||||||
let registry = self.registry_ref(target);
|
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 {
|
Ok(match delta {
|
||||||
RegistryDelta::AddNode { id, node } => RegistryDelta::RemoveNode { id: *id, snapshot: node.clone() },
|
RegistryDelta::AddNode { id, node } => RegistryDelta::RemoveNode { id: *id, snapshot: node.clone() },
|
||||||
RegistryDelta::RemoveNode { id, snapshot } => RegistryDelta::AddNode { id: *id, node: snapshot.clone() },
|
RegistryDelta::RemoveNode { id, snapshot } => RegistryDelta::AddNode { id: *id, node: snapshot.clone() },
|
||||||
&RegistryDelta::SetNodeInputs { id, .. } => RegistryDelta::SetNodeInputs { id, inputs: node(id).inputs.clone() },
|
&RegistryDelta::SetNodeInputs { id, .. } => {
|
||||||
&RegistryDelta::SetNodeImplementation { id, .. } => RegistryDelta::SetNodeImplementation {
|
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||||
id,
|
RegistryDelta::SetNodeInputs { id, inputs: node.inputs.clone() }
|
||||||
implementation: node(id).implementation.clone(),
|
}
|
||||||
},
|
|
||||||
&RegistryDelta::ChangeNodeInput { id, index: input_idx, .. } => {
|
&RegistryDelta::ChangeNodeInput { id, index: input_idx, .. } => {
|
||||||
let node = node(id);
|
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||||
let slot = node.inputs().get(input_idx as usize).unwrap_or(&unset);
|
let slot = node.inputs().get(input_idx as usize).ok_or(CrdtError::InputIndexOutOfBounds(input_idx as usize))?;
|
||||||
RegistryDelta::ChangeNodeInput {
|
RegistryDelta::ChangeNodeInput {
|
||||||
id,
|
id,
|
||||||
index: input_idx,
|
index: input_idx,
|
||||||
new_input: slot.input.clone(),
|
new_input: slot.input.clone(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
&RegistryDelta::ChangeNodeAttribute { id, ref delta } => RegistryDelta::ChangeNodeAttribute {
|
&RegistryDelta::ChangeNodeAttribute { id, ref delta } => {
|
||||||
id,
|
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||||
delta: reverse_attribute_delta(delta, node(id).attributes()),
|
RegistryDelta::ChangeNodeAttribute {
|
||||||
},
|
id,
|
||||||
|
delta: reverse_attribute_delta(delta, node.attributes()),
|
||||||
|
}
|
||||||
|
}
|
||||||
&RegistryDelta::ChangeNodeInputAttribute { id, index, ref delta } => {
|
&RegistryDelta::ChangeNodeInputAttribute { id, index, ref delta } => {
|
||||||
let node = node(id);
|
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||||
let input = node.inputs().get(index as usize).unwrap_or(&unset);
|
let input = node.inputs().get(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
|
||||||
RegistryDelta::ChangeNodeInputAttribute {
|
RegistryDelta::ChangeNodeInputAttribute {
|
||||||
id,
|
id,
|
||||||
index,
|
index,
|
||||||
@@ -421,15 +384,15 @@ impl Document {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
&RegistryDelta::SetNetworkExport { id, index, .. } => {
|
&RegistryDelta::SetNetworkExport { id, index, .. } => {
|
||||||
// Absent network or slot: pre-op there was no export to point at.
|
// If the network is absent the forward op will resurrect it; the reverse is "set the export to None"
|
||||||
let export_target = network(id).and_then(|net| net.exports.get(index as usize)).and_then(|s| s.target.clone());
|
// since pre-forward there was no export to point at.
|
||||||
|
let export_target = registry.networks.get(&id).and_then(|net| net.exports.get(index as usize)).and_then(|s| s.target.clone());
|
||||||
RegistryDelta::SetNetworkExport { id, index, export: export_target }
|
RegistryDelta::SetNetworkExport { id, index, export: export_target }
|
||||||
}
|
}
|
||||||
RegistryDelta::AddNetwork { id, network } => RegistryDelta::RemoveNetwork { id: *id, snapshot: network.clone() },
|
RegistryDelta::AddNetwork { id, network } => RegistryDelta::RemoveNetwork { id: *id, snapshot: network.clone() },
|
||||||
&RegistryDelta::RemoveNetwork { id, ref snapshot } => RegistryDelta::AddNetwork { id, network: snapshot.clone() },
|
&RegistryDelta::RemoveNetwork { id, ref snapshot } => RegistryDelta::AddNetwork { id, network: snapshot.clone() },
|
||||||
&RegistryDelta::ChangeNetworkAttribute { id, ref delta } => {
|
&RegistryDelta::ChangeNetworkAttribute { id, ref delta } => {
|
||||||
let empty = Attributes::new();
|
let current = registry.networks.get(&id).map(|net| &net.attributes).ok_or(CrdtError::NetworkDoesNotExist(id))?;
|
||||||
let current = network(id).map_or(&empty, |net| &net.attributes);
|
|
||||||
RegistryDelta::ChangeNetworkAttribute {
|
RegistryDelta::ChangeNetworkAttribute {
|
||||||
id,
|
id,
|
||||||
delta: reverse_attribute_delta(delta, current),
|
delta: reverse_attribute_delta(delta, current),
|
||||||
@@ -443,9 +406,9 @@ impl Document {
|
|||||||
&RegistryDelta::RegisterPeer { peer, user } => RegistryDelta::RegisterPeer { peer, user },
|
&RegistryDelta::RegisterPeer { peer, user } => RegistryDelta::RegisterPeer { peer, user },
|
||||||
&RegistryDelta::SetResourceHash { id, .. } => RegistryDelta::SetResourceHash {
|
&RegistryDelta::SetResourceHash { id, .. } => RegistryDelta::SetResourceHash {
|
||||||
id,
|
id,
|
||||||
hash: resource(id).and_then(|entry| entry.hash),
|
hash: registry.resources.get(&id).and_then(|entry| entry.hash),
|
||||||
},
|
},
|
||||||
&RegistryDelta::AddSource { id, key, .. } => match resource(id).and_then(|entry| entry.source(&key)) {
|
&RegistryDelta::AddSource { id, key, .. } => match registry.resources.get(&id).and_then(|entry| entry.source(&key)) {
|
||||||
// The slot already held a source: undo restores it.
|
// The slot already held a source: undo restores it.
|
||||||
Some(existing) => RegistryDelta::AddSource {
|
Some(existing) => RegistryDelta::AddSource {
|
||||||
id,
|
id,
|
||||||
@@ -455,7 +418,7 @@ impl Document {
|
|||||||
// The slot was empty: undo removes what this op added.
|
// The slot was empty: undo removes what this op added.
|
||||||
None => RegistryDelta::RemoveSource { id, key },
|
None => RegistryDelta::RemoveSource { id, key },
|
||||||
},
|
},
|
||||||
&RegistryDelta::RemoveSource { id, key } => match resource(id).and_then(|entry| entry.source(&key)) {
|
&RegistryDelta::RemoveSource { id, key } => match registry.resources.get(&id).and_then(|entry| entry.source(&key)) {
|
||||||
Some(existing) => RegistryDelta::AddSource {
|
Some(existing) => RegistryDelta::AddSource {
|
||||||
id,
|
id,
|
||||||
key,
|
key,
|
||||||
@@ -478,346 +441,27 @@ impl Document {
|
|||||||
RegistryDelta::AddResource { id, entry: snapshot }
|
RegistryDelta::AddResource { id, entry: snapshot }
|
||||||
}
|
}
|
||||||
RegistryDelta::Merge { extra_parents } => RegistryDelta::Merge { extra_parents: extra_parents.clone() },
|
RegistryDelta::Merge { extra_parents } => RegistryDelta::Merge { extra_parents: extra_parents.clone() },
|
||||||
&RegistryDelta::Other(_) => RegistryDelta::Other(Value::None),
|
&RegistryDelta::Other(_) => RegistryDelta::Other(serde_json::Value::Null),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An entity whose existence and every field are last-writer-wins on a timestamp.
|
|
||||||
pub(crate) trait Entity: Sized {
|
|
||||||
/// The newest stamp of an addition or a write: the latest evidence the entity exists.
|
|
||||||
fn presence(&self) -> TimeStamp;
|
|
||||||
fn set_presence(&mut self, timestamp: TimeStamp);
|
|
||||||
/// Stamps every field at `timestamp`, the way an addition writes all of them.
|
|
||||||
fn stamp_all(&mut self, timestamp: TimeStamp);
|
|
||||||
/// Folds `other` in, keeping whichever value of each field is newer.
|
|
||||||
fn merge(&mut self, other: Self);
|
|
||||||
/// Content for writes to land on before the addition, every field at the origin so the addition's win.
|
|
||||||
fn placeholder() -> Self;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Entity for Node {
|
|
||||||
fn presence(&self) -> TimeStamp {
|
|
||||||
self.presence
|
|
||||||
}
|
|
||||||
fn set_presence(&mut self, timestamp: TimeStamp) {
|
|
||||||
self.presence = timestamp;
|
|
||||||
}
|
|
||||||
fn placeholder() -> Self {
|
|
||||||
Node::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(0)), 0)
|
|
||||||
}
|
|
||||||
fn stamp_all(&mut self, timestamp: TimeStamp) {
|
|
||||||
self.presence = timestamp;
|
|
||||||
self.network_timestamp = timestamp;
|
|
||||||
self.inputs_timestamp = timestamp;
|
|
||||||
self.implementation_timestamp = timestamp;
|
|
||||||
self.inputs.iter_mut().for_each(|slot| stamp_slot(slot, timestamp));
|
|
||||||
self.attributes.stamp(timestamp);
|
|
||||||
}
|
|
||||||
fn merge(&mut self, other: Self) {
|
|
||||||
if other.network_timestamp > self.network_timestamp {
|
|
||||||
self.network = other.network;
|
|
||||||
self.network_timestamp = other.network_timestamp;
|
|
||||||
}
|
|
||||||
if other.implementation_timestamp > self.implementation_timestamp {
|
|
||||||
self.implementation = other.implementation;
|
|
||||||
self.implementation_timestamp = other.implementation_timestamp;
|
|
||||||
}
|
|
||||||
merge_inputs(self, other.inputs, other.inputs_timestamp);
|
|
||||||
self.attributes.merge(other.attributes);
|
|
||||||
self.presence = self.presence.max(other.presence);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Entity for Network {
|
|
||||||
fn presence(&self) -> TimeStamp {
|
|
||||||
self.presence
|
|
||||||
}
|
|
||||||
fn set_presence(&mut self, timestamp: TimeStamp) {
|
|
||||||
self.presence = timestamp;
|
|
||||||
}
|
|
||||||
fn placeholder() -> Self {
|
|
||||||
Network::default()
|
|
||||||
}
|
|
||||||
fn stamp_all(&mut self, timestamp: TimeStamp) {
|
|
||||||
self.presence = timestamp;
|
|
||||||
self.exports_timestamp = timestamp;
|
|
||||||
self.exports.iter_mut().for_each(|slot| slot.timestamp = timestamp);
|
|
||||||
self.attributes.stamp(timestamp);
|
|
||||||
}
|
|
||||||
fn merge(&mut self, other: Self) {
|
|
||||||
// As `merge_inputs`: the newer list decides the slot count, and a slot written after that shape survives past it.
|
|
||||||
let (mut newer, shape, older) = if other.exports_timestamp > self.exports_timestamp {
|
|
||||||
(other.exports, other.exports_timestamp, std::mem::take(&mut self.exports))
|
|
||||||
} else {
|
|
||||||
(std::mem::take(&mut self.exports), self.exports_timestamp, other.exports)
|
|
||||||
};
|
|
||||||
for (index, incoming) in older.into_iter().enumerate() {
|
|
||||||
if index >= newer.len() {
|
|
||||||
if incoming.timestamp <= shape {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
newer.resize_with(index + 1, || ExportSlot { target: None, timestamp: shape });
|
|
||||||
}
|
|
||||||
if incoming.timestamp > newer[index].timestamp {
|
|
||||||
newer[index] = incoming;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
self.exports = newer;
|
|
||||||
self.exports_timestamp = shape;
|
|
||||||
self.attributes.merge(other.attributes);
|
|
||||||
self.presence = self.presence.max(other.presence);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Entity for ResourceEntry {
|
|
||||||
fn presence(&self) -> TimeStamp {
|
|
||||||
self.presence
|
|
||||||
}
|
|
||||||
fn set_presence(&mut self, timestamp: TimeStamp) {
|
|
||||||
self.presence = timestamp;
|
|
||||||
}
|
|
||||||
fn placeholder() -> Self {
|
|
||||||
ResourceEntry::default()
|
|
||||||
}
|
|
||||||
fn stamp_all(&mut self, timestamp: TimeStamp) {
|
|
||||||
self.presence = timestamp;
|
|
||||||
self.hash_timestamp = timestamp;
|
|
||||||
self.stamp_sources(timestamp);
|
|
||||||
}
|
|
||||||
fn merge(&mut self, other: Self) {
|
|
||||||
if other.hash_timestamp > self.hash_timestamp {
|
|
||||||
self.hash = other.hash;
|
|
||||||
self.hash_timestamp = other.hash_timestamp;
|
|
||||||
}
|
|
||||||
self.merge_sources(other.sources, other.sources_timestamp);
|
|
||||||
self.presence = self.presence.max(other.presence);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn stamp_slot(slot: &mut InputSlot, timestamp: TimeStamp) {
|
|
||||||
slot.timestamp = timestamp;
|
|
||||||
slot.attributes.stamp(timestamp);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Stamps a slot of a written input list. Attributes carried over with their own stamps keep them, and a floor carried
|
|
||||||
/// with them, so they only win where they already did; what arrives unstamped is written at `timestamp`.
|
|
||||||
fn stamp_listed_slot(slot: &mut InputSlot, timestamp: TimeStamp) {
|
|
||||||
slot.timestamp = timestamp;
|
|
||||||
slot.attributes.stamp_unstamped(timestamp);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Folds an input list stamped `timestamp` into the node's: the newer list decides the slot count, a slot written after that
|
|
||||||
/// shape survives past it, and a slot both hold keeps its newer value, so list and slot writes land alike in any order.
|
|
||||||
fn merge_inputs(node: &mut Node, other: Vec<InputSlot>, timestamp: TimeStamp) {
|
|
||||||
let (mut newer, shape, older) = if timestamp > node.inputs_timestamp {
|
|
||||||
(other, timestamp, std::mem::take(&mut node.inputs))
|
|
||||||
} else {
|
|
||||||
(std::mem::take(&mut node.inputs), node.inputs_timestamp, other)
|
|
||||||
};
|
|
||||||
// A slot the older list lacks was absent as of that list's shape, as a write past its end would find it.
|
|
||||||
let older_shape = if shape == timestamp { node.inputs_timestamp } else { timestamp };
|
|
||||||
for slot in newer.iter_mut().skip(older.len()) {
|
|
||||||
slot.attributes.merge(Attributes::empty_at(older_shape));
|
|
||||||
}
|
|
||||||
for (index, incoming) in older.into_iter().enumerate() {
|
|
||||||
if index >= newer.len() {
|
|
||||||
if slot_newest(&incoming) <= shape {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
newer.resize_with(index + 1, || InputSlot::unset(shape));
|
|
||||||
}
|
|
||||||
let slot = &mut newer[index];
|
|
||||||
if incoming.timestamp > slot.timestamp {
|
|
||||||
slot.input = incoming.input;
|
|
||||||
slot.timestamp = incoming.timestamp;
|
|
||||||
}
|
|
||||||
slot.attributes.merge(incoming.attributes);
|
|
||||||
}
|
|
||||||
node.inputs = newer;
|
|
||||||
node.inputs_timestamp = shape;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The newest write the slot carries, its attributes included.
|
|
||||||
fn slot_newest(slot: &InputSlot) -> TimeStamp {
|
|
||||||
slot.timestamp.max(slot.attributes.newest())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The slot at `index` for a write at `timestamp`; past the end it exists only if the write is newer than the list's shape.
|
|
||||||
fn slot_for_write(node: &mut Node, index: usize, timestamp: TimeStamp, mode: ApplyMode) -> Result<Option<&mut InputSlot>, CrdtError> {
|
|
||||||
if index >= node.inputs.len() {
|
|
||||||
if index >= MAX_INPUT_SLOTS || mode == ApplyMode::Strict {
|
|
||||||
return Err(CrdtError::InputIndexOutOfBounds(index));
|
|
||||||
}
|
|
||||||
if mode != ApplyMode::Force && timestamp <= node.inputs_timestamp {
|
|
||||||
return Ok(None);
|
|
||||||
}
|
|
||||||
let shape = node.inputs_timestamp;
|
|
||||||
node.inputs.resize_with(index + 1, || InputSlot::unset(shape));
|
|
||||||
}
|
|
||||||
Ok(node.inputs.get_mut(index))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The entity's content wherever it sits: live, or held by its tombstone.
|
|
||||||
fn content_mut<'a, K: Hash + Eq + Copy, T>(live: &'a mut HashMap<K, T>, dead: &'a mut HashMap<K, Tombstone<T>>, id: K) -> Option<&'a mut T> {
|
|
||||||
live.get_mut(&id).or_else(|| dead.get_mut(&id).map(|mark| &mut mark.content))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Revives a removed entity whose presence has grown past its removal. A placeholder stays dead.
|
|
||||||
fn revive_if_newer<K: Hash + Eq + Copy, T: Entity>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K) {
|
|
||||||
if dead.get(&id).is_some_and(|mark| !mark.placeholder && mark.content.presence() > mark.timestamp) {
|
|
||||||
let mark = dead.remove(&id).expect("checked above");
|
|
||||||
live.insert(id, mark.content);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Folds an addition's or removal's content into what is held under `id`. It proves the entity was added, so a placeholder
|
|
||||||
/// holding it stops being one.
|
|
||||||
fn merge_entity<K: Hash + Eq + Copy, T: Entity>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, content: T) {
|
|
||||||
if let Some(mark) = dead.get_mut(&id).filter(|mark| mark.placeholder) {
|
|
||||||
// The placeholder holds only early writes: they land on the real content as if the addition came first.
|
|
||||||
let early = std::mem::replace(&mut mark.content, content);
|
|
||||||
mark.content.merge(early);
|
|
||||||
mark.placeholder = false;
|
|
||||||
} else if let Some(existing) = content_mut(live, dead, id) {
|
|
||||||
existing.merge(content);
|
|
||||||
} else {
|
|
||||||
live.insert(id, content);
|
|
||||||
}
|
|
||||||
revive_if_newer(live, dead, id);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An addition at `timestamp`: every field written at `timestamp`, live unless a newer removal holds it dead.
|
|
||||||
fn add_entity<K: Hash + Eq + Copy, T: Entity>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, mut content: T, timestamp: TimeStamp, force: bool) {
|
|
||||||
if force {
|
|
||||||
dead.remove(&id);
|
|
||||||
live.insert(id, content);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
content.stamp_all(timestamp);
|
|
||||||
merge_entity(live, dead, id, content);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A removal at `timestamp`: dead unless a newer addition or write holds it live. The snapshot folds in first, so a removal of an
|
|
||||||
/// entity never seen still lands.
|
|
||||||
fn remove_entity<K: Hash + Eq + Copy, T: Entity>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, snapshot: T, timestamp: TimeStamp, force: bool) {
|
|
||||||
merge_entity(live, dead, id, snapshot);
|
|
||||||
if let Some(mark) = dead.get_mut(&id) {
|
|
||||||
mark.timestamp = if force { timestamp } else { mark.timestamp.max(timestamp) };
|
|
||||||
} else if live.get(&id).is_some_and(|content| force || timestamp > content.presence()) {
|
|
||||||
let content = live.remove(&id).expect("checked above");
|
|
||||||
dead.insert(
|
|
||||||
id,
|
|
||||||
Tombstone {
|
|
||||||
content,
|
|
||||||
timestamp,
|
|
||||||
placeholder: false,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A write at `timestamp` to the entity under `id`, wherever its content sits: it revives an older removal, and lands on a
|
|
||||||
/// placeholder for an entity never seen. A fresh local edit on one gets `missing()` instead.
|
|
||||||
fn write_entity<K: Hash + Eq + Copy, T: Entity>(
|
|
||||||
live: &mut HashMap<K, T>,
|
|
||||||
dead: &mut HashMap<K, Tombstone<T>>,
|
|
||||||
id: K,
|
|
||||||
timestamp: TimeStamp,
|
|
||||||
mode: ApplyMode,
|
|
||||||
missing: impl FnOnce() -> CrdtError,
|
|
||||||
f: impl FnOnce(&mut T) -> Result<(), CrdtError>,
|
|
||||||
) -> Result<(), CrdtError> {
|
|
||||||
let force = mode == ApplyMode::Force;
|
|
||||||
let unseen = !live.contains_key(&id) && !dead.contains_key(&id);
|
|
||||||
if unseen {
|
|
||||||
if mode == ApplyMode::Strict {
|
|
||||||
return Err(missing());
|
|
||||||
}
|
|
||||||
dead.insert(
|
|
||||||
id,
|
|
||||||
Tombstone {
|
|
||||||
content: T::placeholder(),
|
|
||||||
timestamp: TimeStamp::ORIGIN,
|
|
||||||
placeholder: true,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let content = content_mut(live, dead, id).expect("held above");
|
|
||||||
if let Err(error) = f(content) {
|
|
||||||
// A rejected op changes nothing, so the placeholder made for it goes too.
|
|
||||||
if unseen {
|
|
||||||
dead.remove(&id);
|
|
||||||
}
|
|
||||||
return Err(error);
|
|
||||||
}
|
|
||||||
content.set_presence(content.presence().max(timestamp));
|
|
||||||
if force && let Some(mark) = dead.remove(&id) {
|
|
||||||
live.insert(id, mark.content);
|
|
||||||
}
|
|
||||||
revive_if_newer(live, dead, id);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A fresh local edit cannot name a node never seen. Checked before an op's first write, so a refused op changes nothing.
|
|
||||||
fn ensure_seen(registry: &Registry, ids: &[NodeId], mode: ApplyMode) -> Result<(), CrdtError> {
|
|
||||||
let unseen = |id: &&NodeId| !registry.node_instances.contains_key(id) && !registry.removed_nodes.contains_key(id);
|
|
||||||
match ids.iter().find(unseen) {
|
|
||||||
Some(&id) if mode == ApplyMode::Strict => Err(CrdtError::TargetNodeDoesNotExist(id)),
|
|
||||||
_ => Ok(()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// [`write_entity()`] to a node; with a no-op `f`, records a reference to it.
|
|
||||||
fn write_node(registry: &mut Registry, id: NodeId, timestamp: TimeStamp, mode: ApplyMode, f: impl FnOnce(&mut Node) -> Result<(), CrdtError>) -> Result<(), CrdtError> {
|
|
||||||
write_entity(
|
|
||||||
&mut registry.node_instances,
|
|
||||||
&mut registry.removed_nodes,
|
|
||||||
id,
|
|
||||||
timestamp,
|
|
||||||
mode,
|
|
||||||
|| CrdtError::TargetNodeDoesNotExist(id),
|
|
||||||
f,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn write_network(registry: &mut Registry, id: NetworkId, timestamp: TimeStamp, mode: ApplyMode, f: impl FnOnce(&mut Network) -> Result<(), CrdtError>) -> Result<(), CrdtError> {
|
|
||||||
write_entity(&mut registry.networks, &mut registry.removed_networks, id, timestamp, mode, || CrdtError::NetworkDoesNotExist(id), f)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// [`write_entity()`] for a resource, creating an entry never seen first, since single-field resource ops are upserts.
|
|
||||||
fn upsert_resource(registry: &mut Registry, id: ResourceId, timestamp: TimeStamp, f: impl FnOnce(&mut ResourceEntry)) {
|
|
||||||
if !registry.resources.contains_key(&id) && !registry.removed_resources.contains_key(&id) {
|
|
||||||
registry.resources.insert(
|
|
||||||
id,
|
|
||||||
ResourceEntry {
|
|
||||||
presence: timestamp,
|
|
||||||
..ResourceEntry::default()
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let entry = content_mut(&mut registry.resources, &mut registry.removed_resources, id).expect("held above");
|
|
||||||
f(entry);
|
|
||||||
entry.set_presence(entry.presence().max(timestamp));
|
|
||||||
revive_if_newer(&mut registry.resources, &mut registry.removed_resources, id);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Which of a [`Document`]'s two registries an apply targets: the working copy (retired state plus
|
/// Which of a [`Document`]'s two registries an apply targets: the working copy (retired state plus
|
||||||
/// live hot ops) or the retired snapshot (retired deltas only). Retirement targets the snapshot so
|
/// live hot ops) or the retired snapshot (retired deltas only). Retirement targets the snapshot so
|
||||||
/// reverses capture pre-op values; the hot path and undo/redo target the working copy.
|
/// reverses capture pre-op values; the hot path and undo/redo target the working copy.
|
||||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
pub(crate) enum RegistryTarget {
|
pub(crate) enum RegistryTarget {
|
||||||
Working,
|
Working,
|
||||||
Retired,
|
Snapshot,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// How [`Document::apply_op_with`] treats what it finds.
|
/// How [`Document::apply_op_with`] resolves structural collisions and LWW timestamp ties.
|
||||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
pub(crate) enum ApplyMode {
|
pub(crate) enum ApplyMode {
|
||||||
/// A fresh local edit: adding what exists or writing to what was never seen is an error.
|
/// Fresh local/remote edit: structural ops error on duplicate/missing targets; LWW uses strict `>`.
|
||||||
Strict,
|
Live,
|
||||||
/// An op from a peer or from persisted state: every arm is a timestamp comparison.
|
/// Replay/retire: structural ops skip duplicate/missing targets; LWW still uses strict `>`.
|
||||||
Idempotent,
|
Idempotent,
|
||||||
/// Silent-zone undo/redo rewind: every write lands, whatever its timestamp.
|
/// Silent-zone undo/redo rewind: structural ops are idempotent and LWW arms assign unconditionally.
|
||||||
Force,
|
Force,
|
||||||
}
|
}
|
||||||
@@ -10,12 +10,9 @@ use serde::Serialize;
|
|||||||
|
|
||||||
use crate::attr::*;
|
use crate::attr::*;
|
||||||
use crate::metadata_source::{NoMetadata, NodeMetadataSource};
|
use crate::metadata_source::{NoMetadata, NodeMetadataSource};
|
||||||
use crate::{
|
use crate::{AttributesWrite, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ProtoNode, ROOT_NETWORK, Registry, ResourceHash, ResourceId, TimeStamp};
|
||||||
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 + '_ {
|
fn map_serialization_error(key: &str) -> impl FnOnce(serde_json::Error) -> ConversionError + '_ {
|
||||||
move |e| ConversionError::SerializationError(format!("{key}: {e:?}"))
|
move |e| ConversionError::SerializationError(format!("{key}: {e:?}"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,7 +40,7 @@ impl NodePath {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn to_global_id(&self, peer: PeerId) -> NodeId {
|
fn to_global_id(&self, peer: PeerId) -> NodeId {
|
||||||
let bytes = postcard::to_stdvec(&(peer, self)).expect("NodePath must serialize");
|
let bytes = rmp_serde::to_vec(&(peer, self)).expect("NodePath must serialize");
|
||||||
let digest = blake3::hash(&bytes);
|
let digest = blake3::hash(&bytes);
|
||||||
let mut truncated = [0u8; 8];
|
let mut truncated = [0u8; 8];
|
||||||
truncated.copy_from_slice(&digest.as_bytes()[..8]);
|
truncated.copy_from_slice(&digest.as_bytes()[..8]);
|
||||||
@@ -55,7 +52,7 @@ impl NodePath {
|
|||||||
/// depending on traversal order. A domain tag keeps it from colliding with this node's own
|
/// depending on traversal order. A domain tag keeps it from colliding with this node's own
|
||||||
/// `to_global_id`. The root network is `ROOT_NETWORK` and never goes through here.
|
/// `to_global_id`. The root network is `ROOT_NETWORK` and never goes through here.
|
||||||
fn owned_network_id(&self, peer: PeerId) -> NetworkId {
|
fn owned_network_id(&self, peer: PeerId) -> NetworkId {
|
||||||
let bytes = postcard::to_stdvec(&("network", peer, self)).expect("NodePath must serialize");
|
let bytes = rmp_serde::to_vec(&("network", peer, self)).expect("NodePath must serialize");
|
||||||
let digest = blake3::hash(&bytes);
|
let digest = blake3::hash(&bytes);
|
||||||
let mut truncated = [0u8; 8];
|
let mut truncated = [0u8; 8];
|
||||||
truncated.copy_from_slice(&digest.as_bytes()[..8]);
|
truncated.copy_from_slice(&digest.as_bytes()[..8]);
|
||||||
@@ -120,29 +117,45 @@ impl TryFrom<&NodeNetwork> for Registry {
|
|||||||
pub type DeclarationBytes = HashMap<ResourceHash, Vec<u8>>;
|
pub type DeclarationBytes = HashMap<ResourceHash, Vec<u8>>;
|
||||||
|
|
||||||
/// A `from_runtime` conversion result: the reference-only [`Registry`] plus the proto-node
|
/// A `from_runtime` conversion result: the reference-only [`Registry`] plus the proto-node
|
||||||
/// declarations it extracted, as bytes keyed by content hash (for the caller's byte store) and as
|
/// declaration *bytes* it extracted, keyed by content hash. `document-graph-storage` doesn't own a byte
|
||||||
/// decoded [`ProtoNode`]s keyed by id (for the caller's declaration cache).
|
/// store, so the caller (the `Gdd`) persists these into its content store; the registry only holds
|
||||||
|
/// the `ResourceId`/`ResourceHash` references.
|
||||||
pub struct RuntimeConversion {
|
pub struct RuntimeConversion {
|
||||||
pub registry: Registry,
|
pub registry: Registry,
|
||||||
pub declaration_bytes: DeclarationBytes,
|
pub declaration_bytes: DeclarationBytes,
|
||||||
pub declarations: crate::Declarations,
|
|
||||||
/// Each network's runtime `metadata_path` mapped to its stable storage `NetworkId`, for associating
|
/// Each network's runtime `metadata_path` mapped to its stable storage `NetworkId`, for associating
|
||||||
/// per-network, per-peer view state (`session.json`) without re-deriving ids.
|
/// per-network, per-peer view state (`session.json`) without re-deriving ids.
|
||||||
pub network_ids: HashMap<Vec<RuntimeNodeId>, NetworkId>,
|
pub network_ids: HashMap<Vec<RuntimeNodeId>, NetworkId>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Encode a [`ProtoNode`] declaration to its content-addressed bytes: through the self-describing
|
impl RuntimeConversion {
|
||||||
/// [`Value`] (so serde aliases keep working and the on-disk shape stays migratable), then postcard.
|
/// Rebuild the [`Declarations`](crate::Declarations) map (`ResourceId` → [`ProtoNode`]) from the
|
||||||
/// Paired with [`decode_declaration`].
|
/// extracted bytes, for callers that keep the bytes in hand instead of routing them through a
|
||||||
|
/// byte store (tests, the round-trip CLI). Editor/`Gdd` paths persist the bytes and resolve via
|
||||||
|
/// their byte store instead.
|
||||||
|
pub fn declarations(&self) -> Result<crate::Declarations, ConversionError> {
|
||||||
|
self.declaration_bytes
|
||||||
|
.iter()
|
||||||
|
.map(|(hash, bytes)| {
|
||||||
|
let proto = decode_declaration(bytes).map_err(|error| ConversionError::SerializationError(format!("declaration {hash}: {error}")))?;
|
||||||
|
Ok((ResourceId::from_hash(hash), proto))
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encode a [`ProtoNode`] declaration to its content-addressed bytes: through a self-describing
|
||||||
|
/// `serde_json::Value` (so serde aliases keep working and the on-disk shape stays migratable), then
|
||||||
|
/// rmp-serialized (which encodes the intermediate `Value` compactly). Paired with [`decode_declaration`].
|
||||||
pub fn encode_declaration(proto: &ProtoNode) -> Result<Vec<u8>, String> {
|
pub fn encode_declaration(proto: &ProtoNode) -> Result<Vec<u8>, String> {
|
||||||
let value = to_value(proto).map_err(|error| error.to_string())?;
|
let value = serde_json::to_value(proto).map_err(|error| error.to_string())?;
|
||||||
postcard::to_stdvec(&value).map_err(|error| error.to_string())
|
rmp_serde::to_vec(&value).map_err(|error| error.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Decode a [`ProtoNode`] declaration from the bytes [`encode_declaration`] produced.
|
/// Decode a [`ProtoNode`] declaration from the bytes [`encode_declaration`] produced.
|
||||||
pub fn decode_declaration(bytes: &[u8]) -> Result<ProtoNode, String> {
|
pub fn decode_declaration(bytes: &[u8]) -> Result<ProtoNode, String> {
|
||||||
let value: Value = postcard::from_bytes(bytes).map_err(|error| error.to_string())?;
|
let value: serde_json::Value = rmp_serde::from_slice(bytes).map_err(|error| error.to_string())?;
|
||||||
from_value(&value).map_err(|error| error.to_string())
|
serde_json::from_value(value).map_err(|error| error.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Registry {
|
impl Registry {
|
||||||
@@ -164,7 +177,6 @@ impl Registry {
|
|||||||
let mut ctx = ConversionContext {
|
let mut ctx = ConversionContext {
|
||||||
declaration_ids: HashMap::new(),
|
declaration_ids: HashMap::new(),
|
||||||
declaration_bytes: HashMap::new(),
|
declaration_bytes: HashMap::new(),
|
||||||
declarations: HashMap::new(),
|
|
||||||
network_ids: HashMap::new(),
|
network_ids: HashMap::new(),
|
||||||
metadata,
|
metadata,
|
||||||
peer,
|
peer,
|
||||||
@@ -183,7 +195,6 @@ impl Registry {
|
|||||||
Ok(RuntimeConversion {
|
Ok(RuntimeConversion {
|
||||||
registry,
|
registry,
|
||||||
declaration_bytes: ctx.declaration_bytes,
|
declaration_bytes: ctx.declaration_bytes,
|
||||||
declarations: ctx.declarations,
|
|
||||||
network_ids: ctx.network_ids,
|
network_ids: ctx.network_ids,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -192,7 +203,7 @@ impl Registry {
|
|||||||
/// Snapshot the runtime [`ResourceRegistry`](graphene_resource::ResourceRegistry) into the storage
|
/// Snapshot the runtime [`ResourceRegistry`](graphene_resource::ResourceRegistry) into the storage
|
||||||
/// [`ResourceStore`](crate::ResourceStore). Each source's chain position becomes a fractional
|
/// [`ResourceStore`](crate::ResourceStore). Each source's chain position becomes a fractional
|
||||||
/// [`Priority`](crate::Priority) (index-as-priority preserves order); the `DataSource` body is
|
/// [`Priority`](crate::Priority) (index-as-priority preserves order); the `DataSource` body is
|
||||||
/// stored type-erased as [`Value`] so its on-disk shape can migrate freely. All
|
/// stored type-erased as `serde_json::Value` so its on-disk shape can migrate freely. All
|
||||||
/// timestamps are `ORIGIN`, since this is a bootstrap snapshot, not an edit.
|
/// timestamps are `ORIGIN`, since this is a bootstrap snapshot, not an edit.
|
||||||
fn convert_resources(resources: &graphene_resource::ResourceRegistry, referenced: &std::collections::HashSet<ResourceId>, peer: PeerId, registry: &mut Registry) -> Result<(), ConversionError> {
|
fn convert_resources(resources: &graphene_resource::ResourceRegistry, referenced: &std::collections::HashSet<ResourceId>, peer: PeerId, registry: &mut Registry) -> Result<(), ConversionError> {
|
||||||
for id in resources.ids() {
|
for id in resources.ids() {
|
||||||
@@ -220,14 +231,12 @@ pub fn convert_resource_entry(resources: &graphene_resource::ResourceRegistry, i
|
|||||||
priority: crate::Priority::new(position as f64).expect("enumerate index is finite"),
|
priority: crate::Priority::new(position as f64).expect("enumerate index is finite"),
|
||||||
peer,
|
peer,
|
||||||
};
|
};
|
||||||
let body = to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
|
let body = serde_json::to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
|
||||||
// Built rather than written: the chain is put in place as converted, floor and all at the origin.
|
entry.set_source(
|
||||||
entry.force_set_source(
|
|
||||||
key,
|
key,
|
||||||
crate::SourceValue {
|
crate::SourceValue {
|
||||||
source: body,
|
source: body,
|
||||||
timestamp: TimeStamp::ORIGIN,
|
timestamp: TimeStamp::ORIGIN,
|
||||||
deleted: false,
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -280,8 +289,6 @@ struct ConversionContext<'m, M: NodeMetadataSource + ?Sized> {
|
|||||||
declaration_ids: HashMap<String, ResourceId>,
|
declaration_ids: HashMap<String, ResourceId>,
|
||||||
/// Extracted declaration content keyed by hash, handed back for the caller's byte store.
|
/// Extracted declaration content keyed by hash, handed back for the caller's byte store.
|
||||||
declaration_bytes: DeclarationBytes,
|
declaration_bytes: DeclarationBytes,
|
||||||
/// The same declarations decoded, keyed by id, handed back for the caller's declaration cache.
|
|
||||||
declarations: crate::Declarations,
|
|
||||||
/// Maps each network's runtime `metadata_path` to its stable storage `NetworkId`, so the caller can
|
/// Maps each network's runtime `metadata_path` to its stable storage `NetworkId`, so the caller can
|
||||||
/// associate per-network, per-peer view state (in `session.json`) with networks without re-deriving ids.
|
/// associate per-network, per-peer view state (in `session.json`) with networks without re-deriving ids.
|
||||||
network_ids: HashMap<Vec<RuntimeNodeId>, NetworkId>,
|
network_ids: HashMap<Vec<RuntimeNodeId>, NetworkId>,
|
||||||
@@ -322,7 +329,7 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
|
|||||||
runtime_node_id: *runtime_node_id,
|
runtime_node_id: *runtime_node_id,
|
||||||
};
|
};
|
||||||
let mut node = convert_node(doc_node, location, registry, ctx, true)?;
|
let mut node = convert_node(doc_node, location, registry, ctx, true)?;
|
||||||
node.attributes.set(node::ORIGINAL_NODE_ID, Value::Int(runtime_node_id.0.into()), TimeStamp::ORIGIN);
|
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(runtime_node_id.0), TimeStamp::ORIGIN);
|
||||||
registry.node_instances.insert(global_id, node);
|
registry.node_instances.insert(global_id, node);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -338,18 +345,10 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
|
|||||||
.collect::<Result<Vec<_>, ConversionError>>()?;
|
.collect::<Result<Vec<_>, ConversionError>>()?;
|
||||||
|
|
||||||
let mut attributes = crate::Attributes::new();
|
let mut attributes = crate::Attributes::new();
|
||||||
write_ui_network_attributes(&mut attributes, node_network, metadata_path, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
|
write_ui_network_attributes(&mut attributes, ctx.metadata, metadata_path, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
|
||||||
write_scope_injections(&mut attributes, node_network, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
|
write_scope_injections(&mut attributes, node_network, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
|
||||||
|
|
||||||
registry.networks.insert(
|
registry.networks.insert(network_id, Network { exports, attributes });
|
||||||
network_id,
|
|
||||||
Network {
|
|
||||||
presence: TimeStamp::ORIGIN,
|
|
||||||
exports,
|
|
||||||
exports_timestamp: TimeStamp::ORIGIN,
|
|
||||||
attributes,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
ctx.network_ids.insert(metadata_path.to_vec(), network_id);
|
ctx.network_ids.insert(metadata_path.to_vec(), network_id);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -421,7 +420,6 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
|
|||||||
let mut inputs = Vec::with_capacity(doc_node.inputs.len());
|
let mut inputs = Vec::with_capacity(doc_node.inputs.len());
|
||||||
for (input_index, input) in doc_node.inputs.iter().enumerate() {
|
for (input_index, input) in doc_node.inputs.iter().enumerate() {
|
||||||
let mut input_attrs = convert_input_attributes(input)?;
|
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)?;
|
write_ui_input_attributes(&mut input_attrs, ctx.metadata, metadata_path, runtime_node_id, input_index, timestamp)?;
|
||||||
|
|
||||||
inputs.push(InputSlot {
|
inputs.push(InputSlot {
|
||||||
@@ -443,7 +441,7 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
|
|||||||
let implementation = convert_implementation(&doc_node.implementation, &node_path, child_metadata_path, registry, ctx, recurse)?;
|
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.
|
// 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
|
attributes
|
||||||
.set_if_not_default(node::CALL_ARGUMENT, &doc_node.call_argument, &concrete!(Context), timestamp)
|
.set_if_not_default(node::CALL_ARGUMENT, &doc_node.call_argument, &concrete!(Context), timestamp)
|
||||||
.map_err(map_serialization_error(node::CALL_ARGUMENT))?;
|
.map_err(map_serialization_error(node::CALL_ARGUMENT))?;
|
||||||
@@ -460,11 +458,7 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
|
|||||||
write_ui_attributes(&mut attributes, ctx.metadata, metadata_path, runtime_node_id, timestamp)?;
|
write_ui_attributes(&mut attributes, ctx.metadata, metadata_path, runtime_node_id, timestamp)?;
|
||||||
|
|
||||||
Ok(Node {
|
Ok(Node {
|
||||||
presence: timestamp,
|
|
||||||
network_timestamp: timestamp,
|
|
||||||
inputs_timestamp: timestamp,
|
|
||||||
implementation,
|
implementation,
|
||||||
implementation_timestamp: timestamp,
|
|
||||||
inputs,
|
inputs,
|
||||||
attributes,
|
attributes,
|
||||||
network: network_id,
|
network: network_id,
|
||||||
@@ -483,7 +477,11 @@ pub fn encode_context_features(context_features: &ContextDependencies) -> Result
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn encode_if_not_default<T: Serialize + PartialEq>(key: &str, value: &T, default: &T) -> Result<crate::AttributeDelta, ConversionError> {
|
fn encode_if_not_default<T: Serialize + PartialEq>(key: &str, value: &T, default: &T) -> Result<crate::AttributeDelta, ConversionError> {
|
||||||
let value = if value == default { None } else { Some(to_value(value).map_err(map_serialization_error(key))?) };
|
let value = if value == default {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(serde_json::to_value(value).map_err(map_serialization_error(key))?)
|
||||||
|
};
|
||||||
|
|
||||||
Ok(crate::AttributeDelta { key: key.to_string(), value })
|
Ok(crate::AttributeDelta { key: key.to_string(), value })
|
||||||
}
|
}
|
||||||
@@ -531,14 +529,14 @@ fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
|
|||||||
(node::ui::PINNED, metadata.pinned(metadata_path, runtime_node_id)),
|
(node::ui::PINNED, metadata.pinned(metadata_path, runtime_node_id)),
|
||||||
] {
|
] {
|
||||||
if value {
|
if value {
|
||||||
attributes.set(key, Value::Bool(true), timestamp);
|
attributes.set(key, serde_json::Value::Bool(true), timestamp);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(name) = metadata.display_name(metadata_path, runtime_node_id)
|
if let Some(name) = metadata.display_name(metadata_path, runtime_node_id)
|
||||||
&& !name.is_empty()
|
&& !name.is_empty()
|
||||||
{
|
{
|
||||||
attributes.set(node::ui::DISPLAY_NAME, Value::Str(name.to_string()), timestamp);
|
attributes.set(node::ui::DISPLAY_NAME, serde_json::Value::String(name.to_string()), timestamp);
|
||||||
}
|
}
|
||||||
|
|
||||||
// One whole-vec attribute; per-slot LWW would be overkill for rename-on-output.
|
// One whole-vec attribute; per-slot LWW would be overkill for rename-on-output.
|
||||||
@@ -549,13 +547,6 @@ fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
|
|||||||
.map_err(map_serialization_error(node::ui::OUTPUT_NAMES))?;
|
.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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -563,25 +554,20 @@ fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
|
|||||||
/// does it: a runtime ID is not stable across a round trip.
|
/// does it: a runtime ID is not stable across a round trip.
|
||||||
fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
|
fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
|
||||||
attributes: &mut crate::Attributes,
|
attributes: &mut crate::Attributes,
|
||||||
node_network: &NodeNetwork,
|
metadata: &M,
|
||||||
network_path: &[RuntimeNodeId],
|
network_path: &[RuntimeNodeId],
|
||||||
parent_path: Option<&NodePath>,
|
parent_path: Option<&NodePath>,
|
||||||
network_id: NetworkId,
|
network_id: NetworkId,
|
||||||
ids: NodeIds<'_, M>,
|
ids: NodeIds<'_, M>,
|
||||||
timestamp: TimeStamp,
|
timestamp: TimeStamp,
|
||||||
) -> Result<(), ConversionError> {
|
) -> Result<(), ConversionError> {
|
||||||
// The same source the IDs resolve through, so a network's attributes and the nodes they name agree.
|
|
||||||
let Some(metadata) = ids.metadata else { return Ok(()) };
|
|
||||||
if let Some(reference) = metadata.reference(network_path) {
|
if let Some(reference) = metadata.reference(network_path) {
|
||||||
attributes.set(node::ui::REFERENCE, Value::Str(reference.to_string()), timestamp);
|
attributes.set(node::ui::REFERENCE, serde_json::Value::String(reference.to_string()), timestamp);
|
||||||
}
|
}
|
||||||
|
|
||||||
let to_storage_id = |runtime_id: RuntimeNodeId| ids.resolve(&child_path(parent_path, network_id, runtime_id), runtime_id);
|
let to_storage_id = |runtime_id: RuntimeNodeId| ids.resolve(&child_path(parent_path, network_id, runtime_id), runtime_id);
|
||||||
|
|
||||||
// Only nodes the converted network still holds: the read side drops a stored ID it cannot find, so
|
let pinned_order = metadata.pinned_order(network_path);
|
||||||
// persisting one for a node deleted or reparented elsewhere would leave stored state disagreeing with
|
|
||||||
// what a peer converting the same input produces.
|
|
||||||
let pinned_order: Vec<_> = metadata.pinned_order(network_path).into_iter().filter(|pinned| node_network.nodes.contains_key(pinned)).collect();
|
|
||||||
if !pinned_order.is_empty() {
|
if !pinned_order.is_empty() {
|
||||||
let stored: Vec<NodeId> = pinned_order.into_iter().map(to_storage_id).collect();
|
let stored: Vec<NodeId> = pinned_order.into_iter().map(to_storage_id).collect();
|
||||||
attributes
|
attributes
|
||||||
@@ -604,7 +590,7 @@ fn write_ui_input_attributes<M: NodeMetadataSource + ?Sized>(
|
|||||||
) -> Result<(), ConversionError> {
|
) -> Result<(), ConversionError> {
|
||||||
let non_empty_string = |key: &'static str, value: Option<&str>, attributes: &mut crate::Attributes| {
|
let non_empty_string = |key: &'static str, value: Option<&str>, attributes: &mut crate::Attributes| {
|
||||||
if let Some(value) = value.filter(|s| !s.is_empty()) {
|
if let Some(value) = value.filter(|s| !s.is_empty()) {
|
||||||
attributes.set(key, Value::Str(value.to_string()), timestamp);
|
attributes.set(key, serde_json::Value::String(value.to_string()), timestamp);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -626,7 +612,7 @@ fn convert_input<M: NodeMetadataSource + ?Sized>(input: &GraphCraftNodeInput, pa
|
|||||||
index: (*output_index).try_into().map_err(|_| ConversionError::IndexOverflow(*output_index))?,
|
index: (*output_index).try_into().map_err(|_| ConversionError::IndexOverflow(*output_index))?,
|
||||||
},
|
},
|
||||||
GraphCraftNodeInput::Value { tagged_value, exposed } => {
|
GraphCraftNodeInput::Value { tagged_value, exposed } => {
|
||||||
let value = to_value(&**tagged_value).map_err(|e| ConversionError::SerializationError(format!("{e:?}")))?;
|
let value = serde_json::to_value(&**tagged_value).map_err(|e| ConversionError::SerializationError(format!("{e:?}")))?;
|
||||||
NodeInput::Value { value, exposed: *exposed }
|
NodeInput::Value { value, exposed: *exposed }
|
||||||
}
|
}
|
||||||
GraphCraftNodeInput::Scope(s) => NodeInput::Scope(s.clone()),
|
GraphCraftNodeInput::Scope(s) => NodeInput::Scope(s.clone()),
|
||||||
@@ -640,7 +626,7 @@ fn convert_input<M: NodeMetadataSource + ?Sized>(input: &GraphCraftNodeInput, pa
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The non-ui attributes a slot carries, derived from the input itself: the declared type of an
|
/// The non-ui attributes a slot carries, derived from the input itself: the declared type of an
|
||||||
/// import, and a reflection node's metadata.
|
/// import, and a reflection node.s metadata. Public for staging paths that rebuild a node.s slots.
|
||||||
pub fn convert_input_attributes(input: &GraphCraftNodeInput) -> Result<crate::Attributes, ConversionError> {
|
pub fn convert_input_attributes(input: &GraphCraftNodeInput) -> Result<crate::Attributes, ConversionError> {
|
||||||
let mut attributes = crate::Attributes::new();
|
let mut attributes = crate::Attributes::new();
|
||||||
let timestamp = TimeStamp::ORIGIN;
|
let timestamp = TimeStamp::ORIGIN;
|
||||||
@@ -691,7 +677,6 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
|
|||||||
|
|
||||||
register_declaration_resource(registry, id, hash, ctx.peer);
|
register_declaration_resource(registry, id, hash, ctx.peer);
|
||||||
ctx.declaration_bytes.insert(hash, bytes);
|
ctx.declaration_bytes.insert(hash, bytes);
|
||||||
ctx.declarations.insert(id, proto);
|
|
||||||
ctx.declaration_ids.insert(identifier_str, id);
|
ctx.declaration_ids.insert(identifier_str, id);
|
||||||
|
|
||||||
Implementation::ProtoNode(id)
|
Implementation::ProtoNode(id)
|
||||||
@@ -785,7 +770,6 @@ impl<'m> ScopedConversion<'m> {
|
|||||||
ctx: ConversionContext {
|
ctx: ConversionContext {
|
||||||
declaration_ids: HashMap::new(),
|
declaration_ids: HashMap::new(),
|
||||||
declaration_bytes: HashMap::new(),
|
declaration_bytes: HashMap::new(),
|
||||||
declarations: HashMap::new(),
|
|
||||||
network_ids: HashMap::new(),
|
network_ids: HashMap::new(),
|
||||||
metadata,
|
metadata,
|
||||||
peer,
|
peer,
|
||||||
@@ -807,7 +791,7 @@ impl<'m> ScopedConversion<'m> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let mut node = convert_node(doc_node, location, registry, &mut self.ctx, recurse)?;
|
let mut node = convert_node(doc_node, location, registry, &mut self.ctx, recurse)?;
|
||||||
node.attributes.set(node::ORIGINAL_NODE_ID, Value::Int(local_id.0.into()), TimeStamp::ORIGIN);
|
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(local_id.0), TimeStamp::ORIGIN);
|
||||||
registry.node_instances.insert(self.resolver.node_id(local_path, local_id), node);
|
registry.node_instances.insert(self.resolver.node_id(local_path, local_id), node);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -830,25 +814,24 @@ impl<'m> ScopedConversion<'m> {
|
|||||||
.collect::<Result<Vec<_>, ConversionError>>()?;
|
.collect::<Result<Vec<_>, ConversionError>>()?;
|
||||||
|
|
||||||
let mut attributes = crate::Attributes::new();
|
let mut attributes = crate::Attributes::new();
|
||||||
write_ui_network_attributes(&mut attributes, node_network, local_path, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
|
write_ui_network_attributes(
|
||||||
|
&mut attributes,
|
||||||
|
self.ctx.metadata,
|
||||||
|
local_path,
|
||||||
|
owner_path.as_ref(),
|
||||||
|
network_id,
|
||||||
|
self.ctx.ids(local_path),
|
||||||
|
TimeStamp::ORIGIN,
|
||||||
|
)?;
|
||||||
write_scope_injections(&mut attributes, node_network, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
|
write_scope_injections(&mut attributes, node_network, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
|
||||||
|
|
||||||
registry.networks.insert(
|
registry.networks.insert(network_id, Network { exports, attributes });
|
||||||
network_id,
|
|
||||||
Network {
|
|
||||||
presence: TimeStamp::ORIGIN,
|
|
||||||
exports,
|
|
||||||
exports_timestamp: TimeStamp::ORIGIN,
|
|
||||||
attributes,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The extracted proto-node declarations: the bytes for the caller's byte store, and the same
|
/// The extracted proto-node declaration bytes, for the caller to persist into its byte store.
|
||||||
/// declarations decoded for its declaration cache.
|
pub fn finish(self) -> DeclarationBytes {
|
||||||
pub fn finish(self) -> (DeclarationBytes, crate::Declarations) {
|
self.ctx.declaration_bytes
|
||||||
(self.ctx.declaration_bytes, self.ctx.declarations)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -864,10 +847,7 @@ pub fn node_value_resource_refs(node: &Node) -> impl Iterator<Item = ResourceId>
|
|||||||
/// The `TaggedValue::Resource` ID referenced by a stored value input, if any.
|
/// The `TaggedValue::Resource` ID referenced by a stored value input, if any.
|
||||||
pub fn value_resource_ref(input: &NodeInput) -> Option<ResourceId> {
|
pub fn value_resource_ref(input: &NodeInput) -> Option<ResourceId> {
|
||||||
match input {
|
match input {
|
||||||
NodeInput::Value { value: Value::Object(fields), .. } => match fields.as_slice() {
|
NodeInput::Value { value, .. } => value.get("Resource").and_then(|id| serde_json::from_value(id.clone()).ok()),
|
||||||
[(key, id)] if key == "Resource" => from_value(id).ok(),
|
|
||||||
_ => None,
|
|
||||||
},
|
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -879,8 +859,8 @@ mod resource_ref_shape {
|
|||||||
#[test]
|
#[test]
|
||||||
fn resource_ref_shape_matches_serde() {
|
fn resource_ref_shape_matches_serde() {
|
||||||
let id = ResourceId::from_hash(&ResourceHash::from(b"shape test".as_slice()));
|
let id = ResourceId::from_hash(&ResourceHash::from(b"shape test".as_slice()));
|
||||||
let value = to_value(&TaggedValue::Resource(id)).expect("TaggedValue::Resource serializes");
|
let value = serde_json::to_value(TaggedValue::Resource(id)).expect("TaggedValue::Resource serializes");
|
||||||
let parsed = value_resource_ref(&NodeInput::Value { value, exposed: false });
|
let parsed: Option<ResourceId> = value.get("Resource").and_then(|inner| serde_json::from_value(inner.clone()).ok());
|
||||||
assert_eq!(parsed, Some(id), "The shape peek in node_value_resource_refs must match TaggedValue's serde form");
|
assert_eq!(parsed, Some(id), "The shape peek in node_value_resource_refs must match TaggedValue's serde form");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,26 +3,21 @@
|
|||||||
//! [`History`] owns the deltas in topological order (every parent precedes its children) plus an
|
//! [`History`] owns the deltas in topological order (every parent precedes its children) plus an
|
||||||
//! index from [`Rev`] to position for O(1) lookup. The order is a valid replay order, so it is what
|
//! index from [`Rev`] to position for O(1) lookup. The order is a valid replay order, so it is what
|
||||||
//! gets serialized to the on-disk history file and what [`crate::Session::replay_from_history`]
|
//! gets serialized to the on-disk history file and what [`crate::Session::replay_from_history`]
|
||||||
//! consumes. Appending a commit keeps the order; deltas arriving out of it are put back by
|
//! consumes. Retired commits have a single writer in every regime (solo editing, or leader-ordered
|
||||||
//! a canonical sort.
|
//! collaboration where the leader serializes retired commits), so appending preserves the order by
|
||||||
|
//! construction. The only operation that introduces out-of-order deltas is [`merge`](History::merge),
|
||||||
|
//! which re-sorts the combined set into the canonical order to restore the invariant.
|
||||||
|
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use crate::{CrdtError, Delta, RegistryDelta, ResourceHash, Rev, TimeStamp, Value};
|
use crate::{AttributesWrite, CrdtError, Delta, Rev, TimeStamp};
|
||||||
|
|
||||||
/// Every mutator maintains the indexes, so the tips and named hashes are probes, not scans of a growing history.
|
|
||||||
#[derive(Clone, Debug, Default)]
|
#[derive(Clone, Debug, Default)]
|
||||||
pub struct History {
|
pub struct History {
|
||||||
/// Deltas in topological order. Mutated only via [`push`](Self::push).
|
/// Deltas in topological order. Mutated only via [`push`](Self::push).
|
||||||
deltas: Vec<Delta>,
|
deltas: Vec<Delta>,
|
||||||
/// `Rev` to its position in `deltas`. Kept in sync with `deltas` by every mutator.
|
/// `Rev` to its position in `deltas`. Kept in sync with `deltas` by every mutator.
|
||||||
index: HashMap<Rev, usize>,
|
index: HashMap<Rev, usize>,
|
||||||
/// Every rev some delta names as a parent.
|
|
||||||
referenced: HashSet<Rev>,
|
|
||||||
/// Deltas no other delta names as a parent.
|
|
||||||
tips: HashSet<Rev>,
|
|
||||||
/// Content hashes the deltas name, from resource additions and removals.
|
|
||||||
resource_hashes: HashSet<ResourceHash>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl History {
|
impl History {
|
||||||
@@ -32,9 +27,8 @@ impl History {
|
|||||||
|
|
||||||
/// Build from deltas already in topological order (the on-disk load path), indexing them in place.
|
/// Build from deltas already in topological order (the on-disk load path), indexing them in place.
|
||||||
pub fn from_ordered(deltas: Vec<Delta>) -> Self {
|
pub fn from_ordered(deltas: Vec<Delta>) -> Self {
|
||||||
let mut history = Self::default();
|
let index = deltas.iter().enumerate().map(|(position, delta)| (delta.id, position)).collect();
|
||||||
deltas.into_iter().for_each(|delta| history.push(delta));
|
Self { deltas, index }
|
||||||
history
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get(&self, rev: Rev) -> Option<&Delta> {
|
pub fn get(&self, rev: Rev) -> Option<&Delta> {
|
||||||
@@ -45,11 +39,6 @@ impl History {
|
|||||||
self.index.contains_key(&rev)
|
self.index.contains_key(&rev)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The content hashes named by any resource addition or removal in history.
|
|
||||||
pub fn resource_hashes(&self) -> &HashSet<ResourceHash> {
|
|
||||||
&self.resource_hashes
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn len(&self) -> usize {
|
pub fn len(&self) -> usize {
|
||||||
self.deltas.len()
|
self.deltas.len()
|
||||||
}
|
}
|
||||||
@@ -62,25 +51,10 @@ impl History {
|
|||||||
/// (idempotent re-apply) overwrites the existing entry in place rather than appending, so the
|
/// (idempotent re-apply) overwrites the existing entry in place rather than appending, so the
|
||||||
/// order and index are unchanged.
|
/// order and index are unchanged.
|
||||||
pub fn push(&mut self, delta: Delta) {
|
pub fn push(&mut self, delta: Delta) {
|
||||||
match &delta.kind {
|
|
||||||
RegistryDelta::AddResource { entry, .. } => self.resource_hashes.extend(entry.hash),
|
|
||||||
RegistryDelta::RemoveResource { snapshot, .. } => self.resource_hashes.extend(snapshot.hash),
|
|
||||||
RegistryDelta::SetResourceHash { hash: Some(hash), .. } => {
|
|
||||||
self.resource_hashes.insert(*hash);
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
if let Some(&position) = self.index.get(&delta.id) {
|
if let Some(&position) = self.index.get(&delta.id) {
|
||||||
self.deltas[position] = delta;
|
self.deltas[position] = delta;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
for parent in delta.all_parents() {
|
|
||||||
self.referenced.insert(parent);
|
|
||||||
self.tips.remove(&parent);
|
|
||||||
}
|
|
||||||
if !self.referenced.contains(&delta.id) {
|
|
||||||
self.tips.insert(delta.id);
|
|
||||||
}
|
|
||||||
self.index.insert(delta.id, self.deltas.len());
|
self.index.insert(delta.id, self.deltas.len());
|
||||||
self.deltas.push(delta);
|
self.deltas.push(delta);
|
||||||
}
|
}
|
||||||
@@ -145,24 +119,11 @@ impl History {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `roots` and everything reachable from them through all parent links. Unknown roots are skipped.
|
|
||||||
pub(crate) fn ancestors(&self, roots: impl IntoIterator<Item = Rev>) -> HashSet<Rev> {
|
|
||||||
let mut seen = HashSet::new();
|
|
||||||
let mut stack: Vec<Rev> = roots.into_iter().filter(|rev| self.contains(*rev)).collect();
|
|
||||||
while let Some(rev) = stack.pop() {
|
|
||||||
if seen.insert(rev)
|
|
||||||
&& let Some(delta) = self.get(rev)
|
|
||||||
{
|
|
||||||
stack.extend(delta.all_parents());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
seen
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The current tips: revs that no other delta lists as a parent (the divergent heads). A linear
|
/// The current tips: revs that no other delta lists as a parent (the divergent heads). A linear
|
||||||
/// history has exactly one tip; concurrent branches have several. Sorted ascending for determinism.
|
/// history has exactly one tip; concurrent branches have several. Sorted ascending for determinism.
|
||||||
pub fn tips(&self) -> Vec<Rev> {
|
pub fn tips(&self) -> Vec<Rev> {
|
||||||
let mut tips: Vec<Rev> = self.tips.iter().copied().collect();
|
let referenced: std::collections::HashSet<Rev> = self.deltas.iter().flat_map(|delta| delta.all_parents()).collect();
|
||||||
|
let mut tips: Vec<Rev> = self.deltas.iter().map(|delta| delta.id).filter(|rev| !referenced.contains(rev)).collect();
|
||||||
tips.sort_unstable();
|
tips.sort_unstable();
|
||||||
tips
|
tips
|
||||||
}
|
}
|
||||||
@@ -181,7 +142,7 @@ impl History {
|
|||||||
|
|
||||||
/// Set a local annotation attribute (e.g. a commit message) on a retired delta in place. Excluded
|
/// Set a local annotation attribute (e.g. a commit message) on a retired delta in place. Excluded
|
||||||
/// from the delta's `Rev`, so identity and the index are unchanged. Returns whether the delta was found.
|
/// from the delta's `Rev`, so identity and the index are unchanged. Returns whether the delta was found.
|
||||||
pub fn annotate(&mut self, rev: Rev, key: &str, value: Value, timestamp: TimeStamp) -> bool {
|
pub fn annotate(&mut self, rev: Rev, key: &str, value: serde_json::Value, timestamp: TimeStamp) -> bool {
|
||||||
match self.index.get(&rev) {
|
match self.index.get(&rev) {
|
||||||
Some(&position) => {
|
Some(&position) => {
|
||||||
self.deltas[position].attributes.set(key, value, timestamp);
|
self.deltas[position].attributes.set(key, value, timestamp);
|
||||||
|
|||||||
@@ -56,8 +56,6 @@ pub const ROOT_NETWORK: NetworkId = NetworkId(0);
|
|||||||
/// Upper bound on a network's export slot count, guarding `SetExport` against a malicious or corrupted
|
/// Upper bound on a network's export slot count, guarding `SetExport` against a malicious or corrupted
|
||||||
/// slot index forcing an unbounded `exports` allocation.
|
/// slot index forcing an unbounded `exports` allocation.
|
||||||
pub(crate) const MAX_EXPORT_SLOTS: usize = 1 << 16;
|
pub(crate) const MAX_EXPORT_SLOTS: usize = 1 << 16;
|
||||||
/// A per-slot write can bring a slot past the end of the list into being, so it is capped the same way.
|
|
||||||
pub(crate) const MAX_INPUT_SLOTS: usize = 1 << 16;
|
|
||||||
|
|
||||||
/// Per-device identity. Stable per `(device, document)`. Used for CRDT tiebreaking and `NodeId`
|
/// Per-device identity. Stable per `(device, document)`. Used for CRDT tiebreaking and `NodeId`
|
||||||
/// scoping. Globally unique across all peers ever in a document.
|
/// scoping. Globally unique across all peers ever in a document.
|
||||||
@@ -121,9 +119,9 @@ pub(crate) fn compute_rev(parent: Option<Rev>, author: PeerId, timestamp: TimeSt
|
|||||||
let mut parents: Vec<Rev> = parent.into_iter().chain(extra_parents.iter().copied()).collect();
|
let mut parents: Vec<Rev> = parent.into_iter().chain(extra_parents.iter().copied()).collect();
|
||||||
parents.sort_unstable();
|
parents.sort_unstable();
|
||||||
parents.dedup();
|
parents.dedup();
|
||||||
postcard::to_stdvec(&("merge", parents)).expect("Merge identity fields must serialize")
|
rmp_serde::to_vec(&("merge", parents)).expect("Merge identity fields must serialize")
|
||||||
}
|
}
|
||||||
_ => postcard::to_stdvec(&(parent, author, timestamp, delta_type)).expect("Delta identity fields must serialize"),
|
_ => rmp_serde::to_vec(&(parent, author, timestamp, delta_type)).expect("Delta identity fields must serialize"),
|
||||||
};
|
};
|
||||||
hasher.update(&bytes);
|
hasher.update(&bytes);
|
||||||
let digest = hasher.finalize();
|
let digest = hasher.finalize();
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ pub mod model;
|
|||||||
pub mod registry;
|
pub mod registry;
|
||||||
pub mod resources;
|
pub mod resources;
|
||||||
pub mod session;
|
pub mod session;
|
||||||
pub mod value;
|
|
||||||
|
|
||||||
#[cfg(any(feature = "conversion", test))]
|
#[cfg(any(feature = "conversion", test))]
|
||||||
pub mod from_runtime;
|
pub mod from_runtime;
|
||||||
@@ -28,7 +27,6 @@ pub use model::*;
|
|||||||
pub use registry::*;
|
pub use registry::*;
|
||||||
pub use resources::*;
|
pub use resources::*;
|
||||||
pub use session::*;
|
pub use session::*;
|
||||||
pub use value::{Value, ValueError, from_value, to_value};
|
|
||||||
|
|
||||||
#[cfg(any(feature = "conversion", test))]
|
#[cfg(any(feature = "conversion", test))]
|
||||||
pub use from_runtime::{
|
pub use from_runtime::{
|
||||||
@@ -42,7 +40,6 @@ pub use to_runtime::Declarations;
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
mod bookkeeping;
|
|
||||||
mod crdt;
|
mod crdt;
|
||||||
mod round_trip;
|
mod round_trip;
|
||||||
}
|
}
|
||||||
@@ -8,8 +8,6 @@ use std::collections::HashMap;
|
|||||||
|
|
||||||
use core_types::uuid::NodeId as RuntimeNodeId;
|
use core_types::uuid::NodeId as RuntimeNodeId;
|
||||||
|
|
||||||
use crate::Value;
|
|
||||||
|
|
||||||
/// One node's editor-side metadata, produced by `Registry::to_runtime_with_metadata`. One entry per
|
/// One node's editor-side metadata, produced by `Registry::to_runtime_with_metadata`. One entry per
|
||||||
/// node, since every node carries an identity to restore even when it carries no `ui::*` attribute.
|
/// node, since every node carries an identity to restore even when it carries no `ui::*` attribute.
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
@@ -28,7 +26,6 @@ pub struct NodeMetadataEntry {
|
|||||||
/// returns an error if this length does not match the node's input count.
|
/// returns an error if this length does not match the node's input count.
|
||||||
pub input_metadata: Vec<InputMetadataEntry>,
|
pub input_metadata: Vec<InputMetadataEntry>,
|
||||||
pub output_names: Vec<String>,
|
pub output_names: Vec<String>,
|
||||||
pub output_descriptions: Vec<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Per-network metadata. Separate from `NodeMetadataEntry` since these are
|
/// Per-network metadata. Separate from `NodeMetadataEntry` since these are
|
||||||
@@ -41,9 +38,10 @@ pub struct NetworkMetadataEntry {
|
|||||||
/// Stable storage id of this network. Lets the editor associate per-network, per-peer view state
|
/// Stable storage id of this network. Lets the editor associate per-network, per-peer view state
|
||||||
/// (the node-graph nav, in `session.json`) with a network across reparenting.
|
/// (the node-graph nav, in `session.json`) with a network across reparenting.
|
||||||
pub network_id: crate::NetworkId,
|
pub network_id: crate::NetworkId,
|
||||||
/// Matches the runtime's `NodeNetworkPersistentMetadata::reference`: the definition lineage tag.
|
/// Matches the runtime's `NodeNetworkPersistentMetadata::reference` — definition lineage tag.
|
||||||
pub reference: Option<String>,
|
pub reference: Option<String>,
|
||||||
/// The display order of the network's pinned nodes.
|
/// The display order of the network's pinned nodes. Shared for the same reason the pinned flag is:
|
||||||
|
/// a shared set with per-peer ordering could never reconcile.
|
||||||
pub pinned_order: Vec<RuntimeNodeId>,
|
pub pinned_order: Vec<RuntimeNodeId>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,11 +53,11 @@ pub struct InputMetadataEntry {
|
|||||||
pub input_description: Option<String>,
|
pub input_description: Option<String>,
|
||||||
pub widget_override: Option<String>,
|
pub widget_override: Option<String>,
|
||||||
/// Reassembled from `ui::input_data::<sub_key>` attributes.
|
/// Reassembled from `ui::input_data::<sub_key>` attributes.
|
||||||
pub input_data: HashMap<String, Value>,
|
pub input_data: HashMap<String, serde_json::Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Editor-side metadata source. Methods default to "no data" so implementors only override what
|
/// Editor-side metadata source. Methods default to "no data" so implementors only override what
|
||||||
/// they carry. Returns are type-erased as [`Value`] where the underlying types live editor-side (PTZ, etc.).
|
/// they carry. Returns are JSON-shaped where the underlying types live editor-side (PTZ, etc.).
|
||||||
pub trait NodeMetadataSource {
|
pub trait NodeMetadataSource {
|
||||||
fn position(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Option<Position> {
|
fn position(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Option<Position> {
|
||||||
None
|
None
|
||||||
@@ -80,10 +78,6 @@ pub trait NodeMetadataSource {
|
|||||||
fn output_names(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Vec<String> {
|
fn output_names(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Vec<String> {
|
||||||
Vec::new()
|
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> {
|
fn input_name(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId, _input_index: usize) -> Option<&str> {
|
||||||
None
|
None
|
||||||
@@ -95,7 +89,7 @@ pub trait NodeMetadataSource {
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
/// Returns owned to stay object-safe. Each entry is stored as `ui::input_data::<key>` for per-key LWW.
|
/// Returns owned to stay object-safe. Each entry is stored as `ui::input_data::<key>` for per-key LWW.
|
||||||
fn input_data(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId, _input_index: usize) -> HashMap<String, Value> {
|
fn input_data(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId, _input_index: usize) -> HashMap<String, serde_json::Value> {
|
||||||
HashMap::new()
|
HashMap::new()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,12 +98,9 @@ pub trait NodeMetadataSource {
|
|||||||
fn storage_node_id(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Option<crate::NodeId> {
|
fn storage_node_id(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Option<crate::NodeId> {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The definition the network was instantiated from, if it still names one.
|
|
||||||
fn reference(&self, _network_path: &[RuntimeNodeId]) -> Option<&str> {
|
fn reference(&self, _network_path: &[RuntimeNodeId]) -> Option<&str> {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The display order of the network's pinned nodes.
|
/// The display order of the network's pinned nodes.
|
||||||
fn pinned_order(&self, _network_path: &[RuntimeNodeId]) -> Vec<RuntimeNodeId> {
|
fn pinned_order(&self, _network_path: &[RuntimeNodeId]) -> Vec<RuntimeNodeId> {
|
||||||
Vec::new()
|
Vec::new()
|
||||||
|
|||||||
@@ -1,26 +1,13 @@
|
|||||||
use crate::{Attributes, NetworkId, NodeId, ResourceId, TimeStamp, Value, attributes_value_equal};
|
use crate::{Attributes, NetworkId, NodeId, ResourceId, TimeStamp, attributes_value_equal};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::borrow::Cow;
|
use std::borrow::Cow;
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
pub struct Node {
|
pub struct Node {
|
||||||
/// The latest addition or write, so a concurrent removal resolves by stamp; see [`Registry::removed_nodes`](crate::Registry::removed_nodes).
|
|
||||||
#[serde(default)]
|
|
||||||
pub(crate) presence: TimeStamp,
|
|
||||||
pub(crate) network: NetworkId,
|
|
||||||
/// When the node was last added, which decides its network between concurrent additions of one id.
|
|
||||||
#[serde(default)]
|
|
||||||
pub(crate) network_timestamp: TimeStamp,
|
|
||||||
pub(crate) implementation: Implementation,
|
pub(crate) implementation: Implementation,
|
||||||
/// When the implementation was last written, so a swap resolves by last-writer-wins rather than by
|
|
||||||
/// the order ops happen to arrive in. Absent from documents written before swaps were expressible.
|
|
||||||
#[serde(default)]
|
|
||||||
pub(crate) implementation_timestamp: TimeStamp,
|
|
||||||
pub(crate) inputs: Vec<InputSlot>,
|
pub(crate) inputs: Vec<InputSlot>,
|
||||||
/// When the input list last changed shape, so list and slot writes resolve alike in either order.
|
|
||||||
#[serde(default)]
|
|
||||||
pub(crate) inputs_timestamp: TimeStamp,
|
|
||||||
pub(crate) attributes: Attributes,
|
pub(crate) attributes: Attributes,
|
||||||
|
pub(crate) network: NetworkId,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Node {
|
impl Node {
|
||||||
@@ -56,25 +43,14 @@ impl Node {
|
|||||||
attributes_value_equal(&self.attributes, &other.attributes)
|
attributes_value_equal(&self.attributes, &other.attributes)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A node in `network` whose `inputs` slots are unset, for a caller that fills them in with
|
|
||||||
/// `ChangeNodeInput`. The slot count is fixed at creation, since changing an input addresses a
|
|
||||||
/// slot by position.
|
|
||||||
pub fn new(network: NetworkId, implementation: Implementation, inputs: usize) -> Self {
|
|
||||||
Self {
|
|
||||||
presence: TimeStamp::ORIGIN,
|
|
||||||
network_timestamp: TimeStamp::ORIGIN,
|
|
||||||
inputs_timestamp: TimeStamp::ORIGIN,
|
|
||||||
implementation,
|
|
||||||
implementation_timestamp: TimeStamp::ORIGIN,
|
|
||||||
inputs: vec![InputSlot::unset(TimeStamp::ORIGIN); inputs],
|
|
||||||
attributes: Attributes::new(),
|
|
||||||
network,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pub(crate) fn dummy() -> Self {
|
pub(crate) fn dummy() -> Self {
|
||||||
Self::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::new()), 0)
|
Self {
|
||||||
|
implementation: Implementation::ProtoNode(ResourceId::new()),
|
||||||
|
inputs: vec![],
|
||||||
|
attributes: Attributes::new(),
|
||||||
|
network: crate::ROOT_NETWORK,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,22 +63,6 @@ pub struct InputSlot {
|
|||||||
pub attributes: Attributes,
|
pub attributes: Attributes,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl InputSlot {
|
|
||||||
/// A slot holding nothing, stamped `timestamp`.
|
|
||||||
pub fn unset(timestamp: TimeStamp) -> Self {
|
|
||||||
// `to_runtime` reads this back as a `TaggedValue`, whose unit `None` variant encodes as this string.
|
|
||||||
// Pinned by `unset_input_slot_deserializes_as_tagged_value_none`.
|
|
||||||
Self {
|
|
||||||
input: NodeInput::Value {
|
|
||||||
value: Value::Str("None".to_string()),
|
|
||||||
exposed: false,
|
|
||||||
},
|
|
||||||
timestamp,
|
|
||||||
attributes: Attributes::empty_at(timestamp),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
pub enum NodeInput {
|
pub enum NodeInput {
|
||||||
Node {
|
Node {
|
||||||
@@ -110,7 +70,7 @@ pub enum NodeInput {
|
|||||||
index: u32,
|
index: u32,
|
||||||
},
|
},
|
||||||
Value {
|
Value {
|
||||||
value: Value,
|
value: serde_json::Value,
|
||||||
exposed: bool,
|
exposed: bool,
|
||||||
},
|
},
|
||||||
Scope(Cow<'static, str>),
|
Scope(Cow<'static, str>),
|
||||||
@@ -132,13 +92,7 @@ pub enum Implementation {
|
|||||||
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||||
pub struct Network {
|
pub struct Network {
|
||||||
/// The latest addition or write; see [`Node::presence`](crate::Node).
|
|
||||||
#[serde(default)]
|
|
||||||
pub(crate) presence: TimeStamp,
|
|
||||||
pub exports: Vec<ExportSlot>,
|
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
|
/// Per-network `ui::*` state (navigation, previewing). Separate from `Node.attributes` so
|
||||||
/// view-state edits LWW independently.
|
/// view-state edits LWW independently.
|
||||||
pub attributes: Attributes,
|
pub attributes: Attributes,
|
||||||
@@ -166,7 +120,7 @@ impl Network {
|
|||||||
|
|
||||||
/// One positional export slot. `target == None` marks an empty/removed slot. Timestamp drives LWW
|
/// One positional export slot. `target == None` marks an empty/removed slot. Timestamp drives LWW
|
||||||
/// on concurrent `SetExport` ops.
|
/// on concurrent `SetExport` ops.
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
pub struct ExportSlot {
|
pub struct ExportSlot {
|
||||||
pub target: Option<NodeInput>,
|
pub target: Option<NodeInput>,
|
||||||
pub timestamp: TimeStamp,
|
pub timestamp: TimeStamp,
|
||||||
@@ -200,19 +154,6 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `to_runtime` has to read back what `Node::new` writes into an unset slot, so its literal must stay
|
|
||||||
/// in step with how `TaggedValue::None` serializes.
|
|
||||||
#[test]
|
|
||||||
fn unset_input_slot_deserializes_as_tagged_value_none() {
|
|
||||||
let node = Node::new(crate::ROOT_NETWORK, Implementation::Network(crate::ROOT_NETWORK), 1);
|
|
||||||
let NodeInput::Value { value, .. } = &node.inputs()[0].input else {
|
|
||||||
panic!("a fresh slot holds a value input");
|
|
||||||
};
|
|
||||||
|
|
||||||
let tagged: graph_craft::document::value::TaggedValue = crate::from_value(value).expect("the unset slot value must deserialize");
|
|
||||||
assert_eq!(tagged, graph_craft::document::value::TaggedValue::None);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A `SetExport(None)` truncation leaves a trailing empty slot. Such a network is value-equal to
|
/// A `SetExport(None)` truncation leaves a trailing empty slot. Such a network is value-equal to
|
||||||
/// the same network without that slot, so the soak oracle doesn't false-report drift.
|
/// the same network without that slot, so the soak oracle doesn't false-report drift.
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -1,10 +1,7 @@
|
|||||||
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceEntry, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
|
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
/// The live document. Every field, existence included, is last-writer-wins on a timestamp, so the registry depends on the
|
|
||||||
/// set of ops applied and not their order. A removed entity keeps a tombstone: an older op lands on it, a newer one
|
|
||||||
/// revives the entity.
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||||
pub struct Registry {
|
pub struct Registry {
|
||||||
pub node_instances: HashMap<NodeId, Node>,
|
pub node_instances: HashMap<NodeId, Node>,
|
||||||
@@ -12,58 +9,13 @@ pub struct Registry {
|
|||||||
/// Content-addressable resources (images, fonts, eventually proto-node declarations) referenced
|
/// Content-addressable resources (images, fonts, eventually proto-node declarations) referenced
|
||||||
/// by `ResourceId`. See [`ResourceStore`].
|
/// by `ResourceId`. See [`ResourceStore`].
|
||||||
pub resources: ResourceStore,
|
pub resources: ResourceStore,
|
||||||
/// Which person each device is, from `RegistryDelta::RegisterPeer`, so undo and authorship scope by person.
|
/// Append-only mapping from per-device `PeerId` to per-human `UserId`.
|
||||||
pub peer_users: HashMap<PeerId, PeerRegistration>,
|
/// Registered by each device's first contribution via `RegistryDelta::RegisterPeer`.
|
||||||
|
pub peer_users: HashMap<PeerId, UserId>,
|
||||||
pub attributes: Attributes,
|
pub attributes: Attributes,
|
||||||
/// Tombstones of removed nodes, so an op on one is ordered against its removal whichever arrives first.
|
|
||||||
#[serde(default)]
|
|
||||||
pub removed_nodes: HashMap<NodeId, Tombstone<Node>>,
|
|
||||||
/// Tombstones of removed networks; see [`removed_nodes`](Self::removed_nodes).
|
|
||||||
#[serde(default)]
|
|
||||||
pub removed_networks: HashMap<NetworkId, Tombstone<Network>>,
|
|
||||||
/// Tombstones of removed resources; see [`removed_nodes`](Self::removed_nodes).
|
|
||||||
#[serde(default)]
|
|
||||||
pub removed_resources: HashMap<ResourceId, Tombstone<ResourceEntry>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
pub struct PeerRegistration {
|
|
||||||
pub user: UserId,
|
|
||||||
pub timestamp: TimeStamp,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A removed entity's content, for reviving it, and its removal stamp.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
|
||||||
pub struct Tombstone<T> {
|
|
||||||
pub content: T,
|
|
||||||
pub timestamp: TimeStamp,
|
|
||||||
/// Nothing has added the entity yet: it stays dead until an addition folds in, the content holding writes that came first.
|
|
||||||
#[serde(default)]
|
|
||||||
pub placeholder: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Registry {
|
impl Registry {
|
||||||
/// The node under `id`, live or as removed, for a reference to a node the runtime cannot hold.
|
|
||||||
pub(crate) fn node_or_removed(&self, id: NodeId) -> Option<&Node> {
|
|
||||||
self.node_instances.get(&id).or_else(|| self.removed_nodes.get(&id).map(|mark| &mark.content))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The network under `id`, live or as it was when removed.
|
|
||||||
pub(crate) fn network_or_removed(&self, id: NetworkId) -> Option<&Network> {
|
|
||||||
self.networks.get(&id).or_else(|| self.removed_networks.get(&id).map(|mark| &mark.content))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The live entities alone, for a document starting a history of its own: tombstones only order removals against ops
|
|
||||||
/// that share this one.
|
|
||||||
pub fn without_tombstones(&self) -> Registry {
|
|
||||||
Registry {
|
|
||||||
removed_nodes: HashMap::new(),
|
|
||||||
removed_networks: HashMap::new(),
|
|
||||||
removed_resources: HashMap::new(),
|
|
||||||
..self.clone()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// True if both registries agree on every value-bearing field, ignoring per-slot and
|
/// 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
|
/// 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
|
/// state at a stamped slot doesn't count as drift. `peer_users` is excluded: it isn't diffed by
|
||||||
@@ -133,10 +85,10 @@ impl Registry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn attributes_value_equal(a: &Attributes, b: &Attributes) -> bool {
|
pub(crate) fn attributes_value_equal(a: &Attributes, b: &Attributes) -> bool {
|
||||||
if a.live().count() != b.live().count() {
|
if a.len() != b.len() {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
a.live().all(|(key, value)| b.get(key).is_some_and(|other| !other.deleted && value.value == other.value))
|
a.iter().all(|(key, value)| b.get(key).is_some_and(|other| value.value == other.value))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Value-level resource comparison: same resolved hashes and same source chains (keyed by
|
/// Value-level resource comparison: same resolved hashes and same source chains (keyed by
|
||||||
@@ -148,92 +100,54 @@ pub(crate) fn resources_value_equal(a: &ResourceStore, b: &ResourceStore) -> boo
|
|||||||
a.iter().all(|(id, entry)| {
|
a.iter().all(|(id, entry)| {
|
||||||
b.get(id).is_some_and(|other| {
|
b.get(id).is_some_and(|other| {
|
||||||
entry.hash == other.hash
|
entry.hash == other.hash
|
||||||
&& entry.live_sources().count() == other.live_sources().count()
|
&& entry.sources.len() == other.sources.len()
|
||||||
&& entry.live_sources().all(|(key, value)| other.source(key).is_some_and(|other_value| value.source == other_value.source))
|
&& entry.sources.iter().all(|(key, value)| other.source(key).is_some_and(|other_value| value.source == other_value.source))
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Stable identity for any timestamp in a `Registry`, tombstoned content and existence stamps included. Used by
|
/// Stable identity for any timestamped slot in a `Registry`. Used by `order_consistent`.
|
||||||
/// `order_consistent`.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||||
enum TimestampKey {
|
enum TimestampKey {
|
||||||
/// A whole-entity stamp under its field name: presence, a shape or floor, a removal.
|
|
||||||
Node(NodeId, &'static str),
|
|
||||||
NodeInput(NodeId, usize),
|
NodeInput(NodeId, usize),
|
||||||
NodeInputFloor(NodeId, usize),
|
|
||||||
NodeInputAttribute(NodeId, usize, String),
|
NodeInputAttribute(NodeId, usize, String),
|
||||||
NodeAttribute(NodeId, String),
|
NodeAttribute(NodeId, String),
|
||||||
Network(NetworkId, &'static str),
|
|
||||||
NetworkExport(NetworkId, usize),
|
NetworkExport(NetworkId, usize),
|
||||||
NetworkAttribute(NetworkId, String),
|
NetworkAttribute(NetworkId, String),
|
||||||
DocumentAttribute(String),
|
DocumentAttribute(String),
|
||||||
Resource(ResourceId, &'static str),
|
ResourceHash(ResourceId),
|
||||||
ResourceSource(ResourceId, SourceKey),
|
ResourceSource(ResourceId, SourceKey),
|
||||||
Document(&'static str),
|
|
||||||
PeerRegistration(PeerId),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn collect_timestamps(registry: &Registry) -> HashMap<TimestampKey, TimeStamp> {
|
fn collect_timestamps(registry: &Registry) -> HashMap<TimestampKey, TimeStamp> {
|
||||||
let mut out = HashMap::new();
|
let mut out = HashMap::new();
|
||||||
let nodes = registry.node_instances.iter().chain(registry.removed_nodes.iter().map(|(id, mark)| (id, &mark.content)));
|
for (node_id, node) in ®istry.node_instances {
|
||||||
for (&id, node) in nodes {
|
|
||||||
for (field, timestamp) in [
|
|
||||||
("presence", node.presence),
|
|
||||||
("network", node.network_timestamp),
|
|
||||||
("inputs", node.inputs_timestamp),
|
|
||||||
("implementation", node.implementation_timestamp),
|
|
||||||
("attributes", node.attributes.floor()),
|
|
||||||
] {
|
|
||||||
out.insert(TimestampKey::Node(id, field), timestamp);
|
|
||||||
}
|
|
||||||
for (i, slot) in node.inputs.iter().enumerate() {
|
for (i, slot) in node.inputs.iter().enumerate() {
|
||||||
out.insert(TimestampKey::NodeInput(id, i), slot.timestamp);
|
out.insert(TimestampKey::NodeInput(*node_id, i), slot.timestamp);
|
||||||
out.insert(TimestampKey::NodeInputFloor(id, i), slot.attributes.floor());
|
|
||||||
for (key, value) in &slot.attributes {
|
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 {
|
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 (network_id, network) in ®istry.networks {
|
||||||
for (&id, network) in networks {
|
|
||||||
for (field, timestamp) in [("presence", network.presence), ("exports", network.exports_timestamp), ("attributes", network.attributes.floor())] {
|
|
||||||
out.insert(TimestampKey::Network(id, field), timestamp);
|
|
||||||
}
|
|
||||||
for (i, slot) in network.exports.iter().enumerate() {
|
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 {
|
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 {
|
for (key, value) in ®istry.attributes {
|
||||||
out.insert(TimestampKey::DocumentAttribute(key.clone()), value.timestamp);
|
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 ®istry.resources {
|
||||||
for (&id, entry) in resources {
|
out.insert(TimestampKey::ResourceHash(*id), entry.hash_timestamp);
|
||||||
for (field, timestamp) in [("presence", entry.presence), ("hash", entry.hash_timestamp), ("sources", entry.sources_timestamp)] {
|
|
||||||
out.insert(TimestampKey::Resource(id, field), timestamp);
|
|
||||||
}
|
|
||||||
for (source_key, source_value) in &entry.sources {
|
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
|
out
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::{PeerId, TimeStamp, Value, from_value, to_value};
|
use crate::{PeerId, TimeStamp};
|
||||||
use graphene_resource::{ResourceHash, ResourceId};
|
use graphene_resource::{ResourceHash, ResourceId};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
@@ -11,27 +11,13 @@ pub struct SourceKey {
|
|||||||
pub peer: PeerId,
|
pub peer: PeerId,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One entry in a resource's source chain. The `source` body is type-erased (`Value`)
|
/// One entry in a resource's source chain. The `source` body is type-erased (`serde_json::Value`)
|
||||||
/// so the on-disk `DataSource` shape can evolve through migrations without the storage layer
|
/// so the on-disk `DataSource` shape can evolve through migrations without the storage layer
|
||||||
/// committing to a Rust enum; `timestamp` drives LWW on re-setting this same entry.
|
/// committing to a Rust enum; `timestamp` drives LWW on re-setting this same entry.
|
||||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
pub struct SourceValue {
|
pub struct SourceValue {
|
||||||
pub source: Value,
|
pub source: serde_json::Value,
|
||||||
pub timestamp: TimeStamp,
|
pub timestamp: TimeStamp,
|
||||||
/// A removed source stays as a stamped tombstone, which readers see as absent.
|
|
||||||
#[serde(default)]
|
|
||||||
pub deleted: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl SourceValue {
|
|
||||||
/// The tombstone of a source removed at `timestamp`.
|
|
||||||
pub fn deleted(timestamp: TimeStamp) -> Self {
|
|
||||||
Self {
|
|
||||||
source: Value::None,
|
|
||||||
timestamp,
|
|
||||||
deleted: true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A single content-addressable resource: an ordered, conflict-mergeable chain of fallback sources
|
/// A single content-addressable resource: an ordered, conflict-mergeable chain of fallback sources
|
||||||
@@ -40,12 +26,8 @@ impl SourceValue {
|
|||||||
/// resource agree by construction, since the hash is content-derived).
|
/// resource agree by construction, since the hash is content-derived).
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
|
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
|
||||||
pub struct ResourceEntry {
|
pub struct ResourceEntry {
|
||||||
/// The latest addition or write; see [`Node::presence`](crate::Node).
|
|
||||||
pub(crate) presence: TimeStamp,
|
|
||||||
/// Fallback chain kept sorted by `SourceKey`, so iteration yields highest-priority first.
|
/// Fallback chain kept sorted by `SourceKey`, so iteration yields highest-priority first.
|
||||||
pub sources: Vec<(SourceKey, SourceValue)>,
|
pub sources: Vec<(SourceKey, SourceValue)>,
|
||||||
/// When `sources` was last written whole, by an addition; a key the chain lacks is deleted as of then.
|
|
||||||
pub sources_timestamp: TimeStamp,
|
|
||||||
pub hash: Option<ResourceHash>,
|
pub hash: Option<ResourceHash>,
|
||||||
pub hash_timestamp: TimeStamp,
|
pub hash_timestamp: TimeStamp,
|
||||||
}
|
}
|
||||||
@@ -57,22 +39,12 @@ impl<'de> Deserialize<'de> for ResourceEntry {
|
|||||||
// collapse any duplicate keys, keeping the higher-timestamp value (LWW).
|
// collapse any duplicate keys, keeping the higher-timestamp value (LWW).
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct Raw {
|
struct Raw {
|
||||||
#[serde(default)]
|
|
||||||
presence: TimeStamp,
|
|
||||||
sources: Vec<(SourceKey, SourceValue)>,
|
sources: Vec<(SourceKey, SourceValue)>,
|
||||||
#[serde(default)]
|
|
||||||
sources_timestamp: TimeStamp,
|
|
||||||
hash: Option<ResourceHash>,
|
hash: Option<ResourceHash>,
|
||||||
hash_timestamp: TimeStamp,
|
hash_timestamp: TimeStamp,
|
||||||
}
|
}
|
||||||
|
|
||||||
let Raw {
|
let Raw { mut sources, hash, hash_timestamp } = Raw::deserialize(deserializer)?;
|
||||||
presence,
|
|
||||||
mut sources,
|
|
||||||
sources_timestamp,
|
|
||||||
hash,
|
|
||||||
hash_timestamp,
|
|
||||||
} = Raw::deserialize(deserializer)?;
|
|
||||||
sources.sort_by_key(|(a, _)| *a);
|
sources.sort_by_key(|(a, _)| *a);
|
||||||
sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| {
|
sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| {
|
||||||
// `dedup_by` keeps the first of each run; sorting is stable, so resolve duplicates by LWW.
|
// `dedup_by` keeps the first of each run; sorting is stable, so resolve duplicates by LWW.
|
||||||
@@ -85,13 +57,7 @@ impl<'de> Deserialize<'de> for ResourceEntry {
|
|||||||
true
|
true
|
||||||
});
|
});
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self { sources, hash, hash_timestamp })
|
||||||
presence,
|
|
||||||
sources,
|
|
||||||
sources_timestamp,
|
|
||||||
hash,
|
|
||||||
hash_timestamp,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,91 +66,54 @@ impl ResourceEntry {
|
|||||||
/// source entry and the resolved hash carry `timestamp` so later LWW writes order against it.
|
/// source entry and the resolved hash carry `timestamp` so later LWW writes order against it.
|
||||||
/// The bytes themselves are persisted separately by the caller's byte store.
|
/// The bytes themselves are persisted separately by the caller's byte store.
|
||||||
pub fn embedded(hash: ResourceHash, peer: PeerId, timestamp: TimeStamp) -> Self {
|
pub fn embedded(hash: ResourceHash, peer: PeerId, timestamp: TimeStamp) -> Self {
|
||||||
let embedded = to_value(&graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
|
let embedded = serde_json::to_value(graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
|
||||||
let priority = Priority::new(0.).expect("0. is finite");
|
let priority = Priority::new(0.).expect("0. is finite");
|
||||||
let sources = vec![(
|
let sources = vec![(SourceKey { priority, peer }, SourceValue { source: embedded, timestamp })];
|
||||||
SourceKey { priority, peer },
|
|
||||||
SourceValue {
|
|
||||||
source: embedded,
|
|
||||||
timestamp,
|
|
||||||
deleted: false,
|
|
||||||
},
|
|
||||||
)];
|
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
presence: timestamp,
|
|
||||||
sources,
|
sources,
|
||||||
sources_timestamp: timestamp,
|
|
||||||
hash: Some(hash),
|
hash: Some(hash),
|
||||||
hash_timestamp: timestamp,
|
hash_timestamp: timestamp,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The live source stored under `key`, if any; a tombstone is absent.
|
/// The source body and timestamp stored under `key`, if any.
|
||||||
pub fn source(&self, key: &SourceKey) -> Option<&SourceValue> {
|
pub fn source(&self, key: &SourceKey) -> Option<&SourceValue> {
|
||||||
self.find(key).ok().map(|index| &self.sources[index].1).filter(|value| !value.deleted)
|
self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)).ok().map(|index| &self.sources[index].1)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The live sources in precedence order, tombstones skipped.
|
/// Insert or LWW-overwrite the entry at `key`. A re-set at an existing key wins only if `value`'s
|
||||||
pub(crate) fn live_sources(&self) -> impl Iterator<Item = (&SourceKey, &SourceValue)> {
|
/// timestamp is strictly newer; a fresh key is inserted in sorted position.
|
||||||
self.sources.iter().filter(|(_, value)| !value.deleted).map(|(key, value)| (key, value))
|
pub fn set_source(&mut self, key: SourceKey, value: SourceValue) {
|
||||||
|
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
|
||||||
|
Ok(index) => {
|
||||||
|
if value.timestamp > self.sources[index].1.timestamp {
|
||||||
|
self.sources[index].1 = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(index) => self.sources.insert(index, (key, value)),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn find(&self, key: &SourceKey) -> Result<usize, usize> {
|
/// Like [`set_source`](Self::set_source) but assigns unconditionally (silent-zone rewind), where the
|
||||||
self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key))
|
/// precomputed reverse/forward value is authoritative even if its timestamp ties what it replaces.
|
||||||
}
|
pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) {
|
||||||
|
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
|
||||||
/// The stamp that decides a write to `key`: its entry's, tombstone included, or the chain's floor.
|
|
||||||
fn deciding_timestamp(&self, key: &SourceKey) -> TimeStamp {
|
|
||||||
self.find(key).map_or(self.sources_timestamp, |index| self.sources[index].1.timestamp)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn put(&mut self, key: SourceKey, value: SourceValue) {
|
|
||||||
match self.find(&key) {
|
|
||||||
Ok(index) => self.sources[index].1 = value,
|
Ok(index) => self.sources[index].1 = value,
|
||||||
Err(index) => self.sources.insert(index, (key, value)),
|
Err(index) => self.sources.insert(index, (key, value)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Writes the chain whole at `timestamp`: the floor deletes every other key without a tombstone per key.
|
/// Remove the entry at `key` if its timestamp is strictly older than `timestamp` (LWW). Returns
|
||||||
pub(crate) fn stamp_sources(&mut self, timestamp: TimeStamp) {
|
/// whether anything was removed.
|
||||||
self.sources.retain(|(_, value)| !value.deleted);
|
|
||||||
self.sources.iter_mut().for_each(|(_, value)| value.timestamp = timestamp);
|
|
||||||
self.sources_timestamp = timestamp;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Folds another chain in key by key, as attribute maps merge.
|
|
||||||
pub(crate) fn merge_sources(&mut self, other: Vec<(SourceKey, SourceValue)>, other_floor: TimeStamp) {
|
|
||||||
self.sources.retain(|(_, value)| value.timestamp >= other_floor);
|
|
||||||
for (key, value) in other {
|
|
||||||
match self.find(&key) {
|
|
||||||
Ok(index) if value.timestamp > self.sources[index].1.timestamp => self.sources[index].1 = value,
|
|
||||||
Err(index) if value.timestamp >= self.sources_timestamp => self.sources.insert(index, (key, value)),
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
self.sources_timestamp = self.sources_timestamp.max(other_floor);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Insert or LWW-overwrite the entry at `key`; a re-set wins only with a strictly newer stamp.
|
|
||||||
pub fn set_source(&mut self, key: SourceKey, value: SourceValue) {
|
|
||||||
if value.timestamp > self.deciding_timestamp(&key) {
|
|
||||||
self.put(key, value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Like [`set_source`](Self::set_source) but assigns unconditionally (silent-zone rewind, or building an entry).
|
|
||||||
pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) {
|
|
||||||
self.put(key, value);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Remove the source at `key` if `timestamp` is newer than what decides it, leaving a tombstone. Returns whether it landed.
|
|
||||||
pub fn remove_source(&mut self, key: &SourceKey, timestamp: TimeStamp) -> bool {
|
pub fn remove_source(&mut self, key: &SourceKey, timestamp: TimeStamp) -> bool {
|
||||||
if timestamp <= self.deciding_timestamp(key) {
|
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)) {
|
||||||
return false;
|
Ok(index) if timestamp > self.sources[index].1.timestamp => {
|
||||||
|
self.sources.remove(index);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
_ => false,
|
||||||
}
|
}
|
||||||
self.put(*key, SourceValue::deleted(timestamp));
|
|
||||||
true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Like [`remove_source`](Self::remove_source) but removes unconditionally (silent-zone rewind).
|
/// Like [`remove_source`](Self::remove_source) but removes unconditionally (silent-zone rewind).
|
||||||
@@ -201,14 +130,18 @@ impl ResourceEntry {
|
|||||||
/// True if the chain already carries a `DataSource::Embedded` source. Decodes each source body into
|
/// 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.
|
/// `DataSource` so a shape change in the serialized form can't slip an embedded source past detection.
|
||||||
pub fn has_embedded_source(&self) -> bool {
|
pub fn has_embedded_source(&self) -> bool {
|
||||||
self.live_sources()
|
self.sources.iter().any(|(_, value)| {
|
||||||
.any(|(_, value)| matches!(from_value::<graphene_resource::DataSource>(&value.source), Ok(graphene_resource::DataSource::Embedded)))
|
matches!(
|
||||||
|
serde_json::from_value::<graphene_resource::DataSource>(value.source.clone()),
|
||||||
|
Ok(graphene_resource::DataSource::Embedded)
|
||||||
|
)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A `SourceKey` ordered strictly ahead of every current source, so an inserted entry becomes the
|
/// A `SourceKey` ordered strictly ahead of every current source, so an inserted entry becomes the
|
||||||
/// highest-precedence fallback.
|
/// highest-precedence fallback.
|
||||||
pub fn highest_precedence_key(&self, peer: PeerId) -> SourceKey {
|
pub fn highest_precedence_key(&self, peer: PeerId) -> SourceKey {
|
||||||
let min_priority = self.live_sources().next().map(|(key, _)| key.priority.value()).unwrap_or(0.);
|
let min_priority = self.sources.first().map(|(key, _)| key.priority.value()).unwrap_or(0.);
|
||||||
SourceKey {
|
SourceKey {
|
||||||
priority: Priority::new(min_priority - 1.).expect("finite priority minus one is finite"),
|
priority: Priority::new(min_priority - 1.).expect("finite priority minus one is finite"),
|
||||||
peer,
|
peer,
|
||||||
@@ -292,15 +225,15 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Deserialization routes through `Priority::new`, so a non-finite value on disk is rejected rather
|
/// Deserialization routes through `Priority::new`, so a non-finite value on disk is rejected rather
|
||||||
/// than silently producing an unsound map key. Postcard (the storage format) can carry a
|
/// than silently producing an unsound map key. MessagePack (the storage format) can carry a
|
||||||
/// non-finite `f64`, unlike JSON, so this guards the real round-trip path.
|
/// non-finite `f64`, unlike JSON, so this guards the real round-trip path.
|
||||||
#[test]
|
#[test]
|
||||||
fn priority_deserialize_validates_finiteness() {
|
fn priority_deserialize_validates_finiteness() {
|
||||||
let finite = postcard::to_stdvec(&3.5_f64).unwrap();
|
let finite = rmp_serde::to_vec(&3.5_f64).unwrap();
|
||||||
assert!(postcard::from_bytes::<Priority>(&finite).is_ok());
|
assert!(rmp_serde::from_slice::<Priority>(&finite).is_ok());
|
||||||
|
|
||||||
let non_finite = postcard::to_stdvec(&f64::INFINITY).unwrap();
|
let non_finite = rmp_serde::to_vec(&f64::INFINITY).unwrap();
|
||||||
assert!(postcard::from_bytes::<Priority>(&non_finite).is_err(), "a non-finite priority on disk must be rejected");
|
assert!(rmp_serde::from_slice::<Priority>(&non_finite).is_err(), "a non-finite priority on disk must be rejected");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `ResourceEntry`'s accessors rely on `sources` being sorted by `SourceKey`. Deserializing an
|
/// `ResourceEntry`'s accessors rely on `sources` being sorted by `SourceKey`. Deserializing an
|
||||||
@@ -315,23 +248,20 @@ mod tests {
|
|||||||
peer: PeerId(1),
|
peer: PeerId(1),
|
||||||
},
|
},
|
||||||
SourceValue {
|
SourceValue {
|
||||||
source: Value::Float(priority),
|
source: serde_json::json!(priority),
|
||||||
timestamp: TimeStamp::ORIGIN,
|
timestamp: TimeStamp::ORIGIN,
|
||||||
deleted: false,
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
// Build a deliberately unsorted chain as a literal (bypassing the sorted-insert API), then round-trip it through `Value`.
|
// Serialize a deliberately unsorted chain through the raw shape, then deserialize as `ResourceEntry`.
|
||||||
let unsorted = ResourceEntry {
|
let unsorted = serde_json::json!({
|
||||||
presence: TimeStamp::ORIGIN,
|
"sources": [source(2.), source(0.), source(1.)],
|
||||||
sources_timestamp: TimeStamp::ORIGIN,
|
"hash": null,
|
||||||
sources: vec![source(2.), source(0.), source(1.)],
|
"hash_timestamp": TimeStamp::ORIGIN,
|
||||||
hash: None,
|
});
|
||||||
hash_timestamp: TimeStamp::ORIGIN,
|
|
||||||
};
|
|
||||||
|
|
||||||
let entry: ResourceEntry = from_value(&to_value(&unsorted).expect("serialize")).expect("deserialize");
|
let entry: ResourceEntry = serde_json::from_value(unsorted).expect("deserialize");
|
||||||
let priorities: Vec<f64> = entry.sources.iter().map(|(key, _)| key.priority.value()).collect();
|
let priorities: Vec<f64> = entry.sources.iter().map(|(key, _)| key.priority.value()).collect();
|
||||||
assert_eq!(priorities, vec![0., 1., 2.], "sources must be sorted by SourceKey after deserialization");
|
assert_eq!(priorities, vec![0., 1., 2.], "sources must be sorted by SourceKey after deserialization");
|
||||||
}
|
}
|
||||||
@@ -348,23 +278,20 @@ mod tests {
|
|||||||
(
|
(
|
||||||
key,
|
key,
|
||||||
SourceValue {
|
SourceValue {
|
||||||
source: Value::Str(body.into()),
|
source: serde_json::json!(body),
|
||||||
timestamp: TimeStamp { counter, peer: PeerId(1) },
|
timestamp: TimeStamp { counter, peer: PeerId(1) },
|
||||||
deleted: false,
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
let with_duplicates = ResourceEntry {
|
let with_duplicates = serde_json::json!({
|
||||||
presence: TimeStamp::ORIGIN,
|
"sources": [entry(5, "newer"), entry(1, "older")],
|
||||||
sources_timestamp: TimeStamp::ORIGIN,
|
"hash": null,
|
||||||
sources: vec![entry(5, "newer"), entry(1, "older")],
|
"hash_timestamp": TimeStamp::ORIGIN,
|
||||||
hash: None,
|
});
|
||||||
hash_timestamp: TimeStamp::ORIGIN,
|
|
||||||
};
|
|
||||||
|
|
||||||
let resource: ResourceEntry = from_value(&to_value(&with_duplicates).expect("serialize")).expect("deserialize");
|
let resource: ResourceEntry = serde_json::from_value(with_duplicates).expect("deserialize");
|
||||||
assert_eq!(resource.sources.len(), 1, "duplicate keys must collapse to one entry");
|
assert_eq!(resource.sources.len(), 1, "duplicate keys must collapse to one entry");
|
||||||
assert_eq!(resource.sources[0].1.source, Value::Str("newer".into()), "the higher-timestamp value must win");
|
assert_eq!(resource.sources[0].1.source, serde_json::json!("newer"), "the higher-timestamp value must win");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,9 +2,7 @@
|
|||||||
use crate::NodeMetadataSource;
|
use crate::NodeMetadataSource;
|
||||||
#[cfg(any(feature = "conversion", test))]
|
#[cfg(any(feature = "conversion", test))]
|
||||||
use crate::from_runtime;
|
use crate::from_runtime;
|
||||||
use crate::{
|
use crate::{ApplyMode, Delta, Document, History, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId};
|
||||||
ApplyMode, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId, Value, to_value,
|
|
||||||
};
|
|
||||||
use graphene_resource::{ResourceHash, ResourceId};
|
use graphene_resource::{ResourceHash, ResourceId};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::{HashMap, HashSet};
|
||||||
@@ -29,15 +27,22 @@ impl Session {
|
|||||||
Self::with_peer(PeerId(core_types::uuid::generate_uuid()))
|
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.
|
/// Construct a session bound to a specific `PeerId`. Used by tests; production code wants
|
||||||
|
/// `Session::new`.
|
||||||
pub fn with_peer(peer: PeerId) -> Self {
|
pub fn with_peer(peer: PeerId) -> Self {
|
||||||
Self::with_identity(peer, UserId(peer.0))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A session for device `peer` used by person `user`, whom its registration records.
|
|
||||||
pub fn with_identity(peer: PeerId, user: UserId) -> Self {
|
|
||||||
Self {
|
Self {
|
||||||
document: Document::empty(peer, user),
|
document: Document {
|
||||||
|
working_registry: Registry::default(),
|
||||||
|
retired_snapshot: Registry::default(),
|
||||||
|
history: History::new(),
|
||||||
|
hot_log: Vec::new(),
|
||||||
|
head: None,
|
||||||
|
redo_stack: Vec::new(),
|
||||||
|
clock: LamportClock::new(peer),
|
||||||
|
peer,
|
||||||
|
last_broadcast_rev: None,
|
||||||
|
next_node_counter: 0,
|
||||||
|
},
|
||||||
remote_tips: HashMap::new(),
|
remote_tips: HashMap::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -46,15 +51,6 @@ impl Session {
|
|||||||
self.document.peer
|
self.document.peer
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn user(&self) -> UserId {
|
|
||||||
self.document.user
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn user_of(&self, peer: PeerId) -> Option<UserId> {
|
|
||||||
let registered = || self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user);
|
|
||||||
(peer == self.document.peer).then_some(self.document.user).or_else(registered)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn registry(&self) -> &Registry {
|
pub fn registry(&self) -> &Registry {
|
||||||
&self.document.working_registry
|
&self.document.working_registry
|
||||||
}
|
}
|
||||||
@@ -68,7 +64,8 @@ impl Session {
|
|||||||
/// Diff the current registry against a fresh conversion of `network`, then commit each emitted
|
/// Diff the current registry against a fresh conversion of `network`, then commit each emitted
|
||||||
/// op as its own `Delta` on the local chain. One `clock.tick()` per op (strictly causal within
|
/// op as its own `Delta` on the local chain. One `clock.tick()` per op (strictly causal within
|
||||||
/// a commit). Returns the new `Rev`s in commit order (empty if nothing changed) plus the
|
/// a commit). Returns the new `Rev`s in commit order (empty if nothing changed) plus the
|
||||||
/// conversion, whose extracted declarations the caller persists and caches.
|
/// proto-node declaration bytes the conversion extracted, keyed by content hash, for the caller
|
||||||
|
/// to persist into its byte store (`document-graph-storage` itself is byte-unaware).
|
||||||
///
|
///
|
||||||
/// Stages the diff as hot ops rather than retired deltas: each op is applied to the registry and
|
/// Stages the diff as hot ops rather than retired deltas: each op is applied to the registry and
|
||||||
/// pushed onto the hot log. The caller persists the returned hot frames and then calls `retire`
|
/// pushed onto the hot log. The caller persists the returned hot frames and then calls `retire`
|
||||||
@@ -79,11 +76,11 @@ impl Session {
|
|||||||
network: &graph_craft::document::NodeNetwork,
|
network: &graph_craft::document::NodeNetwork,
|
||||||
metadata: &M,
|
metadata: &M,
|
||||||
resources: &graphene_resource::ResourceRegistry,
|
resources: &graphene_resource::ResourceRegistry,
|
||||||
) -> Result<(Vec<HotOp>, from_runtime::RuntimeConversion), CommitError> {
|
) -> Result<(Vec<HotOp>, from_runtime::DeclarationBytes), CommitError> {
|
||||||
let conversion = Registry::convert_from_runtime(network, metadata, resources, self.document.peer)?;
|
let conversion = Registry::convert_from_runtime(network, metadata, resources, self.document.peer)?;
|
||||||
let ops = crate::delta::compute_deltas(&self.document.working_registry, &conversion.registry);
|
let ops = crate::delta::compute_deltas(&self.document.working_registry, &conversion.registry);
|
||||||
let hot_ops = self.stage_ops(ops)?;
|
let hot_ops = self.stage_ops(ops)?;
|
||||||
Ok((hot_ops, conversion))
|
Ok((hot_ops, conversion.declaration_bytes))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Resolve each runtime `network_path` to its stable [`NetworkId`] for this document's peer, so the
|
/// Resolve each runtime `network_path` to its stable [`NetworkId`] for this document's peer, so the
|
||||||
@@ -108,7 +105,7 @@ impl Session {
|
|||||||
/// Used on a throwaway session clone at export time so the exported registry and history agree;
|
/// Used on a throwaway session clone at export time so the exported registry and history agree;
|
||||||
/// callers must guarantee the bytes are available in the export's resource store.
|
/// callers must guarantee the bytes are available in the export's resource store.
|
||||||
pub fn embed_resource_sources(&mut self, ids: impl IntoIterator<Item = ResourceId>) -> Result<Vec<Rev>, CrdtError> {
|
pub fn embed_resource_sources(&mut self, ids: impl IntoIterator<Item = ResourceId>) -> Result<Vec<Rev>, CrdtError> {
|
||||||
let embedded = to_value(&graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
|
let embedded = serde_json::to_value(graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
|
||||||
|
|
||||||
let mut ops = Vec::new();
|
let mut ops = Vec::new();
|
||||||
for id in ids {
|
for id in ids {
|
||||||
@@ -144,45 +141,25 @@ impl Session {
|
|||||||
///
|
///
|
||||||
/// The peer's first contribution is preceded by a `RegisterPeer` op, so the device's
|
/// The peer's first contribution is preceded by a `RegisterPeer` op, so the device's
|
||||||
/// `PeerId → UserId` mapping is established (and, under causal delivery, observed by other peers)
|
/// `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.
|
/// before any of its edits. A no-op batch doesn't register — registration rides a real edit.
|
||||||
pub(crate) fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
|
fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
|
||||||
// A batch is staged whole or not at all.
|
|
||||||
let mut pending: Vec<RegistryDelta> = ops.into_iter().collect();
|
let mut pending: Vec<RegistryDelta> = ops.into_iter().collect();
|
||||||
if pending.is_empty() {
|
if pending.is_empty() {
|
||||||
return Ok(Vec::new());
|
return Ok(Vec::new());
|
||||||
}
|
}
|
||||||
|
|
||||||
let (peer, user) = (self.document.peer, self.document.user);
|
if !self.document.working_registry.peer_users.contains_key(&self.document.peer) {
|
||||||
if self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user) != Some(user) {
|
let user = UserId(self.document.peer.0);
|
||||||
pending.insert(0, RegistryDelta::RegisterPeer { peer, user });
|
pending.insert(0, RegistryDelta::RegisterPeer { peer: self.document.peer, user });
|
||||||
}
|
}
|
||||||
|
|
||||||
// A reused sequence would fall under the retired marks, so a batch running past the end is refused.
|
|
||||||
if self.document.last_hot_sequence.0.checked_add(pending.len() as u64).is_none() {
|
|
||||||
return Err(CrdtError::SequencesExhausted);
|
|
||||||
}
|
|
||||||
|
|
||||||
let sequence_before = self.document.last_hot_sequence;
|
|
||||||
let mut staged = Vec::with_capacity(pending.len());
|
let mut staged = Vec::with_capacity(pending.len());
|
||||||
for op in pending {
|
for op in pending {
|
||||||
let sequence = HotSequence(self.document.last_hot_sequence.0 + 1);
|
|
||||||
let hot_op = HotOp {
|
let hot_op = HotOp {
|
||||||
op,
|
op,
|
||||||
timestamp: self.document.clock.tick(),
|
timestamp: self.document.clock.tick(),
|
||||||
sequence,
|
|
||||||
};
|
};
|
||||||
if let Err(error) = self.document.stage_hot_op(hot_op.clone(), ApplyMode::Strict) {
|
self.document.apply_hot_op(hot_op.clone())?;
|
||||||
// The run continues where it was, so no sequence goes unused.
|
|
||||||
self.document.last_hot_sequence = sequence_before;
|
|
||||||
if !staged.is_empty() {
|
|
||||||
let taken: HashSet<HotOpId> = staged.iter().map(HotOp::id).collect();
|
|
||||||
self.document.hot_log.retain(|hot_op| !taken.contains(&hot_op.id()));
|
|
||||||
self.document.resync_hot_timestamps();
|
|
||||||
self.document.rebuild_working();
|
|
||||||
}
|
|
||||||
return Err(error);
|
|
||||||
}
|
|
||||||
self.document.last_hot_sequence = sequence;
|
|
||||||
staged.push(hot_op);
|
staged.push(hot_op);
|
||||||
}
|
}
|
||||||
Ok(staged)
|
Ok(staged)
|
||||||
@@ -190,23 +167,19 @@ impl Session {
|
|||||||
|
|
||||||
/// Wrap each op as a `Delta`, apply it, and chain it onto the local history. One tick per op.
|
/// 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
|
/// Operates on the *retired snapshot*: reverses are computed against and forward ops applied to it,
|
||||||
/// reflects the ops, staged before retirement or equal to the snapshot when nothing is hot.
|
/// so each `reverse` captures the true pre-op value rather than the hot-polluted working state. The
|
||||||
|
/// working registry already reflects these ops (they were staged as hot ops before retirement, or
|
||||||
|
/// equal the snapshot when there are none), so it is left untouched.
|
||||||
///
|
///
|
||||||
/// `idempotent`: pass `true` when the snapshot already reflects the op (retirement of an already-
|
/// `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.
|
/// applied hot op) so duplicate structural inserts no-op rather than error.
|
||||||
fn commit_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>, idempotent: bool) -> Result<Vec<Rev>, CrdtError> {
|
fn commit_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>, idempotent: bool) -> Result<Vec<Rev>, CrdtError> {
|
||||||
self.commit_ops_authored_at(ops.into_iter().map(|op| (op, None)), idempotent)
|
let target = RegistryTarget::Snapshot;
|
||||||
}
|
|
||||||
|
|
||||||
/// [`commit_ops`](Self::commit_ops) for ops paired with their authored stamp (`None` to mint one), which retirement keeps
|
|
||||||
/// so LWW resolves as it did live.
|
|
||||||
fn commit_ops_authored_at(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Option<TimeStamp>)>, idempotent: bool) -> Result<Vec<Rev>, CrdtError> {
|
|
||||||
let target = RegistryTarget::Retired;
|
|
||||||
let ops = ops.into_iter();
|
let ops = ops.into_iter();
|
||||||
let mut produced = Vec::with_capacity(ops.size_hint().0);
|
let mut produced = Vec::with_capacity(ops.size_hint().0);
|
||||||
|
|
||||||
for (op, authored_at) in ops {
|
for op in ops {
|
||||||
// A new edit abandons any undone-forward branch: those revs stay in the DAG but are no
|
// A new edit abandons any undone-forward branch: those revs stay in the DAG but are no
|
||||||
// longer reachable via redo. (Mirrors the legacy editor clearing its redo history on
|
// longer reachable via redo. (Mirrors the legacy editor clearing its redo history on
|
||||||
// commit.) Done on the first real op so a no-op commit doesn't silently disable redo.
|
// commit.) Done on the first real op so a no-op commit doesn't silently disable redo.
|
||||||
@@ -215,9 +188,9 @@ impl Session {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let reverse = self.document.compute_reverse_delta(target, &op)?;
|
let reverse = self.document.compute_reverse_delta(target, &op)?;
|
||||||
let timestamp = authored_at.unwrap_or_else(|| self.document.clock.tick());
|
let timestamp = self.document.clock.tick();
|
||||||
let parent = self.document.head;
|
let parent = self.document.head;
|
||||||
let author = timestamp.peer;
|
let author = self.document.peer;
|
||||||
|
|
||||||
let delta = Delta::new(parent, author, timestamp, op, reverse);
|
let delta = Delta::new(parent, author, timestamp, op, reverse);
|
||||||
let rev = delta.id;
|
let rev = delta.id;
|
||||||
@@ -228,7 +201,7 @@ impl Session {
|
|||||||
{
|
{
|
||||||
return Err(CrdtError::NotFoundInHistory(parent));
|
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.apply_op_with(target, delta.kind.clone(), delta.timestamp, mode)?;
|
||||||
self.document.history.push(delta);
|
self.document.history.push(delta);
|
||||||
self.document.head = Some(rev);
|
self.document.head = Some(rev);
|
||||||
@@ -241,7 +214,7 @@ impl Session {
|
|||||||
/// Wrap an already-materialized snapshot. Trusts `registry` to match `history`; advances the
|
/// Wrap an already-materialized snapshot. Trusts `registry` to match `history`; advances the
|
||||||
/// clock past every observed timestamp but does not re-apply ops. `history` is taken in on-disk
|
/// clock past every observed timestamp but does not re-apply ops. `history` is taken in on-disk
|
||||||
/// (topological) order.
|
/// (topological) order.
|
||||||
pub fn load(peer: PeerId, user: UserId, registry: Registry, history: Vec<Delta>, head: Option<Rev>, redo_stack: Vec<Rev>, next_node_counter: u64) -> Self {
|
pub fn load(peer: PeerId, registry: Registry, history: Vec<Delta>, head: Option<Rev>, redo_stack: Vec<Rev>, next_node_counter: u64) -> Self {
|
||||||
let mut clock = LamportClock::new(peer);
|
let mut clock = LamportClock::new(peer);
|
||||||
for delta in &history {
|
for delta in &history {
|
||||||
clock.observe(delta.timestamp);
|
clock.observe(delta.timestamp);
|
||||||
@@ -254,11 +227,13 @@ impl Session {
|
|||||||
retired_snapshot: registry.clone(),
|
retired_snapshot: registry.clone(),
|
||||||
working_registry: registry,
|
working_registry: registry,
|
||||||
history: History::from_ordered(history),
|
history: History::from_ordered(history),
|
||||||
|
hot_log: Vec::new(),
|
||||||
head,
|
head,
|
||||||
redo_stack,
|
redo_stack,
|
||||||
clock,
|
clock,
|
||||||
|
peer,
|
||||||
|
last_broadcast_rev: None,
|
||||||
next_node_counter,
|
next_node_counter,
|
||||||
..Document::empty(peer, user)
|
|
||||||
},
|
},
|
||||||
remote_tips: HashMap::new(),
|
remote_tips: HashMap::new(),
|
||||||
}
|
}
|
||||||
@@ -266,8 +241,8 @@ impl Session {
|
|||||||
|
|
||||||
/// Rebuild the registry from scratch by applying every delta in causal order.
|
/// Rebuild the registry from scratch by applying every delta in causal order.
|
||||||
/// `deltas` must be in causal order (every parent before its children).
|
/// `deltas` must be in causal order (every parent before its children).
|
||||||
pub fn replay_from_history(peer: PeerId, user: UserId, deltas: impl IntoIterator<Item = Delta>, next_node_counter: u64) -> Result<Self, CrdtError> {
|
pub fn replay_from_history(peer: PeerId, deltas: impl IntoIterator<Item = Delta>, next_node_counter: u64) -> Result<Self, CrdtError> {
|
||||||
let mut session = Self::with_identity(peer, user);
|
let mut session = Self::with_peer(peer);
|
||||||
session.document.next_node_counter = next_node_counter;
|
session.document.next_node_counter = next_node_counter;
|
||||||
|
|
||||||
for delta in deltas {
|
for delta in deltas {
|
||||||
@@ -282,14 +257,9 @@ impl Session {
|
|||||||
Ok(session)
|
Ok(session)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Which hot ops are done with, for a peer catching up and for persisting. See [`RetiredMarks`].
|
/// Apply a hot op without going through the broadcast stream.
|
||||||
pub fn retired_marks(&self) -> &RetiredMarks {
|
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
|
||||||
&self.document.retired
|
self.document.apply_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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
|
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
|
||||||
@@ -330,44 +300,25 @@ impl Session {
|
|||||||
Ok(Some(merge_rev))
|
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.
|
/// Promote hot ops with timestamp `≤ up_to` into retired deltas, re-applied with fresh
|
||||||
pub fn snapshot_from_history(&self) -> Result<Registry, CrdtError> {
|
/// retirement timestamps so LWW arms bump field timestamps to `T_retire`.
|
||||||
let reachable = self.document.history.ancestors(self.document.head);
|
|
||||||
let mut scratch = Document::empty(self.document.peer, self.document.user);
|
|
||||||
for delta in self.document.history.iter().filter(|delta| reachable.contains(&delta.id)) {
|
|
||||||
scratch.apply_op_with(RegistryTarget::Working, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
|
|
||||||
}
|
|
||||||
Ok(scratch.working_registry)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn history_len(&self) -> usize {
|
|
||||||
self.document.history.len()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The hot ops stamped at or before `up_to`, which [`retire`](Self::retire) drains.
|
|
||||||
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.
|
|
||||||
///
|
///
|
||||||
/// One retired delta per hot op.
|
/// Today: one retired delta per hot op. Coarsening is a future step.
|
||||||
pub fn retire_hot_ops(&mut self, ids: &[HotOpId]) -> Result<Vec<Rev>, CrdtError> {
|
|
||||||
let wanted: HashSet<HotOpId> = ids.iter().copied().collect();
|
|
||||||
let (drained, kept): (Vec<HotOp>, Vec<HotOp>) = self.document.hot_log.drain(..).partition(|hot_op| wanted.contains(&hot_op.id()));
|
|
||||||
self.document.hot_log = kept;
|
|
||||||
self.document.resync_hot_timestamps();
|
|
||||||
self.document.retired.extend(drained.iter().map(HotOp::id));
|
|
||||||
|
|
||||||
let ops = drained.into_iter().map(|hot_op| (hot_op.op, Some(hot_op.timestamp)));
|
|
||||||
self.commit_ops_authored_at(ops, true)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Promote every hot op stamped at or before `up_to`, whatever its author.
|
|
||||||
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, CrdtError> {
|
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, CrdtError> {
|
||||||
let ids = self.hot_ops_up_to(up_to);
|
let mut drained = Vec::new();
|
||||||
self.retire_hot_ops(&ids)
|
let mut remaining = Vec::with_capacity(self.document.hot_log.len());
|
||||||
|
for hot_op in self.document.hot_log.drain(..) {
|
||||||
|
if hot_op.timestamp <= up_to {
|
||||||
|
drained.push(hot_op);
|
||||||
|
} else {
|
||||||
|
remaining.push(hot_op);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.document.hot_log = remaining;
|
||||||
|
|
||||||
|
self.commit_ops(drained.into_iter().map(|hot_op| hot_op.op), true)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Mark a retired delta as the end of a user interaction, so the undo cursor treats it as a checkpoint.
|
/// Mark a retired delta as the end of a user interaction, so the undo cursor treats it as a checkpoint.
|
||||||
/// Called once per interaction by the editor-facing commit path (not by resource/internal commits).
|
/// Called once per interaction by the editor-facing commit path (not by resource/internal commits).
|
||||||
pub fn mark_interaction_end(&mut self, rev: Rev) {
|
pub fn mark_interaction_end(&mut self, rev: Rev) {
|
||||||
@@ -378,7 +329,7 @@ impl Session {
|
|||||||
/// Low-level: set a local annotation attribute (e.g. a commit message) on a retired delta in place.
|
/// Low-level: set a local annotation attribute (e.g. a commit message) on a retired delta in place.
|
||||||
/// Excluded from the delta's content-addressed `Rev`, so identity is unchanged. Returns whether the
|
/// Excluded from the delta's content-addressed `Rev`, so identity is unchanged. Returns whether the
|
||||||
/// delta was found. The `Gdd` layer re-persists the affected history frame after calling this.
|
/// delta was found. The `Gdd` layer re-persists the affected history frame after calling this.
|
||||||
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: Value) -> bool {
|
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: serde_json::Value) -> bool {
|
||||||
let timestamp = self.document.clock.tick();
|
let timestamp = self.document.clock.tick();
|
||||||
self.document.history.annotate(rev, key, value, timestamp)
|
self.document.history.annotate(rev, key, value, timestamp)
|
||||||
}
|
}
|
||||||
@@ -483,9 +434,9 @@ impl Session {
|
|||||||
|
|
||||||
/// Build a synthetic linear history whose replay reproduces `registry`. Each op gets a
|
/// Build a synthetic linear history whose replay reproduces `registry`. Each op gets a
|
||||||
/// freshly-ticked clock timestamp and chains to the previous op's `Rev`.
|
/// freshly-ticked clock timestamp and chains to the previous op's `Rev`.
|
||||||
pub fn bootstrap_from_registry(peer: PeerId, user: UserId, registry: Registry) -> Result<Self, CrdtError> {
|
pub fn bootstrap_from_registry(peer: PeerId, registry: Registry) -> Result<Self, CrdtError> {
|
||||||
let ops = crate::delta::compute_deltas(&Registry::default(), ®istry);
|
let ops = crate::delta::compute_deltas(&Registry::default(), ®istry);
|
||||||
let mut session = Self::with_identity(peer, user);
|
let mut session = Self::with_peer(peer);
|
||||||
session.commit_ops(ops, false)?;
|
session.commit_ops(ops, false)?;
|
||||||
// No hot ops on this path, so the working registry must mirror the freshly-built snapshot.
|
// No hot ops on this path, so the working registry must mirror the freshly-built snapshot.
|
||||||
session.document.working_registry = session.document.retired_snapshot.clone();
|
session.document.working_registry = session.document.retired_snapshot.clone();
|
||||||
@@ -513,45 +464,19 @@ impl Session {
|
|||||||
/// interaction's `AddResource` from the working registry, so a redoable (or re-undoable) interaction's
|
/// 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
|
/// 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
|
/// 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> {
|
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();
|
let mut hashes: HashSet<ResourceHash> = self.document.working_registry.resources.values().filter_map(|entry| entry.hash).collect();
|
||||||
hashes.extend(self.document.history.resource_hashes());
|
|
||||||
hashes
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every proto-node declaration resource referenced by the current registry or anywhere in history,
|
|
||||||
/// with its content hash, or `None` where the hash never resolved.
|
|
||||||
pub fn all_declaration_resources(&self) -> HashMap<ResourceId, Option<ResourceHash>> {
|
|
||||||
let registry = &self.document.working_registry;
|
|
||||||
|
|
||||||
let mut hashes: HashMap<ResourceId, ResourceHash> = registry.resources.iter().filter_map(|(id, entry)| Some((*id, entry.hash?))).collect();
|
|
||||||
for delta in self.document.history.iter() {
|
for delta in self.document.history.iter() {
|
||||||
match &delta.kind {
|
match &delta.kind {
|
||||||
RegistryDelta::AddResource { id, entry } => hashes.extend(entry.hash.map(|hash| (*id, hash))),
|
RegistryDelta::AddResource { entry, .. } => hashes.extend(entry.hash),
|
||||||
RegistryDelta::RemoveResource { id, snapshot } => hashes.extend(snapshot.hash.map(|hash| (*id, hash))),
|
RegistryDelta::RemoveResource { snapshot, .. } => hashes.extend(snapshot.hash),
|
||||||
RegistryDelta::SetResourceHash { id, hash: Some(hash) } => {
|
|
||||||
hashes.insert(*id, *hash);
|
|
||||||
}
|
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let current_nodes = registry.node_instances.values();
|
hashes
|
||||||
let historic_nodes = self.document.history.iter().filter_map(|delta| match &delta.kind {
|
|
||||||
RegistryDelta::AddNode { node, .. } => Some(node),
|
|
||||||
RegistryDelta::RemoveNode { snapshot, .. } => Some(snapshot),
|
|
||||||
_ => None,
|
|
||||||
});
|
|
||||||
|
|
||||||
current_nodes
|
|
||||||
.chain(historic_nodes)
|
|
||||||
.filter_map(|node| match node.implementation() {
|
|
||||||
Implementation::ProtoNode(id) => Some(*id),
|
|
||||||
Implementation::Network(_) => None,
|
|
||||||
})
|
|
||||||
.map(|id| (id, hashes.get(&id).copied()))
|
|
||||||
.collect()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn hot_log(&self) -> &[HotOp] {
|
pub fn hot_log(&self) -> &[HotOp] {
|
||||||
@@ -582,7 +507,7 @@ impl Session {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Test-only: commit a single op as a retired delta on the local chain, returning the result so a
|
/// Test-only: commit a single op as a retired delta on the local chain, returning the result so a
|
||||||
/// test can observe a failure (e.g. `NotFoundInHistory`).
|
/// test can observe a resurrection failure (e.g. `NotFoundInHistory`).
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pub(crate) fn commit_op_for_test(&mut self, op: RegistryDelta) -> Result<(), CrdtError> {
|
pub(crate) fn commit_op_for_test(&mut self, op: RegistryDelta) -> Result<(), CrdtError> {
|
||||||
self.commit_ops(std::iter::once(op), false).map(|_| ())
|
self.commit_ops(std::iter::once(op), false).map(|_| ())
|
||||||
@@ -595,26 +520,6 @@ impl Session {
|
|||||||
pub fn next_node_counter(&self) -> u64 {
|
pub fn next_node_counter(&self) -> u64 {
|
||||||
self.document.next_node_counter
|
self.document.next_node_counter
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The last hot op sequence this peer authored, carried across a reload so none 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.
|
|
||||||
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) {
|
|
||||||
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.
|
|
||||||
pub fn restore_hot_sequence(&mut self, sequence: HotSequence) {
|
|
||||||
self.document.last_hot_sequence = self.document.last_hot_sequence.max(sequence);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Errors from `Session::commit_from_runtime`.
|
/// Errors from `Session::commit_from_runtime`.
|
||||||
@@ -640,120 +545,10 @@ impl Default for Session {
|
|||||||
pub struct HotOp {
|
pub struct HotOp {
|
||||||
pub op: RegistryDelta,
|
pub op: RegistryDelta,
|
||||||
pub timestamp: TimeStamp,
|
pub timestamp: TimeStamp,
|
||||||
/// Position in its author's run. See [`HotSequence`].
|
|
||||||
pub sequence: HotSequence,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl HotOp {
|
|
||||||
/// Identifies the op in the retired marks, which track a contiguous prefix per author.
|
|
||||||
pub fn id(&self) -> HotOpId {
|
|
||||||
HotOpId {
|
|
||||||
peer: self.timestamp.peer,
|
|
||||||
sequence: self.sequence,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Position in one author's run of hot ops, counting from 1 with no gaps. Kept apart from the Lamport
|
|
||||||
/// counter, which skips on observing a higher remote timestamp and so cannot bound a contiguous prefix.
|
|
||||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
|
|
||||||
#[serde(transparent)]
|
|
||||||
pub struct HotSequence(pub u64);
|
|
||||||
|
|
||||||
impl HotSequence {
|
|
||||||
/// Before this author has written anything, covering no op.
|
|
||||||
pub const NONE: Self = Self(0);
|
|
||||||
|
|
||||||
/// The position after this one, for adjacency. Saturates: a run ending at the last position has no successor.
|
|
||||||
pub fn next(self) -> Self {
|
|
||||||
Self(self.0.saturating_add(1))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One hot op's author and position in its run, as the retired marks name it.
|
|
||||||
#[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.
|
|
||||||
#[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)>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sort and coalesce runs, joining any that touch or abut.
|
|
||||||
fn coalesce(runs: &mut Vec<(HotSequence, HotSequence)>) {
|
|
||||||
runs.sort_unstable();
|
|
||||||
runs.dedup_by(|(start, end), (_, last_end)| {
|
|
||||||
let joins = *start <= last_end.next();
|
|
||||||
if joins {
|
|
||||||
*last_end = (*last_end).max(*end);
|
|
||||||
}
|
|
||||||
joins
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RetiredMarks {
|
|
||||||
/// 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
|
|
||||||
.retired_runs
|
|
||||||
.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();
|
|
||||||
*through = (*through).max(remote_through);
|
|
||||||
}
|
|
||||||
for (&peer, runs) in &remote.retired_runs {
|
|
||||||
self.retired_runs.entry(peer).or_default().extend(runs.iter().copied());
|
|
||||||
}
|
|
||||||
self.compact();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Record newly retired 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.compact();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Fold runs that continue their author's prefix into `retired_up_to`, leaving only those past a gap.
|
|
||||||
fn compact(&mut self) {
|
|
||||||
for (&peer, runs) in &mut self.retired_runs {
|
|
||||||
coalesce(runs);
|
|
||||||
let mut through = self.retired_up_to.get(&peer).copied().unwrap_or(HotSequence::NONE);
|
|
||||||
let joined = runs.iter().take_while(|&&(start, end)| {
|
|
||||||
let joins = start <= through.next();
|
|
||||||
if joins {
|
|
||||||
through = through.max(end);
|
|
||||||
}
|
|
||||||
joins
|
|
||||||
});
|
|
||||||
let joined = joined.count();
|
|
||||||
runs.drain(..joined);
|
|
||||||
if through != HotSequence::NONE {
|
|
||||||
self.retired_up_to.insert(peer, through);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
self.retired_runs.retain(|_, runs| !runs.is_empty());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
pub enum CrdtError {
|
pub enum CrdtError {
|
||||||
#[error("This peer has authored every hot op sequence there is")]
|
|
||||||
SequencesExhausted,
|
|
||||||
#[error("Target node {0} does not exist")]
|
#[error("Target node {0} does not exist")]
|
||||||
TargetNodeDoesNotExist(NodeId),
|
TargetNodeDoesNotExist(NodeId),
|
||||||
#[error("Network {0} does not exist")]
|
#[error("Network {0} does not exist")]
|
||||||
@@ -764,6 +559,10 @@ pub enum CrdtError {
|
|||||||
ExportSlotOutOfBounds(u32),
|
ExportSlotOutOfBounds(u32),
|
||||||
#[error("Delta {0} not found in history")]
|
#[error("Delta {0} not found in history")]
|
||||||
NotFoundInHistory(Rev),
|
NotFoundInHistory(Rev),
|
||||||
|
#[error("No history entry resurrects node {0}")]
|
||||||
|
NodeNotInHistory(NodeId),
|
||||||
|
#[error("No history entry resurrects network {0}")]
|
||||||
|
NetworkNotInHistory(NetworkId),
|
||||||
#[error("Nothing to undo")]
|
#[error("Nothing to undo")]
|
||||||
NothingToUndo,
|
NothingToUndo,
|
||||||
#[error("Nothing to redo")]
|
#[error("Nothing to redo")]
|
||||||
@@ -772,6 +571,9 @@ pub enum CrdtError {
|
|||||||
NodeAlreadyExists(NodeId),
|
NodeAlreadyExists(NodeId),
|
||||||
#[error("Network {0} already exists")]
|
#[error("Network {0} already exists")]
|
||||||
NetworkAlreadyExists(NetworkId),
|
NetworkAlreadyExists(NetworkId),
|
||||||
|
/// PeerId is already registered to a different UserId.
|
||||||
|
#[error("Peer {0:?} is already registered to a different user")]
|
||||||
|
PeerRegistrationConflict(PeerId),
|
||||||
#[error("Delta stored under {stored} hashes to {expected}")]
|
#[error("Delta stored under {stored} hashes to {expected}")]
|
||||||
RevMismatch { stored: Rev, expected: Rev },
|
RevMismatch { stored: Rev, expected: Rev },
|
||||||
}
|
}
|
||||||
@@ -1,178 +0,0 @@
|
|||||||
use crate::{AttributeDelta, CrdtError, HotOpId, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, RegistryDelta, Session, UserId, Value};
|
|
||||||
|
|
||||||
fn set_attribute(key: &str, value: u32) -> RegistryDelta {
|
|
||||||
RegistryDelta::ChangeDocumentAttribute {
|
|
||||||
delta: AttributeDelta {
|
|
||||||
key: key.to_string(),
|
|
||||||
value: Some(Value::from(serde_json::json!(value))),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn add_network(id: u64) -> RegistryDelta {
|
|
||||||
RegistryDelta::AddNetwork {
|
|
||||||
id: NetworkId(id),
|
|
||||||
network: Network::default(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every op commutes, so the snapshot folds to the working registry's values whatever the log order.
|
|
||||||
#[test]
|
|
||||||
fn retirement_takes_the_ops_under_the_cutoff_in_any_applied_order() {
|
|
||||||
let mut host = Session::with_peer(PeerId(1));
|
|
||||||
// The log is in arrival order: a guest's later-stamped op sits ahead of an earlier one.
|
|
||||||
let hot = |op, counter, peer| crate::HotOp {
|
|
||||||
op,
|
|
||||||
timestamp: crate::TimeStamp { counter, peer: PeerId(peer) },
|
|
||||||
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");
|
|
||||||
assert_eq!(host.hot_ops_up_to(own.timestamp).len(), 1, "only the op under the cutoff retires");
|
|
||||||
|
|
||||||
host.retire(own.timestamp).expect("retire");
|
|
||||||
assert_eq!(host.hot_log().len(), 1, "the later-stamped op stays hot");
|
|
||||||
assert!(!host.retired_registry().networks.contains_key(&NetworkId(9)));
|
|
||||||
assert!(host.registry().networks.contains_key(&NetworkId(9)));
|
|
||||||
assert!(host.retired_registry().attributes.get("x").is_some_and(|value| !value.deleted));
|
|
||||||
|
|
||||||
host.retire(late.timestamp).expect("retire the rest");
|
|
||||||
assert!(host.hot_log().is_empty());
|
|
||||||
assert!(host.registry().value_equal(host.retired_registry()));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn newest_peer_registration_wins_in_any_order() {
|
|
||||||
// Registration rides the staging path, so the steps go through the hot log and retire.
|
|
||||||
fn stage_and_retire(session: &mut Session, op: RegistryDelta) {
|
|
||||||
let hot = session.stage_ops([op]).expect("stage");
|
|
||||||
let ids: Vec<crate::HotOpId> = hot.iter().map(crate::HotOp::id).collect();
|
|
||||||
session.retire_hot_ops(&ids).expect("retire");
|
|
||||||
}
|
|
||||||
let mut device = Session::with_identity(PeerId(1), UserId(10));
|
|
||||||
stage_and_retire(&mut device, set_attribute("first", 1));
|
|
||||||
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(10));
|
|
||||||
|
|
||||||
// The person at the device changes, so the next batch registers again.
|
|
||||||
device.document.user = UserId(20);
|
|
||||||
stage_and_retire(&mut device, set_attribute("second", 2));
|
|
||||||
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(20));
|
|
||||||
let registrations = device.history().filter(|delta| matches!(delta.kind, RegistryDelta::RegisterPeer { .. })).count();
|
|
||||||
assert_eq!(registrations, 2, "one registration per person the device stood for");
|
|
||||||
|
|
||||||
let mut other = Session::with_peer(PeerId(2));
|
|
||||||
for delta in device.cloned_deltas().into_iter().rev() {
|
|
||||||
other.document.apply_op_idempotent(delta.kind, delta.timestamp).unwrap();
|
|
||||||
}
|
|
||||||
assert_eq!(other.user_of(PeerId(1)), Some(UserId(20)), "the newest registration wins in any order");
|
|
||||||
assert_eq!(other.user_of(PeerId(3)), None, "a peer never registered has no user");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_batch_past_the_last_sequence_is_refused_whole() {
|
|
||||||
let mut session = Session::with_peer(PeerId(1));
|
|
||||||
session.restore_hot_sequence(crate::HotSequence(u64::MAX - 1));
|
|
||||||
assert!(matches!(session.stage_ops([set_attribute("k", 1)]), Err(crate::CrdtError::SequencesExhausted)));
|
|
||||||
assert!(session.hot_log().is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_reopened_session_drops_a_late_copy_of_a_retired_op() {
|
|
||||||
let op = crate::HotOp {
|
|
||||||
op: set_attribute("k", 1),
|
|
||||||
timestamp: crate::TimeStamp { counter: 3, peer: PeerId(2) },
|
|
||||||
sequence: crate::HotSequence(1),
|
|
||||||
};
|
|
||||||
let mut host = Session::with_peer(PeerId(1));
|
|
||||||
host.replay_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();
|
|
||||||
assert!(reopened.hot_log().is_empty());
|
|
||||||
assert!(reopened.retire(op.timestamp).unwrap().is_empty());
|
|
||||||
assert_eq!(reopened.history_len(), host.history_len());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_refused_local_op_leaves_the_working_registry_unchanged() {
|
|
||||||
let mut s = Session::with_peer(PeerId(1));
|
|
||||||
let node = Node::new(NetworkId(1), Implementation::Network(NetworkId(1)), 1);
|
|
||||||
s.stage_ops([
|
|
||||||
RegistryDelta::AddNetwork {
|
|
||||||
id: NetworkId(1),
|
|
||||||
network: Network::default(),
|
|
||||||
},
|
|
||||||
RegistryDelta::AddNode { id: NodeId(1), node },
|
|
||||||
])
|
|
||||||
.unwrap();
|
|
||||||
let before = s.registry().clone();
|
|
||||||
|
|
||||||
let refused = s.stage_ops([RegistryDelta::ChangeNodeInput {
|
|
||||||
id: NodeId(1),
|
|
||||||
index: 0,
|
|
||||||
new_input: NodeInput::Node { id: NodeId(404), index: 0 },
|
|
||||||
}]);
|
|
||||||
assert!(matches!(refused, Err(CrdtError::TargetNodeDoesNotExist(_))));
|
|
||||||
assert_eq!(s.registry(), &before, "the refused op's write to node 1 stayed in the working registry");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The caller only gets the error, so ops left staged would never be persisted or sent.
|
|
||||||
#[test]
|
|
||||||
fn a_refused_batch_stages_nothing() {
|
|
||||||
let mut s = Session::with_peer(PeerId(1));
|
|
||||||
s.stage_ops([RegistryDelta::AddNetwork {
|
|
||||||
id: NetworkId(1),
|
|
||||||
network: Network::default(),
|
|
||||||
}])
|
|
||||||
.unwrap();
|
|
||||||
let hot_before = s.hot_log().len();
|
|
||||||
let refused = s.stage_ops([
|
|
||||||
set_attribute("lands", 1),
|
|
||||||
RegistryDelta::ChangeNodeInput {
|
|
||||||
id: NodeId(404),
|
|
||||||
index: 0,
|
|
||||||
new_input: NodeInput::Value {
|
|
||||||
value: Value::from(serde_json::json!(1)),
|
|
||||||
exposed: false,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
assert!(refused.is_err());
|
|
||||||
assert_eq!(s.hot_log().len(), hot_before, "a refused batch stages nothing");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn retired_marks_round_trip_through_json() {
|
|
||||||
let mut marks = crate::RetiredMarks::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");
|
|
||||||
}
|
|
||||||
@@ -4,7 +4,7 @@ use graph_craft::concrete;
|
|||||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
|
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
|
||||||
|
|
||||||
use crate::InputSlot;
|
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, RegistryTarget, Session, TimeStamp};
|
||||||
|
|
||||||
fn fresh_document(peer: PeerId) -> Document {
|
fn fresh_document(peer: PeerId) -> Document {
|
||||||
Session::with_peer(peer).document
|
Session::with_peer(peer).document
|
||||||
@@ -40,12 +40,9 @@ fn apply_hot_op_advances_clock_past_observed_timestamp() {
|
|||||||
let hot_op = HotOp {
|
let hot_op = HotOp {
|
||||||
op: remove_node_op(NodeId(99)),
|
op: remove_node_op(NodeId(99)),
|
||||||
timestamp: observed,
|
timestamp: observed,
|
||||||
sequence: crate::HotSequence(1),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
document
|
document.apply_hot_op(hot_op).expect("RemoveNode on absent node is a no-op, not an error");
|
||||||
.stage_hot_op(hot_op, crate::document::ApplyMode::Strict)
|
|
||||||
.expect("RemoveNode on absent node is a no-op, not an error");
|
|
||||||
|
|
||||||
assert!(
|
assert!(
|
||||||
document.clock.counter >= observed.counter,
|
document.clock.counter >= observed.counter,
|
||||||
@@ -164,7 +161,7 @@ fn set_document_attribute(key: &str, value: u32) -> RegistryDelta {
|
|||||||
RegistryDelta::ChangeDocumentAttribute {
|
RegistryDelta::ChangeDocumentAttribute {
|
||||||
delta: crate::AttributeDelta {
|
delta: crate::AttributeDelta {
|
||||||
key: key.to_string(),
|
key: key.to_string(),
|
||||||
value: Some(Value::Int(value.into())),
|
value: Some(serde_json::json!(value)),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -266,11 +263,7 @@ fn first_contribution_registers_the_peer() {
|
|||||||
let registrations = first.iter().filter(|hot_op| matches!(hot_op.op, RegistryDelta::RegisterPeer { .. })).count();
|
let registrations = first.iter().filter(|hot_op| matches!(hot_op.op, RegistryDelta::RegisterPeer { .. })).count();
|
||||||
assert_eq!(registrations, 1, "exactly one RegisterPeer on first contribution");
|
assert_eq!(registrations, 1, "exactly one RegisterPeer on first contribution");
|
||||||
assert!(matches!(first[0].op, RegistryDelta::RegisterPeer { .. }), "RegisterPeer must precede the edit ops");
|
assert!(matches!(first[0].op, RegistryDelta::RegisterPeer { .. }), "RegisterPeer must precede the edit ops");
|
||||||
assert_eq!(
|
assert_eq!(session.registry().peer_users.get(&PeerId(7)), Some(&crate::UserId(7)), "peer mapped to its UserId");
|
||||||
session.registry().peer_users.get(&PeerId(7)).map(|registration| registration.user),
|
|
||||||
Some(crate::UserId(7)),
|
|
||||||
"peer mapped to its UserId"
|
|
||||||
);
|
|
||||||
|
|
||||||
// A second, distinct contribution must not re-register.
|
// A second, distinct contribution must not re-register.
|
||||||
let mut other_network = tiny_network();
|
let mut other_network = tiny_network();
|
||||||
@@ -291,9 +284,9 @@ fn first_contribution_registers_the_peer() {
|
|||||||
assert_eq!(fresh.registry().peer_users, peers_before, "a no-op batch must not add a registration");
|
assert_eq!(fresh.registry().peer_users, peers_before, "a no-op batch must not add a registration");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A SetExport newer than a network's removal revives the network from its tombstone instead of erroring.
|
/// A SetExport against a removed network must restore the network from history rather than error.
|
||||||
#[test]
|
#[test]
|
||||||
fn set_network_export_revives_a_removed_network() {
|
fn set_export_resurrects_absent_network() {
|
||||||
let mut document = fresh_document(PeerId(1));
|
let mut document = fresh_document(PeerId(1));
|
||||||
let network_id = NetworkId(7);
|
let network_id = NetworkId(7);
|
||||||
|
|
||||||
@@ -311,7 +304,7 @@ fn set_network_export_revives_a_removed_network() {
|
|||||||
snapshot: Network::default(),
|
snapshot: Network::default(),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
assert!(!document.working_registry.networks.contains_key(&network_id), "network should be removed before the revival");
|
assert!(!document.working_registry.networks.contains_key(&network_id), "network should be removed before the resurrection test");
|
||||||
|
|
||||||
commit_op(
|
commit_op(
|
||||||
&mut document,
|
&mut document,
|
||||||
@@ -322,12 +315,12 @@ fn set_network_export_revives_a_removed_network() {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
assert!(document.working_registry.networks.contains_key(&network_id), "SetExport should have revived the network");
|
assert!(document.working_registry.networks.contains_key(&network_id), "SetExport should have resurrected the network");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An addition into a removed network is evidence the network exists, so it brings the network back.
|
/// Cascading resurrection: bringing a node back must also restore its owning network when absent.
|
||||||
#[test]
|
#[test]
|
||||||
fn add_node_revives_its_removed_network() {
|
fn add_node_resurrects_owning_network() {
|
||||||
use crate::Node;
|
use crate::Node;
|
||||||
|
|
||||||
let mut document = fresh_document(PeerId(1));
|
let mut document = fresh_document(PeerId(1));
|
||||||
@@ -352,13 +345,18 @@ fn add_node_revives_its_removed_network() {
|
|||||||
let node = Node { network: network_id, ..Node::dummy() };
|
let node = Node { network: network_id, ..Node::dummy() };
|
||||||
commit_op(&mut document, RegistryDelta::AddNode { id: node_id, node });
|
commit_op(&mut document, RegistryDelta::AddNode { id: node_id, node });
|
||||||
|
|
||||||
assert!(document.working_registry.networks.contains_key(&network_id), "AddNode should have revived the owning network");
|
assert!(
|
||||||
|
document.working_registry.networks.contains_key(&network_id),
|
||||||
|
"AddNode should have cascaded a resurrection of the owning network"
|
||||||
|
);
|
||||||
assert!(document.working_registry.node_instances.contains_key(&node_id), "the node itself should also be present");
|
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.
|
/// Reverting the same removal twice (the moral equivalent of two peers concurrently resurrecting
|
||||||
|
/// the same node) must not error on the second apply. Today the second revert hits
|
||||||
|
/// `apply_op(AddNode, false)` against a present node and returns `NodeAlreadyExists`.
|
||||||
#[test]
|
#[test]
|
||||||
fn the_same_revival_arriving_twice_lands_once() {
|
fn concurrent_resurrection_via_revert_is_idempotent() {
|
||||||
use crate::Node;
|
use crate::Node;
|
||||||
|
|
||||||
let mut document = fresh_document(PeerId(1));
|
let mut document = fresh_document(PeerId(1));
|
||||||
@@ -375,19 +373,40 @@ fn the_same_revival_arriving_twice_lands_once() {
|
|||||||
let node = Node { network: network_id, ..Node::dummy() };
|
let node = Node { network: network_id, ..Node::dummy() };
|
||||||
commit_op(&mut document, RegistryDelta::AddNode { id: node_id, node: node.clone() });
|
commit_op(&mut document, RegistryDelta::AddNode { id: node_id, node: node.clone() });
|
||||||
commit_op(&mut document, RegistryDelta::RemoveNode { id: node_id, snapshot: node });
|
commit_op(&mut document, RegistryDelta::RemoveNode { id: node_id, snapshot: node });
|
||||||
assert!(!document.working_registry.node_instances.contains_key(&node_id), "node should be removed before the revival");
|
assert!(!document.working_registry.node_instances.contains_key(&node_id), "node should be removed before the resurrection test");
|
||||||
|
|
||||||
let revive = RegistryDelta::AddNode {
|
document.restore_node_from_history(RegistryTarget::Working, node_id).expect("first resurrection should succeed");
|
||||||
id: node_id,
|
assert!(document.working_registry.node_instances.contains_key(&node_id), "first resurrection should bring the node back");
|
||||||
node: Node { network: network_id, ..Node::dummy() },
|
|
||||||
};
|
|
||||||
let at = document.clock.tick();
|
|
||||||
document.apply_op_idempotent(revive.clone(), at).expect("first revival");
|
|
||||||
assert!(document.working_registry.node_instances.contains_key(&node_id), "the first revival brings the node back");
|
|
||||||
|
|
||||||
let second = document.apply_op_idempotent(revive, at);
|
let second = document.restore_node_from_history(RegistryTarget::Working, node_id);
|
||||||
assert!(second.is_ok(), "the same revival again is a no-op, got {second:?}");
|
assert!(second.is_ok(), "second resurrection of an already-present node should be a no-op, got {second:?}");
|
||||||
assert!(document.working_registry.node_instances.contains_key(&node_id));
|
}
|
||||||
|
|
||||||
|
/// History-based resurrection must work when the matching delta is the *root* commit. The history
|
||||||
|
/// walk used to drop the root (its empty parent list short-circuited the iterator before yielding
|
||||||
|
/// it), so a node removed by the very first commit could not be restored.
|
||||||
|
#[test]
|
||||||
|
fn restore_node_from_root_commit() {
|
||||||
|
use crate::Node;
|
||||||
|
|
||||||
|
let mut document = fresh_document(PeerId(1));
|
||||||
|
let node_id = NodeId(42);
|
||||||
|
|
||||||
|
let node = Node::dummy();
|
||||||
|
|
||||||
|
// Seed the working state so the root commit can remove the node (its reverse is the `AddNode` the
|
||||||
|
// resurrection looks for). This `RemoveNode` is the only commit, so the match sits at the root.
|
||||||
|
document.working_registry.networks.insert(ROOT_NETWORK, Network::default());
|
||||||
|
document.retired_snapshot.networks.insert(ROOT_NETWORK, Network::default());
|
||||||
|
document.working_registry.node_instances.insert(node_id, node.clone());
|
||||||
|
document.retired_snapshot.node_instances.insert(node_id, node.clone());
|
||||||
|
commit_op(&mut document, RegistryDelta::RemoveNode { id: node_id, snapshot: node });
|
||||||
|
assert!(!document.working_registry.node_instances.contains_key(&node_id), "node should be removed by the root commit");
|
||||||
|
|
||||||
|
document
|
||||||
|
.restore_node_from_history(RegistryTarget::Working, node_id)
|
||||||
|
.expect("resurrection from the root commit should succeed");
|
||||||
|
assert!(document.working_registry.node_instances.contains_key(&node_id), "node must be restored from the root commit");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Erroring ops still bump the clock: we observed the timestamp on the wire, the fact that the
|
/// Erroring ops still bump the clock: we observed the timestamp on the wire, the fact that the
|
||||||
@@ -436,7 +455,7 @@ fn concurrent_source_adds_at_distinct_priorities_both_survive() {
|
|||||||
RD::AddSource {
|
RD::AddSource {
|
||||||
id,
|
id,
|
||||||
key: source_key(0.5, 1),
|
key: source_key(0.5, 1),
|
||||||
source: Value::Str("embedded".into()),
|
source: serde_json::json!("embedded"),
|
||||||
},
|
},
|
||||||
ts(1, 1),
|
ts(1, 1),
|
||||||
)
|
)
|
||||||
@@ -446,7 +465,7 @@ fn concurrent_source_adds_at_distinct_priorities_both_survive() {
|
|||||||
RD::AddSource {
|
RD::AddSource {
|
||||||
id,
|
id,
|
||||||
key: source_key(0.75, 2),
|
key: source_key(0.75, 2),
|
||||||
source: Value::Str("url".into()),
|
source: serde_json::json!("url"),
|
||||||
},
|
},
|
||||||
ts(1, 2),
|
ts(1, 2),
|
||||||
)
|
)
|
||||||
@@ -456,7 +475,7 @@ fn concurrent_source_adds_at_distinct_priorities_both_survive() {
|
|||||||
assert_eq!(entry.sources.len(), 2, "both concurrent additions survive");
|
assert_eq!(entry.sources.len(), 2, "both concurrent additions survive");
|
||||||
// The chain iterates in priority order.
|
// The chain iterates in priority order.
|
||||||
let bodies: Vec<_> = entry.sources.iter().map(|(_, v)| v.source.clone()).collect();
|
let bodies: Vec<_> = entry.sources.iter().map(|(_, v)| v.source.clone()).collect();
|
||||||
assert_eq!(bodies, vec![Value::Str("embedded".into()), Value::Str("url".into())]);
|
assert_eq!(bodies, vec![serde_json::json!("embedded"), serde_json::json!("url")]);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Re-adding the same source key is LWW on its timestamp: a later write wins, an earlier one is ignored.
|
/// Re-adding the same source key is LWW on its timestamp: a later write wins, an earlier one is ignored.
|
||||||
@@ -471,7 +490,7 @@ fn same_source_key_is_last_writer_wins() {
|
|||||||
RD::AddSource {
|
RD::AddSource {
|
||||||
id,
|
id,
|
||||||
key,
|
key,
|
||||||
source: Value::Str("old".into()),
|
source: serde_json::json!("old"),
|
||||||
},
|
},
|
||||||
ts(5, 1),
|
ts(5, 1),
|
||||||
)
|
)
|
||||||
@@ -482,7 +501,7 @@ fn same_source_key_is_last_writer_wins() {
|
|||||||
RD::AddSource {
|
RD::AddSource {
|
||||||
id,
|
id,
|
||||||
key,
|
key,
|
||||||
source: Value::Str("stale".into()),
|
source: serde_json::json!("stale"),
|
||||||
},
|
},
|
||||||
ts(2, 1),
|
ts(2, 1),
|
||||||
)
|
)
|
||||||
@@ -493,14 +512,14 @@ fn same_source_key_is_last_writer_wins() {
|
|||||||
RD::AddSource {
|
RD::AddSource {
|
||||||
id,
|
id,
|
||||||
key,
|
key,
|
||||||
source: Value::Str("new".into()),
|
source: serde_json::json!("new"),
|
||||||
},
|
},
|
||||||
ts(9, 1),
|
ts(9, 1),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let entry = document.working_registry.resources.get(&id).unwrap();
|
let entry = document.working_registry.resources.get(&id).unwrap();
|
||||||
assert_eq!(entry.source(&key).unwrap().source, Value::Str("new".into()));
|
assert_eq!(entry.source(&key).unwrap().source, serde_json::json!("new"));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// SetResourceHash is LWW on the hash; a later resolve wins, an earlier one is ignored.
|
/// SetResourceHash is LWW on the hash; a later resolve wins, an earlier one is ignored.
|
||||||
@@ -532,26 +551,23 @@ fn remove_source_reverse_restores_prior() {
|
|||||||
RD::AddSource {
|
RD::AddSource {
|
||||||
id,
|
id,
|
||||||
key,
|
key,
|
||||||
source: Value::Str("kept".into()),
|
source: serde_json::json!("kept"),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
// Compute the reverse while the body is still present, then apply the removal.
|
// 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();
|
let reverse = document.compute_reverse_delta(RegistryTarget::Working, &RD::RemoveSource { id, key }).unwrap();
|
||||||
match &reverse {
|
match &reverse {
|
||||||
RD::AddSource { source, .. } => assert_eq!(*source, Value::Str("kept".into()), "reverse of removal re-adds the body"),
|
RD::AddSource { source, .. } => assert_eq!(*source, serde_json::json!("kept"), "reverse of removal re-adds the body"),
|
||||||
other => panic!("expected AddSource reverse, got {other:?}"),
|
other => panic!("expected AddSource reverse, got {other:?}"),
|
||||||
}
|
}
|
||||||
|
|
||||||
document.apply_op(RD::RemoveSource { id, key }, ts(5, 1)).unwrap();
|
document.apply_op(RD::RemoveSource { id, key }, ts(5, 1)).unwrap();
|
||||||
assert!(
|
assert!(document.working_registry.resources.get(&id).unwrap().sources.is_empty(), "source removed");
|
||||||
document.working_registry.resources.get(&id).unwrap().live_sources().next().is_none(),
|
|
||||||
"source removed, a tombstone left"
|
|
||||||
);
|
|
||||||
|
|
||||||
// Applying the reverse restores the chain.
|
// Applying the reverse restores the chain.
|
||||||
document.apply_op(reverse, ts(6, 1)).unwrap();
|
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()));
|
assert_eq!(document.working_registry.resources.get(&id).unwrap().source(&key).unwrap().source, serde_json::json!("kept"));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// AddSource on a fresh slot reverses to a RemoveSource; on an occupied slot it restores the prior body.
|
/// AddSource on a fresh slot reverses to a RemoveSource; on an occupied slot it restores the prior body.
|
||||||
@@ -568,7 +584,7 @@ fn add_source_reverse_depends_on_prior_state() {
|
|||||||
&RD::AddSource {
|
&RD::AddSource {
|
||||||
id,
|
id,
|
||||||
key,
|
key,
|
||||||
source: Value::Str("first".into()),
|
source: serde_json::json!("first"),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -580,7 +596,7 @@ fn add_source_reverse_depends_on_prior_state() {
|
|||||||
RD::AddSource {
|
RD::AddSource {
|
||||||
id,
|
id,
|
||||||
key,
|
key,
|
||||||
source: Value::Str("existing".into()),
|
source: serde_json::json!("existing"),
|
||||||
},
|
},
|
||||||
ts(1, 1),
|
ts(1, 1),
|
||||||
)
|
)
|
||||||
@@ -591,12 +607,12 @@ fn add_source_reverse_depends_on_prior_state() {
|
|||||||
&RD::AddSource {
|
&RD::AddSource {
|
||||||
id,
|
id,
|
||||||
key,
|
key,
|
||||||
source: Value::Str("overwrite".into()),
|
source: serde_json::json!("overwrite"),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
match reverse_overwrite {
|
match reverse_overwrite {
|
||||||
RD::AddSource { source, .. } => assert_eq!(source, Value::Str("existing".into()), "reverse restores prior body"),
|
RD::AddSource { source, .. } => assert_eq!(source, serde_json::json!("existing"), "reverse restores prior body"),
|
||||||
other => panic!("expected AddSource reverse, got {other:?}"),
|
other => panic!("expected AddSource reverse, got {other:?}"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -605,18 +621,9 @@ fn add_source_reverse_depends_on_prior_state() {
|
|||||||
|
|
||||||
use crate::{ResourceEntry, ResourceStore, SourceValue};
|
use crate::{ResourceEntry, ResourceStore, SourceValue};
|
||||||
|
|
||||||
fn entry_with_source(priority: f64, peer: u64, body: Value, hash: Option<ResourceHash>) -> ResourceEntry {
|
fn entry_with_source(priority: f64, peer: u64, body: serde_json::Value, hash: Option<ResourceHash>) -> ResourceEntry {
|
||||||
ResourceEntry {
|
ResourceEntry {
|
||||||
presence: ts(1, peer),
|
sources: vec![(source_key(priority, peer), SourceValue { source: body, timestamp: ts(1, peer) })],
|
||||||
sources: vec![(
|
|
||||||
source_key(priority, peer),
|
|
||||||
SourceValue {
|
|
||||||
source: body,
|
|
||||||
timestamp: ts(1, peer),
|
|
||||||
deleted: false,
|
|
||||||
},
|
|
||||||
)],
|
|
||||||
sources_timestamp: TimeStamp::ORIGIN,
|
|
||||||
hash,
|
hash,
|
||||||
hash_timestamp: ts(1, peer),
|
hash_timestamp: ts(1, peer),
|
||||||
}
|
}
|
||||||
@@ -633,10 +640,10 @@ fn compute_deltas_ignores_unchanged_resources() {
|
|||||||
let hash = ResourceHash::from(&b"img"[..]);
|
let hash = ResourceHash::from(&b"img"[..]);
|
||||||
|
|
||||||
let mut from = ResourceStore::new();
|
let mut from = ResourceStore::new();
|
||||||
from.insert(id, entry_with_source(0.0, 1, Value::Str("embedded".into()), Some(hash)));
|
from.insert(id, entry_with_source(0.0, 1, serde_json::json!("embedded"), Some(hash)));
|
||||||
// Same value, different timestamps: must not count as a change.
|
// Same value, different timestamps: must not count as a change.
|
||||||
let mut to = ResourceStore::new();
|
let mut to = ResourceStore::new();
|
||||||
let mut to_entry = entry_with_source(0.0, 1, Value::Str("embedded".into()), Some(hash));
|
let mut to_entry = entry_with_source(0.0, 1, serde_json::json!("embedded"), Some(hash));
|
||||||
to_entry.hash_timestamp = ts(99, 2);
|
to_entry.hash_timestamp = ts(99, 2);
|
||||||
to_entry.sources.iter_mut().for_each(|(_, v)| v.timestamp = ts(99, 2));
|
to_entry.sources.iter_mut().for_each(|(_, v)| v.timestamp = ts(99, 2));
|
||||||
to.insert(id, to_entry);
|
to.insert(id, to_entry);
|
||||||
@@ -656,23 +663,22 @@ fn compute_deltas_diffs_resources_and_round_trips() {
|
|||||||
let hash_new = ResourceHash::from(&b"new"[..]);
|
let hash_new = ResourceHash::from(&b"new"[..]);
|
||||||
|
|
||||||
let mut from = ResourceStore::new();
|
let mut from = ResourceStore::new();
|
||||||
from.insert(kept, entry_with_source(0.0, 1, Value::Str("embedded".into()), Some(hash_old)));
|
from.insert(kept, entry_with_source(0.0, 1, serde_json::json!("embedded"), Some(hash_old)));
|
||||||
from.insert(removed, entry_with_source(0.0, 1, Value::Str("gone".into()), None));
|
from.insert(removed, entry_with_source(0.0, 1, serde_json::json!("gone"), None));
|
||||||
|
|
||||||
let mut to = ResourceStore::new();
|
let mut to = ResourceStore::new();
|
||||||
// `kept`: hash changes and a second source is added.
|
// `kept`: hash changes and a second source is added.
|
||||||
let mut kept_entry = entry_with_source(0.0, 1, Value::Str("embedded".into()), Some(hash_new));
|
let mut kept_entry = entry_with_source(0.0, 1, serde_json::json!("embedded"), Some(hash_new));
|
||||||
kept_entry.set_source(
|
kept_entry.set_source(
|
||||||
source_key(1.0, 1),
|
source_key(1.0, 1),
|
||||||
SourceValue {
|
SourceValue {
|
||||||
source: Value::Str("url".into()),
|
source: serde_json::json!("url"),
|
||||||
timestamp: ts(1, 1),
|
timestamp: ts(1, 1),
|
||||||
deleted: false,
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
to.insert(kept, kept_entry);
|
to.insert(kept, kept_entry);
|
||||||
// `added`: brand new resource.
|
// `added`: brand new resource.
|
||||||
to.insert(added, entry_with_source(0.0, 1, Value::Str("fresh".into()), None));
|
to.insert(added, entry_with_source(0.0, 1, serde_json::json!("fresh"), None));
|
||||||
|
|
||||||
let deltas = crate::delta::compute_deltas(®istry_with_resources(from.clone()), ®istry_with_resources(to.clone()));
|
let deltas = crate::delta::compute_deltas(®istry_with_resources(from.clone()), ®istry_with_resources(to.clone()));
|
||||||
|
|
||||||
@@ -693,8 +699,6 @@ fn compute_deltas_diffs_resources_and_round_trips() {
|
|||||||
// Apply the diff to a document seeded with `from`, then check it matches `to` by value.
|
// Apply the diff to a document seeded with `from`, then check it matches `to` by value.
|
||||||
let mut document = fresh_document(PeerId(1));
|
let mut document = fresh_document(PeerId(1));
|
||||||
document.working_registry = registry_with_resources(from);
|
document.working_registry = registry_with_resources(from);
|
||||||
// A clock is past every stamp in the registry it edits, as a session's persisted clock is.
|
|
||||||
document.clock.observe(ts(1, 1));
|
|
||||||
for op in deltas {
|
for op in deltas {
|
||||||
let timestamp = document.clock.tick();
|
let timestamp = document.clock.tick();
|
||||||
document.apply_op(op, timestamp).expect("apply resource delta");
|
document.apply_op(op, timestamp).expect("apply resource delta");
|
||||||
@@ -742,15 +746,6 @@ fn all_referenced_resource_hashes_survives_undo() {
|
|||||||
session.all_referenced_resource_hashes().contains(&hash),
|
session.all_referenced_resource_hashes().contains(&hash),
|
||||||
"the undone interaction's resource must still be reported so GC keeps its bytes for redo"
|
"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
|
/// A commit that produces no deltas must not touch the redo stack. Redo is only abandoned by a real
|
||||||
@@ -816,7 +811,7 @@ fn embed_resource_sources_preserves_unretired_hot_ops() {
|
|||||||
/// ordered (`BTreeMap`): a hash-randomized map would give the same logical delta different `Rev`s.
|
/// ordered (`BTreeMap`): a hash-randomized map would give the same logical delta different `Rev`s.
|
||||||
#[test]
|
#[test]
|
||||||
fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
||||||
use crate::{AttributeValue, Implementation};
|
use crate::{AttributesWrite, Implementation, Value};
|
||||||
|
|
||||||
let keys = ["ui::position", "ui::display_name", "ui::locked", "ui::pinned", "call_argument", "context_features"];
|
let keys = ["ui::position", "ui::display_name", "ui::locked", "ui::pinned", "call_argument", "context_features"];
|
||||||
|
|
||||||
@@ -826,12 +821,12 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
|||||||
let make_node = |insertion_order: &[&str]| {
|
let make_node = |insertion_order: &[&str]| {
|
||||||
let mut attributes = crate::Attributes::new();
|
let mut attributes = crate::Attributes::new();
|
||||||
for &key in insertion_order {
|
for &key in insertion_order {
|
||||||
attributes.set(key, Value::Str(key.to_string()), TimeStamp::ORIGIN);
|
attributes.set(key, serde_json::json!(key), TimeStamp::ORIGIN);
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut input_attributes = crate::Attributes::new();
|
let mut input_attributes = crate::Attributes::new();
|
||||||
for &key in insertion_order {
|
for &key in insertion_order {
|
||||||
input_attributes.insert(key.to_string(), AttributeValue::new(Value::Str(key.to_string()), TimeStamp::ORIGIN));
|
input_attributes.insert(key.to_string(), Value::new(serde_json::json!(key), TimeStamp::ORIGIN));
|
||||||
}
|
}
|
||||||
|
|
||||||
let inputs = vec![InputSlot {
|
let inputs = vec![InputSlot {
|
||||||
@@ -841,11 +836,7 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
|||||||
}];
|
}];
|
||||||
|
|
||||||
Node {
|
Node {
|
||||||
presence: Default::default(),
|
|
||||||
network_timestamp: Default::default(),
|
|
||||||
inputs_timestamp: Default::default(),
|
|
||||||
implementation: implementation.clone(),
|
implementation: implementation.clone(),
|
||||||
implementation_timestamp: Default::default(),
|
|
||||||
inputs,
|
inputs,
|
||||||
attributes,
|
attributes,
|
||||||
network: ROOT_NETWORK,
|
network: ROOT_NETWORK,
|
||||||
@@ -888,497 +879,3 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
|||||||
|
|
||||||
assert_eq!(delta_forward.id, delta_reversed.id, "Rev must not depend on attribute insertion order");
|
assert_eq!(delta_forward.id, delta_reversed.id, "Rev must not depend on attribute insertion order");
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add_network(id: u64) -> RegistryDelta {
|
|
||||||
let network = Network::default();
|
|
||||||
RegistryDelta::AddNetwork { id: NetworkId(id), network }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn change_node_attribute(id: NodeId, key: &str, value: serde_json::Value) -> RegistryDelta {
|
|
||||||
let delta = crate::AttributeDelta {
|
|
||||||
key: key.into(),
|
|
||||||
value: Some(Value::from(value)),
|
|
||||||
};
|
|
||||||
RegistryDelta::ChangeNodeAttribute { id, delta }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn hot_op(op: RegistryDelta, counter: u64, peer: u64, sequence: u64) -> HotOp {
|
|
||||||
let sequence = crate::HotSequence(sequence);
|
|
||||||
HotOp {
|
|
||||||
op,
|
|
||||||
timestamp: ts(counter, peer),
|
|
||||||
sequence,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An op past a gap is covered without the gap, a filled gap joins the prefix, and absorbing is a union.
|
|
||||||
#[test]
|
|
||||||
fn retired_marks_keep_a_prefix_and_runs_past_gaps() {
|
|
||||||
let author = PeerId(1);
|
|
||||||
let id = |sequence: u64| crate::HotOpId {
|
|
||||||
peer: author,
|
|
||||||
sequence: crate::HotSequence(sequence),
|
|
||||||
};
|
|
||||||
let marks_of = |batches: &[&[u64]]| {
|
|
||||||
let mut marks = crate::RetiredMarks::default();
|
|
||||||
batches.iter().for_each(|batch| marks.extend(batch.iter().map(|&sequence| id(sequence))));
|
|
||||||
marks
|
|
||||||
};
|
|
||||||
let after_a_lost_op: Vec<u64> = (2..=20).collect();
|
|
||||||
let one_by_one: Vec<&[u64]> = after_a_lost_op.chunks(1).collect();
|
|
||||||
|
|
||||||
/// Batches extended in order, batches of a peer's marks absorbed, expected prefix, expected runs past it.
|
|
||||||
type Case<'a> = (&'a [&'a [u64]], &'a [&'a [u64]], u64, Option<usize>);
|
|
||||||
let cases: [Case; 5] = [
|
|
||||||
(&[&[1, 2]], &[], 2, None),
|
|
||||||
(&[&[1, 2], &[4]], &[], 2, Some(1)),
|
|
||||||
(&[&[1, 2], &[4], &[3]], &[], 4, None),
|
|
||||||
(one_by_one.as_slice(), &[], 0, Some(1)),
|
|
||||||
(&[&[1, 4]], &[&[1, 2, 3, 5]], 5, None),
|
|
||||||
];
|
|
||||||
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);
|
|
||||||
assert_eq!(up_to, crate::HotSequence(prefix), "{batches:?}");
|
|
||||||
assert_eq!(marks.retired_runs.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}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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.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));
|
|
||||||
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.
|
|
||||||
#[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");
|
|
||||||
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.retire(winner.timestamp).expect("retire");
|
|
||||||
|
|
||||||
let value = |registry: &crate::Registry| registry.attributes.get("k").map(|attribute| attribute.value.clone());
|
|
||||||
let replayed = host.snapshot_from_history().expect("refold");
|
|
||||||
let values = [value(host.registry()), value(host.retired_registry()), value(&replayed)];
|
|
||||||
assert_eq!(values, [(); 3].map(|_| Some(Value::from(serde_json::json!(1)))), "straggler retires alone: {straggler_retires_alone}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Random ops over a few colliding ids fold to one registry in any order. Removal snapshots are constant or, as a remover
|
|
||||||
/// sends them, a fold of some earlier ops.
|
|
||||||
#[test]
|
|
||||||
fn a_set_of_ops_folds_to_one_registry_in_any_order() {
|
|
||||||
use crate::{Implementation, Priority, ResourceEntry, SourceKey, SourceValue, UserId};
|
|
||||||
use graphene_resource::{ResourceHash, ResourceId};
|
|
||||||
|
|
||||||
struct Lcg(u64);
|
|
||||||
impl Lcg {
|
|
||||||
fn below(&mut self, bound: u64) -> u64 {
|
|
||||||
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
|
||||||
(self.0 >> 33) % bound
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Folds the ops in order.
|
|
||||||
fn fold(ops: &[(RegistryDelta, TimeStamp)]) -> crate::Registry {
|
|
||||||
let mut document = fresh_document(PeerId(9));
|
|
||||||
for (op, at) in ops {
|
|
||||||
document.apply_op_idempotent(op.clone(), *at).unwrap_or_else(|error| panic!("{op:?} at {at:?}: {error}"));
|
|
||||||
}
|
|
||||||
document.working_registry
|
|
||||||
}
|
|
||||||
|
|
||||||
fn random_op(rng: &mut Lcg, at: TimeStamp, seen: &[(RegistryDelta, TimeStamp)], real_snapshots: bool) -> RegistryDelta {
|
|
||||||
let node_id = NodeId(1 + rng.below(4));
|
|
||||||
let network_id = NetworkId(1 + rng.below(3));
|
|
||||||
let resource_id = ResourceId::from(1 + rng.below(2));
|
|
||||||
let input = |rng: &mut Lcg| match rng.below(3) {
|
|
||||||
0 => crate::NodeInput::Node {
|
|
||||||
id: NodeId(1 + rng.below(4)),
|
|
||||||
index: 0,
|
|
||||||
},
|
|
||||||
_ => crate::NodeInput::Value {
|
|
||||||
value: Value::from(serde_json::json!(rng.below(100))),
|
|
||||||
exposed: false,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
// A write, or a deletion one time in four.
|
|
||||||
let attribute = |rng: &mut Lcg, key: &str| crate::AttributeDelta {
|
|
||||||
key: key.into(),
|
|
||||||
value: (rng.below(4) > 0).then(|| Value::from(serde_json::json!(rng.below(100)))),
|
|
||||||
};
|
|
||||||
let key = |rng: &mut Lcg| SourceKey {
|
|
||||||
priority: Priority::new(rng.below(2) as f64).expect("finite"),
|
|
||||||
peer: PeerId(1 + rng.below(2).min(at.peer.0)),
|
|
||||||
};
|
|
||||||
// What a remover saw: some of the ops before it. Two snapshots agreeing on a stamp then agree on the value,
|
|
||||||
// which a fabricated snapshot only does by being constant.
|
|
||||||
let saw = |rng: &mut Lcg| fold(&seen.iter().filter(|_| rng.below(2) == 0).cloned().collect::<Vec<_>>());
|
|
||||||
match rng.below(22) {
|
|
||||||
0 => {
|
|
||||||
// An export list of its own, so additions of different lengths meet.
|
|
||||||
let exports = (0..rng.below(3))
|
|
||||||
.map(|_| crate::ExportSlot {
|
|
||||||
target: Some(input(rng)),
|
|
||||||
timestamp: TimeStamp::ORIGIN,
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
RegistryDelta::AddNetwork {
|
|
||||||
id: network_id,
|
|
||||||
network: Network { exports, ..Default::default() },
|
|
||||||
}
|
|
||||||
}
|
|
||||||
1 => {
|
|
||||||
let snapshot = if real_snapshots { saw(rng).networks.get(&network_id).cloned() } else { Some(Network::default()) };
|
|
||||||
snapshot.map_or(RegistryDelta::Other(Value::None), |snapshot| RegistryDelta::RemoveNetwork { id: network_id, snapshot })
|
|
||||||
}
|
|
||||||
2 | 3 => RegistryDelta::AddNode {
|
|
||||||
id: node_id,
|
|
||||||
node: Node::new(network_id, Implementation::ProtoNode(ResourceId::from(7)), 1 + rng.below(2) as usize),
|
|
||||||
},
|
|
||||||
4 => {
|
|
||||||
let fabricated = || Node::new(NetworkId(1), Implementation::ProtoNode(ResourceId::from(7)), 2);
|
|
||||||
let snapshot = if real_snapshots { saw(rng).node_instances.get(&node_id).cloned() } else { Some(fabricated()) };
|
|
||||||
snapshot.map_or(RegistryDelta::Other(Value::None), |snapshot| RegistryDelta::RemoveNode { id: node_id, snapshot })
|
|
||||||
}
|
|
||||||
5 | 6 => RegistryDelta::ChangeNodeInput {
|
|
||||||
id: node_id,
|
|
||||||
index: rng.below(3) as u32,
|
|
||||||
new_input: input(rng),
|
|
||||||
},
|
|
||||||
7 => RegistryDelta::SetNodeInputs {
|
|
||||||
id: node_id,
|
|
||||||
inputs: (0..1 + rng.below(3))
|
|
||||||
.map(|_| {
|
|
||||||
let mut slot = InputSlot {
|
|
||||||
input: input(rng),
|
|
||||||
timestamp: TimeStamp::ORIGIN,
|
|
||||||
attributes: Default::default(),
|
|
||||||
};
|
|
||||||
// Half the time a slot carries attributes over with earlier stamps, as an implementation swap does.
|
|
||||||
if rng.below(2) == 0 {
|
|
||||||
let floor = TimeStamp {
|
|
||||||
counter: 1 + rng.below(at.counter),
|
|
||||||
peer: PeerId(1 + rng.below(3)),
|
|
||||||
};
|
|
||||||
let label = TimeStamp {
|
|
||||||
counter: floor.counter + rng.below(at.counter - floor.counter + 1),
|
|
||||||
..floor
|
|
||||||
};
|
|
||||||
slot.attributes
|
|
||||||
.insert("label".into(), crate::AttributeValue::new(Value::from(serde_json::json!(rng.below(100))), label));
|
|
||||||
slot.attributes.set_floor(floor);
|
|
||||||
}
|
|
||||||
slot
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
},
|
|
||||||
8 => {
|
|
||||||
let key = ["name", "lock"][rng.below(2) as usize];
|
|
||||||
RegistryDelta::ChangeNodeAttribute {
|
|
||||||
id: node_id,
|
|
||||||
delta: attribute(rng, key),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
9 => RegistryDelta::SetNodeImplementation {
|
|
||||||
id: node_id,
|
|
||||||
implementation: match rng.below(2) {
|
|
||||||
0 => Implementation::Network(network_id),
|
|
||||||
_ => Implementation::ProtoNode(ResourceId::from(rng.below(3))),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
10 => RegistryDelta::SetNetworkExport {
|
|
||||||
id: network_id,
|
|
||||||
index: rng.below(2) as u32,
|
|
||||||
export: match rng.below(2) {
|
|
||||||
0 => None,
|
|
||||||
_ => Some(input(rng)),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
11 => RegistryDelta::AddResource {
|
|
||||||
id: resource_id,
|
|
||||||
entry: ResourceEntry::default(),
|
|
||||||
},
|
|
||||||
12 => {
|
|
||||||
let snapshot = if real_snapshots {
|
|
||||||
saw(rng).resources.get(&resource_id).cloned()
|
|
||||||
} else {
|
|
||||||
Some(ResourceEntry::default())
|
|
||||||
};
|
|
||||||
snapshot.map_or(RegistryDelta::Other(Value::None), |snapshot| RegistryDelta::RemoveResource { id: resource_id, snapshot })
|
|
||||||
}
|
|
||||||
13 => RegistryDelta::SetResourceHash {
|
|
||||||
id: resource_id,
|
|
||||||
hash: Some(ResourceHash::from([rng.below(2) as u8; 32])),
|
|
||||||
},
|
|
||||||
14 => RegistryDelta::AddSource {
|
|
||||||
id: resource_id,
|
|
||||||
key: key(rng),
|
|
||||||
source: Value::from(serde_json::json!(rng.below(100))),
|
|
||||||
},
|
|
||||||
15 => RegistryDelta::ChangeNodeInputAttribute {
|
|
||||||
id: node_id,
|
|
||||||
index: rng.below(3) as u32,
|
|
||||||
delta: attribute(rng, "label"),
|
|
||||||
},
|
|
||||||
16 => RegistryDelta::ChangeNetworkAttribute {
|
|
||||||
id: network_id,
|
|
||||||
delta: attribute(rng, "name"),
|
|
||||||
},
|
|
||||||
17 => RegistryDelta::RemoveSource { id: resource_id, key: key(rng) },
|
|
||||||
18 => RegistryDelta::RegisterPeer {
|
|
||||||
peer: PeerId(1 + rng.below(2)),
|
|
||||||
user: UserId(rng.below(3)),
|
|
||||||
},
|
|
||||||
19 => RegistryDelta::ChangeDocumentAttribute { delta: attribute(rng, "doc") },
|
|
||||||
_ => {
|
|
||||||
// A resource added whole, with content.
|
|
||||||
let mut entry = ResourceEntry {
|
|
||||||
hash: Some(ResourceHash::from([rng.below(2) as u8; 32])),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
let source = SourceValue {
|
|
||||||
source: Value::from(serde_json::json!(rng.below(100))),
|
|
||||||
timestamp: TimeStamp::ORIGIN,
|
|
||||||
deleted: false,
|
|
||||||
};
|
|
||||||
entry.set_source(key(rng), source);
|
|
||||||
RegistryDelta::AddResource { id: resource_id, entry }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for real_snapshots in [false, true] {
|
|
||||||
for seed in 0..300u64 {
|
|
||||||
let mut rng = Lcg(seed);
|
|
||||||
let mut ops: Vec<(RegistryDelta, TimeStamp)> = Vec::new();
|
|
||||||
for i in 0..8 + rng.below(24) {
|
|
||||||
let at = TimeStamp {
|
|
||||||
counter: 1 + i,
|
|
||||||
peer: PeerId(1 + rng.below(3)),
|
|
||||||
};
|
|
||||||
let op = random_op(&mut rng, at, &ops, real_snapshots);
|
|
||||||
ops.push((op, at));
|
|
||||||
}
|
|
||||||
|
|
||||||
let reference = fold(&ops);
|
|
||||||
for _ in 0..6 {
|
|
||||||
let mut shuffled = ops.clone();
|
|
||||||
for i in (1..shuffled.len()).rev() {
|
|
||||||
shuffled.swap(i, rng.below(i as u64 + 1) as usize);
|
|
||||||
}
|
|
||||||
let order: Vec<u64> = shuffled.iter().map(|(_, at)| at.counter).collect();
|
|
||||||
assert_eq!(fold(&shuffled), reference, "seed {seed}, real snapshots {real_snapshots}: folded differently in the order {order:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An entry stamped at its map's floor was written with it, so folding a removal's snapshot keeps it.
|
|
||||||
#[test]
|
|
||||||
fn a_removal_snapshot_keeps_the_attributes_the_addition_wrote() {
|
|
||||||
let mut document = fresh_document(PeerId(1));
|
|
||||||
let id = NodeId(4);
|
|
||||||
let mut node = Node::new(ROOT_NETWORK, crate::Implementation::ProtoNode(graphene_resource::ResourceId::from(7)), 1);
|
|
||||||
node.attributes.set("ui::name", Value::from(serde_json::json!("Layer")), TimeStamp::ORIGIN);
|
|
||||||
node.inputs[0].attributes.set("reflection_metadata", Value::from(serde_json::json!("meta")), TimeStamp::ORIGIN);
|
|
||||||
commit_op(&mut document, add_network(ROOT_NETWORK.0));
|
|
||||||
commit_op(&mut document, RegistryDelta::AddNode { id, node });
|
|
||||||
|
|
||||||
// A removal and a newer write, which revives the node from the tombstone.
|
|
||||||
let removal = RegistryDelta::RemoveNode {
|
|
||||||
id,
|
|
||||||
snapshot: document.working_registry.node_instances[&id].clone(),
|
|
||||||
};
|
|
||||||
let removed_at = document.clock.tick();
|
|
||||||
document.apply_op_idempotent(removal.clone(), removed_at).expect("removal");
|
|
||||||
let written_at = document.clock.tick();
|
|
||||||
document.apply_op_idempotent(change_node_attribute(id, "ui::lock", serde_json::json!(true)), written_at).expect("write");
|
|
||||||
|
|
||||||
let revived = &document.working_registry.node_instances[&id];
|
|
||||||
assert_eq!(revived.attributes.get_typed::<String>("ui::name").as_deref(), Some("Layer"));
|
|
||||||
assert_eq!(revived.inputs()[0].attributes.get_typed::<String>("reflection_metadata").as_deref(), Some("meta"));
|
|
||||||
|
|
||||||
// The same removal replayed into the live node is too old to land and changes nothing.
|
|
||||||
let mut replayed = document.clone();
|
|
||||||
replayed.apply_op_idempotent(removal, removed_at).expect("a replayed removal");
|
|
||||||
assert_eq!(replayed.working_registry, document.working_registry);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_refused_replayed_op_changes_nothing() {
|
|
||||||
use crate::{Implementation, NodeInput};
|
|
||||||
let mut document = fresh_document(PeerId(1));
|
|
||||||
let node = Node::new(NetworkId(1), Implementation::Network(NetworkId(1)), 1);
|
|
||||||
for (op, counter) in [
|
|
||||||
(add_network(1), 1),
|
|
||||||
(RegistryDelta::AddNode { id: NodeId(1), node: node.clone() }, 2),
|
|
||||||
(RegistryDelta::AddNode { id: NodeId(2), node: node.clone() }, 3),
|
|
||||||
(RegistryDelta::RemoveNode { id: NodeId(2), snapshot: node }, 4),
|
|
||||||
] {
|
|
||||||
document.apply_op_idempotent(op, ts(counter, 5)).unwrap();
|
|
||||||
}
|
|
||||||
let before = document.working_registry.clone();
|
|
||||||
|
|
||||||
let out_of_bounds = RegistryDelta::ChangeNodeInput {
|
|
||||||
id: NodeId(1),
|
|
||||||
index: 1 << 20,
|
|
||||||
new_input: NodeInput::Node { id: NodeId(2), index: 0 },
|
|
||||||
};
|
|
||||||
assert!(document.apply_op_idempotent(out_of_bounds, ts(5, 5)).is_err());
|
|
||||||
assert_eq!(document.working_registry, before);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An implementation swap carries a slot's `ui::*` attributes over as the editor held them; a concurrent rename and a
|
|
||||||
/// concurrent first-time attribute on that slot both survive it, whichever lands first.
|
|
||||||
#[test]
|
|
||||||
fn an_implementation_swap_keeps_concurrent_slot_attribute_writes() {
|
|
||||||
use crate::Implementation;
|
|
||||||
use graphene_resource::ResourceId;
|
|
||||||
let slot_attribute = |key: &str, value: &str| RegistryDelta::ChangeNodeInputAttribute {
|
|
||||||
id: NodeId(1),
|
|
||||||
index: 0,
|
|
||||||
delta: crate::AttributeDelta {
|
|
||||||
key: key.into(),
|
|
||||||
value: Some(Value::from(serde_json::json!(value))),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
let mut base = fresh_document(PeerId(1));
|
|
||||||
commit_op(&mut base, add_network(1));
|
|
||||||
let node = Node::new(NetworkId(1), Implementation::ProtoNode(ResourceId::from(7)), 1);
|
|
||||||
commit_op(&mut base, RegistryDelta::AddNode { id: NodeId(1), node });
|
|
||||||
commit_op(&mut base, slot_attribute("ui::name", "a"));
|
|
||||||
|
|
||||||
// The swap as the editor builds it: the new slot with the held slot's `ui::*` attributes and floor carried over.
|
|
||||||
let held = base.working_registry.node_instances[&NodeId(1)].inputs()[0].clone();
|
|
||||||
let mut carried = InputSlot::unset(TimeStamp::ORIGIN);
|
|
||||||
carried.attributes.set_floor(held.attributes.floor());
|
|
||||||
carried.attributes.extend(held.attributes.into_iter().filter(|(key, value)| key.starts_with("ui::") && !value.deleted));
|
|
||||||
let swap = (RegistryDelta::SetNodeInputs { id: NodeId(1), inputs: vec![carried] }, ts(20, 1));
|
|
||||||
let rename = (slot_attribute("ui::name", "b"), ts(10, 2));
|
|
||||||
let describe = (slot_attribute("ui::description", "d"), ts(11, 2));
|
|
||||||
|
|
||||||
for order in [[&swap, &rename, &describe], [&rename, &describe, &swap]] {
|
|
||||||
let mut document = base.clone();
|
|
||||||
for (op, at) in order {
|
|
||||||
document.apply_op_idempotent(op.clone(), *at).expect("apply");
|
|
||||||
}
|
|
||||||
let slot = &document.working_registry.node_instances[&NodeId(1)].inputs()[0];
|
|
||||||
assert_eq!(
|
|
||||||
slot.attributes.get("ui::name").map(|value| value.value.clone()),
|
|
||||||
Some(Value::from(serde_json::json!("b"))),
|
|
||||||
"the rename survives"
|
|
||||||
);
|
|
||||||
assert!(slot.attributes.get("ui::description").is_some_and(|value| !value.deleted), "the first-time attribute survives");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Re-adding a removed network with a shorter export list drops the slots past its end, whichever lands first.
|
|
||||||
#[test]
|
|
||||||
fn a_network_re_added_shorter_keeps_only_its_own_exports() {
|
|
||||||
use crate::ExportSlot;
|
|
||||||
let export = |node: u64| ExportSlot {
|
|
||||||
target: Some(crate::NodeInput::Node { id: NodeId(node), index: 0 }),
|
|
||||||
timestamp: TimeStamp::ORIGIN,
|
|
||||||
};
|
|
||||||
let network = |exports: Vec<ExportSlot>| Network { exports, ..Default::default() };
|
|
||||||
let added = (
|
|
||||||
RegistryDelta::AddNetwork {
|
|
||||||
id: NetworkId(1),
|
|
||||||
network: network(vec![export(1), export(2)]),
|
|
||||||
},
|
|
||||||
ts(1, 1),
|
|
||||||
);
|
|
||||||
let removed = (
|
|
||||||
RegistryDelta::RemoveNetwork {
|
|
||||||
id: NetworkId(1),
|
|
||||||
snapshot: network(vec![export(1), export(2)]),
|
|
||||||
},
|
|
||||||
ts(2, 1),
|
|
||||||
);
|
|
||||||
let re_added = (
|
|
||||||
RegistryDelta::AddNetwork {
|
|
||||||
id: NetworkId(1),
|
|
||||||
network: network(vec![export(3)]),
|
|
||||||
},
|
|
||||||
ts(3, 2),
|
|
||||||
);
|
|
||||||
for order in [[&added, &removed, &re_added], [&re_added, &removed, &added]] {
|
|
||||||
let mut document = fresh_document(PeerId(9));
|
|
||||||
for (op, at) in order {
|
|
||||||
document.apply_op_idempotent(op.clone(), *at).expect("apply");
|
|
||||||
}
|
|
||||||
let exports = &document.working_registry.networks[&NetworkId(1)].exports;
|
|
||||||
assert_eq!(exports.iter().map(|slot| slot.target.clone()).collect::<Vec<_>>(), vec![export(3).target]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Two registries ordering a removal differently against a write are not order-consistent, though their values agree.
|
|
||||||
#[test]
|
|
||||||
fn order_consistency_covers_removal_stamps() {
|
|
||||||
let with_removal_at = |counter: u64| {
|
|
||||||
let mut document = fresh_document(PeerId(1));
|
|
||||||
let node = Node::new(NetworkId(1), crate::Implementation::ProtoNode(graphene_resource::ResourceId::from(7)), 0);
|
|
||||||
document.apply_op_idempotent(RegistryDelta::AddNode { id: NodeId(2), node: node.clone() }, ts(3, 1)).expect("add");
|
|
||||||
document
|
|
||||||
.apply_op_idempotent(RegistryDelta::RemoveNode { id: NodeId(1), snapshot: node }, ts(counter, 1))
|
|
||||||
.expect("remove");
|
|
||||||
document.working_registry
|
|
||||||
};
|
|
||||||
let (earlier, later) = (with_removal_at(2), with_removal_at(4));
|
|
||||||
assert!(earlier.value_equal(&later));
|
|
||||||
assert!(!earlier.order_consistent(&later));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An input naming a node whose addition has not arrived renders as a dangling input, as one naming a removed node does,
|
|
||||||
/// rather than failing the conversion: the placeholder knows nothing of the node's network.
|
|
||||||
#[test]
|
|
||||||
fn an_input_naming_a_node_not_yet_added_renders_dangling() {
|
|
||||||
use crate::Implementation;
|
|
||||||
let (nested, empty, owner, inner, unseen) = (NetworkId(5), NetworkId(6), NodeId(1), NodeId(2), NodeId(3));
|
|
||||||
let mut document = fresh_document(PeerId(1));
|
|
||||||
let ops = [
|
|
||||||
add_network(ROOT_NETWORK.0),
|
|
||||||
add_network(nested.0),
|
|
||||||
add_network(empty.0),
|
|
||||||
RegistryDelta::AddNode {
|
|
||||||
id: owner,
|
|
||||||
node: Node::new(ROOT_NETWORK, Implementation::Network(nested), 0),
|
|
||||||
},
|
|
||||||
RegistryDelta::AddNode {
|
|
||||||
id: inner,
|
|
||||||
node: Node::new(nested, Implementation::Network(empty), 1),
|
|
||||||
},
|
|
||||||
RegistryDelta::ChangeNodeInput {
|
|
||||||
id: inner,
|
|
||||||
index: 0,
|
|
||||||
new_input: crate::NodeInput::Node { id: unseen, index: 0 },
|
|
||||||
},
|
|
||||||
];
|
|
||||||
for (counter, op) in (1..).zip(ops) {
|
|
||||||
document.apply_op_idempotent(op, ts(counter, 2)).expect("apply");
|
|
||||||
}
|
|
||||||
assert!(document.working_registry.removed_nodes.get(&unseen).is_some_and(|mark| mark.placeholder));
|
|
||||||
|
|
||||||
document.working_registry.to_runtime_with_metadata(&crate::Declarations::new()).expect("converts with a dangling input");
|
|
||||||
}
|
|
||||||
@@ -7,7 +7,7 @@ use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput,
|
|||||||
use graph_craft::graphene_compiler::Compiler;
|
use graph_craft::graphene_compiler::Compiler;
|
||||||
use graph_craft::{ProtoNodeIdentifier, Type, concrete};
|
use graph_craft::{ProtoNodeIdentifier, Type, concrete};
|
||||||
|
|
||||||
use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry, from_value};
|
use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry};
|
||||||
|
|
||||||
/// Helper function to verify a NodeNetwork can be compiled successfully.
|
/// Helper function to verify a NodeNetwork can be compiled successfully.
|
||||||
/// Note: This only works for complete networks with all inputs resolved.
|
/// Note: This only works for complete networks with all inputs resolved.
|
||||||
@@ -20,10 +20,12 @@ fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
|
|||||||
|
|
||||||
/// Convert a runtime network to a storage `Registry`, returning the declarations alongside it.
|
/// Convert a runtime network to a storage `Registry`, returning the declarations alongside it.
|
||||||
/// Proto-node declaration content is no longer stored in the registry (it lives in a byte store);
|
/// Proto-node declaration content is no longer stored in the registry (it lives in a byte store);
|
||||||
/// these tests have no byte store, so they keep the extracted `Declarations` in hand for the back-conversion.
|
/// these tests have no byte store, so they keep the extracted bytes in hand and rebuild a
|
||||||
|
/// `Declarations` map for the back-conversion.
|
||||||
fn to_registry(network: &NodeNetwork) -> (Registry, crate::Declarations) {
|
fn to_registry(network: &NodeNetwork) -> (Registry, crate::Declarations) {
|
||||||
let conversion = Registry::convert_from_runtime(network, &crate::NoMetadata, &Default::default(), PeerId(0)).expect("Failed to convert NodeNetwork to Registry");
|
let conversion = Registry::convert_from_runtime(network, &crate::NoMetadata, &Default::default(), PeerId(0)).expect("Failed to convert NodeNetwork to Registry");
|
||||||
(conversion.registry, conversion.declarations)
|
let declarations = conversion.declarations().expect("rebuild declarations");
|
||||||
|
(conversion.registry, declarations)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A one-node network whose single node references `id` via a `TaggedValue::Resource` input, so
|
/// A one-node network whose single node references `id` via a `TaggedValue::Resource` input, so
|
||||||
@@ -475,7 +477,7 @@ fn test_ui_metadata_round_trip() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
let conversion = Registry::convert_from_runtime(&network, &metadata, &Default::default(), PeerId(0)).expect("Failed to convert to Registry with metadata");
|
let conversion = Registry::convert_from_runtime(&network, &metadata, &Default::default(), PeerId(0)).expect("Failed to convert to Registry with metadata");
|
||||||
let declarations = conversion.declarations;
|
let declarations = conversion.declarations().expect("rebuild declarations");
|
||||||
let registry = conversion.registry;
|
let registry = conversion.registry;
|
||||||
|
|
||||||
let (converted, entries) = registry.to_runtime_with_metadata(&declarations).expect("Failed to convert Registry back with metadata");
|
let (converted, entries) = registry.to_runtime_with_metadata(&declarations).expect("Failed to convert Registry back with metadata");
|
||||||
@@ -530,7 +532,7 @@ fn resources_round_trip_through_from_runtime() {
|
|||||||
assert_eq!(entry.sources.len(), 2, "both sources carried through");
|
assert_eq!(entry.sources.len(), 2, "both sources carried through");
|
||||||
|
|
||||||
// The chain iterates in priority order; decode bodies back to DataSource to compare.
|
// The chain iterates in priority order; decode bodies back to DataSource to compare.
|
||||||
let decoded: Vec<DataSource> = entry.sources.iter().map(|(_, v)| from_value(&v.source).expect("source body decodes")).collect();
|
let decoded: Vec<DataSource> = entry.sources.iter().map(|(_, v)| serde_json::from_value(v.source.clone()).expect("source body decodes")).collect();
|
||||||
assert_eq!(decoded, vec![DataSource::Embedded, DataSource::Url("https://example.com/img.png".parse().unwrap())]);
|
assert_eq!(decoded, vec![DataSource::Embedded, DataSource::Url("https://example.com/img.png".parse().unwrap())]);
|
||||||
|
|
||||||
// All source keys carry the document peer.
|
// All source keys carry the document peer.
|
||||||
@@ -609,9 +611,10 @@ fn unreferenced_runtime_resource_is_not_snapshotted() {
|
|||||||
assert!(!registry.resources.contains_key(&orphan), "the unreferenced (orphan) resource must not be snapshotted");
|
assert!(!registry.resources.contains_key(&orphan), "the unreferenced (orphan) resource must not be snapshotted");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A node-input `TaggedValue::Number` must survive the storage round-trip bit-exact. Inputs are stored
|
/// A node-input `TaggedValue::F64` must survive the storage round-trip bit-exact. Inputs are stored as a
|
||||||
/// type-erased as a `Value`, so this guards against any precision loss in the f64
|
/// self-describing `serde_json::Value` (encoded with the registry's MessagePack codec), so this guards
|
||||||
/// -> Value -> f64 path for a value with a full 17-significant-digit mantissa.
|
/// against any precision loss in the f64 -> serde_json::Number -> f64 path for a value with a full
|
||||||
|
/// 17-significant-digit mantissa.
|
||||||
#[test]
|
#[test]
|
||||||
fn node_input_f64_round_trips_bit_exact() {
|
fn node_input_f64_round_trips_bit_exact() {
|
||||||
use graph_craft::document::value::TaggedValue;
|
use graph_craft::document::value::TaggedValue;
|
||||||
@@ -622,7 +625,7 @@ fn node_input_f64_round_trips_bit_exact() {
|
|||||||
nodes: [(
|
nodes: [(
|
||||||
NodeId(0),
|
NodeId(0),
|
||||||
DocumentNode {
|
DocumentNode {
|
||||||
inputs: vec![NodeInput::value(TaggedValue::Number(precise), false)],
|
inputs: vec![NodeInput::value(TaggedValue::F64(precise), false)],
|
||||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
|
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
@@ -639,8 +642,8 @@ fn node_input_f64_round_trips_bit_exact() {
|
|||||||
let NodeInput::Value { tagged_value, .. } = input else {
|
let NodeInput::Value { tagged_value, .. } = input else {
|
||||||
panic!("expected a value input, got {input:?}")
|
panic!("expected a value input, got {input:?}")
|
||||||
};
|
};
|
||||||
let TaggedValue::Number(actual) = &**tagged_value else {
|
let TaggedValue::F64(actual) = &**tagged_value else {
|
||||||
panic!("expected Number, got {:?}", tagged_value)
|
panic!("expected F64, got {:?}", tagged_value)
|
||||||
};
|
};
|
||||||
|
|
||||||
assert_eq!(actual.to_bits(), precise.to_bits(), "f64 node input drifted: {actual} != {precise}");
|
assert_eq!(actual.to_bits(), precise.to_bits(), "f64 node input drifted: {actual} != {precise}");
|
||||||
@@ -650,6 +653,7 @@ fn node_input_f64_round_trips_bit_exact() {
|
|||||||
/// Conversion must reject this rather than silently collapse them and drop a node.
|
/// Conversion must reject this rather than silently collapse them and drop a node.
|
||||||
#[test]
|
#[test]
|
||||||
fn duplicate_runtime_node_id_is_rejected() {
|
fn duplicate_runtime_node_id_is_rejected() {
|
||||||
|
use crate::AttributesWrite;
|
||||||
use crate::TimeStamp;
|
use crate::TimeStamp;
|
||||||
use crate::to_runtime::ConversionError;
|
use crate::to_runtime::ConversionError;
|
||||||
|
|
||||||
@@ -657,7 +661,7 @@ fn duplicate_runtime_node_id_is_rejected() {
|
|||||||
|
|
||||||
// Force both root-network nodes onto the same runtime ID.
|
// Force both root-network nodes onto the same runtime ID.
|
||||||
for node in registry.node_instances.values_mut() {
|
for node in registry.node_instances.values_mut() {
|
||||||
node.attributes.set(crate::attr::node::ORIGINAL_NODE_ID, crate::Value::Int(7), TimeStamp::ORIGIN);
|
node.attributes.set(crate::attr::node::ORIGINAL_NODE_ID, serde_json::json!(7), TimeStamp::ORIGIN);
|
||||||
}
|
}
|
||||||
|
|
||||||
let error = registry.to_runtime_with_metadata(&declarations).expect_err("duplicate runtime ID must error");
|
let error = registry.to_runtime_with_metadata(&declarations).expect_err("duplicate runtime ID must error");
|
||||||
@@ -716,6 +720,7 @@ fn scope_injections_round_trip() {
|
|||||||
/// network) must error rather than emit an injection pointing at a nonexistent runtime node.
|
/// network) must error rather than emit an injection pointing at a nonexistent runtime node.
|
||||||
#[test]
|
#[test]
|
||||||
fn dangling_scope_injection_is_rejected() {
|
fn dangling_scope_injection_is_rejected() {
|
||||||
|
use crate::AttributesWrite;
|
||||||
use crate::TimeStamp;
|
use crate::TimeStamp;
|
||||||
use crate::to_runtime::ConversionError;
|
use crate::to_runtime::ConversionError;
|
||||||
|
|
||||||
@@ -755,11 +760,7 @@ fn cyclic_network_reference_is_rejected() {
|
|||||||
registry.node_instances.insert(
|
registry.node_instances.insert(
|
||||||
crate::NodeId(0),
|
crate::NodeId(0),
|
||||||
Node {
|
Node {
|
||||||
presence: Default::default(),
|
|
||||||
network_timestamp: Default::default(),
|
|
||||||
inputs_timestamp: Default::default(),
|
|
||||||
implementation: Implementation::Network(child_network_id),
|
implementation: Implementation::Network(child_network_id),
|
||||||
implementation_timestamp: Default::default(),
|
|
||||||
inputs: Vec::new(),
|
inputs: Vec::new(),
|
||||||
attributes: crate::Attributes::default(),
|
attributes: crate::Attributes::default(),
|
||||||
network: crate::ROOT_NETWORK,
|
network: crate::ROOT_NETWORK,
|
||||||
@@ -768,11 +769,7 @@ fn cyclic_network_reference_is_rejected() {
|
|||||||
registry.node_instances.insert(
|
registry.node_instances.insert(
|
||||||
crate::NodeId(1),
|
crate::NodeId(1),
|
||||||
Node {
|
Node {
|
||||||
presence: Default::default(),
|
|
||||||
network_timestamp: Default::default(),
|
|
||||||
inputs_timestamp: Default::default(),
|
|
||||||
implementation: Implementation::Network(crate::ROOT_NETWORK),
|
implementation: Implementation::Network(crate::ROOT_NETWORK),
|
||||||
implementation_timestamp: Default::default(),
|
|
||||||
inputs: Vec::new(),
|
inputs: Vec::new(),
|
||||||
attributes: crate::Attributes::default(),
|
attributes: crate::Attributes::default(),
|
||||||
network: child_network_id,
|
network: child_network_id,
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ use rustc_hash::{FxHashMap, FxHashSet};
|
|||||||
|
|
||||||
use crate::attr::*;
|
use crate::attr::*;
|
||||||
use crate::metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry};
|
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};
|
||||||
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
pub enum ConversionError {
|
pub enum ConversionError {
|
||||||
@@ -38,8 +38,7 @@ pub enum ConversionError {
|
|||||||
pub type Declarations = std::collections::HashMap<ResourceId, ProtoNode>;
|
pub type Declarations = std::collections::HashMap<ResourceId, ProtoNode>;
|
||||||
|
|
||||||
impl Registry {
|
impl Registry {
|
||||||
/// Returns the network plus one metadata entry per node, since every node carries an identity to
|
/// Returns the network plus per-node metadata entries (one per node carrying any `ui::*` attribute).
|
||||||
/// restore even when it has no `ui::*` attribute.
|
|
||||||
pub fn to_runtime_with_metadata(&self, declarations: &Declarations) -> Result<(NodeNetwork, Vec<NodeMetadataEntry>), ConversionError> {
|
pub fn to_runtime_with_metadata(&self, declarations: &Declarations) -> Result<(NodeNetwork, Vec<NodeMetadataEntry>), ConversionError> {
|
||||||
let (network, node_entries, _) = self.to_runtime_with_full_metadata(declarations)?;
|
let (network, node_entries, _) = self.to_runtime_with_full_metadata(declarations)?;
|
||||||
Ok((network, node_entries))
|
Ok((network, node_entries))
|
||||||
@@ -51,7 +50,19 @@ impl Registry {
|
|||||||
let mut node_metadata = Some(Vec::new());
|
let mut node_metadata = Some(Vec::new());
|
||||||
let mut network_metadata = Some(Vec::new());
|
let mut network_metadata = Some(Vec::new());
|
||||||
|
|
||||||
let context = ConversionContext::new(self, declarations);
|
// Group nodes by their owning network in one pass, so each `convert_network` call (one per
|
||||||
|
// network, including nested ones) takes its node list by lookup instead of rescanning the whole
|
||||||
|
// flat `node_instances` map, which would be quadratic on graphs with many networks.
|
||||||
|
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
|
||||||
|
for (&global_id, node) in &self.node_instances {
|
||||||
|
nodes_by_network.entry(node.network).or_default().push((global_id, node));
|
||||||
|
}
|
||||||
|
|
||||||
|
let context = ConversionContext {
|
||||||
|
registry: self,
|
||||||
|
declarations,
|
||||||
|
nodes_by_network,
|
||||||
|
};
|
||||||
|
|
||||||
// Reject cycles up front so the recursive conversion below can assume the network reference
|
// Reject cycles up front so the recursive conversion below can assume the network reference
|
||||||
// graph is acyclic and never blow the stack on a self-referential `Implementation::Network`.
|
// graph is acyclic and never blow the stack on a self-referential `Implementation::Network`.
|
||||||
@@ -63,15 +74,15 @@ impl Registry {
|
|||||||
|
|
||||||
/// Rebuild the runtime [`ResourceRegistry`](graphene_resource::ResourceRegistry) from the stored
|
/// Rebuild the runtime [`ResourceRegistry`](graphene_resource::ResourceRegistry) from the stored
|
||||||
/// `resources`. Each entry's source chain is restored in priority order (the chain is kept
|
/// `resources`. Each entry's source chain is restored in priority order (the chain is kept
|
||||||
/// sorted by key) with bodies decoded from their type-erased `Value` form back to
|
/// sorted by key) with bodies decoded from their type-erased `serde_json::Value` form back to
|
||||||
/// `DataSource`; the resolved hash, if any, is restored last. Inverse of `convert_resources` in
|
/// `DataSource`; the resolved hash, if any, is restored last. Inverse of `convert_resources` in
|
||||||
/// `from_runtime`.
|
/// `from_runtime`.
|
||||||
pub fn to_resource_registry(&self) -> Result<graphene_resource::ResourceRegistry, ConversionError> {
|
pub fn to_resource_registry(&self) -> Result<graphene_resource::ResourceRegistry, ConversionError> {
|
||||||
let mut registry = graphene_resource::ResourceRegistry::new();
|
let mut registry = graphene_resource::ResourceRegistry::new();
|
||||||
|
|
||||||
for (id, entry) in &self.resources {
|
for (id, entry) in &self.resources {
|
||||||
for (_, source) in entry.live_sources() {
|
for (_, source) in &entry.sources {
|
||||||
let decoded: graphene_resource::DataSource = from_value(&source.source).map_err(|error| ConversionError::DeserializationError(error.to_string()))?;
|
let decoded: graphene_resource::DataSource = serde_json::from_value(source.source.clone()).map_err(|error| ConversionError::DeserializationError(error.to_string()))?;
|
||||||
registry.push_source_back(id, decoded);
|
registry.push_source_back(id, decoded);
|
||||||
}
|
}
|
||||||
if let Some(hash) = entry.hash {
|
if let Some(hash) = entry.hash {
|
||||||
@@ -92,26 +103,6 @@ struct ConversionContext<'a> {
|
|||||||
nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &'a Node)>>,
|
nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &'a Node)>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> ConversionContext<'a> {
|
|
||||||
fn new(registry: &'a Registry, declarations: &'a Declarations) -> Self {
|
|
||||||
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
|
|
||||||
for (&global_id, node) in ®istry.node_instances {
|
|
||||||
nodes_by_network.entry(node.network).or_default().push((global_id, node));
|
|
||||||
}
|
|
||||||
Self {
|
|
||||||
registry,
|
|
||||||
declarations,
|
|
||||||
nodes_by_network,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The id the node had in the runtime it was converted from, kept as an attribute so a conversion back
|
|
||||||
/// lands it under the id the editor's metadata is keyed by.
|
|
||||||
fn runtime_node_id(global_id: NodeId, node: &Node) -> RuntimeNodeId {
|
|
||||||
RuntimeNodeId(node.attributes.get_typed(node::ORIGINAL_NODE_ID).unwrap_or(global_id.0))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Converts a single network. Recurses through `Implementation::Network` owning nodes.
|
/// Converts a single network. Recurses through `Implementation::Network` owning nodes.
|
||||||
///
|
///
|
||||||
/// **ID remapping:** Registry uses globally hashed IDs; runtime networks need local IDs. We pull
|
/// **ID remapping:** Registry uses globally hashed IDs; runtime networks need local IDs. We pull
|
||||||
@@ -174,7 +165,7 @@ fn convert_network(
|
|||||||
node_collector: &mut Option<Vec<NodeMetadataEntry>>,
|
node_collector: &mut Option<Vec<NodeMetadataEntry>>,
|
||||||
network_collector: &mut Option<Vec<NetworkMetadataEntry>>,
|
network_collector: &mut Option<Vec<NetworkMetadataEntry>>,
|
||||||
) -> Result<NodeNetwork, ConversionError> {
|
) -> Result<NodeNetwork, ConversionError> {
|
||||||
let network = context.registry.network_or_removed(network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
|
let network = context.registry.networks.get(&network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
|
||||||
|
|
||||||
if let Some(collector) = network_collector.as_mut() {
|
if let Some(collector) = network_collector.as_mut() {
|
||||||
collector.push(extract_network_metadata(context.registry, &network.attributes, metadata_path, network_id));
|
collector.push(extract_network_metadata(context.registry, &network.attributes, metadata_path, network_id));
|
||||||
@@ -182,8 +173,8 @@ fn convert_network(
|
|||||||
|
|
||||||
let mut nodes: FxHashMap<RuntimeNodeId, DocumentNode> = FxHashMap::default();
|
let mut nodes: FxHashMap<RuntimeNodeId, DocumentNode> = FxHashMap::default();
|
||||||
for &(global_id, node) in context.nodes_by_network.get(&network_id).map(Vec::as_slice).unwrap_or_default() {
|
for &(global_id, node) in context.nodes_by_network.get(&network_id).map(Vec::as_slice).unwrap_or_default() {
|
||||||
let runtime_id = runtime_node_id(global_id, node);
|
let local_id = node.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(global_id.0);
|
||||||
let local_id = runtime_id.0;
|
let runtime_id = RuntimeNodeId(local_id);
|
||||||
|
|
||||||
if let Some(collector) = node_collector.as_mut() {
|
if let Some(collector) = node_collector.as_mut() {
|
||||||
collector.push(extract_ui_metadata(node, global_id, metadata_path, runtime_id));
|
collector.push(extract_ui_metadata(node, global_id, metadata_path, runtime_id));
|
||||||
@@ -240,7 +231,8 @@ fn read_scope_injections(registry: &Registry, network_id: NetworkId, attributes:
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok((key, (runtime_node_id(storage_id, referenced), ty)))
|
let local_id = referenced.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(storage_id.0);
|
||||||
|
Ok((key, (RuntimeNodeId(local_id), ty)))
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
@@ -255,7 +247,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 locked = node.attributes.get_or(node::ui::LOCKED, false);
|
||||||
let pinned = node.attributes.get_or(node::ui::PINNED, 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_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();
|
let input_metadata: Vec<InputMetadataEntry> = node.inputs.iter().map(|slot| &slot.attributes).map(extract_input_metadata).collect();
|
||||||
|
|
||||||
@@ -270,17 +261,17 @@ fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[R
|
|||||||
pinned,
|
pinned,
|
||||||
input_metadata,
|
input_metadata,
|
||||||
output_names,
|
output_names,
|
||||||
output_descriptions,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Node references stored here are storage IDs, resolved back to runtime-local IDs the way
|
/// Node references stored here are storage IDs, resolved back to runtime-local IDs the way
|
||||||
/// `read_scope_injections` does. A reference to a node that is no longer in this network is dropped
|
/// `read_scope_injections` does. A reference to a node that is no longer in this network is dropped
|
||||||
/// rather than failing the conversion: a pinned node can have been deleted.
|
/// rather than failing the conversion: the preview target or a pinned node can have been deleted.
|
||||||
fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes, network_path: &[RuntimeNodeId], network_id: NetworkId) -> NetworkMetadataEntry {
|
fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes, network_path: &[RuntimeNodeId], network_id: NetworkId) -> NetworkMetadataEntry {
|
||||||
let to_runtime_id = |storage_id: NodeId| {
|
let to_runtime_id = |storage_id: NodeId| {
|
||||||
let node = registry.node_instances.get(&storage_id).filter(|node| node.network == network_id)?;
|
let node = registry.node_instances.get(&storage_id).filter(|node| node.network == network_id)?;
|
||||||
Some(runtime_node_id(storage_id, node))
|
let local_id = node.attributes.get(node::ORIGINAL_NODE_ID).and_then(|value| value.value.as_u64()).unwrap_or(storage_id.0);
|
||||||
|
Some(RuntimeNodeId(local_id))
|
||||||
};
|
};
|
||||||
|
|
||||||
let pinned_order = attributes
|
let pinned_order = attributes
|
||||||
@@ -300,8 +291,8 @@ fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes,
|
|||||||
|
|
||||||
/// Reassembles `input_data` by scanning every attribute under `ui::input_data::` and stripping the prefix.
|
/// Reassembles `input_data` by scanning every attribute under `ui::input_data::` and stripping the prefix.
|
||||||
fn extract_input_metadata(attributes: &crate::Attributes) -> InputMetadataEntry {
|
fn extract_input_metadata(attributes: &crate::Attributes) -> InputMetadataEntry {
|
||||||
let input_data: HashMap<String, Value> = attributes
|
let input_data: HashMap<String, serde_json::Value> = attributes
|
||||||
.live()
|
.iter()
|
||||||
.filter_map(|(key, value)| key.strip_prefix(node::input::ui::DATA_PREFIX).map(|sub_key| (sub_key.to_owned(), value.value.clone())))
|
.filter_map(|(key, value)| key.strip_prefix(node::input::ui::DATA_PREFIX).map(|sub_key| (sub_key.to_owned(), value.value.clone())))
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
@@ -343,27 +334,25 @@ fn convert_node(
|
|||||||
fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput, input_attributes: &crate::Attributes) -> Result<GraphCraftNodeInput, ConversionError> {
|
fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput, input_attributes: &crate::Attributes) -> Result<GraphCraftNodeInput, ConversionError> {
|
||||||
Ok(match input {
|
Ok(match input {
|
||||||
NodeInput::Node { id: node_id, index: output_index } => {
|
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
|
let referenced = registry.node_instances.get(node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
|
||||||
// arrived yet, though its placeholder knows nothing of its network.
|
|
||||||
let referenced = registry.node_or_removed(*node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
|
|
||||||
let placeholder = registry.removed_nodes.get(node_id).is_some_and(|mark| mark.placeholder);
|
|
||||||
|
|
||||||
// Runtime references are local to one network. A cross-network reference would remap to a
|
// 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.
|
// 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 {
|
return Err(ConversionError::CrossNetworkReference {
|
||||||
network: network_id,
|
network: network_id,
|
||||||
referenced: *node_id,
|
referenced: *node_id,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let local_id = referenced.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(node_id.0);
|
||||||
GraphCraftNodeInput::Node {
|
GraphCraftNodeInput::Node {
|
||||||
node_id: runtime_node_id(*node_id, referenced),
|
node_id: RuntimeNodeId(local_id),
|
||||||
output_index: *output_index as usize,
|
output_index: *output_index as usize,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
NodeInput::Value { value, exposed } => {
|
NodeInput::Value { value, exposed } => {
|
||||||
let tagged_value: TaggedValue = from_value(value).map_err(|e| ConversionError::DeserializationError(format!("TaggedValue: {e:?}")))?;
|
let tagged_value: TaggedValue = serde_json::from_value(value.clone()).map_err(|e| ConversionError::DeserializationError(format!("TaggedValue: {e:?}")))?;
|
||||||
GraphCraftNodeInput::Value {
|
GraphCraftNodeInput::Value {
|
||||||
tagged_value: MemoHash::new(tagged_value),
|
tagged_value: MemoHash::new(tagged_value),
|
||||||
exposed: *exposed,
|
exposed: *exposed,
|
||||||
|
|||||||
@@ -1,265 +0,0 @@
|
|||||||
use serde::de::{self, DeserializeOwned, MapAccess, SeqAccess, Visitor};
|
|
||||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
|
||||||
use std::fmt;
|
|
||||||
|
|
||||||
pub fn to_value<T: Serialize + ?Sized>(value: &T) -> Result<Value, ValueError> {
|
|
||||||
serde_json::to_value(value).map(Value::from).map_err(ValueError)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn from_value<T: DeserializeOwned>(value: &Value) -> Result<T, ValueError> {
|
|
||||||
serde_json::from_value(value.clone().into()).map_err(ValueError)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
|
||||||
#[serde(remote = "Self")]
|
|
||||||
pub enum Value {
|
|
||||||
None,
|
|
||||||
Bool(bool),
|
|
||||||
Int(i128),
|
|
||||||
Float(f64),
|
|
||||||
Str(String),
|
|
||||||
Array(Vec<Value>),
|
|
||||||
Object(Vec<(String, Value)>),
|
|
||||||
}
|
|
||||||
|
|
||||||
// Using `Serializer::is_human_readable` to determine whether to serialize tagged.
|
|
||||||
// We assume that any human-readable format is self describing and does not need tags.
|
|
||||||
impl Serialize for Value {
|
|
||||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
|
||||||
if !serializer.is_human_readable() {
|
|
||||||
return Value::serialize(self, serializer);
|
|
||||||
}
|
|
||||||
match self {
|
|
||||||
Value::None => serializer.serialize_unit(),
|
|
||||||
Value::Bool(boolean) => serializer.serialize_bool(*boolean),
|
|
||||||
Value::Int(int) => serializer.serialize_i128(*int),
|
|
||||||
Value::Float(float) => serializer.serialize_f64(*float),
|
|
||||||
Value::Str(string) => serializer.serialize_str(string),
|
|
||||||
Value::Array(array) => serializer.collect_seq(array),
|
|
||||||
Value::Object(object) => serializer.collect_map(object.iter().map(|(key, value)| (key, value))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Using `Deserialize::is_human_readable` to determine whether to deserialize tagged.
|
|
||||||
// We assume that any human-readable format is self describing and does not need tags.
|
|
||||||
impl<'de> Deserialize<'de> for Value {
|
|
||||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
|
||||||
if !deserializer.is_human_readable() {
|
|
||||||
return Value::deserialize(deserializer);
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Untagged;
|
|
||||||
impl<'de> Visitor<'de> for Untagged {
|
|
||||||
type Value = Value;
|
|
||||||
fn visit_unit<E>(self) -> Result<Value, E> {
|
|
||||||
Ok(Value::None)
|
|
||||||
}
|
|
||||||
fn visit_none<E>(self) -> Result<Value, E> {
|
|
||||||
Ok(Value::None)
|
|
||||||
}
|
|
||||||
fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Value, D::Error> {
|
|
||||||
Deserialize::deserialize(deserializer)
|
|
||||||
}
|
|
||||||
fn visit_bool<E>(self, value: bool) -> Result<Value, E> {
|
|
||||||
Ok(Value::Bool(value))
|
|
||||||
}
|
|
||||||
fn visit_i64<E>(self, value: i64) -> Result<Value, E> {
|
|
||||||
Ok(Value::Int(value.into()))
|
|
||||||
}
|
|
||||||
fn visit_u64<E>(self, value: u64) -> Result<Value, E> {
|
|
||||||
Ok(Value::Int(value.into()))
|
|
||||||
}
|
|
||||||
fn visit_i128<E>(self, value: i128) -> Result<Value, E> {
|
|
||||||
Ok(Value::Int(value))
|
|
||||||
}
|
|
||||||
fn visit_u128<E: de::Error>(self, value: u128) -> Result<Value, E> {
|
|
||||||
i128::try_from(value).map(Value::Int).map_err(E::custom)
|
|
||||||
}
|
|
||||||
fn visit_f64<E>(self, value: f64) -> Result<Value, E> {
|
|
||||||
Ok(Value::Float(value))
|
|
||||||
}
|
|
||||||
fn visit_str<E>(self, value: &str) -> Result<Value, E> {
|
|
||||||
Ok(Value::Str(value.to_owned()))
|
|
||||||
}
|
|
||||||
fn visit_string<E>(self, value: String) -> Result<Value, E> {
|
|
||||||
Ok(Value::Str(value))
|
|
||||||
}
|
|
||||||
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Value, A::Error> {
|
|
||||||
let mut array = Vec::with_capacity(seq.size_hint().unwrap_or(0));
|
|
||||||
while let Some(value) = seq.next_element()? {
|
|
||||||
array.push(value);
|
|
||||||
}
|
|
||||||
Ok(Value::Array(array))
|
|
||||||
}
|
|
||||||
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Value, A::Error> {
|
|
||||||
let mut object: Vec<(String, Value)> = Vec::with_capacity(map.size_hint().unwrap_or(0));
|
|
||||||
while let Some(entry) = map.next_entry()? {
|
|
||||||
object.push(entry);
|
|
||||||
}
|
|
||||||
object.sort_by(|a, b| a.0.cmp(&b.0));
|
|
||||||
object.dedup_by(|b, a| {
|
|
||||||
let dedup = b.0 == a.0;
|
|
||||||
if dedup {
|
|
||||||
std::mem::swap(&mut a.1, &mut b.1);
|
|
||||||
}
|
|
||||||
dedup
|
|
||||||
});
|
|
||||||
Ok(Value::Object(object))
|
|
||||||
}
|
|
||||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
|
||||||
formatter.write_str("a valid Value")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
deserializer.deserialize_any(Untagged)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<serde_json::Value> for Value {
|
|
||||||
fn from(value: serde_json::Value) -> Self {
|
|
||||||
use serde_json::Value as Json;
|
|
||||||
match value {
|
|
||||||
Json::Null => Value::None,
|
|
||||||
Json::Bool(boolean) => Value::Bool(boolean),
|
|
||||||
Json::Number(number) => {
|
|
||||||
if let Some(int) = number.as_i64() {
|
|
||||||
Value::Int(int.into())
|
|
||||||
} else if let Some(int) = number.as_u64() {
|
|
||||||
Value::Int(int.into())
|
|
||||||
} else {
|
|
||||||
Value::Float(number.as_f64().unwrap_or(f64::NAN))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Json::String(string) => Value::Str(string),
|
|
||||||
Json::Array(array) => Value::Array(array.into_iter().map(Into::into).collect()),
|
|
||||||
Json::Object(object) => Value::Object(object.into_iter().map(|(key, value)| (key, value.into())).collect()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<Value> for serde_json::Value {
|
|
||||||
fn from(value: Value) -> Self {
|
|
||||||
use serde_json::Value as Json;
|
|
||||||
match value {
|
|
||||||
Value::None => Json::Null,
|
|
||||||
Value::Bool(boolean) => Json::Bool(boolean),
|
|
||||||
Value::Int(int) => match (i64::try_from(int), u64::try_from(int)) {
|
|
||||||
(Ok(int), _) => int.into(),
|
|
||||||
(_, Ok(int)) => int.into(),
|
|
||||||
(Err(_), Err(_)) => (int as f64).into(),
|
|
||||||
},
|
|
||||||
Value::Float(float) => float.into(),
|
|
||||||
Value::Str(string) => Json::String(string),
|
|
||||||
Value::Array(array) => Json::Array(array.into_iter().map(Into::into).collect()),
|
|
||||||
Value::Object(object) => Json::Object(object.into_iter().map(|(key, value)| (key, value.into())).collect()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
|
||||||
#[error(transparent)]
|
|
||||||
pub struct ValueError(serde_json::Error);
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn round_trips_through_postcard() {
|
|
||||||
let value = serde_json::json!({
|
|
||||||
"null": null,
|
|
||||||
"bools": [true, false],
|
|
||||||
"ints": [0, -1, i64::MIN, u64::MAX],
|
|
||||||
"floats": [1.5, -0.25, 1e300],
|
|
||||||
"str": "text",
|
|
||||||
"empty": { "array": [], "object": {} },
|
|
||||||
"nested": { "b": [{ "c": 1 }], "a": "z" },
|
|
||||||
});
|
|
||||||
|
|
||||||
let bytes = postcard::to_stdvec(&Value::from(value.clone())).unwrap();
|
|
||||||
let decoded: Value = postcard::from_bytes(&bytes).unwrap();
|
|
||||||
assert_eq!(serde_json::Value::from(decoded), value);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn round_trips_through_json_untagged() {
|
|
||||||
let json = serde_json::json!({ "a": [1, -2, 2.5, "s", null, true], "b": {}, "c": [] });
|
|
||||||
let value = Value::from(json.clone());
|
|
||||||
let text = serde_json::to_string(&value).unwrap();
|
|
||||||
assert_eq!(text, serde_json::to_string(&json).unwrap());
|
|
||||||
assert_eq!(serde_json::to_value(&value).unwrap(), json);
|
|
||||||
assert_eq!(serde_json::from_str::<Value>(&text).unwrap(), value);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn json_object_keys_sort_and_last_duplicate_wins() {
|
|
||||||
let value: Value = serde_json::from_str(r#"{"b": 1, "a": 2, "b": 3}"#).unwrap();
|
|
||||||
assert_eq!(value, Value::Object(vec![("a".into(), Value::Int(2)), ("b".into(), Value::Int(3))]));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
|
||||||
enum Sample {
|
|
||||||
Unit,
|
|
||||||
Newtype(u8),
|
|
||||||
Tuple(i64, String),
|
|
||||||
Struct { flag: bool, nested: Option<Box<Sample>> },
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
|
||||||
struct Record {
|
|
||||||
samples: Vec<Sample>,
|
|
||||||
by_id: std::collections::BTreeMap<u32, f64>,
|
|
||||||
bytes: Vec<u8>,
|
|
||||||
letter: char,
|
|
||||||
unit: (),
|
|
||||||
big: u64,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn record() -> Record {
|
|
||||||
Record {
|
|
||||||
samples: vec![
|
|
||||||
Sample::Unit,
|
|
||||||
Sample::Newtype(7),
|
|
||||||
Sample::Tuple(-3, "t".into()),
|
|
||||||
Sample::Struct {
|
|
||||||
flag: true,
|
|
||||||
nested: Some(Box::new(Sample::Unit)),
|
|
||||||
},
|
|
||||||
Sample::Struct { flag: false, nested: None },
|
|
||||||
],
|
|
||||||
by_id: [(2, 0.5), (10, -1.)].into(),
|
|
||||||
bytes: vec![0, 255],
|
|
||||||
letter: 'x',
|
|
||||||
unit: (),
|
|
||||||
big: u64::MAX,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn from_value_round_trips_serde_types() {
|
|
||||||
assert_eq!(from_value::<Record>(&to_value(&record()).unwrap()).unwrap(), record());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn number_variants_map_to_serde_json_numbers() {
|
|
||||||
let json = |value: Value| serde_json::Value::from(value);
|
|
||||||
assert_eq!(json(Value::Int(u64::MAX.into())), serde_json::json!(u64::MAX));
|
|
||||||
assert_eq!(json(Value::Int(-1)), serde_json::json!(-1));
|
|
||||||
assert_eq!(json(Value::Int(i128::MAX)), serde_json::json!(i128::MAX as f64));
|
|
||||||
assert_eq!(json(Value::Float(2.)), serde_json::json!(2.));
|
|
||||||
assert_eq!(Value::from(serde_json::json!(2.)), Value::Float(2.));
|
|
||||||
assert_eq!(Value::from(serde_json::json!(2)), Value::Int(2));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn postcard_tags_follow_declaration_order() {
|
|
||||||
let encode = |value: Value| postcard::to_stdvec(&value).unwrap();
|
|
||||||
assert_eq!(encode(Value::None), [0]);
|
|
||||||
assert_eq!(encode(Value::Bool(true)), [1, 1]);
|
|
||||||
assert_eq!(encode(Value::Int(-1)), [2, 1]);
|
|
||||||
assert_eq!(encode(Value::Float(0.)), [3, 0, 0, 0, 0, 0, 0, 0, 0]);
|
|
||||||
assert_eq!(encode(Value::Str("ab".into())), [4, 2, b'a', b'b']);
|
|
||||||
assert_eq!(encode(Value::Array(vec![Value::None])), [5, 1, 0]);
|
|
||||||
assert_eq!(encode(Value::Object(vec![("k".into(), Value::None)])), [6, 1, 1, b'k', 0]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,15 +4,9 @@ version.workspace = true
|
|||||||
license.workspace = true
|
license.workspace = true
|
||||||
authors.workspace = true
|
authors.workspace = true
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
repository.workspace = true
|
|
||||||
readme.workspace = true
|
|
||||||
homepage.workspace = true
|
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
publish.workspace = true
|
publish.workspace = true
|
||||||
|
|
||||||
[lints]
|
|
||||||
workspace = true
|
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["gpu"]
|
default = ["gpu"]
|
||||||
wasm = ["graphene-std/wasm", "interpreted-executor/wasm", "dep:wasm-bindgen"]
|
wasm = ["graphene-std/wasm", "interpreted-executor/wasm", "dep:wasm-bindgen"]
|
||||||
@@ -30,7 +24,6 @@ interpreted-executor = { workspace = true }
|
|||||||
graphene-std = { workspace = true } # NOTE: `core-types` should not be added here because `graphene-std` re-exports its contents
|
graphene-std = { workspace = true } # NOTE: `core-types` should not be added here because `graphene-std` re-exports its contents
|
||||||
preprocessor = { workspace = true }
|
preprocessor = { workspace = true }
|
||||||
math-parser = { workspace = true }
|
math-parser = { workspace = true }
|
||||||
snapping = { workspace = true }
|
|
||||||
|
|
||||||
# Workspace dependencies
|
# Workspace dependencies
|
||||||
js-sys = { workspace = true }
|
js-sys = { workspace = true }
|
||||||
|
|||||||
@@ -14,14 +14,14 @@ impl Editor {
|
|||||||
environment: Environment,
|
environment: Environment,
|
||||||
uuid_random_seed: u64,
|
uuid_random_seed: u64,
|
||||||
resource_storage: Arc<dyn ResourceStorage>,
|
resource_storage: Arc<dyn ResourceStorage>,
|
||||||
document_store: Arc<dyn document_container::store::DocumentStore>,
|
working_copy_root: Option<std::path::PathBuf>,
|
||||||
mut application_io: PlatformApplicationIo,
|
mut application_io: PlatformApplicationIo,
|
||||||
wake: Wake,
|
wake: Wake,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
ENVIRONMENT.set(environment).expect("Editor shoud only be initialized once");
|
ENVIRONMENT.set(environment).expect("Editor shoud only be initialized once");
|
||||||
graphene_std::uuid::set_uuid_seed(uuid_random_seed);
|
graphene_std::uuid::set_uuid_seed(uuid_random_seed);
|
||||||
|
|
||||||
let mut dispatcher = Dispatcher::new(resource_storage, document_store);
|
let mut dispatcher = Dispatcher::new(resource_storage, working_copy_root);
|
||||||
dispatcher.message_handlers.future_message_handler.set_wake(wake);
|
dispatcher.message_handlers.future_message_handler.set_wake(wake);
|
||||||
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
|
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
|
||||||
crate::node_graph_executor::replace_application_io(application_io);
|
crate::node_graph_executor::replace_application_io(application_io);
|
||||||
|
|||||||
+6
-14
@@ -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_MAX_OVEREXTENSION_PIXELS: f64 = 50.;
|
||||||
pub const DRAG_BEYOND_VIEWPORT_SPEED_FACTOR: f64 = 20.;
|
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
|
// SNAPPING POINT
|
||||||
pub const SNAP_POINT_TOLERANCE: f64 = 5.;
|
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.;
|
pub const DRAG_THRESHOLD: f64 = 1.;
|
||||||
|
|
||||||
@@ -183,23 +187,11 @@ pub const AUTO_SAVE_TIMEOUT_SECONDS: u64 = 1;
|
|||||||
|
|
||||||
// INPUT
|
// INPUT
|
||||||
pub const DOUBLE_CLICK_MILLISECONDS: u64 = 500;
|
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
|
// UI
|
||||||
pub const UI_SCALE_DEFAULT: f64 = 1.;
|
pub const UI_SCALE_DEFAULT: f64 = 1.;
|
||||||
pub const UI_SCALE_MIN: f64 = 0.5;
|
pub const UI_SCALE_MIN: f64 = 0.5;
|
||||||
pub const UI_SCALE_MAX: f64 = 3.;
|
pub const UI_SCALE_MAX: f64 = 3.;
|
||||||
|
|
||||||
// DIALOGS
|
|
||||||
pub const MAX_UNSAVED_DOCUMENTS_IN_DIALOG: usize = 5;
|
|
||||||
pub const MAX_DOCUMENT_NAME_LENGTH_IN_DIALOG: usize = 60;
|
|
||||||
|
|
||||||
// ACTIONS
|
// ACTIONS
|
||||||
pub const BLEND_COUNT_PER_LAYER: usize = 10;
|
pub const BLEND_COUNT_PER_LAYER: usize = 10;
|
||||||
+17
-82
@@ -2,7 +2,6 @@ use crate::messages::debug::utility_types::MessageLoggingVerbosity;
|
|||||||
use crate::messages::defer::DeferMessageContext;
|
use crate::messages::defer::DeferMessageContext;
|
||||||
use crate::messages::dialog::DialogMessageContext;
|
use crate::messages::dialog::DialogMessageContext;
|
||||||
use crate::messages::layout::layout_message_handler::LayoutMessageContext;
|
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::portfolio::utility_types::PanelType;
|
||||||
use crate::messages::preferences::preferences_message_handler::PreferencesMessageContext;
|
use crate::messages::preferences::preferences_message_handler::PreferencesMessageContext;
|
||||||
use crate::messages::prelude::*;
|
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.
|
/// For optimization, these are messages guaranteed to be redundant when repeated.
|
||||||
/// 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.
|
/// 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] = &[
|
const SIDE_EFFECT_FREE_MESSAGES: &[MessageDiscriminant] = &[
|
||||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::DocumentStructureChanged)),
|
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::DocumentStructureChanged)),
|
||||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
|
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
|
||||||
NodeGraphMessageDiscriminant::RunDocumentGraph,
|
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::SubmitActiveGraphRender),
|
||||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::SubmitEyedropperPreviewRender),
|
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::SubmitEyedropperPreviewRender),
|
||||||
MessageDiscriminant::MenuBar(MenuBarMessageDiscriminant::SendLayout),
|
|
||||||
MessageDiscriminant::Frontend(FrontendMessageDiscriminant::UpdateUIScale),
|
MessageDiscriminant::Frontend(FrontendMessageDiscriminant::UpdateUIScale),
|
||||||
];
|
];
|
||||||
/// Since we don't need to update the frontend multiple times per frame,
|
/// 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.
|
/// we have a set of messages which we will buffer until the next frame is requested.
|
||||||
const FRONTEND_UPDATE_MESSAGES: &[MessageDiscriminant] = &[
|
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::UpdateDocumentWidgets),
|
||||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::Overlays(OverlaysMessageDiscriminant::Draw))),
|
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::Overlays(OverlaysMessageDiscriminant::Draw))),
|
||||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::RenderRulers)),
|
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::RenderRulers)),
|
||||||
@@ -96,25 +84,21 @@ const DEBUG_MESSAGE_BLOCK_LIST: &[MessageDiscriminant] = &[
|
|||||||
MessageDiscriminant::Broadcast(BroadcastMessageDiscriminant::TriggerEvent(EventMessageDiscriminant::AnimationFrame)),
|
MessageDiscriminant::Broadcast(BroadcastMessageDiscriminant::TriggerEvent(EventMessageDiscriminant::AnimationFrame)),
|
||||||
MessageDiscriminant::Animation(AnimationMessageDiscriminant::IncrementFrameCounter),
|
MessageDiscriminant::Animation(AnimationMessageDiscriminant::IncrementFrameCounter),
|
||||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::AutoSaveAllDocuments),
|
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.
|
// 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"];
|
const DEBUG_MESSAGE_ENDING_BLOCK_LIST: &[&str] = &["PointerMove", "PointerOutsideViewport", "Overlays", "Draw", "CurrentTime", "Time"];
|
||||||
|
|
||||||
impl Dispatcher {
|
impl Dispatcher {
|
||||||
pub fn new(resource_storage: Arc<dyn ResourceStorage>, document_store: Arc<dyn document_container::store::DocumentStore>) -> Self {
|
pub fn new(resource_storage: Arc<dyn ResourceStorage>, working_copy_root: Option<std::path::PathBuf>) -> Self {
|
||||||
let mut s = Self::default();
|
let mut s = Self::default();
|
||||||
s.message_handlers.resource_storage_message_handler = ResourceStorageMessageHandler::new(resource_storage);
|
s.message_handlers.resource_storage_message_handler = ResourceStorageMessageHandler::new(resource_storage);
|
||||||
s.message_handlers.portfolio_message_handler.set_document_store(document_store);
|
s.message_handlers.portfolio_message_handler.set_working_copy_root(working_copy_root);
|
||||||
s
|
s
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self {
|
pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self {
|
||||||
let mut s = Self::new(
|
let mut s = Self::new(Arc::new(graph_craft::application_io::resource::HashMapResourceStorage::new()), None);
|
||||||
Arc::new(graph_craft::application_io::resource::HashMapResourceStorage::new()),
|
|
||||||
Arc::new(document_container::store::MemoryStore::default()),
|
|
||||||
);
|
|
||||||
s.message_handlers.portfolio_message_handler = PortfolioMessageHandler::with_executor(executor);
|
s.message_handlers.portfolio_message_handler = PortfolioMessageHandler::with_executor(executor);
|
||||||
s
|
s
|
||||||
}
|
}
|
||||||
@@ -271,7 +255,6 @@ impl Dispatcher {
|
|||||||
ipp: &self.message_handlers.input_preprocessor_message_handler,
|
ipp: &self.message_handlers.input_preprocessor_message_handler,
|
||||||
preferences: &self.message_handlers.preferences_message_handler,
|
preferences: &self.message_handlers.preferences_message_handler,
|
||||||
current_tool: &self.message_handlers.tool_message_handler.tool_state.tool_data.active_tool_type,
|
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,
|
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(),
|
timing_information: self.message_handlers.animation_message_handler.timing_information(),
|
||||||
animation: &self.message_handlers.animation_message_handler,
|
animation: &self.message_handlers.animation_message_handler,
|
||||||
@@ -287,7 +270,7 @@ impl Dispatcher {
|
|||||||
let layout = &self.message_handlers.portfolio_message_handler.workspace.panel_layout;
|
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.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.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.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.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;
|
menu_bar_message_handler.show_storage_preferences = self.message_handlers.preferences_message_handler.show_storage_preferences;
|
||||||
@@ -298,45 +281,26 @@ impl Dispatcher {
|
|||||||
.active_document_id
|
.active_document_id
|
||||||
.and_then(|document_id| self.message_handlers.portfolio_message_handler.documents.get_mut(&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 selected_nodes = document.network_interface.selected_nodes();
|
||||||
let network_interface = &document.network_interface;
|
let metadata = &document.network_interface.document_network_metadata().persistent_metadata;
|
||||||
let layer_metadata = document.metadata();
|
|
||||||
let metadata = &network_interface.document_network_metadata().persistent_metadata;
|
|
||||||
|
|
||||||
// Layers only exist in the document network, so a selection inside a subgraph has none
|
|
||||||
let in_document_network = document.selection_network_path().is_empty();
|
|
||||||
|
|
||||||
menu_bar_message_handler.has_active_document = true;
|
menu_bar_message_handler.has_active_document = true;
|
||||||
menu_bar_message_handler.canvas_tilted = document.document_ptz.tilt() != 0.;
|
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.canvas_flipped = document.document_ptz.flip;
|
||||||
menu_bar_message_handler.rulers_visible = document.rulers_visible;
|
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.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_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_layers = selected_nodes.selected_visible_layers(&document.network_interface).next().is_some();
|
||||||
menu_bar_message_handler.has_selected_visible_layers = in_document_network && selected_nodes.selected_visible_layers(network_interface).next().is_some();
|
|
||||||
menu_bar_message_handler.has_selected_visible_and_unlocked_layers =
|
|
||||||
in_document_network && selected_nodes.selected_visible_and_unlocked_layers(network_interface).next().is_some();
|
|
||||||
menu_bar_message_handler.has_selected_groups = in_document_network
|
|
||||||
&& selected_nodes
|
|
||||||
.selected_layers(layer_metadata)
|
|
||||||
.any(|layer| layer.has_children(layer_metadata) && !network_interface.is_artboard(&layer.to_node(), &[]));
|
|
||||||
menu_bar_message_handler.has_selection_history = (!metadata.selection_undo_history.is_empty(), !metadata.selection_redo_history.is_empty());
|
menu_bar_message_handler.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 {
|
} else {
|
||||||
menu_bar_message_handler.has_active_document = false;
|
menu_bar_message_handler.has_active_document = false;
|
||||||
menu_bar_message_handler.canvas_tilted = false;
|
menu_bar_message_handler.canvas_tilted = false;
|
||||||
menu_bar_message_handler.canvas_flipped = false;
|
menu_bar_message_handler.canvas_flipped = false;
|
||||||
menu_bar_message_handler.rulers_visible = false;
|
menu_bar_message_handler.rulers_visible = false;
|
||||||
menu_bar_message_handler.node_graph_open = 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_nodes = false;
|
||||||
menu_bar_message_handler.has_selected_layers = 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.has_selection_history = (false, false);
|
||||||
menu_bar_message_handler.make_path_editable_is_allowed = false;
|
menu_bar_message_handler.make_path_editable_is_allowed = false;
|
||||||
}
|
}
|
||||||
@@ -353,13 +317,11 @@ impl Dispatcher {
|
|||||||
Message::Tool(message) => {
|
Message::Tool(message) => {
|
||||||
let Some(document_id) = self.message_handlers.portfolio_message_handler.active_document_id() else {
|
let Some(document_id) = self.message_handlers.portfolio_message_handler.active_document_id() else {
|
||||||
warn!("Called ToolMessage without an active document.\nGot {message:?}");
|
warn!("Called ToolMessage without an active document.\nGot {message:?}");
|
||||||
self.cleanup_queues(false);
|
return;
|
||||||
continue;
|
|
||||||
};
|
};
|
||||||
let Some(document) = self.message_handlers.portfolio_message_handler.documents.get_mut(&document_id) else {
|
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:?}");
|
warn!("Called ToolMessage with an invalid active document.\nGot {message:?}");
|
||||||
self.cleanup_queues(false);
|
return;
|
||||||
continue;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let context = ToolMessageContext {
|
let context = ToolMessageContext {
|
||||||
@@ -468,33 +430,6 @@ mod test {
|
|||||||
use crate::messages::portfolio::ingest::utility_types::IngestAction;
|
use crate::messages::portfolio::ingest::utility_types::IngestAction;
|
||||||
pub use crate::test_utils::test_prelude::*;
|
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]
|
#[tokio::test]
|
||||||
/// This test will fail when you make changes to the underlying serialization format for a document.
|
/// This test will fail when you make changes to the underlying serialization format for a document.
|
||||||
async fn check_if_demo_art_opens() {
|
async fn check_if_demo_art_opens() {
|
||||||
@@ -552,7 +487,7 @@ mod test {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Check if the graph renders
|
// 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}"));
|
print_problem_to_terminal_on_failure(&format!("Failed to evaluate the graph for document '{document_name}':\n{e}"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,5 +19,3 @@ pub mod node_graph_executor;
|
|||||||
pub mod test_utils;
|
pub mod test_utils;
|
||||||
pub mod utility_traits;
|
pub mod utility_traits;
|
||||||
pub mod utility_types;
|
pub mod utility_types;
|
||||||
|
|
||||||
pub use document_container::store as document_store;
|
|
||||||
@@ -14,13 +14,7 @@ impl MessageHandler<BroadcastMessage, ()> for BroadcastMessageHandler {
|
|||||||
BroadcastMessage::TriggerEvent(message) => self.event.process_message(message, responses, EventMessageContext { listeners: &mut self.listeners }),
|
BroadcastMessage::TriggerEvent(message) => self.event.process_message(message, responses, EventMessageContext { listeners: &mut self.listeners }),
|
||||||
|
|
||||||
// Messages
|
// Messages
|
||||||
BroadcastMessage::SubscribeEvent { on, send } => {
|
BroadcastMessage::SubscribeEvent { on, send } => self.listeners.entry(on).or_default().push(*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::UnsubscribeEvent { on, send } => self.listeners.entry(on).or_default().retain(|msg| *msg != *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;)
|
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::consts::DEFAULT_STROKE_WIDTH;
|
||||||
use crate::messages::clipboard::utility_types::{ClipboardContent, ClipboardContentRaw, ClipboardItem, ClipboardLayer, ClipboardResource, ResourceData};
|
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::graph_operation::utility_types::TransformIn;
|
||||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
|
||||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||||
@@ -80,18 +79,23 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
|||||||
}
|
}
|
||||||
|
|
||||||
ClipboardMessage::CopyLayers => {
|
ClipboardMessage::CopyLayers => {
|
||||||
let Some(active_document) = portfolio.active_document() else { return };
|
if current_tool == &ToolType::Path {
|
||||||
|
|
||||||
// The Path tool copies the points it's editing in the viewport
|
|
||||||
if current_tool == &ToolType::Path && !active_document.graph_view_overlay_open() {
|
|
||||||
responses.add(PathToolMessage::Copy);
|
responses.add(PathToolMessage::Copy);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let SelectionParts { layers, chain_nodes, other_nodes } = active_document.partition_selection();
|
let Some(active_document) = portfolio.active_document_id.and_then(|id| portfolio.documents.get_mut(&id)) else {
|
||||||
let mut items = Vec::new();
|
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| {
|
ordered_last_elements.sort_by_key(|layer| {
|
||||||
let Some(parent) = layer.parent(active_document.metadata()) else { return usize::MAX };
|
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)
|
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<_>>();
|
.collect::<Vec<_>>();
|
||||||
tree_path.reverse();
|
tree_path.reverse();
|
||||||
|
|
||||||
items.push(ClipboardItem::Layer(ClipboardLayer {
|
buffer.push(ClipboardLayer {
|
||||||
nodes: active_document.network_interface.copy_nodes(©_ids, &[]).collect(),
|
nodes: active_document.network_interface.copy_nodes(©_ids, &[]).collect(),
|
||||||
visible: active_document.network_interface.selected_nodes().layer_visible(layer, &active_document.network_interface),
|
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),
|
locked: active_document.network_interface.selected_nodes().layer_locked(layer, &active_document.network_interface),
|
||||||
collapsed: active_document.collapsed.0.contains(&tree_path),
|
collapsed: active_document.collapsed.0.contains(&tree_path),
|
||||||
}));
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let copies = chain_nodes
|
responses.add(ClipboardMessage::WriteItems {
|
||||||
.iter()
|
items: buffer.into_iter().map(ClipboardItem::Layer).collect(),
|
||||||
.filter_map(|node_id| active_document.network_interface.copy_chain_node(node_id, &[]))
|
});
|
||||||
.collect::<Vec<_>>();
|
|
||||||
if !copies.is_empty() {
|
|
||||||
items.push(ClipboardItem::ChainNodes(copies));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Other nodes are kept under their own IDs, so a paste can tell when it's over the same nodes
|
|
||||||
if !other_nodes.is_empty() {
|
|
||||||
let copy_ids = active_document.with_layer_content(&other_nodes).into_iter().map(|node_id| (node_id, node_id)).collect();
|
|
||||||
let nodes = active_document.network_interface.copy_nodes(©_ids, active_document.selection_network_path()).collect();
|
|
||||||
items.push(ClipboardItem::Nodes(nodes));
|
|
||||||
}
|
|
||||||
|
|
||||||
responses.add(ClipboardMessage::WriteItems { items });
|
|
||||||
}
|
}
|
||||||
ClipboardMessage::CutLayers => {
|
ClipboardMessage::CutLayers => {
|
||||||
let Some(active_document) = portfolio.active_document() else { return };
|
if current_tool == &ToolType::Path {
|
||||||
|
|
||||||
if current_tool == &ToolType::Path && !active_document.graph_view_overlay_open() {
|
|
||||||
responses.add(PathToolMessage::Cut);
|
responses.add(PathToolMessage::Cut);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let SelectionParts { layers, chain_nodes, other_nodes } = active_document.partition_selection();
|
if let Some(active_document) = portfolio.active_document()
|
||||||
responses.add(ClipboardMessage::CopyLayers);
|
&& active_document.graph_view_overlay_open()
|
||||||
|
{
|
||||||
// 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
|
responses.add(NodeGraphMessage::Cut);
|
||||||
let deleted_with_children = layers.iter().map(|layer| layer.to_node()).chain(other_nodes).collect::<Vec<_>>();
|
|
||||||
if deleted_with_children.is_empty() && chain_nodes.is_empty() {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
responses.add(DocumentMessage::AddTransaction);
|
|
||||||
if !deleted_with_children.is_empty() {
|
responses.add(ClipboardMessage::CopyLayers);
|
||||||
responses.add(NodeGraphMessage::DeleteNodes {
|
responses.add(DocumentMessage::DeleteSelectedLayers);
|
||||||
node_ids: deleted_with_children,
|
|
||||||
delete_children: true,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if !chain_nodes.is_empty() {
|
|
||||||
responses.add(NodeGraphMessage::DeleteNodes {
|
|
||||||
node_ids: chain_nodes,
|
|
||||||
delete_children: false,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
|
||||||
responses.add(NodeGraphMessage::SelectedNodesUpdated);
|
|
||||||
responses.add(NodeGraphMessage::SendGraph);
|
|
||||||
}
|
}
|
||||||
ClipboardMessage::WriteItems { items } => {
|
ClipboardMessage::WriteItems { items } => {
|
||||||
let has_content = items.iter().any(|item| match item {
|
let has_content = items.iter().any(|item| match item {
|
||||||
ClipboardItem::Layer(entry) => !entry.nodes.is_empty(),
|
ClipboardItem::Layer(entry) => !entry.nodes.is_empty(),
|
||||||
ClipboardItem::Nodes(nodes) => !nodes.is_empty(),
|
ClipboardItem::Nodes(nodes) => !nodes.is_empty(),
|
||||||
ClipboardItem::ChainNodes(copies) => !copies.is_empty(),
|
|
||||||
ClipboardItem::Vector(vector) => !vector.is_empty(),
|
ClipboardItem::Vector(vector) => !vector.is_empty(),
|
||||||
ClipboardItem::Resource(_) => true,
|
ClipboardItem::Resource(_) => true,
|
||||||
});
|
});
|
||||||
@@ -194,7 +167,6 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
|||||||
match item {
|
match item {
|
||||||
ClipboardItem::Layer(entry) => entry.nodes.iter().for_each(|(_, template)| network_interface::collect_template_resources(template, &mut resource_ids)),
|
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::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(_) => {}
|
ClipboardItem::Vector(_) | ClipboardItem::Resource(_) => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -255,7 +227,6 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
|||||||
|
|
||||||
let mut layers = Vec::new();
|
let mut layers = Vec::new();
|
||||||
let mut node_groups = Vec::new();
|
let mut node_groups = Vec::new();
|
||||||
let mut chain_node_groups = Vec::new();
|
|
||||||
let mut vectors = Vec::new();
|
let mut vectors = Vec::new();
|
||||||
let mut resources = Vec::new();
|
let mut resources = Vec::new();
|
||||||
for item in items {
|
for item in items {
|
||||||
@@ -273,12 +244,6 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
|||||||
}
|
}
|
||||||
node_groups.push(nodes);
|
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::Vector(vector) => vectors.push(vector),
|
||||||
ClipboardItem::Resource(resource) => resources.push(resource),
|
ClipboardItem::Resource(resource) => resources.push(resource),
|
||||||
}
|
}
|
||||||
@@ -314,10 +279,7 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
|||||||
responses.add(ClipboardMessage::PasteLayers { entries: layers });
|
responses.add(ClipboardMessage::PasteLayers { entries: layers });
|
||||||
}
|
}
|
||||||
for nodes in node_groups {
|
for nodes in node_groups {
|
||||||
responses.add(DocumentMessage::PasteNodes { nodes });
|
responses.add(NodeGraphMessage::InsertNodes { nodes });
|
||||||
}
|
|
||||||
for copies in chain_node_groups {
|
|
||||||
responses.add(DocumentMessage::PasteChainNodes { copies });
|
|
||||||
}
|
}
|
||||||
for paths in vectors {
|
for paths in vectors {
|
||||||
responses.add(ClipboardMessage::PasteVectors { paths });
|
responses.add(ClipboardMessage::PasteVectors { paths });
|
||||||
@@ -340,6 +302,7 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
|||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
parent_tree_path.reverse();
|
parent_tree_path.reverse();
|
||||||
|
|
||||||
|
let mut all_new_ids = Vec::new();
|
||||||
let mut layers = Vec::new();
|
let mut layers = Vec::new();
|
||||||
|
|
||||||
let mut added_nodes = false;
|
let mut added_nodes = false;
|
||||||
@@ -358,6 +321,8 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
|||||||
added_nodes = true;
|
added_nodes = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
all_new_ids.extend(new_ids.values().copied());
|
||||||
|
|
||||||
responses.add(NodeGraphMessage::AddNodes { nodes: entry.nodes, new_ids });
|
responses.add(NodeGraphMessage::AddNodes { nodes: entry.nodes, new_ids });
|
||||||
responses.add(NodeGraphMessage::MoveLayerToStack { layer, parent, insert_index: 0 });
|
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::RunDocumentGraph);
|
||||||
responses.add(NodeGraphMessage::SelectedNodesSet {
|
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: all_new_ids });
|
||||||
nodes: layers.iter().map(|layer| layer.to_node()).collect(),
|
|
||||||
});
|
|
||||||
responses.add(DeferMessage::AfterGraphRun {
|
responses.add(DeferMessage::AfterGraphRun {
|
||||||
messages: vec![PortfolioMessage::CenterLayers { layers }.into()],
|
messages: vec![PortfolioMessage::CenterLayers { layers }.into()],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ClipboardMessage::PasteVectors { paths } => {
|
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 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
|
// 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 });
|
responses.add(PathToolMessage::Paste { paths });
|
||||||
return;
|
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() {
|
if let Some(document) = portfolio.active_document() {
|
||||||
let mut layers = Vec::new();
|
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::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;
|
||||||
use base64::engine::general_purpose::STANDARD as BASE64;
|
use base64::engine::general_purpose::STANDARD as BASE64;
|
||||||
use glam::DAffine2;
|
use glam::DAffine2;
|
||||||
@@ -27,8 +27,6 @@ pub type ClipboardVectorEntry = (LayerNodeIdentifier, Vector, DAffine2);
|
|||||||
pub enum ClipboardItem {
|
pub enum ClipboardItem {
|
||||||
Layer(ClipboardLayer),
|
Layer(ClipboardLayer),
|
||||||
Nodes(Vec<(NodeId, NodeTemplate)>),
|
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>),
|
Vector(Vec<ClipboardVectorEntry>),
|
||||||
Resource(ClipboardResource),
|
Resource(ClipboardResource),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -107,11 +107,7 @@ impl MessageHandler<ColorPickerMessage, ()> for ColorPickerMessageHandler {
|
|||||||
self.gradient_cyclic = ramp.gradient_cyclic;
|
self.gradient_cyclic = ramp.gradient_cyclic;
|
||||||
self.gradient_hue_direction = ramp.gradient_hue_direction;
|
self.gradient_hue_direction = ramp.gradient_hue_direction;
|
||||||
self.gradient_interpolation = ramp.gradient_interpolation;
|
self.gradient_interpolation = ramp.gradient_interpolation;
|
||||||
let mut gradient = Gradient::from(ramp);
|
let gradient = Gradient::from(ramp);
|
||||||
// An empty gradient renders solid black, so it's edited as black to black, which looks the same but has stops to edit
|
|
||||||
if gradient.is_empty() {
|
|
||||||
gradient = Gradient::from(vec![Color::BLACK, Color::BLACK]);
|
|
||||||
}
|
|
||||||
let first_color = gradient.color(0).unwrap_or(Color::BLACK);
|
let first_color = gradient.color(0).unwrap_or(Color::BLACK);
|
||||||
self.gradient = Some(gradient);
|
self.gradient = Some(gradient);
|
||||||
self.adopt_color(first_color);
|
self.adopt_color(first_color);
|
||||||
@@ -827,6 +823,7 @@ fn rgb_input(channel: RgbChannel, value: Option<f64>, tooltip_label: &'static st
|
|||||||
.disabled(disabled)
|
.disabled(disabled)
|
||||||
.min(0.)
|
.min(0.)
|
||||||
.max(255.)
|
.max(255.)
|
||||||
|
.min_width(1)
|
||||||
.display_decimal_places(0)
|
.display_decimal_places(0)
|
||||||
.tooltip_label(tooltip_label)
|
.tooltip_label(tooltip_label)
|
||||||
.tooltip_description("Integers 0–255.")
|
.tooltip_description("Integers 0–255.")
|
||||||
@@ -840,6 +837,7 @@ fn hsv_input(channel: HsvChannel, value: Option<f64>, max: f64, unit: &'static s
|
|||||||
.disabled(disabled)
|
.disabled(disabled)
|
||||||
.min(0.)
|
.min(0.)
|
||||||
.max(max)
|
.max(max)
|
||||||
|
.min_width(1)
|
||||||
.unit(unit)
|
.unit(unit)
|
||||||
.display_decimal_places(1)
|
.display_decimal_places(1)
|
||||||
.tooltip_label(tooltip_label)
|
.tooltip_label(tooltip_label)
|
||||||
|
|||||||
@@ -123,16 +123,13 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
|||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
let export_type = vec![
|
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(),
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
DropdownInput::new(entries)
|
DropdownInput::new(entries).selected_index(selected_index.map(|index| index as u32)).min_width(200).widget_instance(),
|
||||||
.selected_index(selected_index.map(|index| index as u32))
|
|
||||||
.sizing(WidgetSizing::default().min_width(200))
|
|
||||||
.widget_instance(),
|
|
||||||
];
|
];
|
||||||
|
|
||||||
let resolution = vec![
|
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(),
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
NumberInput::new(Some(self.scale_factor))
|
NumberInput::new(Some(self.scale_factor))
|
||||||
.unit("")
|
.unit("")
|
||||||
@@ -141,7 +138,7 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
|||||||
.increment_step(0.5)
|
.increment_step(0.5)
|
||||||
.disabled(self.file_type == FileType::Svg)
|
.disabled(self.file_type == FileType::Svg)
|
||||||
.on_update(|number_input: &NumberInput| ExportDialogMessage::ScaleFactor { factor: number_input.value.unwrap() }.into())
|
.on_update(|number_input: &NumberInput| ExportDialogMessage::ScaleFactor { factor: number_input.value.unwrap() }.into())
|
||||||
.sizing(WidgetSizing::default().min_width(200))
|
.min_width(200)
|
||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -180,7 +177,7 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let export_area = vec![
|
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(),
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
DropdownInput::new(entries).selected_index(Some(index as u32)).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::layout::utility_types::widget_prelude::*;
|
||||||
|
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||||
use crate::messages::prelude::*;
|
use crate::messages::prelude::*;
|
||||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
|
||||||
use glam::UVec2;
|
use glam::UVec2;
|
||||||
use graph_craft::document::NodeId;
|
use graph_craft::document::NodeId;
|
||||||
use graphene_std::Color;
|
use graphene_std::Color;
|
||||||
@@ -26,7 +26,23 @@ impl MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHa
|
|||||||
|
|
||||||
if self.infinite {
|
if self.infinite {
|
||||||
// Infinite canvas: add a locked white background layer
|
// 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 {
|
} else if self.dimensions.x > 0 && self.dimensions.y > 0 {
|
||||||
// Finite canvas: create an artboard with the specified dimensions
|
// Finite canvas: create an artboard with the specified dimensions
|
||||||
responses.add(GraphOperationMessage::NewArtboard {
|
responses.add(GraphOperationMessage::NewArtboard {
|
||||||
@@ -84,22 +100,17 @@ impl DialogLayoutHolder for NewDocumentDialogMessageHandler {
|
|||||||
impl LayoutHolder for NewDocumentDialogMessageHandler {
|
impl LayoutHolder for NewDocumentDialogMessageHandler {
|
||||||
fn layout(&self) -> Layout {
|
fn layout(&self) -> Layout {
|
||||||
let name = vec![
|
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(),
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
TextInput::new(&self.name)
|
TextInput::new(&self.name)
|
||||||
.on_update(|text_input: &TextInput| NewDocumentDialogMessage::Name { name: text_input.value.clone() }.into())
|
.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
|
.min_width(204) // Matches the 100px of both NumberInputs below + the 4px of the Unrelated-type separator
|
||||||
.sizing(WidgetSizing::default().min_width(204))
|
|
||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
];
|
];
|
||||||
|
|
||||||
let checkbox_id = CheckboxId::new();
|
let checkbox_id = CheckboxId::new();
|
||||||
let infinite = vec![
|
let infinite = vec![
|
||||||
TextLabel::new("Infinite Canvas")
|
TextLabel::new("Infinite Canvas").table_align(true).min_width(90).for_checkbox(checkbox_id).widget_instance(),
|
||||||
.table_align(true)
|
|
||||||
.sizing(WidgetSizing::fixed(90))
|
|
||||||
.for_checkbox(checkbox_id)
|
|
||||||
.widget_instance(),
|
|
||||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
CheckboxInput::new(self.infinite)
|
CheckboxInput::new(self.infinite)
|
||||||
.on_update(|checkbox_input: &CheckboxInput| NewDocumentDialogMessage::Infinite { infinite: checkbox_input.checked }.into())
|
.on_update(|checkbox_input: &CheckboxInput| NewDocumentDialogMessage::Infinite { infinite: checkbox_input.checked }.into())
|
||||||
@@ -108,7 +119,7 @@ impl LayoutHolder for NewDocumentDialogMessageHandler {
|
|||||||
];
|
];
|
||||||
|
|
||||||
let scale = vec![
|
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(),
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
NumberInput::new(Some(self.dimensions.x as f64))
|
NumberInput::new(Some(self.dimensions.x as f64))
|
||||||
.label("W")
|
.label("W")
|
||||||
@@ -117,7 +128,7 @@ impl LayoutHolder for NewDocumentDialogMessageHandler {
|
|||||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||||
.is_integer(true)
|
.is_integer(true)
|
||||||
.disabled(self.infinite)
|
.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())
|
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsX { width: number_input.value.unwrap() }.into())
|
||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||||
@@ -128,7 +139,7 @@ impl LayoutHolder for NewDocumentDialogMessageHandler {
|
|||||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||||
.is_integer(true)
|
.is_integer(true)
|
||||||
.disabled(self.infinite)
|
.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())
|
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsY { height: number_input.value.unwrap() }.into())
|
||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -177,7 +177,6 @@ impl PreferencesDialogMessageHandler {
|
|||||||
}),
|
}),
|
||||||
])
|
])
|
||||||
.selected_index(Some(preferences.selection_mode as u32))
|
.selected_index(Some(preferences.selection_mode as u32))
|
||||||
.sizing(WidgetSizing::default().shrink(false))
|
|
||||||
.widget_instance();
|
.widget_instance();
|
||||||
let selection_mode = vec![
|
let selection_mode = vec![
|
||||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
@@ -267,7 +266,6 @@ impl PreferencesDialogMessageHandler {
|
|||||||
.on_update(move |_| PreferencesMessage::GraphWireStyle { style: GraphWireStyle::GridAligned }.into()),
|
.on_update(move |_| PreferencesMessage::GraphWireStyle { style: GraphWireStyle::GridAligned }.into()),
|
||||||
])
|
])
|
||||||
.selected_index(Some(preferences.graph_wire_style as u32))
|
.selected_index(Some(preferences.graph_wire_style as u32))
|
||||||
.sizing(WidgetSizing::default().shrink(false))
|
|
||||||
.widget_instance();
|
.widget_instance();
|
||||||
let graph_wire_style = vec![
|
let graph_wire_style = vec![
|
||||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
|
|||||||
@@ -1,10 +1,6 @@
|
|||||||
use crate::consts::{MAX_DOCUMENT_NAME_LENGTH_IN_DIALOG, MAX_UNSAVED_DOCUMENTS_IN_DIALOG};
|
|
||||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||||
use crate::messages::prelude::*;
|
use crate::messages::prelude::*;
|
||||||
|
|
||||||
use std::borrow::Cow;
|
|
||||||
use std::fmt::Write;
|
|
||||||
|
|
||||||
/// A dialog for confirming the closing of all documents viewable via `File -> Close All` in the menu bar.
|
/// A dialog for confirming the closing of all documents viewable via `File -> Close All` in the menu bar.
|
||||||
pub struct CloseAllDocumentsDialog {
|
pub struct CloseAllDocumentsDialog {
|
||||||
pub unsaved_document_names: Vec<String>,
|
pub unsaved_document_names: Vec<String>,
|
||||||
@@ -34,26 +30,7 @@ impl DialogLayoutHolder for CloseAllDocumentsDialog {
|
|||||||
|
|
||||||
impl LayoutHolder for CloseAllDocumentsDialog {
|
impl LayoutHolder for CloseAllDocumentsDialog {
|
||||||
fn layout(&self) -> Layout {
|
fn layout(&self) -> Layout {
|
||||||
let mut unsaved_list = "• ".to_string()
|
let unsaved_list = "• ".to_string() + &self.unsaved_document_names.join("\n• ");
|
||||||
+ &self
|
|
||||||
.unsaved_document_names
|
|
||||||
.iter()
|
|
||||||
.take(MAX_UNSAVED_DOCUMENTS_IN_DIALOG)
|
|
||||||
.map(|name| {
|
|
||||||
if name.chars().count() > MAX_DOCUMENT_NAME_LENGTH_IN_DIALOG {
|
|
||||||
Cow::Owned(name.chars().take(MAX_DOCUMENT_NAME_LENGTH_IN_DIALOG).chain(std::iter::once('…')).collect())
|
|
||||||
} else {
|
|
||||||
Cow::Borrowed(name.as_str())
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n• ");
|
|
||||||
|
|
||||||
let remaining = self.unsaved_document_names.len().saturating_sub(MAX_UNSAVED_DOCUMENTS_IN_DIALOG);
|
|
||||||
if remaining > 0 {
|
|
||||||
let s = if remaining == 1 { "" } else { "s" };
|
|
||||||
let _ = write!(unsaved_list, "\n... and {remaining} more document{s}");
|
|
||||||
}
|
|
||||||
|
|
||||||
Layout(vec![
|
Layout(vec![
|
||||||
LayoutGroup::row(vec![TextLabel::new("Save documents before closing them?").bold(true).multiline(true).widget_instance()]),
|
LayoutGroup::row(vec![TextLabel::new("Save documents before closing them?").bold(true).multiline(true).widget_instance()]),
|
||||||
|
|||||||
@@ -51,13 +51,7 @@ impl LayoutHolder for DemoArtworkDialog {
|
|||||||
|
|
||||||
let buttons = chunk
|
let buttons = chunk
|
||||||
.iter()
|
.iter()
|
||||||
.map(|(name, _, filename)| {
|
.map(|(name, _, filename)| TextButton::new(*name).min_width(256).flush(true).on_update(|_| make_dialog(name, filename)).widget_instance())
|
||||||
TextButton::new(*name)
|
|
||||||
.sizing(WidgetSizing::default().min_width(256))
|
|
||||||
.flush(true)
|
|
||||||
.on_update(|_| make_dialog(name, filename))
|
|
||||||
.widget_instance()
|
|
||||||
})
|
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
vec![LayoutGroup::row(images), LayoutGroup::row(buttons), LayoutGroup::row(vec![])]
|
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::app_window::app_window_message_handler::AppWindowPlatform;
|
||||||
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage, FileDialogOptions, FileFilter, FileType, RasterizedImage};
|
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage, FileDialogOptions, FileFilter, FileType, RasterizedImage};
|
||||||
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
|
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::layout::utility_types::widget_prelude::*;
|
||||||
use crate::messages::portfolio::document::node_graph::utility_types::{
|
use crate::messages::portfolio::document::node_graph::utility_types::{
|
||||||
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, NodeGraphErrorDiagnostic,
|
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, NodeGraphErrorDiagnostic,
|
||||||
@@ -68,8 +67,6 @@ pub enum FrontendMessage {
|
|||||||
SendUIMetadata {
|
SendUIMetadata {
|
||||||
#[serde(rename = "nodeDescriptions")]
|
#[serde(rename = "nodeDescriptions")]
|
||||||
node_descriptions: Vec<(String, String)>,
|
node_descriptions: Vec<(String, String)>,
|
||||||
#[serde(rename = "nodeIcons")]
|
|
||||||
node_icons: Vec<(String, IconName)>,
|
|
||||||
#[serde(rename = "nodeTypes")]
|
#[serde(rename = "nodeTypes")]
|
||||||
node_types: Vec<FrontendNodeType>,
|
node_types: Vec<FrontendNodeType>,
|
||||||
},
|
},
|
||||||
@@ -121,9 +118,22 @@ pub enum FrontendMessage {
|
|||||||
filename: String,
|
filename: String,
|
||||||
},
|
},
|
||||||
TriggerPersistenceReadState,
|
TriggerPersistenceReadState,
|
||||||
|
TriggerPersistenceReadDocument {
|
||||||
|
#[serde(rename = "documentId")]
|
||||||
|
document_id: DocumentId,
|
||||||
|
},
|
||||||
TriggerPersistenceWriteState {
|
TriggerPersistenceWriteState {
|
||||||
state: PersistedState,
|
state: PersistedState,
|
||||||
},
|
},
|
||||||
|
TriggerPersistenceDeleteDocument {
|
||||||
|
#[serde(rename = "documentId")]
|
||||||
|
document_id: DocumentId,
|
||||||
|
},
|
||||||
|
TriggerPersistenceWriteDocument {
|
||||||
|
#[serde(rename = "documentId")]
|
||||||
|
document_id: DocumentId,
|
||||||
|
document: String,
|
||||||
|
},
|
||||||
TriggerOpenLaunchDocuments,
|
TriggerOpenLaunchDocuments,
|
||||||
TriggerLoadPreferences,
|
TriggerLoadPreferences,
|
||||||
TriggerSavePreferences {
|
TriggerSavePreferences {
|
||||||
@@ -210,23 +220,6 @@ pub enum FrontendMessage {
|
|||||||
layout_target: LayoutTarget,
|
layout_target: LayoutTarget,
|
||||||
diff: Vec<WidgetDiff>, // TODO: Align this with what's generated
|
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 {
|
UpdateImportReorderIndex {
|
||||||
#[serde(rename = "importIndex")]
|
#[serde(rename = "importIndex")]
|
||||||
index: Option<usize>,
|
index: Option<usize>,
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use graph_craft::application_io::resource::ResourceHash;
|
||||||
|
|
||||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||||
use crate::messages::portfolio::utility_types::WorkspacePanelLayout;
|
use crate::messages::portfolio::utility_types::WorkspacePanelLayout;
|
||||||
use crate::messages::prelude::*;
|
use crate::messages::prelude::*;
|
||||||
@@ -10,6 +12,9 @@ pub struct DocumentInfo {
|
|||||||
pub id: DocumentId,
|
pub id: DocumentId,
|
||||||
pub name: String,
|
pub name: String,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
#[cfg_attr(feature = "wasm", tsify(type = "unknown"))]
|
||||||
|
pub resources: Option<Box<[ResourceHash]>>,
|
||||||
|
#[serde(default)]
|
||||||
pub path: Option<PathBuf>,
|
pub path: Option<PathBuf>,
|
||||||
pub is_saved: bool,
|
pub is_saved: bool,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,8 +16,6 @@ pub enum InputMapperMessage {
|
|||||||
KeyUpNoRepeat(Key),
|
KeyUpNoRepeat(Key),
|
||||||
#[child]
|
#[child]
|
||||||
DoubleClick(MouseButton),
|
DoubleClick(MouseButton),
|
||||||
#[child]
|
|
||||||
DoubleTap(Key),
|
|
||||||
|
|
||||||
// Messages
|
// Messages
|
||||||
PointerMove,
|
PointerMove,
|
||||||
|
|||||||
@@ -40,7 +40,6 @@ impl InputMapperMessageHandler {
|
|||||||
.chain(self.mapping.key_up_no_repeat.iter())
|
.chain(self.mapping.key_up_no_repeat.iter())
|
||||||
.chain(self.mapping.key_down_no_repeat.iter())
|
.chain(self.mapping.key_down_no_repeat.iter())
|
||||||
.chain(self.mapping.double_click.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.wheel_scroll))
|
||||||
.chain(std::iter::once(&self.mapping.pointer_move));
|
.chain(std::iter::once(&self.mapping.pointer_move));
|
||||||
let all_mapping_entries = all_key_mapping_entries.flat_map(|entry| entry.0.iter());
|
let all_mapping_entries = all_key_mapping_entries.flat_map(|entry| entry.0.iter());
|
||||||
@@ -70,7 +69,6 @@ impl InputMapperMessageHandler {
|
|||||||
use InputMapperMessage as IMM;
|
use InputMapperMessage as IMM;
|
||||||
match entry.input {
|
match entry.input {
|
||||||
IMM::KeyDown(key) | IMM::KeyUp(key) | IMM::KeyDownNoRepeat(key) | IMM::KeyUpNoRepeat(key) => keys.push(key),
|
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(Minus); action_dispatch=TransformLayerMessage::TypeNegate),
|
||||||
entry!(KeyDown(Comma); action_dispatch=TransformLayerMessage::TypeDecimalPoint),
|
entry!(KeyDown(Comma); action_dispatch=TransformLayerMessage::TypeDecimalPoint),
|
||||||
entry!(KeyDown(Period); 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
|
// 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!(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!(KeyUp(MouseLeft); action_dispatch=SelectToolMessage::DragStop { remove_from_selection: Alt }),
|
||||||
entry!(KeyDown(Enter); action_dispatch=SelectToolMessage::Enter),
|
entry!(KeyDown(Enter); action_dispatch=SelectToolMessage::Enter),
|
||||||
@@ -118,7 +118,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
|||||||
//
|
//
|
||||||
// ArtboardToolMessage
|
// ArtboardToolMessage
|
||||||
entry!(KeyDown(MouseLeft); action_dispatch=ArtboardToolMessage::PointerDown),
|
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!(KeyUp(MouseLeft); action_dispatch=ArtboardToolMessage::PointerUp),
|
||||||
entry!(KeyDown(Delete); action_dispatch=ArtboardToolMessage::DeleteSelected),
|
entry!(KeyDown(Delete); action_dispatch=ArtboardToolMessage::DeleteSelected),
|
||||||
entry!(KeyDown(Backspace); 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),
|
entry!(KeyDown(Escape); action_dispatch=EyedropperToolMessage::Abort),
|
||||||
//
|
//
|
||||||
// TextToolMessage
|
// 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!(KeyDown(MouseLeft); action_dispatch=TextToolMessage::DragStart),
|
||||||
entry!(KeyUp(MouseLeft); action_dispatch=TextToolMessage::DragStop),
|
entry!(KeyUp(MouseLeft); action_dispatch=TextToolMessage::DragStop),
|
||||||
entry!(KeyDown(MouseRight); action_dispatch=TextToolMessage::Abort),
|
entry!(KeyDown(MouseRight); action_dispatch=TextToolMessage::Abort),
|
||||||
@@ -176,7 +176,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
|||||||
// GradientToolMessage
|
// GradientToolMessage
|
||||||
entry!(DoubleClick(MouseButton::Left); action_dispatch=GradientToolMessage::DoubleClick),
|
entry!(DoubleClick(MouseButton::Left); action_dispatch=GradientToolMessage::DoubleClick),
|
||||||
entry!(KeyDown(MouseLeft); action_dispatch=GradientToolMessage::PointerDown),
|
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!(KeyUp(MouseLeft); action_dispatch=GradientToolMessage::PointerUp),
|
||||||
entry!(KeyDown(Delete); action_dispatch=GradientToolMessage::DeleteStop),
|
entry!(KeyDown(Delete); action_dispatch=GradientToolMessage::DeleteStop),
|
||||||
entry!(KeyDown(Backspace); 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(Escape); action_dispatch=ShapeToolMessage::Abort),
|
||||||
entry!(KeyDown(BracketLeft); action_dispatch=ShapeToolMessage::DecreaseSides),
|
entry!(KeyDown(BracketLeft); action_dispatch=ShapeToolMessage::DecreaseSides),
|
||||||
entry!(KeyDown(BracketRight); action_dispatch=ShapeToolMessage::IncreaseSides),
|
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, 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, 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 }),
|
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(KeyG); action_dispatch=PathToolMessage::GRS { key: KeyG }),
|
||||||
entry!(KeyDown(KeyR); action_dispatch=PathToolMessage::GRS { key: KeyR }),
|
entry!(KeyDown(KeyR); action_dispatch=PathToolMessage::GRS { key: KeyR }),
|
||||||
entry!(KeyDown(KeyS); action_dispatch=PathToolMessage::GRS { key: KeyS }),
|
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(Delete); action_dispatch=PathToolMessage::Delete),
|
||||||
entry!(KeyDown(KeyA); modifiers=[Accel], action_dispatch=PathToolMessage::SelectAll),
|
entry!(KeyDown(KeyA); modifiers=[Accel], action_dispatch=PathToolMessage::SelectAll),
|
||||||
entry!(KeyDown(KeyA); modifiers=[Accel, Shift], canonical, action_dispatch=PathToolMessage::DeselectAllSelected),
|
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)),
|
entry!(KeyDown(KeyJ); modifiers=[Accel], action_dispatch=ToolMessage::Path(PathToolMessage::ClosePath)),
|
||||||
//
|
//
|
||||||
// PenToolMessage
|
// 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!(KeyDownNoRepeat(Tab); action_dispatch=PenToolMessage::SwapHandles),
|
||||||
entry!(KeyDown(MouseLeft); action_dispatch=PenToolMessage::DragStart { append_to_selected: Shift }),
|
entry!(KeyDown(MouseLeft); action_dispatch=PenToolMessage::DragStart { append_to_selected: Shift }),
|
||||||
entry!(KeyUp(MouseLeft); action_dispatch=PenToolMessage::DragStop),
|
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),
|
entry!(KeyDown(Escape); action_dispatch=FreehandToolMessage::Abort),
|
||||||
//
|
//
|
||||||
// SplineToolMessage
|
// 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!(KeyDown(MouseLeft); action_dispatch=SplineToolMessage::DragStart { append_to_selected: Shift }),
|
||||||
entry!(KeyUp(MouseLeft); action_dispatch=SplineToolMessage::DragStop),
|
entry!(KeyUp(MouseLeft); action_dispatch=SplineToolMessage::DragStop),
|
||||||
entry!(KeyDown(MouseRight); action_dispatch=SplineToolMessage::Confirm),
|
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),
|
entry!(KeyDown(Tab); action_dispatch=ToolMessage::ToggleSelectVsPath),
|
||||||
//
|
//
|
||||||
// DocumentMessage
|
// 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!(KeyDownNoRepeat(Escape); action_dispatch=DocumentMessage::Escape),
|
||||||
entry!(KeyDown(Delete); action_dispatch=DocumentMessage::DeleteSelectedLayers),
|
entry!(KeyDown(Delete); action_dispatch=DocumentMessage::DeleteSelectedLayers),
|
||||||
entry!(KeyDown(Backspace); 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(KeyA); modifiers=[Alt], action_dispatch=DocumentMessage::DeselectAllLayers),
|
||||||
entry!(KeyDown(KeyS); modifiers=[Accel], action_dispatch=DocumentMessage::SaveDocument),
|
entry!(KeyDown(KeyS); modifiers=[Accel], action_dispatch=DocumentMessage::SaveDocument),
|
||||||
entry!(KeyDown(KeyS); modifiers=[Accel, Shift], action_dispatch=DocumentMessage::SaveDocumentAs),
|
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(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(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 }),
|
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
|
// NavigationMessage
|
||||||
entry!(KeyDown(MouseMiddle); modifiers=[Alt], action_dispatch=NavigationMessage::BeginCanvasTilt { was_dispatched_from_menu: false }),
|
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(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(MouseMiddle); modifiers=[Control], action_dispatch=NavigationMessage::BeginCanvasZoom),
|
||||||
entry!(KeyDown(MouseLeft); modifiers=[Control, Alt, Space], action_dispatch=NavigationMessage::BeginCanvasZoom { artwork_behind_graph: true }),
|
entry!(KeyDown(MouseLeft); modifiers=[Control, Space], action_dispatch=NavigationMessage::BeginCanvasZoom),
|
||||||
entry!(KeyDown(MouseMiddle); modifiers=[Control], action_dispatch=NavigationMessage::BeginCanvasZoom { artwork_behind_graph: false }),
|
entry!(KeyDown(MouseMiddle); action_dispatch=NavigationMessage::BeginCanvasPan),
|
||||||
entry!(KeyDown(MouseLeft); modifiers=[Control, Space], action_dispatch=NavigationMessage::BeginCanvasZoom { artwork_behind_graph: false }),
|
entry!(KeyDown(MouseLeft); modifiers=[Space], action_dispatch=NavigationMessage::BeginCanvasPan),
|
||||||
entry!(KeyDown(MouseMiddle); action_dispatch=NavigationMessage::BeginCanvasPan { artwork_behind_graph: false }),
|
|
||||||
entry!(KeyDown(MouseLeft); modifiers=[Space], action_dispatch=NavigationMessage::BeginCanvasPan { artwork_behind_graph: false }),
|
|
||||||
entry!(KeyDown(NumpadAdd); modifiers=[Accel], action_dispatch=NavigationMessage::CanvasZoomIncrease { center_on_mouse: false }),
|
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.
|
// `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(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(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!(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=[Control], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel),
|
||||||
entry!(WheelScroll; modifiers=[Command, Alt], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel { artwork_behind_graph: true }),
|
entry!(WheelScroll; modifiers=[Command], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel),
|
||||||
entry!(WheelScroll; modifiers=[Control], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel { artwork_behind_graph: false }),
|
entry!(WheelScroll; modifiers=[Shift], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: true }),
|
||||||
entry!(WheelScroll; modifiers=[Command], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel { artwork_behind_graph: false }),
|
entry!(WheelScroll; disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: false }),
|
||||||
entry!(WheelScroll; modifiers=[Shift, Alt], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: true, artwork_behind_graph: true }),
|
|
||||||
entry!(WheelScroll; modifiers=[Alt], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: false, artwork_behind_graph: true }),
|
|
||||||
entry!(WheelScroll; modifiers=[Shift], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: true, artwork_behind_graph: false }),
|
|
||||||
entry!(WheelScroll; disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: false, artwork_behind_graph: false }),
|
|
||||||
// On Mac, the OS already converts Shift+scroll into horizontal scrolling so we have to reverse the behavior from normal to produce the same outcome
|
// 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=[Control], disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: is_mac }),
|
||||||
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=[Shift], disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: !is_mac }),
|
||||||
entry!(WheelScroll; modifiers=[Alt], disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel { artwork_behind_graph: true }),
|
entry!(WheelScroll; disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel),
|
||||||
entry!(WheelScroll; modifiers=[Control], disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: is_mac, artwork_behind_graph: false }),
|
|
||||||
entry!(WheelScroll; modifiers=[Shift], disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: !is_mac, artwork_behind_graph: false }),
|
|
||||||
entry!(WheelScroll; disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel { artwork_behind_graph: false }),
|
|
||||||
entry!(KeyDown(PageUp); modifiers=[Shift], action_dispatch=NavigationMessage::CanvasPanByViewportFraction { delta: DVec2::new(1., 0.) }),
|
entry!(KeyDown(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(PageDown); modifiers=[Shift], action_dispatch=NavigationMessage::CanvasPanByViewportFraction { delta: DVec2::new(-1., 0.) }),
|
||||||
entry!(KeyDown(PageUp); action_dispatch=NavigationMessage::CanvasPanByViewportFraction { delta: DVec2::new(0., 1.) }),
|
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(Space); modifiers=[Shift], action_dispatch=AnimationMessage::ToggleLivePreview),
|
||||||
entry!(KeyDown(Home); modifiers=[Shift], action_dispatch=AnimationMessage::RestartAnimation),
|
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()));
|
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`
|
// 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 {
|
for sublist in &mut double_click {
|
||||||
sort(sublist)
|
sort(sublist)
|
||||||
}
|
}
|
||||||
// Sort the sublists of `double_tap`
|
|
||||||
for sublist in &mut double_tap {
|
|
||||||
sort(sublist)
|
|
||||||
}
|
|
||||||
// Sort `wheel_scroll`
|
// Sort `wheel_scroll`
|
||||||
sort(&mut wheel_scroll);
|
sort(&mut wheel_scroll);
|
||||||
// Sort `pointer_move`
|
// Sort `pointer_move`
|
||||||
@@ -501,7 +489,6 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
|||||||
key_up_no_repeat,
|
key_up_no_repeat,
|
||||||
key_down_no_repeat,
|
key_down_no_repeat,
|
||||||
double_click,
|
double_click,
|
||||||
double_tap,
|
|
||||||
wheel_scroll,
|
wheel_scroll,
|
||||||
pointer_move,
|
pointer_move,
|
||||||
pointer_shake,
|
pointer_shake,
|
||||||
|
|||||||
@@ -119,7 +119,6 @@ macro_rules! mapping {
|
|||||||
let mut key_up_no_repeat = KeyMappingEntries::key_array();
|
let mut key_up_no_repeat = KeyMappingEntries::key_array();
|
||||||
let mut key_down_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_click = KeyMappingEntries::mouse_buttons_arrays();
|
||||||
let mut double_tap = KeyMappingEntries::key_array();
|
|
||||||
let mut wheel_scroll = KeyMappingEntries::new();
|
let mut wheel_scroll = KeyMappingEntries::new();
|
||||||
let mut pointer_move = KeyMappingEntries::new();
|
let mut pointer_move = KeyMappingEntries::new();
|
||||||
let mut pointer_shake = 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::KeyDownNoRepeat(key) => &mut key_down_no_repeat[key as usize],
|
||||||
InputMapperMessage::KeyUpNoRepeat(key) => &mut key_up_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::DoubleClick(key) => &mut double_click[key as usize],
|
||||||
InputMapperMessage::DoubleTap(key) => &mut double_tap[key as usize],
|
|
||||||
InputMapperMessage::WheelScroll => &mut wheel_scroll,
|
InputMapperMessage::WheelScroll => &mut wheel_scroll,
|
||||||
InputMapperMessage::PointerMove => &mut pointer_move,
|
InputMapperMessage::PointerMove => &mut pointer_move,
|
||||||
InputMapperMessage::PointerShake => &mut pointer_shake,
|
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_up_no_repeat: [KeyMappingEntries; NUMBER_OF_KEYS],
|
||||||
pub key_down_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_click: [KeyMappingEntries; NUMBER_OF_MOUSE_BUTTONS],
|
||||||
pub double_tap: [KeyMappingEntries; NUMBER_OF_KEYS],
|
|
||||||
pub wheel_scroll: KeyMappingEntries,
|
pub wheel_scroll: KeyMappingEntries,
|
||||||
pub pointer_move: KeyMappingEntries,
|
pub pointer_move: KeyMappingEntries,
|
||||||
pub pointer_shake: KeyMappingEntries,
|
pub pointer_shake: KeyMappingEntries,
|
||||||
@@ -37,7 +36,6 @@ impl Mapping {
|
|||||||
InputMapperMessage::KeyDownNoRepeat(key) => &self.key_down_no_repeat[*key as usize],
|
InputMapperMessage::KeyDownNoRepeat(key) => &self.key_down_no_repeat[*key as usize],
|
||||||
InputMapperMessage::KeyUpNoRepeat(key) => &self.key_up_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::DoubleClick(key) => &self.double_click[*key as usize],
|
||||||
InputMapperMessage::DoubleTap(key) => &self.double_tap[*key as usize],
|
|
||||||
InputMapperMessage::WheelScroll => &self.wheel_scroll,
|
InputMapperMessage::WheelScroll => &self.wheel_scroll,
|
||||||
InputMapperMessage::PointerMove => &self.pointer_move,
|
InputMapperMessage::PointerMove => &self.pointer_move,
|
||||||
InputMapperMessage::PointerShake => &self.pointer_shake,
|
InputMapperMessage::PointerShake => &self.pointer_shake,
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
use crate::application::Editor;
|
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::keyboard::{Key, KeyStates, ModifierKeys};
|
||||||
use crate::messages::input_mapper::utility_types::misc::FrameTimeInfo;
|
use crate::messages::input_mapper::utility_types::misc::FrameTimeInfo;
|
||||||
use crate::messages::input_mapper::utility_types::pointer::{MouseButton, MouseKeys, PointerState};
|
use crate::messages::input_mapper::utility_types::pointer::{MouseButton, MouseKeys, PointerState};
|
||||||
@@ -18,18 +17,6 @@ pub struct InputPreprocessorMessageHandler {
|
|||||||
pub keyboard: KeyStates,
|
pub keyboard: KeyStates,
|
||||||
pub mouse: PointerState,
|
pub mouse: PointerState,
|
||||||
pointer_down_time: f64,
|
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]
|
#[message_handler_data]
|
||||||
@@ -39,7 +26,6 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
|||||||
|
|
||||||
match message {
|
match message {
|
||||||
InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys } => {
|
InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys } => {
|
||||||
self.double_tap_state = DoubleTapState::Idle;
|
|
||||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||||
|
|
||||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
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 } => {
|
InputPreprocessorMessage::KeyDown { key, key_repeat, modifier_keys } => {
|
||||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||||
self.keyboard.set(key as usize);
|
self.keyboard.set(key as usize);
|
||||||
|
|
||||||
if !key_repeat {
|
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::KeyDownNoRepeat(key));
|
||||||
}
|
}
|
||||||
responses.add(InputMapperMessage::KeyDown(key));
|
responses.add(InputMapperMessage::KeyDown(key));
|
||||||
@@ -85,22 +56,9 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
|||||||
if !key_repeat {
|
if !key_repeat {
|
||||||
responses.add(InputMapperMessage::KeyUpNoRepeat(key));
|
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));
|
responses.add(InputMapperMessage::KeyUp(key));
|
||||||
}
|
}
|
||||||
InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys } => {
|
InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys } => {
|
||||||
self.double_tap_state = DoubleTapState::Idle;
|
|
||||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||||
|
|
||||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
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);
|
self.translate_mouse_event(pointer_state, false, responses);
|
||||||
}
|
}
|
||||||
InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys } => {
|
InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys } => {
|
||||||
self.double_tap_state = DoubleTapState::Idle;
|
|
||||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||||
|
|
||||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
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));
|
self.frame_time.advance_timestamp(Duration::from_millis(timestamp));
|
||||||
}
|
}
|
||||||
InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys } => {
|
InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys } => {
|
||||||
self.double_tap_state = DoubleTapState::Idle;
|
|
||||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||||
|
|
||||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||||
@@ -237,10 +193,8 @@ impl InputPreprocessorMessageHandler {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod 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::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::*;
|
use crate::messages::prelude::*;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -345,310 +299,4 @@ mod test {
|
|||||||
assert!(responses.contains(&InputMapperMessage::KeyDown(Key::Control).into()));
|
assert!(responses.contains(&InputMapperMessage::KeyDown(Key::Control).into()));
|
||||||
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,
|
widget_id: WidgetId,
|
||||||
file: DroppedFile,
|
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::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::layout::utility_types::widget_prelude::*;
|
||||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||||
use crate::messages::prelude::*;
|
use crate::messages::prelude::*;
|
||||||
@@ -94,41 +91,6 @@ impl MessageHandler<LayoutMessage, LayoutMessageContext<'_>> for LayoutMessageHa
|
|||||||
responses.add((dropdown_input.on_file_drop.callback)(&file));
|
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.
|
// 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)));
|
stack.extend(layout.0.iter().enumerate().map(|(index, val)| ([widget_path.as_slice(), &[index]].concat(), val)));
|
||||||
}
|
}
|
||||||
LayoutGroup::Table(WidgetTable { rows, .. }) => {
|
LayoutGroup::Table(WidgetTable { rows, .. }) => {
|
||||||
@@ -358,29 +320,6 @@ impl LayoutMessageHandler {
|
|||||||
responses.add(callback_message);
|
responses.add(callback_message);
|
||||||
}
|
}
|
||||||
Widget::ImageLabel(_) => {}
|
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::ShortcutLabel(_) => {}
|
||||||
Widget::IconLabel(_) => {}
|
Widget::IconLabel(_) => {}
|
||||||
Widget::NodeCatalog(node_type_input) => match action {
|
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) => {
|
Widget::ParameterExposeButton(parameter_expose_button) => {
|
||||||
let callback_message = match action {
|
let callback_message = match action {
|
||||||
WidgetValueAction::Commit => (parameter_expose_button.on_commit.callback)(&()),
|
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::input_widgets::*;
|
||||||
use super::widgets::label_widgets::*;
|
use super::widgets::label_widgets::*;
|
||||||
use crate::application::generate_uuid;
|
use crate::application::generate_uuid;
|
||||||
use crate::messages::frontend::IconName;
|
|
||||||
use crate::messages::input_mapper::utility_types::keyboard::KeysGroup;
|
use crate::messages::input_mapper::utility_types::keyboard::KeysGroup;
|
||||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
|
||||||
use crate::messages::prelude::*;
|
use crate::messages::prelude::*;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::collections::hash_map::DefaultHasher;
|
use std::collections::hash_map::DefaultHasher;
|
||||||
@@ -60,18 +58,18 @@ define_layout_target!(
|
|||||||
DialogColumn2,
|
DialogColumn2,
|
||||||
/// Contains the widgets located directly above the canvas to the right, for example the zoom in and out buttons.
|
/// Contains the widgets located directly above the canvas to the right, for example the zoom in and out buttons.
|
||||||
DocumentBar,
|
DocumentBar,
|
||||||
/// Visibility and lock toggles for the selection at the bottom left of the Layers panel.
|
/// Controls for adding, grouping, and deleting layers at the bottom of the Layers panel.
|
||||||
LayersPanelBottomLeftBar,
|
LayersPanelBottomBar,
|
||||||
/// Controls for adding, grouping, and deleting layers at the bottom right of the Layers panel.
|
|
||||||
LayersPanelBottomRightBar,
|
|
||||||
/// Blending options at the top of the Layers panel.
|
/// Blending options at the top of the Layers panel.
|
||||||
LayersPanelControlLeftBar,
|
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.
|
/// The dropdown menu at the very top of the application: File, Edit, etc.
|
||||||
MenuBar,
|
MenuBar,
|
||||||
/// Bar at the top of the node graph containing the location and the "Preview" and "Hide" buttons.
|
/// Bar at the top of the node graph containing the location and the "Preview" and "Hide" buttons.
|
||||||
NodeGraphControlBar,
|
NodeGraphControlBar,
|
||||||
/// The body of the Inspector containing many collapsable sections.
|
/// The body of the Properties panel containing many collapsable sections.
|
||||||
Inspector,
|
PropertiesPanel,
|
||||||
/// The contextual input key/mouse combination shortcuts shown in the status bar at the bottom of the window.
|
/// The contextual input key/mouse combination shortcuts shown in the status bar at the bottom of the window.
|
||||||
StatusBarHints,
|
StatusBarHints,
|
||||||
/// The version information shown in the status bar at the bottom right of the window.
|
/// 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>);
|
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.
|
/// 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 {
|
fn compute_widget_id(layout_target: LayoutTarget, widget_path: &[usize], widget: &Widget) -> WidgetId {
|
||||||
let mut hasher = DefaultHasher::new();
|
let mut hasher = DefaultHasher::new();
|
||||||
@@ -295,7 +276,7 @@ impl<'a> Iterator for WidgetIter<'a> {
|
|||||||
self.table.extend(rows.iter().flatten().flatten().rev());
|
self.table.extend(rows.iter().flatten().flatten().rev());
|
||||||
self.next()
|
self.next()
|
||||||
}
|
}
|
||||||
Some(LayoutGroup::NodeSection(NodeSection { layout, .. })) => {
|
Some(LayoutGroup::Section(WidgetSection { layout, .. })) => {
|
||||||
for layout_row in &layout.0 {
|
for layout_row in &layout.0 {
|
||||||
self.stack.push(layout_row);
|
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.table.extend(rows.iter_mut().flatten().flatten().rev());
|
||||||
self.next()
|
self.next()
|
||||||
}
|
}
|
||||||
Some(LayoutGroup::NodeSection(NodeSection { layout, .. })) => {
|
Some(LayoutGroup::Section(WidgetSection { layout, .. })) => {
|
||||||
for layout_row in &mut layout.0 {
|
for layout_row in &mut layout.0 {
|
||||||
self.stack.push(layout_row);
|
self.stack.push(layout_row);
|
||||||
}
|
}
|
||||||
@@ -364,7 +345,7 @@ pub enum LayoutGroup {
|
|||||||
Column(WidgetColumn),
|
Column(WidgetColumn),
|
||||||
Row(WidgetRow),
|
Row(WidgetRow),
|
||||||
Table(WidgetTable),
|
Table(WidgetTable),
|
||||||
NodeSection(NodeSection),
|
Section(WidgetSection),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||||
@@ -390,47 +371,25 @@ pub struct WidgetTable {
|
|||||||
pub unstyled: bool,
|
pub unstyled: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A wire drawn between Inspector sections, styled like the graph's wire carrying the same data.
|
/// 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))]
|
|
||||||
#[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.
|
|
||||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
|
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
|
||||||
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||||
pub struct NodeSection {
|
pub struct WidgetSection {
|
||||||
/// The node's name shown in the section header: its implementation name, followed in parentheses by its given alias if it has one.
|
/// 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,
|
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).
|
/// The node definition's description, shown as the header's tooltip (empty when it has none).
|
||||||
pub description: String,
|
pub description: String,
|
||||||
/// Whether the node is visible rather than hidden (shown as the eye icon).
|
/// Whether the node is visible rather than hidden (shown as the eye icon).
|
||||||
pub visible: bool,
|
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,
|
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).
|
/// 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,
|
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.
|
/// Whether this section is expanded to show its contents, as opposed to being collapsed down to just its header.
|
||||||
pub expanded: bool,
|
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,
|
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,
|
pub layout: Layout,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -465,18 +424,13 @@ impl LayoutGroup {
|
|||||||
Self::Table(WidgetTable { rows, unstyled })
|
Self::Table(WidgetTable { rows, unstyled })
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
pub fn section(name: impl Into<String>, description: impl Into<String>, visible: bool, pinned: bool, expanded: bool, id: u64, layout: Layout) -> Self {
|
||||||
pub fn section(name: impl Into<String>, icon: Option<IconName>, description: impl Into<String>, visible: bool, pinned: bool, expanded: bool, id: u64, layout: Layout) -> Self {
|
Self::Section(WidgetSection {
|
||||||
Self::NodeSection(NodeSection {
|
|
||||||
name: name.into(),
|
name: name.into(),
|
||||||
icon,
|
|
||||||
description: description.into(),
|
description: description.into(),
|
||||||
visible,
|
visible,
|
||||||
pinned,
|
pinned,
|
||||||
draggable: false,
|
draggable: false,
|
||||||
chain_wire: None,
|
|
||||||
output_wire: None,
|
|
||||||
node_reference: false,
|
|
||||||
expanded,
|
expanded,
|
||||||
id,
|
id,
|
||||||
layout,
|
layout,
|
||||||
@@ -500,9 +454,7 @@ impl LayoutGroup {
|
|||||||
Widget::IconLabel(x) => &mut x.tooltip_description,
|
Widget::IconLabel(x) => &mut x.tooltip_description,
|
||||||
Widget::ImageButton(x) => &mut x.tooltip_description,
|
Widget::ImageButton(x) => &mut x.tooltip_description,
|
||||||
Widget::ImageLabel(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::NumberInput(x) => &mut x.tooltip_description,
|
||||||
Widget::ParameterChainToggle(x) => &mut x.tooltip_description,
|
|
||||||
Widget::PopoverButton(x) => &mut x.tooltip_description,
|
Widget::PopoverButton(x) => &mut x.tooltip_description,
|
||||||
Widget::TextAreaInput(x) => &mut x.tooltip_description,
|
Widget::TextAreaInput(x) => &mut x.tooltip_description,
|
||||||
Widget::TextButton(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,
|
name: current_name,
|
||||||
icon: current_icon,
|
|
||||||
description: current_description,
|
description: current_description,
|
||||||
visible: current_visible,
|
visible: current_visible,
|
||||||
pinned: current_pinned,
|
pinned: current_pinned,
|
||||||
draggable: current_draggable,
|
draggable: current_draggable,
|
||||||
chain_wire: current_chain_wire,
|
|
||||||
output_wire: current_output_wire,
|
|
||||||
node_reference: current_node_reference,
|
|
||||||
expanded: current_expanded,
|
expanded: current_expanded,
|
||||||
id: current_id,
|
id: current_id,
|
||||||
layout: current_layout,
|
layout: current_layout,
|
||||||
}),
|
}),
|
||||||
Self::NodeSection(NodeSection {
|
Self::Section(WidgetSection {
|
||||||
name: new_name,
|
name: new_name,
|
||||||
icon: new_icon,
|
|
||||||
description: new_description,
|
description: new_description,
|
||||||
visible: new_visible,
|
visible: new_visible,
|
||||||
pinned: new_pinned,
|
pinned: new_pinned,
|
||||||
draggable: new_draggable,
|
draggable: new_draggable,
|
||||||
chain_wire: new_chain_wire,
|
|
||||||
output_wire: new_output_wire,
|
|
||||||
node_reference: new_node_reference,
|
|
||||||
expanded: new_expanded,
|
expanded: new_expanded,
|
||||||
id: new_id,
|
id: new_id,
|
||||||
layout: new_layout,
|
layout: new_layout,
|
||||||
@@ -605,42 +549,30 @@ impl Diffable for LayoutGroup {
|
|||||||
// TODO: Diff insersion and deletion of items
|
// TODO: Diff insersion and deletion of items
|
||||||
if current_layout.0.len() != new_layout.0.len()
|
if current_layout.0.len() != new_layout.0.len()
|
||||||
|| *current_name != new_name
|
|| *current_name != new_name
|
||||||
|| *current_icon != new_icon
|
|
||||||
|| *current_description != new_description
|
|| *current_description != new_description
|
||||||
|| *current_visible != new_visible
|
|| *current_visible != new_visible
|
||||||
|| *current_pinned != new_pinned
|
|| *current_pinned != new_pinned
|
||||||
|| *current_draggable != new_draggable
|
|| *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_expanded != new_expanded
|
||||||
|| *current_id != new_id
|
|| *current_id != new_id
|
||||||
{
|
{
|
||||||
// Update self to reflect new changes
|
// Update self to reflect new changes
|
||||||
current_name.clone_from(&new_name);
|
current_name.clone_from(&new_name);
|
||||||
current_icon.clone_from(&new_icon);
|
|
||||||
current_description.clone_from(&new_description);
|
current_description.clone_from(&new_description);
|
||||||
*current_visible = new_visible;
|
*current_visible = new_visible;
|
||||||
*current_pinned = new_pinned;
|
*current_pinned = new_pinned;
|
||||||
*current_draggable = new_draggable;
|
*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_expanded = new_expanded;
|
||||||
*current_id = new_id;
|
*current_id = new_id;
|
||||||
current_layout.clone_from(&new_layout);
|
current_layout.clone_from(&new_layout);
|
||||||
|
|
||||||
// Push an update layout group to the diff
|
// Push an update layout group to the diff
|
||||||
let new_value = Self::NodeSection(NodeSection {
|
let new_value = Self::Section(WidgetSection {
|
||||||
name: new_name,
|
name: new_name,
|
||||||
icon: new_icon,
|
|
||||||
description: new_description,
|
description: new_description,
|
||||||
visible: new_visible,
|
visible: new_visible,
|
||||||
pinned: new_pinned,
|
pinned: new_pinned,
|
||||||
draggable: new_draggable,
|
draggable: new_draggable,
|
||||||
chain_wire: new_chain_wire,
|
|
||||||
output_wire: new_output_wire,
|
|
||||||
node_reference: new_node_reference,
|
|
||||||
expanded: new_expanded,
|
expanded: new_expanded,
|
||||||
id: new_id,
|
id: new_id,
|
||||||
layout: new_layout,
|
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);
|
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);
|
layout.replace_widget_ids(layout_target, widget_path, checkbox_map);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -883,11 +815,9 @@ pub enum Widget {
|
|||||||
IconLabel(IconLabel),
|
IconLabel(IconLabel),
|
||||||
ImageButton(ImageButton),
|
ImageButton(ImageButton),
|
||||||
ImageLabel(ImageLabel),
|
ImageLabel(ImageLabel),
|
||||||
MathExpressionInput(MathExpressionInput),
|
|
||||||
ShortcutLabel(ShortcutLabel),
|
ShortcutLabel(ShortcutLabel),
|
||||||
NodeCatalog(NodeCatalog),
|
NodeCatalog(NodeCatalog),
|
||||||
NumberInput(NumberInput),
|
NumberInput(NumberInput),
|
||||||
ParameterChainToggle(ParameterChainToggle),
|
|
||||||
ParameterExposeButton(ParameterExposeButton),
|
ParameterExposeButton(ParameterExposeButton),
|
||||||
ReferencePointInput(ReferencePointInput),
|
ReferencePointInput(ReferencePointInput),
|
||||||
PopoverButton(PopoverButton),
|
PopoverButton(PopoverButton),
|
||||||
@@ -902,78 +832,12 @@ pub enum Widget {
|
|||||||
WorkingColorsInput(WorkingColorsInput),
|
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.
|
/// 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))]
|
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
|
||||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||||
pub struct WidgetDiff {
|
pub struct WidgetDiff {
|
||||||
/// A path to the change
|
/// 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.
|
/// An empty path [] shows that the entire panel has changed and is sent when the UI is first created.
|
||||||
#[serde(rename = "widgetPath")]
|
#[serde(rename = "widgetPath")]
|
||||||
pub widget_path: Vec<usize>,
|
pub widget_path: Vec<usize>,
|
||||||
@@ -1007,7 +871,6 @@ impl DiffUpdate {
|
|||||||
Widget::DropdownInput(widget) => widget.tooltip_shortcut.as_mut(),
|
Widget::DropdownInput(widget) => widget.tooltip_shortcut.as_mut(),
|
||||||
Widget::IconButton(widget) => widget.tooltip_shortcut.as_mut(),
|
Widget::IconButton(widget) => widget.tooltip_shortcut.as_mut(),
|
||||||
Widget::NumberInput(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::ParameterExposeButton(widget) => widget.tooltip_shortcut.as_mut(),
|
||||||
Widget::PopoverButton(widget) => widget.tooltip_shortcut.as_mut(),
|
Widget::PopoverButton(widget) => widget.tooltip_shortcut.as_mut(),
|
||||||
Widget::TextButton(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::ShortcutLabel(widget) => widget.shortcut.as_mut(),
|
||||||
Widget::IconLabel(_)
|
Widget::IconLabel(_)
|
||||||
| Widget::ImageLabel(_)
|
| Widget::ImageLabel(_)
|
||||||
| Widget::MathExpressionInput(_)
|
|
||||||
| Widget::NodeCatalog(_)
|
| Widget::NodeCatalog(_)
|
||||||
| Widget::ReferencePointInput(_)
|
| Widget::ReferencePointInput(_)
|
||||||
| Widget::RadioInput(_)
|
| 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
|
// Apply shortcut conversions to all widgets that have menu lists
|
||||||
let convert_menu_lists = |widget_instance: &mut WidgetInstance| match &mut *widget_instance.widget {
|
let convert_menu_lists = |widget_instance: &mut WidgetInstance| match &mut *widget_instance.widget {
|
||||||
Widget::DropdownInput(dropdown_input) => {
|
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,6 +1,4 @@
|
|||||||
pub mod layout_widget;
|
pub mod layout_widget;
|
||||||
pub mod math_expression;
|
|
||||||
pub mod tooltip_markdown;
|
|
||||||
pub mod widgets;
|
pub mod widgets;
|
||||||
|
|
||||||
pub mod widget_prelude {
|
pub mod widget_prelude {
|
||||||
|
|||||||
@@ -1,78 +0,0 @@
|
|||||||
//! Tooltips render a subset of Markdown: `code` spans, fenced code blocks, `**bold**`, and `*italic*`, where a backslash makes a
|
|
||||||
//! following backslash, asterisk, or backtick literal. Text from outside the editor goes through these so it shows exactly as written.
|
|
||||||
|
|
||||||
/// Escapes text so its backslashes, asterisks, and backticks show as themselves rather than as formatting.
|
|
||||||
pub fn escape_markdown(text: &str) -> String {
|
|
||||||
let mut escaped = String::with_capacity(text.len());
|
|
||||||
for character in text.chars() {
|
|
||||||
if matches!(character, '\\' | '*' | '`') {
|
|
||||||
escaped.push('\\');
|
|
||||||
}
|
|
||||||
escaped.push(character);
|
|
||||||
}
|
|
||||||
escaped
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wraps text in a code span that nothing inside can close, as in CommonMark: the fence outruns every run of backticks within,
|
|
||||||
/// and a space pads the text where it would touch the fence or lose its own edge spaces to the span's trimming.
|
|
||||||
pub fn markdown_code_span(text: &str) -> String {
|
|
||||||
if text.is_empty() {
|
|
||||||
return String::new();
|
|
||||||
}
|
|
||||||
|
|
||||||
let longest_run = text.split(|character| character != '`').map(str::len).max().unwrap_or_default();
|
|
||||||
let fence = "`".repeat(longest_run + 1);
|
|
||||||
|
|
||||||
let touches_fence = text.starts_with('`') || text.ends_with('`');
|
|
||||||
let loses_edge_spaces = text.starts_with(' ') && text.ends_with(' ') && text.contains(|character| character != ' ');
|
|
||||||
let padding = if touches_fence || loses_edge_spaces { " " } else { "" };
|
|
||||||
|
|
||||||
format!("{fence}{padding}{text}{padding}{fence}")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wraps text in a fenced code block that nothing inside can close, as in CommonMark: the fence outruns every run of backticks within.
|
|
||||||
/// The fences are lines of their own, so the block goes at the start of a line.
|
|
||||||
pub fn markdown_code_block(text: &str) -> String {
|
|
||||||
if text.is_empty() {
|
|
||||||
return String::new();
|
|
||||||
}
|
|
||||||
|
|
||||||
let longest_run = text.split(|character| character != '`').map(str::len).max().unwrap_or_default();
|
|
||||||
let fence = "`".repeat(longest_run.max(2) + 1);
|
|
||||||
|
|
||||||
format!("{fence}\n{text}\n{fence}")
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn escaped_text_holds_no_formatting() {
|
|
||||||
assert_eq!(escape_markdown("a*b*c"), "a\\*b\\*c");
|
|
||||||
assert_eq!(escape_markdown("`code`"), "\\`code\\`");
|
|
||||||
assert_eq!(escape_markdown("ends with \\"), "ends with \\\\");
|
|
||||||
assert_eq!(escape_markdown("<b>&</b>"), "<b>&</b>", "HTML is the tooltip's to escape");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn code_spans_contain_anything() {
|
|
||||||
assert_eq!(markdown_code_span("x"), "`x`");
|
|
||||||
assert_eq!(markdown_code_span("a`b"), "``a`b``");
|
|
||||||
assert_eq!(markdown_code_span("a``b`"), "``` a``b` ```");
|
|
||||||
assert_eq!(markdown_code_span("`"), "`` ` ``");
|
|
||||||
assert_eq!(markdown_code_span(" x "), "` x `");
|
|
||||||
assert_eq!(markdown_code_span(" "), "` `");
|
|
||||||
assert_eq!(markdown_code_span("a\\"), "`a\\`", "a backslash is literal inside a span");
|
|
||||||
assert_eq!(markdown_code_span("**<i>**"), "`**<i>**`");
|
|
||||||
assert_eq!(markdown_code_span(""), "");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn code_blocks_contain_anything() {
|
|
||||||
assert_eq!(markdown_code_block("x\n^"), "```\nx\n^\n```");
|
|
||||||
assert_eq!(markdown_code_block("```\n**<i>**"), "````\n```\n**<i>**\n````");
|
|
||||||
assert_eq!(markdown_code_block("`"), "```\n`\n```");
|
|
||||||
assert_eq!(markdown_code_block(""), "");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -33,10 +33,6 @@ pub struct IconButton {
|
|||||||
#[serde(rename = "tooltipShortcut")]
|
#[serde(rename = "tooltipShortcut")]
|
||||||
pub tooltip_shortcut: Option<ActionShortcut>,
|
pub tooltip_shortcut: Option<ActionShortcut>,
|
||||||
|
|
||||||
// Drag and drop
|
|
||||||
#[serde(rename = "dragDropKinds")]
|
|
||||||
pub drag_drop_kinds: DragDropKinds,
|
|
||||||
|
|
||||||
// Callbacks
|
// Callbacks
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||||
@@ -49,19 +45,6 @@ pub struct IconButton {
|
|||||||
pub on_drag_drop: WidgetCallback<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))]
|
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||||
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder)]
|
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder)]
|
||||||
#[derivative(Debug, PartialEq, Default)]
|
#[derivative(Debug, PartialEq, Default)]
|
||||||
@@ -130,33 +113,6 @@ pub struct ParameterExposeButton {
|
|||||||
pub on_commit: WidgetCallback<()>,
|
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))]
|
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||||
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Default, WidgetBuilder)]
|
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Default, WidgetBuilder)]
|
||||||
#[derivative(Debug, PartialEq)]
|
#[derivative(Debug, PartialEq)]
|
||||||
@@ -181,7 +137,10 @@ pub struct TextButton {
|
|||||||
pub emphasized: bool,
|
pub emphasized: bool,
|
||||||
pub flush: bool,
|
pub flush: bool,
|
||||||
pub narrow: bool,
|
pub narrow: bool,
|
||||||
pub sizing: WidgetSizing,
|
|
||||||
|
// Sizing
|
||||||
|
#[serde(rename = "minWidth")]
|
||||||
|
pub min_width: u32,
|
||||||
|
|
||||||
// Tooltips
|
// Tooltips
|
||||||
#[serde(rename = "tooltipLabel")]
|
#[serde(rename = "tooltipLabel")]
|
||||||
@@ -248,9 +207,14 @@ pub struct ColorInput {
|
|||||||
pub disabled: bool,
|
pub disabled: bool,
|
||||||
pub mixed: bool,
|
pub mixed: bool,
|
||||||
|
|
||||||
|
// Sizing
|
||||||
|
#[serde(rename = "minWidth")]
|
||||||
|
pub min_width: u32,
|
||||||
|
#[serde(rename = "maxWidth")]
|
||||||
|
pub max_width: u32,
|
||||||
|
|
||||||
// Styling
|
// Styling
|
||||||
pub narrow: bool,
|
pub narrow: bool,
|
||||||
pub sizing: WidgetSizing,
|
|
||||||
|
|
||||||
// Tooltips
|
// Tooltips
|
||||||
#[serde(rename = "tooltipLabel")]
|
#[serde(rename = "tooltipLabel")]
|
||||||
|
|||||||
Loaded 100 of 520 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user