mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
321
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aa50c42930 | ||
|
|
c73976f407 | ||
|
|
cac1c47b86 | ||
|
|
1426f6401f | ||
|
|
6b951c1806 | ||
|
|
1f860aae6a | ||
|
|
e415714b04 | ||
|
|
a6016b2c03 | ||
|
|
c12f8f1115 | ||
|
|
4e7d72d4b8 | ||
|
|
41d42fe794 | ||
|
|
21dfe04bf8 | ||
|
|
0f26893ec1 | ||
|
|
0cd428f1b1 | ||
|
|
39ed962e16 | ||
|
|
6a5417ed3d | ||
|
|
29052a58db | ||
|
|
84d11b9285 | ||
|
|
5a6192bbd6 | ||
|
|
ca831c00db | ||
|
|
fe8ca88752 | ||
|
|
8fd2529e27 | ||
|
|
641fcc88c6 | ||
|
|
78e35eb6ea | ||
|
|
3302a3b0b8 | ||
|
|
41d295f140 | ||
|
|
a955d6b458 | ||
|
|
97bc10e4c3 | ||
|
|
3af6834d3c | ||
|
|
277641d27e | ||
|
|
f3e945c5d8 | ||
|
|
aef750153b | ||
|
|
f4d37524c8 | ||
|
|
e5b910f840 | ||
|
|
25f49e8750 | ||
|
|
1ef7c9c2c2 | ||
|
|
f34ec257e7 | ||
|
|
1e5b2c7f62 | ||
|
|
c6b669fc88 | ||
|
|
d814b610da | ||
|
|
5181c74205 | ||
|
|
4cb711e3f8 | ||
|
|
e8aea0728a | ||
|
|
6f809fda73 | ||
|
|
ba84e2a968 | ||
|
|
72387d17ad | ||
|
|
048a4c4b70 | ||
|
|
b262195549 | ||
|
|
68a2fb2be3 | ||
|
|
50911a6a25 | ||
|
|
79f3571b02 | ||
|
|
34ea9c59fd | ||
|
|
92ec2069ad | ||
|
|
20e70e7bc9 | ||
|
|
084f14e973 | ||
|
|
694d3d34b3 | ||
|
|
ed457093b1 | ||
|
|
7d44f6ec9e | ||
|
|
54c140e4f3 | ||
|
|
5987c449b2 | ||
|
|
c7605d12a6 | ||
|
|
d9533de9ea | ||
|
|
bc33e14c35 | ||
|
|
2b06d27729 | ||
|
|
b685ca77f2 | ||
|
|
e5b1fad675 | ||
|
|
eb11eec5bb | ||
|
|
182c2a1554 | ||
|
|
913d7093ea | ||
|
|
938fc1783a | ||
|
|
d452ac0de1 | ||
|
|
95bbeb6634 | ||
|
|
5176bfd331 | ||
|
|
db761cf8ed | ||
|
|
34e03038df | ||
|
|
bb3643541d | ||
|
|
ff99f3605c | ||
|
|
9cf037e992 | ||
|
|
888cdf17b0 | ||
|
|
9aef511891 | ||
|
|
0d88e8be9f | ||
|
|
56d38b3f61 | ||
|
|
a6c56c8655 | ||
|
|
2c84bb478f | ||
|
|
9cdaf06ca9 | ||
|
|
027218f16c | ||
|
|
f1ccb74625 | ||
|
|
cb5fabc6ad | ||
|
|
2448157af8 | ||
|
|
d718cdb225 | ||
|
|
dcc9059041 | ||
|
|
d70eae205d | ||
|
|
ed6922d7eb | ||
|
|
abb099a1c3 | ||
|
|
a4d01bfd11 | ||
|
|
d38c767312 | ||
|
|
aba941e81d | ||
|
|
8c67ad508f | ||
|
|
9ca897963f | ||
|
|
2575b94e8f | ||
|
|
b03e4fb215 | ||
|
|
c0eb2ee4ff | ||
|
|
faa5c9d3db | ||
|
|
bedb0d4159 | ||
|
|
94b9d279a2 | ||
|
|
7c4b029d76 | ||
|
|
9ba3c16e79 | ||
|
|
511b4da9f5 | ||
|
|
2c15dc838e | ||
|
|
73b2ef1d58 | ||
|
|
9d2031f7d0 | ||
|
|
7b609ea781 | ||
|
|
5e918af371 | ||
|
|
6e9cac3b32 | ||
|
|
893cbfe450 | ||
|
|
e40ee486a9 | ||
|
|
58182bc2d3 | ||
|
|
3fb8b10f80 | ||
|
|
6fe533a875 | ||
|
|
feea006fc3 | ||
|
|
73897111d0 | ||
|
|
e76dcb15aa | ||
|
|
538959ea90 | ||
|
|
c33f8ae75b | ||
|
|
3126a5b278 | ||
|
|
5f6c18893e | ||
|
|
cdc6f11d92 | ||
|
|
c4b22c03b9 | ||
|
|
6ab9d0360a | ||
|
|
01da817f61 | ||
|
|
040bd71f82 | ||
|
|
f2b0f7c533 | ||
|
|
a2918887f6 | ||
|
|
7b993c5de6 | ||
|
|
3da7f6cea3 | ||
|
|
7569bdb9cb | ||
|
|
4e8a44650e | ||
|
|
b4346fd47d | ||
|
|
e9a18a6437 | ||
|
|
77b0be5c15 | ||
|
|
4bceae26f2 | ||
|
|
c0f50d41d7 | ||
|
|
0b2aa3798a | ||
|
|
13cd718c90 | ||
|
|
39c7ba39cf | ||
|
|
6635e0aeff | ||
|
|
98dabd7ff5 | ||
|
|
a244cc13d0 | ||
|
|
fb71ea426d | ||
|
|
217f32eb88 | ||
|
|
7fb36123e9 | ||
|
|
46220ac268 | ||
|
|
887dbaca2c | ||
|
|
44369cb12b | ||
|
|
56c772de4c | ||
|
|
93e34d00e5 | ||
|
|
46f048b07c | ||
|
|
4b130b4319 | ||
|
|
da0f70bb5f | ||
|
|
5821816228 | ||
|
|
8eaa541c8c | ||
|
|
e4adf16eba | ||
|
|
a8d257e7d6 | ||
|
|
49c592013c | ||
|
|
80db9c13c8 | ||
|
|
cf87796072 | ||
|
|
8859e6b1a0 | ||
|
|
1f23991a72 | ||
|
|
2be252d7b4 | ||
|
|
2c1acbdc62 | ||
|
|
61e751f278 | ||
|
|
cdd62ed269 | ||
|
|
f12094ced6 | ||
|
|
b5c4aa4598 | ||
|
|
da8ae2be43 | ||
|
|
157c011953 | ||
|
|
ae6807f8e3 | ||
|
|
17ba74485a | ||
|
|
1f2eef5f8f | ||
|
|
1b6513b954 | ||
|
|
74fddff589 | ||
|
|
7e24f810c6 | ||
|
|
306cf1110f | ||
|
|
b610eede20 | ||
|
|
21f671555a | ||
|
|
951059aa3a | ||
|
|
e68254eff3 | ||
|
|
61cf619f4b | ||
|
|
7914a09d4b | ||
|
|
95e2cbca15 | ||
|
|
724bb0fc17 | ||
|
|
fb171cd5ac | ||
|
|
cb46be0430 | ||
|
|
7ffc9b9e3b | ||
|
|
58a65c69e9 | ||
|
|
d1d50ec469 | ||
|
|
e25e32ee8a | ||
|
|
d560a39856 | ||
|
|
00e08359a3 | ||
|
|
116ce622d4 | ||
|
|
082fb5d959 | ||
|
|
043f28cc23 | ||
|
|
b7413dd22c | ||
|
|
586737247e | ||
|
|
055b7f0055 | ||
|
|
4a042bade2 | ||
|
|
3aa018a15c | ||
|
|
8508dc6c9d | ||
|
|
fbba0cd037 | ||
|
|
ae7c51a964 | ||
|
|
0c49026c9a | ||
|
|
bc29166d4c | ||
|
|
0f3e3f7337 | ||
|
|
a03db0ac6c | ||
|
|
932ed8653e | ||
|
|
5ab3f067fe | ||
|
|
3df028cb18 | ||
|
|
e423dd96de | ||
|
|
bef58bf395 | ||
|
|
131abf5883 | ||
|
|
3859bd713e | ||
|
|
ac40f1838f | ||
|
|
9055a5f3d5 | ||
|
|
d32caeab52 | ||
|
|
15f4aa8f98 | ||
|
|
99ce2ea565 | ||
|
|
87200f3c2a | ||
|
|
214632c5ec | ||
|
|
64fb4eda61 | ||
|
|
f9e30c4c77 | ||
|
|
bfa48439c8 | ||
|
|
a717403db8 | ||
|
|
fdf13f91cb | ||
|
|
65e0969721 | ||
|
|
8f265e7660 | ||
|
|
98e6b97072 | ||
|
|
a3e9074955 | ||
|
|
04afada5b3 | ||
|
|
3e183fbd28 | ||
|
|
849d6a17be | ||
|
|
20ba069fe0 | ||
|
|
c82093f153 | ||
|
|
010785d8db | ||
|
|
69774d445c | ||
|
|
b42c632474 | ||
|
|
f195e363a5 | ||
|
|
40f99152ce | ||
|
|
3b1170b148 | ||
|
|
3a20091d3a | ||
|
|
e5206c3b50 | ||
|
|
fbc736e1cc | ||
|
|
d7da2ba9e7 | ||
|
|
a5784c8f0b | ||
|
|
83fbaca6f2 | ||
|
|
b6f73b0691 | ||
|
|
557f8020bb | ||
|
|
fb94d99807 | ||
|
|
264601c5f7 | ||
|
|
5db7e1816a | ||
|
|
5b02edfd9a | ||
|
|
7c0a4073e9 | ||
|
|
275100eab0 | ||
|
|
42cd2a4303 | ||
|
|
e4f81fc947 | ||
|
|
492cf18cb0 | ||
|
|
05630bab6e | ||
|
|
a465948ad4 | ||
|
|
63cf0151e2 | ||
|
|
9c7a633d5b | ||
|
|
166241b0e8 | ||
|
|
ea49f3c2fc | ||
|
|
100f81c307 | ||
|
|
886ff03ef2 | ||
|
|
7a1d1f3238 | ||
|
|
612afb7ebb | ||
|
|
daf3f25d21 | ||
|
|
a2de2a9c09 | ||
|
|
98be2b8c79 | ||
|
|
83fda4f08c | ||
|
|
20c6ba19d3 | ||
|
|
7eeb7d84cd | ||
|
|
7ddc66adbe | ||
|
|
c20a243fc2 | ||
|
|
3eecc31bfd | ||
|
|
7099f056dc | ||
|
|
9680d34abf | ||
|
|
592b2fbe32 | ||
|
|
60f80682c5 | ||
|
|
9fc4fcc7a0 | ||
|
|
7915800d73 | ||
|
|
c91be74a55 | ||
|
|
abe2a565d1 | ||
|
|
6154e4d219 | ||
|
|
62b7ccf40c | ||
|
|
9b45af854a | ||
|
|
562e6602eb | ||
|
|
8fb18012cf | ||
|
|
2b3161773f | ||
|
|
167d733f02 | ||
|
|
ee499be31f | ||
|
|
d385f3c69b | ||
|
|
e372f78b7e | ||
|
|
8686b2c891 | ||
|
|
e3aa32bc83 | ||
|
|
77d439ec35 | ||
|
|
c30054579f | ||
|
|
81a319430b | ||
|
|
1fb6fcb447 | ||
|
|
32d244e700 | ||
|
|
0877f9d50e | ||
|
|
14c1dd0397 | ||
|
|
daf7b3e7b9 | ||
|
|
bdf53070f2 | ||
|
|
0d0ec96709 | ||
|
|
6feaf4ec9d | ||
|
|
5541769dc5 | ||
|
|
1fccb112cb | ||
|
|
eb50be844b | ||
|
|
0f0f62c2e9 | ||
|
|
f5b1fee85f | ||
|
|
6f8c4b2adb |
No files matched your search
@@ -1,2 +1,2 @@
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/6687dc6d3d8552948458d00d35e2bee3a40ab66b.tar.gz
|
||||
7663b4a35f377a5d3363430a725a1d5f634fbdc56adca5e43167786b8fe1b253
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/0d004aa61e6b48d316e8e5db6d59ccc4788f192d.tar.gz
|
||||
772d64518be43c99977ba56f69e574531c56e83d2df2f42ab066f77f74b0dd1f
|
||||
@@ -2,25 +2,11 @@
|
||||
"image": "mcr.microsoft.com/devcontainers/base:debian",
|
||||
"features": {
|
||||
"ghcr.io/devcontainers/features/rust:1": {
|
||||
"profile": "default",
|
||||
"targets": "wasm32-unknown-unknown"
|
||||
"profile": "default"
|
||||
},
|
||||
"ghcr.io/devcontainers/features/node:1": {
|
||||
// NOTICE: keep in sync with `.nvmrc`
|
||||
"version": "24"
|
||||
}
|
||||
},
|
||||
// NOTICE: keep these tool versions in sync with `.github/workflows/build.yml`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
|
||||
"containerEnv": {
|
||||
"WASM_BINDGEN_CLI_VERSION": "0.2.121",
|
||||
"CARGO_ABOUT_VERSION": "0.9.2",
|
||||
"BINARYEN_VERSION": "130",
|
||||
"CARGO_BINSTALL_VERSION": "1.23.0"
|
||||
},
|
||||
"onCreateCommand": {
|
||||
"Install cargo-about and wasm-bindgen-cli": "curl -sSfL https://github.com/cargo-bins/cargo-binstall/releases/download/v$CARGO_BINSTALL_VERSION/cargo-binstall-$(uname -m)-unknown-linux-musl.tgz | tar xz -C $CARGO_HOME/bin && BINSTALL_DISABLE_TELEMETRY=true cargo binstall --no-confirm cargo-about@$CARGO_ABOUT_VERSION wasm-bindgen-cli@$WASM_BINDGEN_CLI_VERSION",
|
||||
"Install Binaryen wasm-opt": "curl -sSfL https://github.com/WebAssembly/binaryen/releases/download/version_$BINARYEN_VERSION/binaryen-version_$BINARYEN_VERSION-$(uname -m)-linux.tar.gz | tar xz -C $CARGO_HOME/bin --strip-components=2 binaryen-version_$BINARYEN_VERSION/bin/wasm-opt"
|
||||
"ghcr.io/devcontainers/features/node:1": {}
|
||||
},
|
||||
"onCreateCommand": "cargo install cargo-about && cargo install -f [email protected]",
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
// NOTE: Keep this in sync with `.vscode/extensions.json`
|
||||
@@ -30,16 +16,14 @@
|
||||
"tamasfe.even-better-toml",
|
||||
// Web
|
||||
"dbaeumer.vscode-eslint",
|
||||
"esbenp.prettier-vscode",
|
||||
"svelte.svelte-vscode",
|
||||
"vitaliymaz.vscode-svg-previewer",
|
||||
// Code quality
|
||||
"wayou.vscode-todo-highlight",
|
||||
"streetsidesoftware.code-spell-checker",
|
||||
// Git
|
||||
// Helpful
|
||||
"mhutchie.git-graph",
|
||||
"qezhu.gitlink",
|
||||
// Helpful
|
||||
"wmaurer.change-case"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
# Keavon Chambers (@Keavon [email protected])
|
||||
|
||||
|
||||
# Dennis Kobert (@TrueDoctor [email protected])
|
||||
|
||||
/document/format/ @TrueDoctor
|
||||
|
||||
/node-graph/graph-craft/ @TrueDoctor
|
||||
/node-graph/preprocessor/ @TrueDoctor
|
||||
/node-graph/node-macro/ @TrueDoctor
|
||||
/node-graph/interpreted-executor/ @TrueDoctor
|
||||
/node-graph/graphene-cli/ @TrueDoctor
|
||||
|
||||
# Timon Schelling (@timon-schelling [email protected])
|
||||
|
||||
/.nix/ @timon-schelling
|
||||
/flake.nix @timon-schelling
|
||||
/flake.lock @timon-schelling
|
||||
|
||||
/desktop/ @timon-schelling
|
||||
|
||||
/editor/src/messages/future/ @timon-schelling
|
||||
/editor/src/messages/resource_storage/ @timon-schelling
|
||||
/editor/src/messages/network/ @timon-schelling
|
||||
/editor/src/messages/app_window/ @timon-schelling
|
||||
/editor/src/messages/clipboard/ @timon-schelling
|
||||
/editor/src/messages/viewport/ @timon-schelling
|
||||
|
||||
/libraries/wgpu-sync/ @timon-schelling
|
||||
|
||||
/node-graph/libraries/canvas-utils/ @timon-schelling
|
||||
|
||||
/tools/cargo-run/ @timon-schelling
|
||||
/tools/third-party-licenses/ @timon-schelling
|
||||
+10
-24
@@ -58,7 +58,6 @@ jobs:
|
||||
RUSTC_WRAPPER: /usr/bin/sccache
|
||||
CARGO_INCREMENTAL: 0
|
||||
SCCACHE_DIR: /var/lib/github-actions/.cache
|
||||
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.121"
|
||||
BINARYEN_VERSION: "130"
|
||||
steps:
|
||||
@@ -303,11 +302,9 @@ jobs:
|
||||
pull-requests: write
|
||||
|
||||
env:
|
||||
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.121"
|
||||
BINARYEN_VERSION: "130"
|
||||
CARGO_ABOUT_VERSION: "0.9.2"
|
||||
CARGO_BINSTALL_VERSION: "1.23.0"
|
||||
CARGO_ABOUT_VERSION: "0.9.0"
|
||||
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
@@ -344,9 +341,7 @@ jobs:
|
||||
frontend/package-lock.json
|
||||
|
||||
- name: 📦 Install Cargo-binstall
|
||||
uses: cargo-bins/cargo-binstall@v1.23.0
|
||||
with:
|
||||
version: ${{ env.CARGO_BINSTALL_VERSION }}
|
||||
uses: cargo-bins/cargo-binstall@main
|
||||
|
||||
- name: 🚧 Install native dependencies
|
||||
shell: pwsh
|
||||
@@ -502,11 +497,9 @@ jobs:
|
||||
pull-requests: write
|
||||
|
||||
env:
|
||||
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.121"
|
||||
BINARYEN_VERSION: "130"
|
||||
CARGO_ABOUT_VERSION: "0.9.2"
|
||||
CARGO_BINSTALL_VERSION: "1.23.0"
|
||||
CARGO_ABOUT_VERSION: "0.9.0"
|
||||
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
@@ -542,11 +535,6 @@ jobs:
|
||||
package-lock.json
|
||||
frontend/package-lock.json
|
||||
|
||||
- name: 📦 Install Cargo-binstall
|
||||
uses: cargo-bins/[email protected]
|
||||
with:
|
||||
version: ${{ env.CARGO_BINSTALL_VERSION }}
|
||||
|
||||
- name: 🚧 Install native dependencies
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
@@ -556,7 +544,8 @@ jobs:
|
||||
brew install \
|
||||
pkg-config \
|
||||
openssl@3 \
|
||||
llvm
|
||||
llvm \
|
||||
cargo-binstall
|
||||
|
||||
echo "OPENSSL_DIR=$(brew --prefix openssl@3)" >> $GITHUB_ENV
|
||||
echo "PKG_CONFIG_PATH=$(brew --prefix openssl@3)/lib/pkgconfig" >> $GITHUB_ENV
|
||||
@@ -661,20 +650,17 @@ jobs:
|
||||
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Graphite Helper.app"
|
||||
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Graphite Helper (GPU).app"
|
||||
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Graphite Helper (Renderer).app"
|
||||
find "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries" -name "*.dylib" -exec codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" {} \;
|
||||
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework"
|
||||
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libcef_sandbox.dylib"
|
||||
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libEGL.dylib"
|
||||
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libGLESv2.dylib"
|
||||
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libvk_swiftshader.dylib"
|
||||
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH" --deep
|
||||
|
||||
codesign --verify --deep --strict --verbose=4 "$APP_PATH"
|
||||
|
||||
ditto -c -k --keepParent "$APP_PATH" "$ZIP_PATH"
|
||||
SUBMISSION_ID=$(xcrun notarytool submit "$ZIP_PATH" --wait --output-format json --apple-id "$APPLE_EMAIL" --team-id "$APPLE_TEAM_ID" --password "$APPLE_PASSWORD" | tee /dev/stderr | jq -r '.id')
|
||||
STATUS=$(xcrun notarytool info "$SUBMISSION_ID" --output-format json --apple-id "$APPLE_EMAIL" --team-id "$APPLE_TEAM_ID" --password "$APPLE_PASSWORD" | jq -r '.status')
|
||||
if [ "$STATUS" != "Accepted" ]; then
|
||||
echo "Notarization failed with status: $STATUS"
|
||||
xcrun notarytool log "$SUBMISSION_ID" --apple-id "$APPLE_EMAIL" --team-id "$APPLE_TEAM_ID" --password "$APPLE_PASSWORD"
|
||||
exit 1
|
||||
fi
|
||||
xcrun notarytool submit "$ZIP_PATH" --wait --apple-id "$APPLE_EMAIL" --team-id "$APPLE_TEAM_ID" --password "$APPLE_PASSWORD"
|
||||
rm "$ZIP_PATH"
|
||||
|
||||
xcrun stapler staple -v "$APP_PATH"
|
||||
|
||||
@@ -13,4 +13,3 @@ flamegraph.svg
|
||||
.direnv
|
||||
.DS_Store
|
||||
.nvim.lua
|
||||
/.devcontainer/devcontainer-lock.json
|
||||
@@ -1,7 +1,7 @@
|
||||
{ pkgs, ... }:
|
||||
|
||||
let
|
||||
toolchain = pkgs.rust-bin.nightly."2026-07-03".default.override {
|
||||
toolchain = pkgs.rust-bin.nightly."2026-04-11".default.override {
|
||||
extensions = [
|
||||
"rust-src"
|
||||
"rust-analyzer"
|
||||
@@ -32,12 +32,11 @@ let
|
||||
(finalAttrs: {
|
||||
pname = "rustc_codegen_spirv";
|
||||
version = "0.10.0-alpha.1";
|
||||
src = pkgs.fetchgit {
|
||||
url = "https://github.com/Rust-GPU/rust-gpu";
|
||||
rev = "2fff75a21a1909945ac85f5818843dd9960004d7";
|
||||
sha256 = "sha256-clUt4jUh4D9EmoXZFgur1RrMYob4X5jti2e2hvBnAx8=";
|
||||
src = pkgs.fetchCrate {
|
||||
inherit (finalAttrs) pname version;
|
||||
sha256 = "sha256-zJEpExkPgYzwo7fR4ge4GxJNj7H5yo4bJ4eTOw36+7c=";
|
||||
};
|
||||
cargoHash = "sha256-9dGb+RDYpJKaIhkMPkZAx1M1VGE3gMfCD2T84i1VtV8=";
|
||||
cargoHash = "sha256-J1rtbfGqrL2NJ7Bu2pYfDwCdUmnECB/kzxrpYluA0kY=";
|
||||
cargoBuildFlags = [
|
||||
"-p"
|
||||
"rustc_codegen_spirv"
|
||||
|
||||
+12
-14
@@ -1,10 +1,10 @@
|
||||
{ pkgs, ... }:
|
||||
|
||||
let
|
||||
version = "151.3.24+g2384915+chromium-151.0.7922.174";
|
||||
version = "149.0.5+g6770623+chromium-149.0.7827.197";
|
||||
hashes = {
|
||||
aarch64-linux = "sha256-R5ZbnDallYvdbW/bP+M2DzjRfWWRTvY2q63hSIHNxZs=";
|
||||
x86_64-linux = "sha256-21PEP9rOi37krw8AUSARbWlzqp2Ot3AsBhe635voaE4=";
|
||||
aarch64-linux = "sha256-cBAvcvs1rAg5EKJkCt81RZYupCWpUNIC/nLt3PJow7Q=";
|
||||
x86_64-linux = "sha256-OPGMBJmvvLiLdBDniBQwx7LmTGGI59AcesJdILSeqcs=";
|
||||
};
|
||||
|
||||
selectSystem =
|
||||
@@ -12,19 +12,17 @@ let
|
||||
attrs.${pkgs.stdenv.hostPlatform.system}
|
||||
or (throw "Unsupported system ${pkgs.stdenv.hostPlatform.system}");
|
||||
|
||||
url = "https://cef-builds.spotifycdn.com/cef_binary_${version}_${
|
||||
selectSystem {
|
||||
aarch64-linux = "linuxarm64";
|
||||
x86_64-linux = "linux64";
|
||||
}
|
||||
}_minimal.tar.bz2";
|
||||
|
||||
src = pkgs.fetchurl {
|
||||
inherit url;
|
||||
url = "https://cef-builds.spotifycdn.com/cef_binary_${version}_${
|
||||
selectSystem {
|
||||
aarch64-linux = "linuxarm64";
|
||||
x86_64-linux = "linux64";
|
||||
}
|
||||
}_minimal.tar.bz2";
|
||||
hash = selectSystem hashes;
|
||||
};
|
||||
in
|
||||
pkgs.cef-binary.overrideAttrs {
|
||||
pkgs.cef-binary.overrideAttrs (finalAttrs: {
|
||||
version = builtins.head (builtins.split "\\+" version);
|
||||
inherit src;
|
||||
postInstall = ''
|
||||
@@ -40,9 +38,9 @@ pkgs.cef-binary.overrideAttrs {
|
||||
echo '${
|
||||
builtins.toJSON {
|
||||
type = "minimal";
|
||||
name = builtins.baseNameOf url;
|
||||
name = builtins.baseNameOf finalAttrs.src.url;
|
||||
sha1 = "";
|
||||
}
|
||||
}' > $out/archive.json
|
||||
'';
|
||||
}
|
||||
})
|
||||
Vendored
-1
@@ -6,7 +6,6 @@
|
||||
"tamasfe.even-better-toml",
|
||||
// Web
|
||||
"dbaeumer.vscode-eslint",
|
||||
"esbenp.prettier-vscode",
|
||||
"svelte.svelte-vscode",
|
||||
"vitaliymaz.vscode-svg-previewer",
|
||||
// Code quality
|
||||
|
||||
Generated
+588
-569
File diff suppressed because it is too large.
Load diff
+17
-34
@@ -15,7 +15,6 @@ members = [
|
||||
"frontend/wrapper",
|
||||
"libraries/dyn-any",
|
||||
"libraries/math-parser",
|
||||
"libraries/ipsum",
|
||||
"libraries/wgpu-sync",
|
||||
"node-graph/libraries/graphene-hash",
|
||||
"node-graph/libraries/*",
|
||||
@@ -41,7 +40,6 @@ default-members = [
|
||||
"frontend/wrapper",
|
||||
"libraries/dyn-any",
|
||||
"libraries/math-parser",
|
||||
"libraries/ipsum",
|
||||
"node-graph/graph-craft",
|
||||
"node-graph/interpreted-executor",
|
||||
"node-graph/node-macro",
|
||||
@@ -53,12 +51,12 @@ default-members = [
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
rust-version = "1.98"
|
||||
rust-version = "1.88"
|
||||
edition = "2024"
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
homepage = "https://graphite.art"
|
||||
repository = "https://github.com/GraphiteEditor/Graphite"
|
||||
license = "MIT OR Apache-2.0"
|
||||
license = "Apache-2.0"
|
||||
version = "0.0.0"
|
||||
readme = "README.md"
|
||||
publish = false
|
||||
@@ -82,7 +80,6 @@ no-std-types = { path = "node-graph/libraries/no-std-types" }
|
||||
raster-types = { path = "node-graph/libraries/raster-types" }
|
||||
vector-types = { path = "node-graph/libraries/vector-types" }
|
||||
graphic-types = { path = "node-graph/libraries/graphic-types" }
|
||||
brush-types = { path = "node-graph/libraries/brush-types" }
|
||||
rendering = { path = "node-graph/libraries/rendering" }
|
||||
brush-nodes = { path = "node-graph/nodes/brush" }
|
||||
blending-nodes = { path = "node-graph/nodes/blending" }
|
||||
@@ -107,14 +104,13 @@ wgpu-sync = { path = "libraries/wgpu-sync" }
|
||||
graphite-proc-macros = { path = "proc-macros" }
|
||||
graphite-editor = { path = "editor" }
|
||||
graphene-canvas-utils = { path = "node-graph/libraries/canvas-utils" }
|
||||
ipsum = { path = "libraries/ipsum" }
|
||||
|
||||
# Workspace dependencies
|
||||
rustc-hash = "2.0"
|
||||
bytemuck = { version = "1.13", features = ["derive", "min_const_generics"] }
|
||||
serde = { version = "1.0", features = ["derive", "rc"] }
|
||||
serde_json = "1.0"
|
||||
postcard = { version = "1.1", default-features = false, features = ["use-std"] }
|
||||
rmp-serde = "1.3"
|
||||
serde_bytes = "0.11"
|
||||
serde-wasm-bindgen = "0.6"
|
||||
reqwest = { version = "0.13", features = ["blocking", "json"] }
|
||||
@@ -143,7 +139,7 @@ wgpu = { version = "29.0", features = [
|
||||
"strict_asserts",
|
||||
] }
|
||||
once_cell = "1.13" # Remove and replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>)
|
||||
wasm-bindgen = "=0.2.121" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned in `.github/workflows/build.yml`, `.devcontainer/devcontainer.json`, `.nix/dev.nix`, `.nix/pkgs/graphite.nix`, and `tools/cargo-run/src/requirements.rs`. We pin this version because wasm-bindgen upgrades may break various things.
|
||||
wasm-bindgen = "=0.2.121" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned across CI workflows, devcontainer, Nix, and the `cargo-run` tool. We pin this version because wasm-bindgen upgrades may break various things.
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "=0.3.98"
|
||||
web-sys = { version = "=0.3.98", features = [
|
||||
@@ -164,16 +160,16 @@ web-sys = { version = "=0.3.98", features = [
|
||||
"HtmlImageElement",
|
||||
"ImageBitmapRenderingContext",
|
||||
] }
|
||||
winit = "0.31.0-beta.2"
|
||||
winit = { git = "https://github.com/rust-windowing/winit.git" }
|
||||
keyboard-types = "0.8"
|
||||
url = "2.5"
|
||||
tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-multi-thread"] }
|
||||
# Linebender ecosystem (BEGIN)
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
vello = "0.10"
|
||||
vello_encoding = "0.10"
|
||||
vello = "0.9"
|
||||
vello_encoding = "0.9"
|
||||
resvg = "0.47"
|
||||
usvg = "0.47"
|
||||
simplecss = "0.2"
|
||||
parley = { version = "0.9", default-features = false, features = ["std"] }
|
||||
skrifa = "0.42"
|
||||
polycool = "0.4"
|
||||
@@ -181,12 +177,10 @@ color = "0.3"
|
||||
# Linebender ecosystem (END)
|
||||
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
|
||||
rand_chacha = "0.9"
|
||||
glam = { version = "0.33", default-features = false, features = [
|
||||
glam = { version = "0.32.1", default-features = false, features = [
|
||||
"nostd-libm",
|
||||
"scalar-math",
|
||||
"bytemuck",
|
||||
"debug-glam-assert",
|
||||
"all-types",
|
||||
] }
|
||||
base64 = "0.22"
|
||||
blake3 = "1.5"
|
||||
@@ -196,13 +190,6 @@ image = { version = "0.25", default-features = false, features = [
|
||||
"jpeg",
|
||||
"bmp",
|
||||
"gif",
|
||||
"webp",
|
||||
"tiff",
|
||||
"ico",
|
||||
"tga",
|
||||
"hdr",
|
||||
"exr",
|
||||
"serde",
|
||||
] }
|
||||
pretty_assertions = "1.4"
|
||||
fern = { version = "0.7", features = ["colored"] }
|
||||
@@ -222,7 +209,6 @@ syn = { version = "2.0", default-features = false, features = [
|
||||
"proc-macro",
|
||||
] }
|
||||
lyon_geom = "1.0"
|
||||
delaunator = "1.0"
|
||||
petgraph = { version = "0.7", default-features = false, features = ["graphmap"] }
|
||||
half = { version = "2.4", default-features = false, features = ["bytemuck"] }
|
||||
tinyvec = { version = "1", features = ["std"] }
|
||||
@@ -231,8 +217,8 @@ gungraun = { version = "0.18" }
|
||||
ndarray = "0.16"
|
||||
strum = { version = "0.27", features = ["derive"] }
|
||||
dirs = "6.0"
|
||||
cef = "151"
|
||||
cef-dll-sys = "151"
|
||||
cef = "149"
|
||||
cef-dll-sys = "149"
|
||||
include_dir = "0.7"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
tracing = "0.1"
|
||||
@@ -240,12 +226,8 @@ rfd = "0.17"
|
||||
open = "5.3"
|
||||
spin = "0.10"
|
||||
clap = "4.5"
|
||||
|
||||
# Ensure these are kept in sync with .nix/deps/rust-gpu.nix
|
||||
# Git commit required for glam=0.33 support (TODO: use release when new version is published. Last publish was Apr 17)
|
||||
spirv-std = { git = "https://github.com/Rust-GPU/rust-gpu.git", rev = "2fff75a21a1909945ac85f5818843dd9960004d7", features = ["bytemuck"] }
|
||||
cargo-gpu-install = { git = "https://github.com/Rust-GPU/rust-gpu.git", rev = "2fff75a21a1909945ac85f5818843dd9960004d7", default-features = false }
|
||||
|
||||
spirv-std = { version = "0.10.0-alpha.1", features = ["bytemuck"] }
|
||||
cargo-gpu-install = { version = "0.10.0-alpha.1", default-features = false }
|
||||
qrcodegen = "1.8"
|
||||
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
|
||||
scraper = "0.25"
|
||||
@@ -275,7 +257,8 @@ lto = "thin"
|
||||
debug = true
|
||||
|
||||
[patch.crates-io]
|
||||
winit = { git = "https://github.com/timon-schelling/winit", branch = "graphite" }
|
||||
# Force cargo to use only one version of the dpi crate (vendoring breaks without this)
|
||||
dpi = { git = "https://github.com/rust-windowing/winit.git" }
|
||||
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
|
||||
cef = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-151" }
|
||||
cef-dll-sys = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-151" }
|
||||
cef = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-149" }
|
||||
cef-dll-sys = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-149" }
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
Copyright (c) Graphite contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
File renamed without changes.
@@ -80,6 +80,4 @@ Graphite is 100% community built and funded. Please become a part of keeping the
|
||||
|
||||
Are you a graphics programmer or Rust developer? Graphite aims to be one of the most approachable projects for putting your engineering skills to use in the world of open source. See [instructions here](https://graphite.art/volunteer/guide/) for setting up the project and getting started.
|
||||
|
||||
## License
|
||||
|
||||
Graphite's source code is dual-licensed under your choice of either the [MIT license](LICENSE-MIT) or the [Apache License 2.0](LICENSE-APACHE), at your option, unless otherwise noted within the repository. By submitting code for inclusion in the project, you agree to license your contributions under both licenses, and that you have the authority to do so.
|
||||
*By submitting code for inclusion in the project, you are agreeing to license your changes under the Apache 2.0 license, and that you have the authority to do so. Some directories may have other licenses, like dual-licensed MIT/Apache 2.0, and code submissions to those directories mean you agree to the applicable license(s).*
|
||||
@@ -22,6 +22,8 @@ accepted = [
|
||||
workarounds = ["ring"]
|
||||
ignore-build-dependencies = true
|
||||
ignore-dev-dependencies = true
|
||||
# Clearly Defined's API would occasionally (every few months) return errors for at least a full day (maybe some weird rate limiting?), but we can just disable to perform local checking (see #1653)
|
||||
no-clearly-defined = true
|
||||
|
||||
# https://raw.githubusercontent.com/briansmith/webpki/main/LICENSE
|
||||
# is the ISC license but test code within the repo is BSD-3-Clause, but is not compiled into the crate when we use it
|
||||
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":fLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[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":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[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":"","sources":[]}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1789832635968548900,{"inputs":[{"Node":{"node_id":1924303400883620400,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.9822506,"green":0.2050787Line truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[194878846429432339,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3Line truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[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":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[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_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[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_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[183952488591282082,{"inputs":[{"Node":{"node_id":17965270694495451178,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,-6.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"impleLine truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"I64":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"I64":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_vaLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5],"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[4388711862172196665,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":"","sources":[]}}],[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_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[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_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_value":{"CellularReturnType":"CellValue"},"exposed":false}},{"ValueLine truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"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_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[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_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[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":"","sources":[]}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::artboard::Artboard>"}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Node":{"node_id":6,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":4}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[2,{"inputs":Line truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"outLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[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":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":null},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"core_types::vector::SplineNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":Line 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":6559102076450693000,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[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_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[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":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.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]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0]]},"regions":{"add":[],"remove":[],"segLine 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":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[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":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[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_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implemeLine 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_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[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":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[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_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[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":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[76,{"inputs":[{"Node":{"node_id":77,"output_index":0}},{"Node":{"node_id":16164610528699022118,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodesLine truncated
|
||||
+7
-13
@@ -1,18 +1,12 @@
|
||||
[package]
|
||||
name = "graphite-desktop"
|
||||
version = "0.1.0"
|
||||
description = "Graphite Desktop"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
|
||||
[[bin]]
|
||||
name = "graphite"
|
||||
@@ -50,12 +44,12 @@ rfd = { workspace = true }
|
||||
open = { workspace = true }
|
||||
lzma-rust2 = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
url = { workspace = true }
|
||||
rand = { workspace = true, features = ["thread_rng"] }
|
||||
clap = { workspace = true, features = ["derive"] }
|
||||
interprocess = "2.4.2"
|
||||
fd-lock = "4.0.4"
|
||||
ctrlc = "3.5.1"
|
||||
window_clipboard = "0.5"
|
||||
|
||||
# Windows-specific dependencies
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
|
||||
@@ -1,18 +1,12 @@
|
||||
[package]
|
||||
name = "graphite-desktop-bundle"
|
||||
version = "0.0.0"
|
||||
description = "Graphite Desktop Bundle"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
|
||||
[dependencies]
|
||||
cef-dll-sys = { workspace = true }
|
||||
|
||||
@@ -7,9 +7,6 @@ mod mac;
|
||||
#[cfg(target_os = "windows")]
|
||||
mod win;
|
||||
|
||||
// Avoid incorrect warnings about an unused dependency (this crate sets `DEP_CEF_DLL_WRAPPER_CEF_DIR` which is used in `build.rs`)
|
||||
use cef_dll_sys as _;
|
||||
|
||||
fn main() {
|
||||
#[cfg(target_os = "linux")]
|
||||
linux::main().unwrap();
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
[package]
|
||||
name = "graphite-desktop-embedded-resources"
|
||||
version = "0.1.0"
|
||||
description = "Graphite Desktop Embedded Resources"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
|
||||
[dependencies]
|
||||
include_dir = { workspace = true }
|
||||
|
||||
@@ -1,18 +1,12 @@
|
||||
[package]
|
||||
name = "graphite-desktop-platform-linux"
|
||||
version = "0.0.0"
|
||||
description = "Graphite Desktop Platform Linux"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
|
||||
[[bin]]
|
||||
name = "graphite"
|
||||
|
||||
@@ -1,18 +1,12 @@
|
||||
[package]
|
||||
name = "graphite-desktop-platform-mac"
|
||||
version = "0.0.0"
|
||||
description = "Graphite Desktop Platform Mac"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
|
||||
[features]
|
||||
main = ["dep:graphite-desktop"]
|
||||
|
||||
@@ -1,18 +1,12 @@
|
||||
[package]
|
||||
name = "graphite-desktop-platform-win"
|
||||
version = "0.0.0"
|
||||
description = "Graphite Desktop Platform Windows"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
|
||||
[[bin]]
|
||||
name = "graphite"
|
||||
|
||||
+110
-141
@@ -9,23 +9,20 @@ use std::sync::mpsc::{Receiver, SyncSender};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::data_transfer::{DataTransferSendBuilder, TypeHint};
|
||||
use winit::dpi::PhysicalSize;
|
||||
use winit::event::{ElementState, MouseButton, StartCause, WindowEvent};
|
||||
use winit::event_loop::run_on_demand::EventLoopExtRunOnDemand;
|
||||
use winit::event_loop::{ActiveEventLoop, AsyncRequestSerial, ControlFlow, DndAction, EventLoop};
|
||||
use winit::dpi::{PhysicalPosition, PhysicalSize};
|
||||
use winit::event::{ButtonSource, ElementState, MouseButton, StartCause, WindowEvent};
|
||||
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
|
||||
use winit::window::WindowId;
|
||||
|
||||
use crate::dirs;
|
||||
use crate::event::{AppEvent, AppEventScheduler};
|
||||
use crate::input::InputState;
|
||||
use crate::persist;
|
||||
use crate::preferences;
|
||||
use crate::render::{RenderError, RenderState};
|
||||
use crate::ui::{InputEvent, UiCommand, UiInstance};
|
||||
use crate::ui::{UiCommand, UiInstance};
|
||||
use crate::window::Window;
|
||||
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, IngestAction, Preferences};
|
||||
use crate::wrapper::{DesktopWrapper, FolderStore, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
|
||||
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, InputMessage, MouseKeys, MouseState, Preferences};
|
||||
use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
|
||||
|
||||
pub(crate) struct App {
|
||||
render_state: Option<RenderState>,
|
||||
@@ -36,9 +33,8 @@ pub(crate) struct App {
|
||||
window_maximized: bool,
|
||||
window_fullscreen: bool,
|
||||
window_pending_drag: bool,
|
||||
pending_dnd_fetch: Option<AsyncRequestSerial>,
|
||||
pending_clipboard_fetch: Option<AsyncRequestSerial>,
|
||||
input_state: InputState,
|
||||
pointer_position: PhysicalPosition<f64>,
|
||||
pointer_lock_position: Option<PhysicalPosition<f64>>,
|
||||
ui_scale: f64,
|
||||
app_event_receiver: Receiver<AppEvent>,
|
||||
app_event_scheduler: AppEventScheduler,
|
||||
@@ -99,13 +95,12 @@ impl App {
|
||||
let wake = Arc::new(move || {
|
||||
wake_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Wake));
|
||||
});
|
||||
let desktop_wrapper = DesktopWrapper::new(
|
||||
rand::rng().random(),
|
||||
Arc::new(resource_storage),
|
||||
Arc::new(FolderStore::new(dirs::app_autosave_documents_dir())),
|
||||
wgpu_context.clone(),
|
||||
wake,
|
||||
);
|
||||
let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), dirs::app_autosave_documents_dir(), wgpu_context.clone(), wake);
|
||||
|
||||
let completion_render_sender = start_render_sender.clone();
|
||||
DesktopWrapper::set_completion_notifier(move || {
|
||||
let _ = completion_render_sender.try_send(());
|
||||
});
|
||||
|
||||
Self {
|
||||
render_state: None,
|
||||
@@ -116,9 +111,8 @@ impl App {
|
||||
window_maximized: false,
|
||||
window_fullscreen: false,
|
||||
window_pending_drag: false,
|
||||
pending_dnd_fetch: None,
|
||||
pending_clipboard_fetch: None,
|
||||
input_state: InputState::new(),
|
||||
pointer_position: Default::default(),
|
||||
pointer_lock_position: Default::default(),
|
||||
ui_scale: 1.,
|
||||
app_event_receiver,
|
||||
app_event_scheduler,
|
||||
@@ -136,8 +130,8 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn run(mut self, mut event_loop: EventLoop) -> ExitReason {
|
||||
event_loop.run_app_on_demand(&mut self).unwrap();
|
||||
pub(crate) fn run(mut self, event_loop: EventLoop) -> ExitReason {
|
||||
event_loop.run_app(&mut self).unwrap();
|
||||
self.exit_reason
|
||||
}
|
||||
|
||||
@@ -211,15 +205,15 @@ impl App {
|
||||
};
|
||||
self.send_or_queue_web_message(bytes);
|
||||
}
|
||||
DesktopFrontendMessage::OpenFileDialog { title, options, action } => {
|
||||
DesktopFrontendMessage::OpenFileDialog { title, filters, multiple, context } => {
|
||||
let app_event_scheduler = self.app_event_scheduler.clone();
|
||||
let _ = thread::spawn(move || {
|
||||
let mut dialog = AsyncFileDialog::new().set_title(title);
|
||||
for filter in options.filters {
|
||||
for filter in filters {
|
||||
dialog = dialog.add_filter(filter.name, &filter.extensions);
|
||||
}
|
||||
|
||||
let handles = if options.multiple {
|
||||
let handles = if multiple {
|
||||
futures::executor::block_on(dialog.pick_files()).unwrap_or_default()
|
||||
} else {
|
||||
futures::executor::block_on(dialog.pick_file()).into_iter().collect()
|
||||
@@ -229,8 +223,7 @@ impl App {
|
||||
let path = handle.path().to_path_buf();
|
||||
match fs::read(&path) {
|
||||
Ok(content) => {
|
||||
let action = action.clone();
|
||||
let message = DesktopWrapperMessage::IngestFile { path, content, action };
|
||||
let message = DesktopWrapperMessage::FileDialogResult { path, content, context };
|
||||
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
Err(e) => tracing::error!("Failed to read file {}: {}", path.display(), e),
|
||||
@@ -276,8 +269,6 @@ impl App {
|
||||
});
|
||||
}
|
||||
DesktopFrontendMessage::UpdateViewportPhysicalBounds { x, y, width, height } => {
|
||||
self.input_state.set_viewport_info(x, y, width, height, self.window_scale);
|
||||
|
||||
if let Some(render_state) = &mut self.render_state
|
||||
&& let Some(window) = &self.window
|
||||
{
|
||||
@@ -292,9 +283,6 @@ impl App {
|
||||
render_state.set_viewport_scale([viewport_scale_x as f32, viewport_scale_y as f32]);
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::WindowUpdateDirectInput { enabled } => {
|
||||
self.input_state.set_direct_input(enabled);
|
||||
}
|
||||
DesktopFrontendMessage::UpdateUIScale { scale } => {
|
||||
self.ui_scale = scale;
|
||||
self.resize();
|
||||
@@ -313,6 +301,19 @@ impl App {
|
||||
DesktopFrontendMessage::PersistenceReadState => {
|
||||
responses.push(DesktopWrapperMessage::LoadPersistedState { state: persist::read_state() });
|
||||
}
|
||||
DesktopFrontendMessage::PersistenceReadDocument { id } => {
|
||||
if let Some(document) = persist::read_document_content(&id) {
|
||||
responses.push(DesktopWrapperMessage::LoadDocumentContent { id, document });
|
||||
} else {
|
||||
tracing::error!("Failed to read document content for {id:?}");
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::PersistenceWriteDocument { id, document_serialized_content } => {
|
||||
persist::write_document_content(id, document_serialized_content);
|
||||
}
|
||||
DesktopFrontendMessage::PersistenceDeleteDocument { id } => {
|
||||
persist::delete_document(&id);
|
||||
}
|
||||
DesktopFrontendMessage::PersistenceWritePreferences { preferences } => {
|
||||
preferences::write(preferences);
|
||||
}
|
||||
@@ -334,13 +335,19 @@ impl App {
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::ClipboardRead => {
|
||||
self.app_event_scheduler.schedule(AppEvent::ClipboardRead);
|
||||
if let Some(window) = &self.window {
|
||||
let content = window.clipboard_read();
|
||||
let message = DesktopWrapperMessage::ClipboardReadResult { content };
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::ClipboardWrite { content } => {
|
||||
self.app_event_scheduler.schedule(AppEvent::ClipboardWrite { content });
|
||||
if let Some(window) = &mut self.window {
|
||||
window.clipboard_write(content);
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::PointerLock => {
|
||||
self.input_state.lock_pointer();
|
||||
self.pointer_lock_position = Some(self.pointer_position);
|
||||
if let Some(window) = &self.window {
|
||||
window.start_pointer_lock();
|
||||
}
|
||||
@@ -460,32 +467,6 @@ impl App {
|
||||
self.ui_frame_received = true;
|
||||
}
|
||||
}
|
||||
AppEvent::ClipboardRead => {
|
||||
let result = event_loop.clipboard().and_then(|id| {
|
||||
let Some(id) = id else { return Ok(None) };
|
||||
let data_transfer = event_loop.data_transfer(id)?;
|
||||
if !data_transfer.has_type(&TypeHint::Plaintext) {
|
||||
return Ok(None);
|
||||
}
|
||||
event_loop.fetch_data_transfer(id, &TypeHint::Plaintext).map(Some)
|
||||
});
|
||||
match result {
|
||||
Ok(Some(serial)) => self.pending_clipboard_fetch = Some(serial),
|
||||
Ok(None) => self.dispatch_desktop_wrapper_message(DesktopWrapperMessage::ClipboardReadResult { content: None }),
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to read from clipboard: {e}");
|
||||
self.dispatch_desktop_wrapper_message(DesktopWrapperMessage::ClipboardReadResult { content: None });
|
||||
}
|
||||
}
|
||||
}
|
||||
AppEvent::ClipboardWrite { content } => {
|
||||
let send_data = DataTransferSendBuilder::new(content)
|
||||
.with_type(TypeHint::Plaintext, |content: &String, _| Some(content.clone()))
|
||||
.build();
|
||||
if let Err(e) = event_loop.set_clipboard(send_data) {
|
||||
tracing::error!("Failed to write to clipboard: {e}");
|
||||
}
|
||||
}
|
||||
AppEvent::CursorChange(cursor) => {
|
||||
if let Some(window) = &mut self.window {
|
||||
window.set_cursor(event_loop, cursor);
|
||||
@@ -514,11 +495,7 @@ impl App {
|
||||
for path in paths {
|
||||
tracing::info!("Opening file: {}", path.display());
|
||||
if let Ok(content) = fs::read(&path) {
|
||||
let message = DesktopWrapperMessage::IngestFile {
|
||||
path,
|
||||
content,
|
||||
action: IngestAction::Open,
|
||||
};
|
||||
let message = DesktopWrapperMessage::OpenFile { path, content };
|
||||
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
} else {
|
||||
tracing::error!("Failed to read file: {}", path.display());
|
||||
@@ -561,28 +538,28 @@ impl ApplicationHandler for App {
|
||||
}
|
||||
}
|
||||
|
||||
fn window_event(&mut self, event_loop: &dyn ActiveEventLoop, _window_id: WindowId, event: WindowEvent) {
|
||||
fn window_event(&mut self, _event_loop: &dyn ActiveEventLoop, _window_id: WindowId, event: WindowEvent) {
|
||||
// Handle pointer lock release
|
||||
if let WindowEvent::PointerButton {
|
||||
state: ElementState::Released,
|
||||
button,
|
||||
..
|
||||
} = &event && button.clone().mouse_button() == Some(MouseButton::Left)
|
||||
&& let Some(pointer_lock_position) = self.input_state.unlock_pointer()
|
||||
if let Some(pointer_lock_position) = self.pointer_lock_position
|
||||
&& let WindowEvent::PointerButton {
|
||||
state: ElementState::Released,
|
||||
button: ButtonSource::Mouse(MouseButton::Left),
|
||||
..
|
||||
} = event
|
||||
{
|
||||
self.pointer_lock_position = None;
|
||||
if let Some(window) = &self.window {
|
||||
window.end_pointer_lock();
|
||||
}
|
||||
self.ui.send(UiCommand::Input(
|
||||
InputEvent::pointer().position(pointer_lock_position).moved().modifiers(self.input_state.modifiers()).build(),
|
||||
));
|
||||
self.ui.send(UiCommand::Input(WindowEvent::PointerMoved {
|
||||
device_id: None,
|
||||
position: pointer_lock_position,
|
||||
primary: true,
|
||||
source: winit::event::PointerSource::Mouse,
|
||||
}));
|
||||
}
|
||||
|
||||
self.input_state.process(
|
||||
&event,
|
||||
|message| self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Input(message))),
|
||||
|input| self.ui.send(UiCommand::Input(input)),
|
||||
);
|
||||
self.ui.send(UiCommand::Input(event.clone()));
|
||||
|
||||
match event {
|
||||
WindowEvent::CloseRequested => {
|
||||
@@ -624,73 +601,65 @@ impl ApplicationHandler for App {
|
||||
self.exit(Some(ExitReason::UiAccelerationFailure));
|
||||
}
|
||||
}
|
||||
WindowEvent::DragEntered { id, .. } => {
|
||||
let accepts = event_loop.data_transfer(id).is_ok_and(|data_transfer| data_transfer.has_type(&TypeHint::UriList));
|
||||
let actions: &[DndAction] = if accepts { &[DndAction::Copy] } else { &[] };
|
||||
if let Err(e) = event_loop.set_valid_dnd_actions(id, actions) {
|
||||
tracing::error!("Failed to set valid drag and drop actions: {e}");
|
||||
WindowEvent::DragDropped { paths, .. } => {
|
||||
for path in paths {
|
||||
match fs::read(&path) {
|
||||
Ok(content) => {
|
||||
let message = DesktopWrapperMessage::ImportFile { path, content };
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to read dropped file {}: {}", path.display(), e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
WindowEvent::DragDropped { id, .. } => match event_loop.fetch_data_transfer(id, &TypeHint::UriList) {
|
||||
Ok(serial) => self.pending_dnd_fetch = Some(serial),
|
||||
Err(e) => tracing::error!("Failed to fetch dropped data: {e}"),
|
||||
},
|
||||
WindowEvent::DataTransferReceived { serial, ref value, .. } if self.pending_clipboard_fetch == Some(serial) => match value.try_as_string() {
|
||||
Ok(content) => {
|
||||
self.pending_clipboard_fetch = None;
|
||||
let message = DesktopWrapperMessage::ClipboardReadResult { content: Some(content) };
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
|
||||
Err(e) => {
|
||||
self.pending_clipboard_fetch = None;
|
||||
tracing::error!("Failed to read from clipboard: {e}");
|
||||
let message = DesktopWrapperMessage::ClipboardReadResult { content: None };
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
},
|
||||
WindowEvent::DataTransferReceived { serial, ref value, .. } if self.pending_dnd_fetch == Some(serial) => match value.try_as_uris() {
|
||||
Ok(uris) => {
|
||||
self.pending_dnd_fetch = None;
|
||||
let paths = uris.iter().filter_map(|uri| url::Url::parse(uri).ok()?.to_file_path().ok());
|
||||
for path in paths {
|
||||
match fs::read(&path) {
|
||||
Ok(content) => {
|
||||
let message = DesktopWrapperMessage::IngestFile {
|
||||
path,
|
||||
content,
|
||||
action: IngestAction::Import,
|
||||
};
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to read dropped file {}: {}", path.display(), e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
|
||||
Err(e) => {
|
||||
self.pending_dnd_fetch = None;
|
||||
tracing::error!("Failed to read dropped data: {e}");
|
||||
}
|
||||
},
|
||||
|
||||
WindowEvent::PointerMoved { .. } | WindowEvent::PointerLeft { position: Some(_), .. } | WindowEvent::PointerEntered { .. }
|
||||
if !self.input_state.pointer_locked() && self.window_pending_drag =>
|
||||
// Forward and Back buttons are not supported by CEF and thus need to be directly forwarded the editor
|
||||
WindowEvent::PointerButton {
|
||||
button: ButtonSource::Mouse(button),
|
||||
state: ElementState::Pressed,
|
||||
..
|
||||
} => {
|
||||
let mouse_keys = match button {
|
||||
MouseButton::Back => Some(MouseKeys::BACK),
|
||||
MouseButton::Forward => Some(MouseKeys::FORWARD),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(mouse_keys) = mouse_keys {
|
||||
let message = DesktopWrapperMessage::Input(InputMessage::PointerDown {
|
||||
editor_mouse_state: MouseState { mouse_keys, ..Default::default() },
|
||||
modifier_keys: Default::default(),
|
||||
});
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
|
||||
let message = DesktopWrapperMessage::Input(InputMessage::PointerUp {
|
||||
editor_mouse_state: Default::default(),
|
||||
modifier_keys: Default::default(),
|
||||
});
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
}
|
||||
|
||||
WindowEvent::PointerMoved { position, .. } | WindowEvent::PointerLeft { position: Some(position), .. } | WindowEvent::PointerEntered { position, .. }
|
||||
if self.pointer_lock_position.is_none() =>
|
||||
{
|
||||
self.window_pending_drag = false;
|
||||
if let Some(window) = &self.window {
|
||||
window.start_drag();
|
||||
self.pointer_position = position;
|
||||
|
||||
if self.window_pending_drag {
|
||||
self.window_pending_drag = false;
|
||||
if let Some(window) = &self.window {
|
||||
window.start_drag();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
WindowEvent::PointerButton {
|
||||
button,
|
||||
button: ButtonSource::Mouse(MouseButton::Left),
|
||||
state: ElementState::Released,
|
||||
..
|
||||
} if button.clone().mouse_button() == Some(MouseButton::Left) => {
|
||||
} => {
|
||||
self.window_pending_drag = false;
|
||||
}
|
||||
|
||||
@@ -699,7 +668,7 @@ impl ApplicationHandler for App {
|
||||
}
|
||||
|
||||
fn device_event(&mut self, _event_loop: &dyn ActiveEventLoop, _device_id: Option<winit::event::DeviceId>, event: winit::event::DeviceEvent) {
|
||||
if self.input_state.pointer_locked()
|
||||
if self.pointer_lock_position.is_some()
|
||||
&& let winit::event::DeviceEvent::PointerMotion { delta: (x, y) } = event
|
||||
{
|
||||
let message = DesktopWrapperMessage::PointerLockMove { x, y };
|
||||
|
||||
+4
-4
@@ -20,10 +20,10 @@ pub(crate) fn clear_dir(path: &PathBuf) {
|
||||
if let Err(e) = fs::remove_dir_all(&entry_path) {
|
||||
tracing::error!("Failed to remove directory at {:?}: {}", entry_path, e);
|
||||
}
|
||||
} else if entry_path.is_file()
|
||||
&& let Err(e) = fs::remove_file(&entry_path)
|
||||
{
|
||||
tracing::error!("Failed to remove file at {:?}: {}", entry_path, e);
|
||||
} else if entry_path.is_file() {
|
||||
if let Err(e) = fs::remove_file(&entry_path) {
|
||||
tracing::error!("Failed to remove file at {:?}: {}", entry_path, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,10 +8,6 @@ pub(crate) enum AppEvent {
|
||||
WebCommunicationInitialized,
|
||||
DesktopWrapperMessage(DesktopWrapperMessage),
|
||||
NodeGraphExecutionResult(NodeGraphExecutionResult),
|
||||
ClipboardRead,
|
||||
ClipboardWrite {
|
||||
content: String,
|
||||
},
|
||||
Exit,
|
||||
UiCrashed,
|
||||
OpenFiles(Vec<std::path::PathBuf>),
|
||||
|
||||
@@ -1,455 +0,0 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::time::{Duration, Instant};
|
||||
use winit::dpi::PhysicalPosition;
|
||||
use winit::event::{ButtonSource, ElementState, MouseButton, MouseScrollDelta, PointerSource, TabletToolData, TabletToolKind, WindowEvent};
|
||||
use winit::keyboard::ModifiersState;
|
||||
|
||||
use crate::ui::{InputEvent, MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT, PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
|
||||
use crate::wrapper::messages::{EditorPointerState, InputMessage, ModifierKeys, MouseKeys, ScrollDelta};
|
||||
|
||||
// Marks input event as observe-only, meaning it should not result in any input messages being send by the frontend.
|
||||
// And should instead be ignored by frontend input processing and only be used to update the UI state (hover, cursor).
|
||||
// TODO(Timon): Remove and find a less hacky solution
|
||||
trait ObserveOnlyExt {
|
||||
fn observe_only(self) -> Self;
|
||||
}
|
||||
impl ObserveOnlyExt for crate::ui::InputEventBuilder {
|
||||
fn observe_only(self) -> Self {
|
||||
self.num_lock(true)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct InputState {
|
||||
start: Instant,
|
||||
viewport_info: Option<ViewportInfo>,
|
||||
direct_input: bool,
|
||||
modifiers: ModifiersState,
|
||||
pointer_position: PhysicalPosition<f64>,
|
||||
pointer_state: PointerState,
|
||||
click_tracker: ClickTracker,
|
||||
shake_tracker: ShakeTracker,
|
||||
}
|
||||
|
||||
impl InputState {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
start: Instant::now(),
|
||||
viewport_info: None,
|
||||
direct_input: false,
|
||||
modifiers: ModifiersState::default(),
|
||||
pointer_position: PhysicalPosition::default(),
|
||||
pointer_state: PointerState::Hover { route: Route::Ui },
|
||||
click_tracker: ClickTracker::default(),
|
||||
shake_tracker: ShakeTracker::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_viewport_info(&mut self, x: f64, y: f64, width: f64, height: f64, scale: f64) {
|
||||
self.viewport_info = Some(ViewportInfo { x, y, width, height, scale });
|
||||
}
|
||||
|
||||
pub(crate) fn set_direct_input(&mut self, enabled: bool) {
|
||||
self.direct_input = enabled;
|
||||
}
|
||||
|
||||
pub(crate) fn lock_pointer(&mut self) {
|
||||
self.pointer_state = match self.pointer_state {
|
||||
PointerState::Hover { route } => PointerState::Locked {
|
||||
route,
|
||||
keys: MouseKeys::empty(),
|
||||
position: self.pointer_position,
|
||||
},
|
||||
PointerState::Stroke { route, keys } | PointerState::Locked { route, keys, .. } => PointerState::Locked {
|
||||
route,
|
||||
keys,
|
||||
position: self.pointer_position,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) fn unlock_pointer(&mut self) -> Option<PhysicalPosition<f64>> {
|
||||
let PointerState::Locked {
|
||||
route: resume,
|
||||
keys,
|
||||
position: restore,
|
||||
} = self.pointer_state
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
self.pointer_position = restore;
|
||||
self.pointer_state = match keys.is_empty() {
|
||||
true => PointerState::Hover { route: Route::Ui },
|
||||
false => PointerState::Stroke { route: resume, keys },
|
||||
};
|
||||
Some(restore)
|
||||
}
|
||||
|
||||
pub(crate) fn pointer_locked(&self) -> bool {
|
||||
matches!(self.pointer_state, PointerState::Locked { .. })
|
||||
}
|
||||
|
||||
pub(crate) fn modifiers(&self) -> ModifiersState {
|
||||
self.modifiers
|
||||
}
|
||||
|
||||
pub(crate) fn process(&mut self, event: &WindowEvent, mut editor_callback: impl FnMut(InputMessage), mut ui_callback: impl FnMut(InputEvent)) {
|
||||
match event {
|
||||
WindowEvent::PointerMoved { position, source, .. } => {
|
||||
self.pointer_position = *position;
|
||||
|
||||
let route = match self.pointer_state {
|
||||
PointerState::Hover { .. } => {
|
||||
let next = self.route(*position);
|
||||
self.pointer_state = PointerState::Hover { route: next };
|
||||
next
|
||||
}
|
||||
PointerState::Stroke { route, .. } => route,
|
||||
PointerState::Locked { keys, route: resume, .. } => match keys.is_empty() {
|
||||
true => Route::Ui,
|
||||
false => resume,
|
||||
},
|
||||
};
|
||||
match route {
|
||||
Route::Ui => ui_callback(InputEvent::pointer().position(*position).moved().modifiers(self.modifiers).build()),
|
||||
Route::Editor => {
|
||||
if !self.pointer_locked() {
|
||||
ui_callback(InputEvent::pointer().position(*position).moved().modifiers(self.modifiers).observe_only().build());
|
||||
}
|
||||
let editor_mouse_state = match source {
|
||||
PointerSource::TabletTool { kind, data } => self.tablet_pointer_state(kind, data),
|
||||
_ => self.pointer_state(),
|
||||
};
|
||||
let modifier_keys = self.modifier_keys();
|
||||
if self.shake_tracker.detect(*position, self.start.elapsed()) {
|
||||
editor_callback(InputMessage::PointerShake { editor_mouse_state, modifier_keys });
|
||||
}
|
||||
editor_callback(InputMessage::PointerMove { editor_mouse_state, modifier_keys });
|
||||
}
|
||||
}
|
||||
}
|
||||
WindowEvent::PointerEntered { position, .. } => {
|
||||
self.pointer_position = *position;
|
||||
ui_callback(InputEvent::pointer().position(*position).entered().modifiers(self.modifiers).build())
|
||||
}
|
||||
WindowEvent::PointerLeft { position: Some(position), .. } => {
|
||||
self.pointer_position = *position;
|
||||
ui_callback(InputEvent::pointer().position(*position).exited().modifiers(self.modifiers).build())
|
||||
}
|
||||
WindowEvent::PointerLeft { position: None, .. } => ui_callback(InputEvent::pointer().exited().modifiers(self.modifiers).build()),
|
||||
WindowEvent::PointerButton { state, button, position, .. } => {
|
||||
self.pointer_position = *position;
|
||||
|
||||
let mouse_button = button.clone().mouse_button();
|
||||
let keys = match mouse_button {
|
||||
Some(MouseButton::Left) => MouseKeys::LEFT,
|
||||
Some(MouseButton::Right) => MouseKeys::RIGHT,
|
||||
Some(MouseButton::Middle) => MouseKeys::MIDDLE,
|
||||
Some(MouseButton::Back) => MouseKeys::BACK,
|
||||
Some(MouseButton::Forward) => MouseKeys::FORWARD,
|
||||
_ => MouseKeys::NONE,
|
||||
};
|
||||
|
||||
let (pointer, route) = match self.pointer_state {
|
||||
PointerState::Hover { route } => match (state.is_pressed(), keys.is_empty()) {
|
||||
(true, false) => {
|
||||
let route = self.route(*position);
|
||||
(PointerState::Stroke { route, keys }, route)
|
||||
}
|
||||
(true, true) => (PointerState::Hover { route }, self.route(*position)),
|
||||
(false, _) => (PointerState::Hover { route }, route),
|
||||
},
|
||||
PointerState::Stroke { route, keys: mut held } => {
|
||||
match state.is_pressed() {
|
||||
true => held.insert(keys),
|
||||
false => held.remove(keys),
|
||||
}
|
||||
match held.is_empty() {
|
||||
true => (PointerState::Hover { route }, route),
|
||||
false => (PointerState::Stroke { route, keys: held }, route),
|
||||
}
|
||||
}
|
||||
PointerState::Locked { route, keys: mut held, position } => {
|
||||
let resume = if state.is_pressed() && held.is_empty() { Route::Ui } else { route };
|
||||
match state.is_pressed() {
|
||||
true => held.insert(keys),
|
||||
false => held.remove(keys),
|
||||
}
|
||||
(PointerState::Locked { route: resume, keys: held, position }, Route::Ui)
|
||||
}
|
||||
};
|
||||
self.pointer_state = pointer;
|
||||
|
||||
let count = mouse_button.map_or(1, |button| self.click_tracker.input(*position, button, *state));
|
||||
|
||||
let back_or_forward = matches!(mouse_button, Some(MouseButton::Back | MouseButton::Forward));
|
||||
let pointer = InputEvent::pointer().position(*position);
|
||||
let input = match state {
|
||||
ElementState::Pressed => pointer.pressed(button.clone(), count),
|
||||
ElementState::Released => pointer.released(button.clone(), count),
|
||||
}
|
||||
.modifiers(self.modifiers);
|
||||
if self.pointer_locked() || keys.is_empty() || !(back_or_forward || route == Route::Editor) {
|
||||
ui_callback(input.build());
|
||||
return;
|
||||
}
|
||||
if route == Route::Editor {
|
||||
ui_callback(input.observe_only().build());
|
||||
}
|
||||
|
||||
let editor_mouse_state = match button {
|
||||
ButtonSource::TabletTool { kind, data, .. } => self.tablet_pointer_state(kind, data),
|
||||
_ => self.pointer_state(),
|
||||
};
|
||||
let modifier_keys = self.modifier_keys();
|
||||
match state {
|
||||
ElementState::Pressed => editor_callback(InputMessage::PointerDown { editor_mouse_state, modifier_keys }),
|
||||
ElementState::Released if count % 2 == 0 => {
|
||||
editor_callback(InputMessage::PointerUp { editor_mouse_state, modifier_keys });
|
||||
editor_callback(InputMessage::DoubleClick {
|
||||
editor_mouse_state: EditorPointerState {
|
||||
mouse_keys: keys,
|
||||
..editor_mouse_state
|
||||
},
|
||||
modifier_keys,
|
||||
});
|
||||
}
|
||||
ElementState::Released => editor_callback(InputMessage::PointerUp { editor_mouse_state, modifier_keys }),
|
||||
}
|
||||
}
|
||||
WindowEvent::MouseWheel { delta, .. } => {
|
||||
if self.pointer_locked() || self.ui_captures(self.pointer_position) {
|
||||
let input = match delta {
|
||||
MouseScrollDelta::LineDelta(x, y) => InputEvent::pointer().scrolled_lines(f64::from(*x), f64::from(*y)),
|
||||
MouseScrollDelta::PixelDelta(position) => InputEvent::pointer().scrolled_pixels(position.x, position.y),
|
||||
_ => return,
|
||||
};
|
||||
ui_callback(input.modifiers(self.modifiers).build());
|
||||
return;
|
||||
}
|
||||
|
||||
let (x, y) = match delta {
|
||||
MouseScrollDelta::LineDelta(x, y) => (f64::from(*x) * SCROLL_LINE_WIDTH, f64::from(*y) * SCROLL_LINE_HEIGHT),
|
||||
MouseScrollDelta::PixelDelta(position) => (position.x, position.y),
|
||||
_ => return,
|
||||
};
|
||||
|
||||
let scroll_delta = ScrollDelta::new(-x * SCROLL_SPEED_X, -y * SCROLL_SPEED_Y, 0.);
|
||||
|
||||
editor_callback(InputMessage::WheelScroll {
|
||||
editor_mouse_state: EditorPointerState { scroll_delta, ..self.pointer_state() },
|
||||
modifier_keys: self.modifier_keys(),
|
||||
});
|
||||
}
|
||||
WindowEvent::PinchGesture { delta, .. } => {
|
||||
if self.pointer_locked() || self.ui_captures(self.pointer_position) || !delta.is_normal() {
|
||||
ui_callback(InputEvent::pointer().zoomed(*delta).modifiers(self.modifiers).build());
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO: This is a temporary solution to handle pinch gestures, we should handle pinch gestures editor-side instead.
|
||||
let scroll_delta = ScrollDelta::new(0., -delta * PINCH_ZOOM_SPEED, 0.);
|
||||
editor_callback(InputMessage::WheelScroll {
|
||||
editor_mouse_state: EditorPointerState { scroll_delta, ..self.pointer_state() },
|
||||
modifier_keys: self.modifier_keys() | ModifierKeys::CONTROL,
|
||||
});
|
||||
}
|
||||
WindowEvent::ModifiersChanged(modifiers) => {
|
||||
self.modifiers = modifiers.state();
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. } => ui_callback(InputEvent::key(event).modifiers(self.modifiers).build()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn scale(&self) -> f64 {
|
||||
self.viewport_info.as_ref().map_or(1., |info| info.scale)
|
||||
}
|
||||
|
||||
fn ui_captures(&self, position: PhysicalPosition<f64>) -> bool {
|
||||
!self.direct_input || !self.viewport_info.as_ref().is_some_and(|info| info.contains(position))
|
||||
}
|
||||
|
||||
fn route(&self, position: PhysicalPosition<f64>) -> Route {
|
||||
if self.ui_captures(position) { Route::Ui } else { Route::Editor }
|
||||
}
|
||||
|
||||
fn pointer_keys(&self) -> MouseKeys {
|
||||
match self.pointer_state {
|
||||
PointerState::Hover { .. } => MouseKeys::empty(),
|
||||
PointerState::Stroke { keys, .. } | PointerState::Locked { keys, .. } => keys,
|
||||
}
|
||||
}
|
||||
|
||||
fn pointer_state(&self) -> EditorPointerState {
|
||||
EditorPointerState {
|
||||
editor_position: (self.pointer_position.x / self.scale(), self.pointer_position.y / self.scale()).into(),
|
||||
mouse_keys: self.pointer_keys(),
|
||||
time: Some(self.start.elapsed().as_secs_f64() * 1000.),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn tablet_pointer_state(&self, kind: &TabletToolKind, data: &TabletToolData) -> EditorPointerState {
|
||||
EditorPointerState {
|
||||
pressure: data.force.map(|force| force.normalized(None)),
|
||||
tilt: data.clone().tilt().map(|tilt| (f64::from(tilt.x), f64::from(tilt.y)).into()),
|
||||
twist: data.twist.map(f64::from),
|
||||
wheel: data.tangential_force.map(f64::from),
|
||||
eraser: matches!(kind, TabletToolKind::Eraser),
|
||||
..self.pointer_state()
|
||||
}
|
||||
}
|
||||
|
||||
fn modifier_keys(&self) -> ModifierKeys {
|
||||
let mut keys = ModifierKeys::empty();
|
||||
keys.set(ModifierKeys::SHIFT, self.modifiers.shift_key());
|
||||
keys.set(ModifierKeys::CONTROL, self.modifiers.control_key());
|
||||
keys.set(ModifierKeys::ALT, self.modifiers.alt_key());
|
||||
keys.set(ModifierKeys::META_OR_COMMAND, self.modifiers.meta_key());
|
||||
keys
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum PointerState {
|
||||
Hover { route: Route },
|
||||
Stroke { route: Route, keys: MouseKeys },
|
||||
Locked { route: Route, keys: MouseKeys, position: PhysicalPosition<f64> },
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Route {
|
||||
Ui,
|
||||
Editor,
|
||||
}
|
||||
|
||||
struct ViewportInfo {
|
||||
x: f64,
|
||||
y: f64,
|
||||
width: f64,
|
||||
height: f64,
|
||||
scale: f64,
|
||||
}
|
||||
|
||||
impl ViewportInfo {
|
||||
fn contains(&self, position: PhysicalPosition<f64>) -> bool {
|
||||
position.x >= self.x && position.y >= self.y && position.x <= self.x + self.width && position.y <= self.y + self.height
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ClickTracker {
|
||||
left: ClickChains,
|
||||
right: ClickChains,
|
||||
middle: ClickChains,
|
||||
back: ClickChains,
|
||||
forward: ClickChains,
|
||||
}
|
||||
|
||||
impl ClickTracker {
|
||||
fn input(&mut self, position: PhysicalPosition<f64>, button: MouseButton, state: ElementState) -> u32 {
|
||||
let position = (position.x as i32, position.y as i32);
|
||||
let clicks = match button {
|
||||
MouseButton::Left => &mut self.left,
|
||||
MouseButton::Right => &mut self.right,
|
||||
MouseButton::Middle => &mut self.middle,
|
||||
MouseButton::Back => &mut self.back,
|
||||
MouseButton::Forward => &mut self.forward,
|
||||
_ => return 1,
|
||||
};
|
||||
let chain = match state {
|
||||
ElementState::Pressed => &mut clicks.down,
|
||||
ElementState::Released => &mut clicks.up,
|
||||
};
|
||||
|
||||
let now = Instant::now();
|
||||
let count = match chain {
|
||||
Some(previous) => {
|
||||
let within_time = now.saturating_duration_since(previous.time) <= MULTICLICK_TIMEOUT;
|
||||
let dx = position.0.abs_diff(previous.position.0) as usize;
|
||||
let dy = position.1.abs_diff(previous.position.1) as usize;
|
||||
let within_distance = dx <= MULTICLICK_ALLOWED_TRAVEL && dy <= MULTICLICK_ALLOWED_TRAVEL;
|
||||
if within_time && within_distance { previous.count.saturating_add(1) } else { 1 }
|
||||
}
|
||||
None => 1,
|
||||
};
|
||||
*chain = Some(Click { time: now, position, count });
|
||||
count
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ClickChains {
|
||||
down: Option<Click>,
|
||||
up: Option<Click>,
|
||||
}
|
||||
|
||||
struct Click {
|
||||
time: Instant,
|
||||
position: (i32, i32),
|
||||
count: u32,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ShakeTracker {
|
||||
samples: VecDeque<(PhysicalPosition<f64>, Duration)>,
|
||||
last: Option<Duration>,
|
||||
}
|
||||
|
||||
// Keep heuristic and constants in sync with `detectShake` in `frontend/src/utility-functions/input.ts`.
|
||||
impl ShakeTracker {
|
||||
const SENSITIVITY_DIRECTION_CHANGES: usize = 3;
|
||||
const SENSITIVITY_DISTANCE_TO_DISPLACEMENT_RATIO: f64 = 0.1;
|
||||
const DETECTION_WINDOW: Duration = Duration::from_millis(500);
|
||||
const DEBOUNCE: Duration = Duration::from_millis(1000);
|
||||
|
||||
fn detect(&mut self, position: PhysicalPosition<f64>, now: Duration) -> bool {
|
||||
self.samples.push_back((position, now));
|
||||
|
||||
while self.samples.front().is_some_and(|&(_, time)| now.saturating_sub(time) > Self::DETECTION_WINDOW) {
|
||||
self.samples.pop_front();
|
||||
}
|
||||
|
||||
if self.samples.len() <= 3 || self.last.is_some_and(|time| now.saturating_sub(time) <= Self::DEBOUNCE) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut total_distance_squared = 0.;
|
||||
for i in 1..self.samples.len() {
|
||||
let (p1, _) = self.samples[i - 1];
|
||||
let (p2, _) = self.samples[i];
|
||||
total_distance_squared += (p2.x - p1.x).powi(2) + (p2.y - p1.y).powi(2);
|
||||
}
|
||||
|
||||
let mut direction_changes = 0;
|
||||
let mut average = PhysicalPosition::new(0., 0.);
|
||||
let interior_count = self.samples.len() - 2;
|
||||
for i in 0..interior_count {
|
||||
let (p1, _) = self.samples[i];
|
||||
let (p2, _) = self.samples[i + 1];
|
||||
let (p3, _) = self.samples[i + 2];
|
||||
|
||||
let vector1 = (p2.x - p1.x, p2.y - p1.y);
|
||||
let vector2 = (p3.x - p2.x, p3.y - p2.y);
|
||||
if vector1.0 * vector2.0 + vector1.1 * vector2.1 < 0. {
|
||||
direction_changes += 1;
|
||||
}
|
||||
|
||||
average.x += p2.x;
|
||||
average.y += p2.y;
|
||||
}
|
||||
average.x /= interior_count as f64;
|
||||
average.y /= interior_count as f64;
|
||||
|
||||
let (last, _) = self.samples[self.samples.len() - 1];
|
||||
let displacement_squared = (last.x - average.x).powi(2) + (last.y - average.y).powi(2);
|
||||
|
||||
if Self::SENSITIVITY_DISTANCE_TO_DISPLACEMENT_RATIO * total_distance_squared >= displacement_squared && direction_changes >= Self::SENSITIVITY_DIRECTION_CHANGES {
|
||||
self.last = Some(now);
|
||||
self.samples.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,6 @@ mod cli;
|
||||
mod dirs;
|
||||
mod event;
|
||||
mod gpu_context;
|
||||
mod input;
|
||||
mod persist;
|
||||
mod preferences;
|
||||
mod render;
|
||||
|
||||
+51
-50
@@ -1,9 +1,6 @@
|
||||
use crate::wrapper::messages::PersistedState;
|
||||
use crate::wrapper::messages::{DocumentId, PersistedState};
|
||||
|
||||
pub(crate) fn read_state() -> PersistedState {
|
||||
if let Err(error) = migrate_documents() {
|
||||
tracing::error!("Autosave migration failed: {error}");
|
||||
}
|
||||
let path = state_file_path();
|
||||
let data = match std::fs::read_to_string(&path) {
|
||||
Ok(d) => d,
|
||||
@@ -16,13 +13,16 @@ pub(crate) fn read_state() -> PersistedState {
|
||||
return PersistedState::default();
|
||||
}
|
||||
};
|
||||
match ron::from_str(&data) {
|
||||
let loaded = match ron::from_str(&data) {
|
||||
Ok(d) => d,
|
||||
Err(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) {
|
||||
@@ -37,6 +37,46 @@ pub(crate) fn write_state(state: PersistedState) {
|
||||
if let Err(e) = std::fs::write(state_file_path(), data) {
|
||||
tracing::error!("Failed to write persistent data to disk: {e}");
|
||||
}
|
||||
garbage_collect_document_files(state);
|
||||
}
|
||||
|
||||
pub(crate) fn write_document_content(id: DocumentId, document_content: String) {
|
||||
if let Err(e) = std::fs::write(document_content_path(&id), document_content) {
|
||||
tracing::error!("Failed to write document {id:?} to disk: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn read_document_content(id: &DocumentId) -> Option<String> {
|
||||
std::fs::read_to_string(document_content_path(id)).ok()
|
||||
}
|
||||
|
||||
pub(crate) fn delete_document(id: &DocumentId) {
|
||||
if let Err(e) = std::fs::remove_file(document_content_path(id)) {
|
||||
tracing::error!("Failed to delete document {id:?} from disk: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
fn garbage_collect_document_files(state: &PersistedState) {
|
||||
let valid_paths: std::collections::HashSet<_> = state.documents.iter().map(|doc| document_content_path(&doc.id)).collect();
|
||||
|
||||
let directory = crate::dirs::app_autosave_documents_dir();
|
||||
let entries = match std::fs::read_dir(&directory) {
|
||||
Ok(entries) => entries,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to read autosave documents directory: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_file() && !valid_paths.contains(&path) {
|
||||
if 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 {
|
||||
@@ -45,47 +85,8 @@ fn state_file_path() -> std::path::PathBuf {
|
||||
path
|
||||
}
|
||||
|
||||
// TODO: Remove this migration code
|
||||
fn migrate_documents() -> std::io::Result<()> {
|
||||
let root = crate::dirs::app_autosave_documents_dir();
|
||||
let entries = match std::fs::read_dir(&root) {
|
||||
Ok(entries) => entries,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = match entry {
|
||||
Ok(entry) => entry,
|
||||
Err(error) => {
|
||||
tracing::error!("Skipping an unreadable autosave entry: {error}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if let Err(error) = migrate_document(&root, &entry) {
|
||||
tracing::error!("Autosave migration of {} failed: {error}", entry.path().display());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn migrate_document(root: &std::path::Path, entry: &std::fs::DirEntry) -> std::io::Result<()> {
|
||||
let path = entry.path();
|
||||
if !entry.file_type()?.is_file() || path.extension().and_then(|s| s.to_str()) != Some(graphite_desktop_wrapper::FILE_EXTENSION) {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(id) = path.file_stem().and_then(|s| s.to_str()).and_then(|s| u64::from_str_radix(s, 16).ok()) else {
|
||||
return Ok(());
|
||||
};
|
||||
let destination = root.join(format!("{id:016x}"));
|
||||
if !destination.join("legacy.graphite").exists() && !destination.join("manifest.json").exists() {
|
||||
std::fs::create_dir_all(&destination)?;
|
||||
let staging = destination.join("legacy.graphite.migrating");
|
||||
std::fs::copy(&path, &staging)?;
|
||||
std::fs::rename(staging, destination.join("legacy.graphite"))?;
|
||||
}
|
||||
let backup = path.with_extension(format!("{}.migrated", graphite_desktop_wrapper::FILE_EXTENSION));
|
||||
if backup.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
std::fs::rename(path, backup)
|
||||
fn document_content_path(id: &DocumentId) -> std::path::PathBuf {
|
||||
let mut path = crate::dirs::app_autosave_documents_dir();
|
||||
path.push(format!("{:x}.{}", id.0, graphite_desktop_wrapper::FILE_EXTENSION));
|
||||
path
|
||||
}
|
||||
@@ -52,12 +52,13 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
return srgb_to_linear(immediates.background_color);
|
||||
}
|
||||
|
||||
let ui_sample = textureSample(t_ui, s_diffuse, ui_coordinate);
|
||||
if (ui_sample.a >= 0.999) {
|
||||
return srgb_to_linear(ui_sample);
|
||||
let ui_linear = srgb_to_linear(textureSample(t_ui, s_diffuse, ui_coordinate));
|
||||
if (ui_linear.a >= 0.999) {
|
||||
return ui_linear;
|
||||
}
|
||||
|
||||
let ui_srgb = unpremultiply(ui_sample);
|
||||
// UI texture is premultiplied, we need to unpremultiply before blending
|
||||
let ui_srgb = linear_to_srgb(unpremultiply(ui_linear));
|
||||
|
||||
let viewport_coordinate = (in.tex_coords - immediates.viewport_offset) * immediates.viewport_scale;
|
||||
if (viewport_coordinate.x < 0.0 || viewport_coordinate.x > 1.0 ||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use wgpu::PresentMode;
|
||||
|
||||
use crate::window::Window;
|
||||
use crate::wrapper::{Texture, WgpuContext, WgpuCurrentSurfaceTexture, WgpuExecutor, WgpuSurface};
|
||||
use crate::wrapper::{WgpuContext, WgpuCurrentSurfaceTexture, WgpuExecutor, WgpuSurface};
|
||||
|
||||
#[derive(derivative::Derivative)]
|
||||
#[derivative(Debug)]
|
||||
@@ -10,14 +10,14 @@ pub(crate) struct RenderState {
|
||||
executor: WgpuExecutor,
|
||||
config: wgpu::SurfaceConfiguration,
|
||||
render_pipeline: wgpu::RenderPipeline,
|
||||
transparent_texture: Texture,
|
||||
transparent_texture: std::sync::Arc<wgpu::Texture>,
|
||||
sampler: wgpu::Sampler,
|
||||
desired_width: u32,
|
||||
desired_height: u32,
|
||||
viewport_scale: [f32; 2],
|
||||
viewport_offset: [f32; 2],
|
||||
viewport_texture: Option<Texture>,
|
||||
overlays_texture: Option<Texture>,
|
||||
viewport_texture: Option<std::sync::Arc<wgpu::Texture>>,
|
||||
overlays_texture: Option<std::sync::Arc<wgpu::Texture>>,
|
||||
ui_texture: Option<wgpu::Texture>,
|
||||
bind_group: Option<wgpu::BindGroup>,
|
||||
#[derivative(Debug = "ignore")]
|
||||
@@ -46,8 +46,8 @@ impl RenderState {
|
||||
|
||||
surface.configure(&context.device, &config);
|
||||
|
||||
let transparent_texture = Texture::from(context.device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("transparent_fallback"),
|
||||
let transparent_texture = std::sync::Arc::new(context.device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("Transparent Texture"),
|
||||
size: wgpu::Extent3d {
|
||||
width: 1,
|
||||
height: 1,
|
||||
@@ -193,7 +193,7 @@ impl RenderState {
|
||||
self.surface_outdated = true;
|
||||
}
|
||||
|
||||
pub(crate) fn bind_viewport_texture(&mut self, viewport_texture: Texture) {
|
||||
pub(crate) fn bind_viewport_texture(&mut self, viewport_texture: std::sync::Arc<wgpu::Texture>) {
|
||||
self.viewport_texture = Some(viewport_texture);
|
||||
self.update_bindgroup();
|
||||
}
|
||||
@@ -228,10 +228,10 @@ impl RenderState {
|
||||
return;
|
||||
};
|
||||
let size = glam::UVec2::new(viewport_texture.width(), viewport_texture.height());
|
||||
let result = futures::executor::block_on(self.executor.render_vello_scene(&scene, size, &Default::default(), None));
|
||||
let result = self.executor.render_vello_scene(&scene, size, &Default::default(), None);
|
||||
match result {
|
||||
Ok(texture) => {
|
||||
self.overlays_texture = Some(texture);
|
||||
self.overlays_texture = Some(texture.into());
|
||||
}
|
||||
Err(e) => {
|
||||
self.overlays_texture = None;
|
||||
|
||||
@@ -43,6 +43,13 @@ pub(crate) struct Window {
|
||||
#[allow(dead_code)]
|
||||
native_handle: native::NativeWindowImpl,
|
||||
custom_cursors: HashMap<CustomCursorSource, CustomCursor>,
|
||||
clipboard: Option<window_clipboard::Clipboard>,
|
||||
}
|
||||
impl Drop for Window {
|
||||
fn drop(&mut self) {
|
||||
// Clipboard must be dropped before `winit_window`
|
||||
drop(self.clipboard.take());
|
||||
}
|
||||
}
|
||||
|
||||
impl Window {
|
||||
@@ -63,10 +70,12 @@ impl Window {
|
||||
|
||||
let winit_window = event_loop.create_window(attributes).unwrap();
|
||||
let native_handle = native::NativeWindowImpl::new(winit_window.as_ref(), app_event_scheduler);
|
||||
let clipboard = unsafe { window_clipboard::Clipboard::connect(&winit_window) }.ok();
|
||||
Self {
|
||||
winit_window: winit_window.into(),
|
||||
native_handle,
|
||||
custom_cursors: HashMap::new(),
|
||||
clipboard,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,4 +208,28 @@ impl Window {
|
||||
pub(crate) fn update_menu(&self, entries: Vec<MenuItem>) {
|
||||
self.native_handle.update_menu(entries);
|
||||
}
|
||||
|
||||
pub(crate) fn clipboard_read(&self) -> Option<String> {
|
||||
let Some(clipboard) = &self.clipboard else {
|
||||
tracing::error!("Clipboard not available");
|
||||
return None;
|
||||
};
|
||||
match clipboard.read() {
|
||||
Ok(data) => Some(data),
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to read from clipboard: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn clipboard_write(&mut self, data: String) {
|
||||
let Some(clipboard) = &mut self.clipboard else {
|
||||
tracing::error!("Clipboard not available");
|
||||
return;
|
||||
};
|
||||
if let Err(e) = clipboard.write(data) {
|
||||
tracing::error!("Failed to write to clipboard: {e}")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -344,14 +344,6 @@ unsafe fn position_helper(main: HWND, helper: HWND) {
|
||||
let h = (r.bottom - r.top) + RESIZE_BAND_THICKNESS * 2;
|
||||
|
||||
let _ = unsafe { SetWindowPos(helper, Some(main), x, y, w, h, SWP_NOACTIVATE | SWP_NOSENDCHANGING) };
|
||||
|
||||
let outer = unsafe { CreateRectRgn(0, 0, w, h) };
|
||||
let inner = unsafe { CreateRectRgn(RESIZE_BAND_THICKNESS, RESIZE_BAND_THICKNESS, w - RESIZE_BAND_THICKNESS, h - RESIZE_BAND_THICKNESS) };
|
||||
let _ = unsafe { CombineRgn(Some(outer), Some(outer), Some(inner), RGN_DIFF) };
|
||||
let _ = unsafe { DeleteObject(inner.into()) };
|
||||
if unsafe { SetWindowRgn(helper, Some(outer), false) } == 0 {
|
||||
let _ = unsafe { DeleteObject(outer.into()) };
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn calculate_hit(helper: HWND, lparam: LPARAM) -> u32 {
|
||||
|
||||
@@ -2,17 +2,9 @@
|
||||
name = "graphite-desktop-ui"
|
||||
description = "Renders the Graphite editor frontend UI into wgpu textures"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
|
||||
+18
-18
@@ -1,23 +1,5 @@
|
||||
use std::time::Duration;
|
||||
|
||||
pub const MULTICLICK_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
pub const MULTICLICK_ALLOWED_TRAVEL: usize = 4;
|
||||
|
||||
pub const SCROLL_LINE_HEIGHT: f64 = 40.;
|
||||
pub const SCROLL_LINE_WIDTH: f64 = 40.;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const SCROLL_SPEED_X: f64 = 3.;
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const SCROLL_SPEED_Y: f64 = 3.;
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub const SCROLL_SPEED_X: f64 = 1.;
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub const SCROLL_SPEED_Y: f64 = 1.;
|
||||
|
||||
pub const PINCH_ZOOM_SPEED: f64 = 300.;
|
||||
|
||||
pub(crate) const RESOURCE_SCHEME: &str = "resources";
|
||||
pub(crate) const RESOURCE_DOMAIN: &str = "resources";
|
||||
|
||||
@@ -35,3 +17,21 @@ pub(crate) const HOST_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) const IPC_BOOTSTRAP_PREFIX: &str = "art.graphite.Graphite.ipc.";
|
||||
|
||||
pub(crate) const SCROLL_LINE_HEIGHT: usize = 40;
|
||||
pub(crate) const SCROLL_LINE_WIDTH: usize = 40;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) const SCROLL_SPEED_X: f32 = 3.;
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) const SCROLL_SPEED_Y: f32 = 3.;
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub(crate) const SCROLL_SPEED_X: f32 = 1.;
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub(crate) const SCROLL_SPEED_Y: f32 = 1.;
|
||||
|
||||
pub(crate) const PINCH_ZOOM_SPEED: f64 = 300.;
|
||||
|
||||
pub(crate) const MULTICLICK_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
pub(crate) const MULTICLICK_ALLOWED_TRAVEL: usize = 4;
|
||||
@@ -223,7 +223,6 @@ fn create_browser(delegate: BrowserDelegate, frames: FrameStreamer, view_info_se
|
||||
.map(|browser| BrowserContext {
|
||||
delegate,
|
||||
browser,
|
||||
input: input::InputState::default(),
|
||||
view_info_sender,
|
||||
_instance_dir: instance_dir,
|
||||
})
|
||||
@@ -253,8 +252,12 @@ pub(crate) enum InitError {
|
||||
pub(crate) struct CefContextHandle;
|
||||
|
||||
impl CefContextHandle {
|
||||
pub(crate) fn process_input(&self, event: InputEvent) {
|
||||
with_context(move |context| input::process(&mut context.input, &context.browser, &event));
|
||||
pub(crate) fn apply_input(&self, events: Vec<InputEvent>) {
|
||||
with_context(move |context| {
|
||||
for event in &events {
|
||||
input::apply(&context.browser, event);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn update_view_info(&self, update: ViewInfoUpdate) {
|
||||
@@ -273,7 +276,6 @@ impl CefContextHandle {
|
||||
struct BrowserContext {
|
||||
delegate: BrowserDelegate,
|
||||
browser: Browser,
|
||||
input: input::InputState,
|
||||
view_info_sender: Sender<ViewInfoUpdate>,
|
||||
_instance_dir: TempDir,
|
||||
}
|
||||
|
||||
+207
-191
@@ -1,235 +1,251 @@
|
||||
pub(crate) mod event;
|
||||
pub(crate) use event::InputEvent;
|
||||
use cef::sys::{cef_key_event_type_t, cef_mouse_button_type_t};
|
||||
use cef::{Browser, ImplBrowser, ImplBrowserHost, KeyEvent, MouseEvent};
|
||||
use winit::event::{ButtonSource, ElementState, MouseButton, MouseScrollDelta, WindowEvent};
|
||||
|
||||
mod keymap;
|
||||
use keymap::{ToCharRepresentation, ToNativeKeycode, ToVKBits};
|
||||
|
||||
use cef::sys::{cef_event_flags_t, cef_key_event_type_t, cef_mouse_button_type_t};
|
||||
use cef::{Browser, ImplBrowser, ImplBrowserHost, KeyEvent, MouseEvent};
|
||||
use winit::dpi::PhysicalPosition;
|
||||
use winit::keyboard::{Key, KeyLocation, NamedKey};
|
||||
mod state;
|
||||
pub(crate) use state::{CefModifiers, InputState};
|
||||
|
||||
use super::consts::{PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
|
||||
use event::{InputEventKind, KeyAction, Modifiers, MouseButton, PointerAction};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct InputState {
|
||||
position: PhysicalPosition<f64>,
|
||||
buttons: ButtonStates,
|
||||
/// A window input translated into the plain data CEF consumes — no winit types, so it can
|
||||
/// be applied to a browser living in another process.
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) enum InputEvent {
|
||||
MouseMove { data: MouseData, leave: bool },
|
||||
MouseClick { data: MouseData, button: MouseButtonKind, up: bool, click_count: i32 },
|
||||
MouseWheel { data: MouseData, delta_x: i32, delta_y: i32 },
|
||||
Key(KeyData),
|
||||
}
|
||||
|
||||
impl InputState {
|
||||
fn pointer_move(&mut self, position: PhysicalPosition<f64>) -> bool {
|
||||
let moved = (position.x as i32, position.y as i32) != (self.position.x as i32, self.position.y as i32);
|
||||
self.position = position;
|
||||
moved
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) struct MouseData {
|
||||
pub(crate) x: i32,
|
||||
pub(crate) y: i32,
|
||||
pub(crate) modifiers: u32,
|
||||
}
|
||||
|
||||
pub(crate) fn process(state: &mut InputState, browser: &Browser, event: &InputEvent) {
|
||||
let Some(host) = browser.host() else { return };
|
||||
match &event.kind {
|
||||
InputEventKind::Pointer { position, action } => {
|
||||
let position = position.unwrap_or(state.position);
|
||||
match *action {
|
||||
PointerAction::Move => {
|
||||
if !state.pointer_move(position) {
|
||||
return;
|
||||
}
|
||||
let flags = event_flags(&event.modifiers, &state.buttons);
|
||||
host.send_mouse_move_event(Some(&mouse_event(position, flags)), 0);
|
||||
}
|
||||
PointerAction::Enter => {
|
||||
state.pointer_move(position);
|
||||
let flags = event_flags(&event.modifiers, &state.buttons);
|
||||
host.send_mouse_move_event(Some(&mouse_event(position, flags)), 0);
|
||||
}
|
||||
PointerAction::Exit => {
|
||||
state.pointer_move(position);
|
||||
let flags = event_flags(&event.modifiers, &state.buttons);
|
||||
host.send_mouse_move_event(Some(&mouse_event(position, flags)), 1);
|
||||
}
|
||||
PointerAction::Press { button, count } | PointerAction::Release { button, count } => {
|
||||
state.pointer_move(position);
|
||||
let cef_button = match button {
|
||||
MouseButton::Left => cef_mouse_button_type_t::MBT_LEFT,
|
||||
MouseButton::Right => cef_mouse_button_type_t::MBT_RIGHT,
|
||||
MouseButton::Middle => cef_mouse_button_type_t::MBT_MIDDLE,
|
||||
MouseButton::Unknown => return,
|
||||
};
|
||||
let up = matches!(action, PointerAction::Release { .. });
|
||||
state.buttons.update(button, !up);
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) enum MouseButtonKind {
|
||||
Left,
|
||||
Right,
|
||||
Middle,
|
||||
}
|
||||
|
||||
// CEF only understands single, double and triple clicks; further clicks alternate between double and triple.
|
||||
let count = match count {
|
||||
0 | 1 => 1,
|
||||
count if count % 2 == 0 => 2,
|
||||
_ => 3,
|
||||
};
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) enum KeyEventKind {
|
||||
RawKeyDown,
|
||||
KeyUp,
|
||||
Char,
|
||||
}
|
||||
|
||||
let flags = event_flags(&event.modifiers, &state.buttons);
|
||||
host.send_mouse_click_event(Some(&mouse_event(position, flags)), cef::MouseButtonType::from(cef_button), up as i32, count);
|
||||
}
|
||||
PointerAction::ScrollLines { x, y } => {
|
||||
let flags = event_flags(&event.modifiers, &state.buttons);
|
||||
let delta_x = (x * SCROLL_LINE_WIDTH * SCROLL_SPEED_X) as i32;
|
||||
let delta_y = (y * SCROLL_LINE_HEIGHT * SCROLL_SPEED_Y) as i32;
|
||||
host.send_mouse_wheel_event(Some(&mouse_event(position, flags)), delta_x, delta_y);
|
||||
}
|
||||
PointerAction::ScrollPixels { x, y } => {
|
||||
let flags = event_flags(&event.modifiers, &state.buttons) | PRECISION_SCROLLING_DELTA;
|
||||
host.send_mouse_wheel_event(Some(&mouse_event(position, flags)), (x * SCROLL_SPEED_X) as i32, (y * SCROLL_SPEED_Y) as i32);
|
||||
}
|
||||
PointerAction::Zoom(delta) => {
|
||||
if !delta.is_normal() {
|
||||
return;
|
||||
}
|
||||
let flags = CONTROL_DOWN | PRECISION_SCROLLING_DELTA;
|
||||
host.send_mouse_wheel_event(Some(&mouse_event(position, flags)), 0, (delta * PINCH_ZOOM_SPEED).round() as i32);
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) struct KeyData {
|
||||
pub(crate) kind: KeyEventKind,
|
||||
pub(crate) modifiers: u32,
|
||||
pub(crate) windows_key_code: i32,
|
||||
pub(crate) native_key_code: i32,
|
||||
pub(crate) character: u16,
|
||||
pub(crate) unmodified_character: u16,
|
||||
}
|
||||
|
||||
/// Turns a winit event into zero or more [`InputEvent`]s, updating the tracked input state
|
||||
/// (cursor position, click counting, modifiers) along the way.
|
||||
pub(crate) fn translate(input_state: &mut InputState, event: &WindowEvent) -> Vec<InputEvent> {
|
||||
match event {
|
||||
WindowEvent::PointerMoved { position, .. } => {
|
||||
if !input_state.cursor_move(position) {
|
||||
return Vec::new();
|
||||
}
|
||||
vec![InputEvent::MouseMove {
|
||||
data: input_state.mouse_data(),
|
||||
leave: false,
|
||||
}]
|
||||
}
|
||||
InputEventKind::Key {
|
||||
key,
|
||||
key_without_modifiers,
|
||||
physical_key,
|
||||
location,
|
||||
text,
|
||||
action,
|
||||
} => {
|
||||
let mut flags = event_flags(&event.modifiers, &state.buttons);
|
||||
WindowEvent::PointerEntered { position, .. } => {
|
||||
let _ = input_state.cursor_move(position);
|
||||
vec![InputEvent::MouseMove {
|
||||
data: input_state.mouse_data(),
|
||||
leave: false,
|
||||
}]
|
||||
}
|
||||
WindowEvent::PointerLeft { position, .. } => {
|
||||
if let Some(position) = position {
|
||||
let _ = input_state.cursor_move(position);
|
||||
}
|
||||
vec![InputEvent::MouseMove {
|
||||
data: input_state.mouse_data(),
|
||||
leave: true,
|
||||
}]
|
||||
}
|
||||
WindowEvent::PointerButton { state, button, position, .. } => {
|
||||
let mouse_button = match button {
|
||||
ButtonSource::Mouse(mouse_button) => mouse_button,
|
||||
_ => {
|
||||
return Vec::new(); // TODO: Handle touch input
|
||||
}
|
||||
};
|
||||
|
||||
let own_flag = match key {
|
||||
Key::Named(NamedKey::Shift) => SHIFT_DOWN,
|
||||
Key::Named(NamedKey::Control) => CONTROL_DOWN,
|
||||
Key::Named(NamedKey::Alt) => ALT_DOWN,
|
||||
Key::Named(NamedKey::AltGraph) => ALTGR_DOWN,
|
||||
Key::Named(NamedKey::Meta) => COMMAND_DOWN,
|
||||
let _ = input_state.cursor_move(position);
|
||||
let click_count = input_state.mouse_input(mouse_button, state).into();
|
||||
let up = matches!(state, ElementState::Released);
|
||||
let button = match mouse_button {
|
||||
MouseButton::Left => MouseButtonKind::Left,
|
||||
MouseButton::Right => MouseButtonKind::Right,
|
||||
MouseButton::Middle => MouseButtonKind::Middle,
|
||||
_ => return Vec::new(),
|
||||
};
|
||||
|
||||
vec![InputEvent::MouseClick {
|
||||
data: input_state.mouse_data(),
|
||||
button,
|
||||
up,
|
||||
click_count,
|
||||
}]
|
||||
}
|
||||
WindowEvent::MouseWheel { delta, phase: _, device_id: _, .. } => {
|
||||
let (mut delta_x, mut delta_y) = match delta {
|
||||
MouseScrollDelta::LineDelta(x, y) => (x * SCROLL_LINE_WIDTH as f32, y * SCROLL_LINE_HEIGHT as f32),
|
||||
MouseScrollDelta::PixelDelta(physical_position) => (physical_position.x as f32, physical_position.y as f32),
|
||||
};
|
||||
delta_x *= SCROLL_SPEED_X;
|
||||
delta_y *= SCROLL_SPEED_Y;
|
||||
|
||||
vec![InputEvent::MouseWheel {
|
||||
data: input_state.mouse_data(),
|
||||
delta_x: delta_x as i32,
|
||||
delta_y: delta_y as i32,
|
||||
}]
|
||||
}
|
||||
WindowEvent::ModifiersChanged(modifiers) => {
|
||||
input_state.modifiers_changed(&modifiers.state());
|
||||
Vec::new()
|
||||
}
|
||||
WindowEvent::KeyboardInput { device_id: _, event, is_synthetic: _ } => {
|
||||
input_state.modifiers_apply_key_event(&event.logical_key, &event.state);
|
||||
|
||||
let mut kind = match (event.state, &event.logical_key) {
|
||||
(ElementState::Pressed, winit::keyboard::Key::Character(_)) => KeyEventKind::Char,
|
||||
(ElementState::Pressed, _) => KeyEventKind::RawKeyDown,
|
||||
(ElementState::Released, _) => KeyEventKind::KeyUp,
|
||||
};
|
||||
|
||||
let modifiers = input_state.cef_modifiers(&event.location, event.repeat).into();
|
||||
|
||||
let windows_key_code = match &event.logical_key {
|
||||
winit::keyboard::Key::Named(named) => named.to_vk_bits(),
|
||||
winit::keyboard::Key::Character(char) => char.chars().next().unwrap_or_default().to_vk_bits(),
|
||||
_ => 0,
|
||||
};
|
||||
match action {
|
||||
KeyAction::Press | KeyAction::Repeat => flags |= own_flag,
|
||||
KeyAction::Release => flags &= !own_flag,
|
||||
}
|
||||
|
||||
flags |= match location {
|
||||
KeyLocation::Left => IS_LEFT,
|
||||
KeyLocation::Right => IS_RIGHT,
|
||||
KeyLocation::Numpad => IS_KEY_PAD,
|
||||
KeyLocation::Standard => 0,
|
||||
};
|
||||
if *action == KeyAction::Repeat {
|
||||
flags |= IS_REPEAT;
|
||||
}
|
||||
let native_key_code = event.physical_key.to_native_keycode();
|
||||
|
||||
let windows_key_code = match key {
|
||||
Key::Named(named) => named.to_vk_bits(),
|
||||
Key::Character(char) => char.chars().next().unwrap_or_default().to_vk_bits(),
|
||||
_ => 0,
|
||||
};
|
||||
let native_key_code = physical_key.to_native_keycode();
|
||||
|
||||
let char_representation = key.to_char_representation();
|
||||
let char_representation = event.logical_key.to_char_representation();
|
||||
#[allow(unused_mut)]
|
||||
let mut character = char_representation as u16;
|
||||
let unmodified_character = key_without_modifiers.to_char_representation() as u16;
|
||||
|
||||
if event.state == ElementState::Pressed && character != 0 {
|
||||
kind = KeyEventKind::Char;
|
||||
}
|
||||
|
||||
let unmodified_character = event.key_without_modifiers.to_char_representation() as u16;
|
||||
|
||||
#[cfg(target_os = "macos")] // See https://www.magpcss.org/ceforum/viewtopic.php?start=10&t=11650
|
||||
if character == 0 && unmodified_character == 0 && text.is_some() {
|
||||
if character == 0 && unmodified_character == 0 && event.text_with_all_modifiers.is_some() {
|
||||
character = 1;
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let _ = text;
|
||||
|
||||
let key_event = |kind: cef_key_event_type_t, windows_key_code: i32| KeyEvent {
|
||||
type_: kind.into(),
|
||||
modifiers: flags,
|
||||
let key = KeyData {
|
||||
kind,
|
||||
modifiers,
|
||||
windows_key_code,
|
||||
native_key_code,
|
||||
character,
|
||||
unmodified_character,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
match action {
|
||||
KeyAction::Press | KeyAction::Repeat if char_representation != '\0' => {
|
||||
host.send_key_event(Some(&key_event(cef_key_event_type_t::KEYEVENT_RAWKEYDOWN, windows_key_code)));
|
||||
host.send_key_event(Some(&key_event(cef_key_event_type_t::KEYEVENT_CHAR, char_representation as i32)));
|
||||
}
|
||||
KeyAction::Press | KeyAction::Repeat => {
|
||||
host.send_key_event(Some(&key_event(cef_key_event_type_t::KEYEVENT_RAWKEYDOWN, windows_key_code)));
|
||||
}
|
||||
KeyAction::Release => {
|
||||
host.send_key_event(Some(&key_event(cef_key_event_type_t::KEYEVENT_KEYUP, windows_key_code)));
|
||||
}
|
||||
if kind == KeyEventKind::Char {
|
||||
// CEF expects a raw key-down before the character event it produces.
|
||||
vec![
|
||||
InputEvent::Key(KeyData {
|
||||
kind: KeyEventKind::RawKeyDown,
|
||||
..key
|
||||
}),
|
||||
InputEvent::Key(KeyData {
|
||||
windows_key_code: char_representation as i32,
|
||||
..key
|
||||
}),
|
||||
]
|
||||
} else {
|
||||
vec![InputEvent::Key(key)]
|
||||
}
|
||||
}
|
||||
WindowEvent::PinchGesture { delta, .. } => {
|
||||
if !delta.is_normal() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let data = MouseData {
|
||||
modifiers: CefModifiers::PINCH_MODIFIERS.into(),
|
||||
..input_state.mouse_data()
|
||||
};
|
||||
|
||||
vec![InputEvent::MouseWheel {
|
||||
data,
|
||||
delta_x: 0,
|
||||
delta_y: (delta * PINCH_ZOOM_SPEED).round() as i32,
|
||||
}]
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ButtonStates {
|
||||
left: bool,
|
||||
right: bool,
|
||||
middle: bool,
|
||||
}
|
||||
|
||||
impl ButtonStates {
|
||||
fn update(&mut self, button: MouseButton, held: bool) {
|
||||
match button {
|
||||
MouseButton::Left => self.left = held,
|
||||
MouseButton::Right => self.right = held,
|
||||
MouseButton::Middle => self.middle = held,
|
||||
MouseButton::Unknown => {}
|
||||
/// Sends a translated [`InputEvent`] to the browser. Must run on the thread owning the browser.
|
||||
pub(crate) fn apply(browser: &Browser, event: &InputEvent) {
|
||||
let Some(host) = browser.host() else { return };
|
||||
match event {
|
||||
InputEvent::MouseMove { data, leave } => {
|
||||
host.send_mouse_move_event(Some(&data.into()), *leave as i32);
|
||||
}
|
||||
InputEvent::MouseClick { data, button, up, click_count } => {
|
||||
let cef_button = cef::MouseButtonType::from(match button {
|
||||
MouseButtonKind::Left => cef_mouse_button_type_t::MBT_LEFT,
|
||||
MouseButtonKind::Right => cef_mouse_button_type_t::MBT_RIGHT,
|
||||
MouseButtonKind::Middle => cef_mouse_button_type_t::MBT_MIDDLE,
|
||||
});
|
||||
host.send_mouse_click_event(Some(&data.into()), cef_button, *up as i32, *click_count);
|
||||
}
|
||||
InputEvent::MouseWheel { data, delta_x, delta_y } => {
|
||||
host.send_mouse_wheel_event(Some(&data.into()), *delta_x, *delta_y);
|
||||
}
|
||||
InputEvent::Key(key) => {
|
||||
let key_event = KeyEvent {
|
||||
type_: match key.kind {
|
||||
KeyEventKind::RawKeyDown => cef_key_event_type_t::KEYEVENT_RAWKEYDOWN,
|
||||
KeyEventKind::KeyUp => cef_key_event_type_t::KEYEVENT_KEYUP,
|
||||
KeyEventKind::Char => cef_key_event_type_t::KEYEVENT_CHAR,
|
||||
}
|
||||
.into(),
|
||||
modifiers: key.modifiers,
|
||||
windows_key_code: key.windows_key_code,
|
||||
native_key_code: key.native_key_code,
|
||||
character: key.character,
|
||||
unmodified_character: key.unmodified_character,
|
||||
..Default::default()
|
||||
};
|
||||
host.send_key_event(Some(&key_event));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn mouse_event(position: PhysicalPosition<f64>, flags: u32) -> MouseEvent {
|
||||
MouseEvent {
|
||||
x: position.x as i32,
|
||||
y: position.y as i32,
|
||||
modifiers: flags,
|
||||
impl From<&MouseData> for MouseEvent {
|
||||
fn from(data: &MouseData) -> Self {
|
||||
MouseEvent {
|
||||
x: data.x,
|
||||
y: data.y,
|
||||
modifiers: data.modifiers,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn event_flags(modifiers: &Modifiers, buttons: &ButtonStates) -> u32 {
|
||||
let bit = |condition: bool, flag: u32| if condition { flag } else { 0 };
|
||||
bit(modifiers.shift, SHIFT_DOWN)
|
||||
| bit(modifiers.control, CONTROL_DOWN)
|
||||
| bit(modifiers.alt, ALT_DOWN)
|
||||
| bit(modifiers.alt_graph, ALTGR_DOWN)
|
||||
| bit(modifiers.meta, COMMAND_DOWN)
|
||||
| bit(modifiers.caps_lock, CAPS_LOCK_ON)
|
||||
| bit(modifiers.num_lock, NUM_LOCK_ON)
|
||||
| bit(buttons.left, LEFT_MOUSE_BUTTON)
|
||||
| bit(buttons.right, RIGHT_MOUSE_BUTTON)
|
||||
| bit(buttons.middle, MIDDLE_MOUSE_BUTTON)
|
||||
}
|
||||
|
||||
const fn flag(flag: cef_event_flags_t) -> u32 {
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
{
|
||||
flag.0
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
flag.0 as u32
|
||||
}
|
||||
}
|
||||
|
||||
const SHIFT_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_SHIFT_DOWN);
|
||||
const CONTROL_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_CONTROL_DOWN);
|
||||
const ALT_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_ALT_DOWN);
|
||||
const ALTGR_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_ALTGR_DOWN);
|
||||
const COMMAND_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_COMMAND_DOWN);
|
||||
const CAPS_LOCK_ON: u32 = flag(cef_event_flags_t::EVENTFLAG_CAPS_LOCK_ON);
|
||||
const NUM_LOCK_ON: u32 = flag(cef_event_flags_t::EVENTFLAG_NUM_LOCK_ON);
|
||||
const LEFT_MOUSE_BUTTON: u32 = flag(cef_event_flags_t::EVENTFLAG_LEFT_MOUSE_BUTTON);
|
||||
const MIDDLE_MOUSE_BUTTON: u32 = flag(cef_event_flags_t::EVENTFLAG_MIDDLE_MOUSE_BUTTON);
|
||||
const RIGHT_MOUSE_BUTTON: u32 = flag(cef_event_flags_t::EVENTFLAG_RIGHT_MOUSE_BUTTON);
|
||||
const IS_LEFT: u32 = flag(cef_event_flags_t::EVENTFLAG_IS_LEFT);
|
||||
const IS_RIGHT: u32 = flag(cef_event_flags_t::EVENTFLAG_IS_RIGHT);
|
||||
const IS_KEY_PAD: u32 = flag(cef_event_flags_t::EVENTFLAG_IS_KEY_PAD);
|
||||
const IS_REPEAT: u32 = flag(cef_event_flags_t::EVENTFLAG_IS_REPEAT);
|
||||
const PRECISION_SCROLLING_DELTA: u32 = flag(cef_event_flags_t::EVENTFLAG_PRECISION_SCROLLING_DELTA);
|
||||
@@ -1,245 +0,0 @@
|
||||
use winit::dpi::PhysicalPosition;
|
||||
use winit::event::{ElementState, KeyEvent};
|
||||
use winit::keyboard::{Key, KeyLocation, ModifiersState, PhysicalKey, SmolStr};
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct InputEvent {
|
||||
pub(crate) kind: InputEventKind,
|
||||
pub(crate) modifiers: Modifiers,
|
||||
}
|
||||
|
||||
impl InputEvent {
|
||||
pub fn pointer() -> PointerInputEventBuilder {
|
||||
PointerInputEventBuilder { position: UnknownPosition }
|
||||
}
|
||||
|
||||
pub fn key(event: &KeyEvent) -> InputEventBuilder {
|
||||
let action = match (event.state, event.repeat) {
|
||||
(ElementState::Pressed, false) => KeyAction::Press,
|
||||
(ElementState::Pressed, true) => KeyAction::Repeat,
|
||||
(ElementState::Released, _) => KeyAction::Release,
|
||||
};
|
||||
InputEventBuilder::new(InputEventKind::Key {
|
||||
key: event.logical_key.clone(),
|
||||
key_without_modifiers: event.key_without_modifiers.clone(),
|
||||
physical_key: event.physical_key,
|
||||
location: event.location,
|
||||
text: event.text_with_all_modifiers.clone(),
|
||||
action,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum MouseButton {
|
||||
Left,
|
||||
Right,
|
||||
Middle,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl From<winit::event::MouseButton> for MouseButton {
|
||||
fn from(button: winit::event::MouseButton) -> Self {
|
||||
match button {
|
||||
winit::event::MouseButton::Left => Self::Left,
|
||||
winit::event::MouseButton::Right => Self::Right,
|
||||
winit::event::MouseButton::Middle => Self::Middle,
|
||||
_ => Self::Unknown,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<winit::event::ButtonSource> for MouseButton {
|
||||
fn from(button: winit::event::ButtonSource) -> Self {
|
||||
button.mouse_button().map_or(Self::Unknown, Self::from)
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PointerInputEventBuilder<P = UnknownPosition> {
|
||||
position: P,
|
||||
}
|
||||
|
||||
impl PointerInputEventBuilder<UnknownPosition> {
|
||||
pub fn position(self, position: PhysicalPosition<f64>) -> PointerInputEventBuilder<PhysicalPosition<f64>> {
|
||||
PointerInputEventBuilder { position }
|
||||
}
|
||||
}
|
||||
|
||||
impl PointerInputEventBuilder<PhysicalPosition<f64>> {
|
||||
pub fn moved(self) -> InputEventBuilder {
|
||||
self.finish(PointerAction::Move)
|
||||
}
|
||||
|
||||
pub fn entered(self) -> InputEventBuilder {
|
||||
self.finish(PointerAction::Enter)
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: PointerPosition> PointerInputEventBuilder<P> {
|
||||
pub fn exited(self) -> InputEventBuilder {
|
||||
self.finish(PointerAction::Exit)
|
||||
}
|
||||
|
||||
pub fn pressed(self, button: impl Into<MouseButton>, count: u32) -> InputEventBuilder {
|
||||
self.finish(PointerAction::Press { button: button.into(), count })
|
||||
}
|
||||
|
||||
pub fn released(self, button: impl Into<MouseButton>, count: u32) -> InputEventBuilder {
|
||||
self.finish(PointerAction::Release { button: button.into(), count })
|
||||
}
|
||||
|
||||
pub fn scrolled_lines(self, x: f64, y: f64) -> InputEventBuilder {
|
||||
self.finish(PointerAction::ScrollLines { x, y })
|
||||
}
|
||||
|
||||
pub fn scrolled_pixels(self, x: f64, y: f64) -> InputEventBuilder {
|
||||
self.finish(PointerAction::ScrollPixels { x, y })
|
||||
}
|
||||
|
||||
pub fn zoomed(self, delta: f64) -> InputEventBuilder {
|
||||
self.finish(PointerAction::Zoom(delta))
|
||||
}
|
||||
|
||||
fn finish(self, action: PointerAction) -> InputEventBuilder {
|
||||
InputEventBuilder::new(InputEventKind::Pointer {
|
||||
position: self.position.position(),
|
||||
action,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct InputEventBuilder {
|
||||
kind: InputEventKind,
|
||||
modifiers: Modifiers,
|
||||
}
|
||||
|
||||
impl InputEventBuilder {
|
||||
fn new(kind: InputEventKind) -> Self {
|
||||
Self {
|
||||
kind,
|
||||
modifiers: Modifiers::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn shift(mut self, on: bool) -> Self {
|
||||
self.modifiers.shift = on;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn control(mut self, on: bool) -> Self {
|
||||
self.modifiers.control = on;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn alt(mut self, on: bool) -> Self {
|
||||
self.modifiers.alt = on;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn alt_graph(mut self, on: bool) -> Self {
|
||||
self.modifiers.alt_graph = on;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn meta(mut self, on: bool) -> Self {
|
||||
self.modifiers.meta = on;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn caps_lock(mut self, on: bool) -> Self {
|
||||
self.modifiers.caps_lock = on;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn num_lock(mut self, on: bool) -> Self {
|
||||
self.modifiers.num_lock = on;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn modifiers(mut self, modifiers: ModifiersState) -> Self {
|
||||
self.modifiers.shift = modifiers.shift_key();
|
||||
self.modifiers.control = modifiers.control_key();
|
||||
self.modifiers.alt = modifiers.alt_key();
|
||||
self.modifiers.meta = modifiers.meta_key();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn build(self) -> InputEvent {
|
||||
InputEvent {
|
||||
kind: self.kind,
|
||||
modifiers: self.modifiers,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(private_bounds)]
|
||||
pub trait PointerPosition: OptionalPosition {}
|
||||
impl PointerPosition for UnknownPosition {}
|
||||
impl PointerPosition for PhysicalPosition<f64> {}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct UnknownPosition;
|
||||
|
||||
trait OptionalPosition {
|
||||
fn position(self) -> Option<PhysicalPosition<f64>>;
|
||||
}
|
||||
impl OptionalPosition for UnknownPosition {
|
||||
fn position(self) -> Option<PhysicalPosition<f64>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
impl OptionalPosition for PhysicalPosition<f64> {
|
||||
fn position(self) -> Option<PhysicalPosition<f64>> {
|
||||
Some(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) enum InputEventKind {
|
||||
Pointer {
|
||||
position: Option<PhysicalPosition<f64>>,
|
||||
action: PointerAction,
|
||||
},
|
||||
Key {
|
||||
key: Key,
|
||||
key_without_modifiers: Key,
|
||||
physical_key: PhysicalKey,
|
||||
location: KeyLocation,
|
||||
text: Option<SmolStr>,
|
||||
action: KeyAction,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) enum PointerAction {
|
||||
Move,
|
||||
Enter,
|
||||
Exit,
|
||||
Press { button: MouseButton, count: u32 },
|
||||
Release { button: MouseButton, count: u32 },
|
||||
ScrollLines { x: f64, y: f64 },
|
||||
ScrollPixels { x: f64, y: f64 },
|
||||
Zoom(f64),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) enum KeyAction {
|
||||
Press,
|
||||
Repeat,
|
||||
Release,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) struct Modifiers {
|
||||
pub(crate) shift: bool,
|
||||
pub(crate) control: bool,
|
||||
pub(crate) alt: bool,
|
||||
pub(crate) alt_graph: bool,
|
||||
pub(crate) meta: bool,
|
||||
pub(crate) caps_lock: bool,
|
||||
pub(crate) num_lock: bool,
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
use cef::sys::cef_event_flags_t;
|
||||
use std::time::Instant;
|
||||
use winit::dpi::PhysicalPosition;
|
||||
use winit::event::{ElementState, MouseButton};
|
||||
use winit::keyboard::{Key, KeyLocation, ModifiersState, NamedKey};
|
||||
|
||||
use super::MouseData;
|
||||
use crate::consts::{MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct InputState {
|
||||
modifiers: ModifiersState,
|
||||
mouse_position: MousePosition,
|
||||
mouse_state: MouseState,
|
||||
mouse_click_tracker: ClickTracker,
|
||||
}
|
||||
impl InputState {
|
||||
pub(crate) fn modifiers_changed(&mut self, modifiers: &ModifiersState) {
|
||||
self.modifiers = *modifiers;
|
||||
}
|
||||
|
||||
pub(crate) fn modifiers_apply_key_event(&mut self, key: &Key, state: &ElementState) {
|
||||
let bits = match key {
|
||||
Key::Named(NamedKey::Shift) => ModifiersState::SHIFT,
|
||||
Key::Named(NamedKey::Control) => ModifiersState::CONTROL,
|
||||
Key::Named(NamedKey::Alt) => ModifiersState::ALT,
|
||||
Key::Named(NamedKey::Meta) => ModifiersState::META,
|
||||
_ => return,
|
||||
};
|
||||
let is_pressed = matches!(state, ElementState::Pressed);
|
||||
self.modifiers.set(bits, is_pressed);
|
||||
}
|
||||
|
||||
pub(crate) fn cursor_move(&mut self, position: &PhysicalPosition<f64>) -> bool {
|
||||
let new = position.into();
|
||||
if self.mouse_position == new {
|
||||
return false;
|
||||
}
|
||||
self.mouse_position = new;
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn mouse_input(&mut self, button: &MouseButton, state: &ElementState) -> ClickCount {
|
||||
self.mouse_state.update(button, state);
|
||||
self.mouse_click_tracker.input(button, state, self.mouse_position)
|
||||
}
|
||||
|
||||
pub(crate) fn cef_modifiers(&self, location: &KeyLocation, is_repeat: bool) -> CefModifiers {
|
||||
CefModifiers::new(self, location, is_repeat)
|
||||
}
|
||||
|
||||
pub(crate) fn cef_mouse_modifiers(&self) -> CefModifiers {
|
||||
self.cef_modifiers(&KeyLocation::Standard, false)
|
||||
}
|
||||
|
||||
pub(crate) fn mouse_data(&self) -> MouseData {
|
||||
MouseData {
|
||||
x: self.mouse_position.x,
|
||||
y: self.mouse_position.y,
|
||||
modifiers: self.cef_mouse_modifiers().into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, Copy, Eq, PartialEq)]
|
||||
pub(crate) struct MousePosition {
|
||||
x: i32,
|
||||
y: i32,
|
||||
}
|
||||
impl From<&PhysicalPosition<f64>> for MousePosition {
|
||||
fn from(position: &PhysicalPosition<f64>) -> Self {
|
||||
Self {
|
||||
x: position.x as i32,
|
||||
y: position.y as i32,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
pub(crate) struct MouseState {
|
||||
left: bool,
|
||||
right: bool,
|
||||
middle: bool,
|
||||
}
|
||||
impl MouseState {
|
||||
pub(crate) fn update(&mut self, button: &MouseButton, state: &ElementState) {
|
||||
match state {
|
||||
ElementState::Pressed => match button {
|
||||
MouseButton::Left => self.left = true,
|
||||
MouseButton::Right => self.right = true,
|
||||
MouseButton::Middle => self.middle = true,
|
||||
_ => {}
|
||||
},
|
||||
ElementState::Released => match button {
|
||||
MouseButton::Left => self.left = false,
|
||||
MouseButton::Right => self.right = false,
|
||||
MouseButton::Middle => self.middle = false,
|
||||
_ => {}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ClickTracker {
|
||||
left: Option<ClickRecord>,
|
||||
middle: Option<ClickRecord>,
|
||||
right: Option<ClickRecord>,
|
||||
}
|
||||
impl ClickTracker {
|
||||
fn input(&mut self, button: &MouseButton, state: &ElementState, position: MousePosition) -> ClickCount {
|
||||
let record = match button {
|
||||
MouseButton::Left => &mut self.left,
|
||||
MouseButton::Right => &mut self.right,
|
||||
MouseButton::Middle => &mut self.middle,
|
||||
_ => return ClickCount::Single,
|
||||
};
|
||||
|
||||
let Some(record) = record else {
|
||||
*record = Some(ClickRecord {
|
||||
down_position: position,
|
||||
up_position: position,
|
||||
..Default::default()
|
||||
});
|
||||
return ClickCount::Single;
|
||||
};
|
||||
|
||||
let now = Instant::now();
|
||||
let within_time = now.saturating_duration_since(record.time) <= MULTICLICK_TIMEOUT;
|
||||
|
||||
let (prev_count, prev_position) = match state {
|
||||
ElementState::Pressed => (record.down_count, record.down_position),
|
||||
ElementState::Released => (record.up_count, record.up_position),
|
||||
};
|
||||
|
||||
let dx = position.x.abs_diff(prev_position.x) as usize;
|
||||
let dy = position.y.abs_diff(prev_position.y) as usize;
|
||||
let within_dist = dx <= MULTICLICK_ALLOWED_TRAVEL && dy <= MULTICLICK_ALLOWED_TRAVEL;
|
||||
|
||||
let count = match (prev_count, within_time, within_dist) {
|
||||
(ClickCount::Single, true, true) => ClickCount::Double,
|
||||
(ClickCount::Double, true, true) => ClickCount::Triple,
|
||||
(ClickCount::Triple, true, true) => ClickCount::Double,
|
||||
_ => ClickCount::Single,
|
||||
};
|
||||
|
||||
record.time = now;
|
||||
|
||||
match state {
|
||||
ElementState::Pressed => {
|
||||
record.down_position = position;
|
||||
record.down_count = count;
|
||||
}
|
||||
ElementState::Released => {
|
||||
record.up_position = position;
|
||||
record.up_count = count;
|
||||
}
|
||||
}
|
||||
|
||||
count
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Default)]
|
||||
pub(crate) enum ClickCount {
|
||||
#[default]
|
||||
Single,
|
||||
Double,
|
||||
Triple,
|
||||
}
|
||||
impl From<ClickCount> for i32 {
|
||||
fn from(count: ClickCount) -> i32 {
|
||||
match count {
|
||||
ClickCount::Single => 1,
|
||||
ClickCount::Double => 2,
|
||||
ClickCount::Triple => 3,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct ClickRecord {
|
||||
time: Instant,
|
||||
down_position: MousePosition,
|
||||
up_position: MousePosition,
|
||||
down_count: ClickCount,
|
||||
up_count: ClickCount,
|
||||
}
|
||||
|
||||
impl Default for ClickRecord {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
time: Instant::now(),
|
||||
down_position: Default::default(),
|
||||
up_position: Default::default(),
|
||||
down_count: Default::default(),
|
||||
up_count: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct CefModifiers(cef_event_flags_t);
|
||||
impl CefModifiers {
|
||||
fn new(input_state: &InputState, location: &KeyLocation, is_repeat: bool) -> Self {
|
||||
let mut inner = cef_event_flags_t::EVENTFLAG_NONE;
|
||||
|
||||
if input_state.modifiers.shift_key() {
|
||||
inner |= cef_event_flags_t::EVENTFLAG_SHIFT_DOWN;
|
||||
}
|
||||
if input_state.modifiers.control_key() {
|
||||
inner |= cef_event_flags_t::EVENTFLAG_CONTROL_DOWN;
|
||||
}
|
||||
if input_state.modifiers.alt_key() {
|
||||
inner |= cef_event_flags_t::EVENTFLAG_ALT_DOWN;
|
||||
}
|
||||
if input_state.modifiers.meta_key() {
|
||||
inner |= cef_event_flags_t::EVENTFLAG_COMMAND_DOWN;
|
||||
}
|
||||
|
||||
if input_state.mouse_state.left {
|
||||
inner |= cef_event_flags_t::EVENTFLAG_LEFT_MOUSE_BUTTON;
|
||||
}
|
||||
if input_state.mouse_state.right {
|
||||
inner |= cef_event_flags_t::EVENTFLAG_RIGHT_MOUSE_BUTTON;
|
||||
}
|
||||
if input_state.mouse_state.middle {
|
||||
inner |= cef_event_flags_t::EVENTFLAG_MIDDLE_MOUSE_BUTTON;
|
||||
}
|
||||
|
||||
if is_repeat {
|
||||
inner |= cef_event_flags_t::EVENTFLAG_IS_REPEAT;
|
||||
}
|
||||
|
||||
inner |= match location {
|
||||
KeyLocation::Left => cef_event_flags_t::EVENTFLAG_IS_LEFT,
|
||||
KeyLocation::Right => cef_event_flags_t::EVENTFLAG_IS_RIGHT,
|
||||
KeyLocation::Numpad => cef_event_flags_t::EVENTFLAG_IS_KEY_PAD,
|
||||
KeyLocation::Standard => cef_event_flags_t::EVENTFLAG_NONE,
|
||||
};
|
||||
|
||||
Self(inner)
|
||||
}
|
||||
|
||||
pub(super) const PINCH_MODIFIERS: Self = Self(cef_event_flags_t(
|
||||
cef_event_flags_t::EVENTFLAG_CONTROL_DOWN.0 | cef_event_flags_t::EVENTFLAG_PRECISION_SCROLLING_DELTA.0,
|
||||
));
|
||||
}
|
||||
|
||||
impl From<CefModifiers> for u32 {
|
||||
fn from(val: CefModifiers) -> Self {
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
return val.0.0;
|
||||
#[cfg(target_os = "windows")]
|
||||
return val.0.0 as u32;
|
||||
}
|
||||
}
|
||||
+15
-5
@@ -22,9 +22,6 @@ mod resources;
|
||||
mod utility;
|
||||
mod view;
|
||||
|
||||
pub use consts::{MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT, PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
|
||||
pub use input::event::{InputEvent, InputEventBuilder, MouseButton, PointerInputEventBuilder, PointerPosition, UnknownPosition};
|
||||
|
||||
pub struct UiContext<S: Stage = Started> {
|
||||
inner: S::ContextData,
|
||||
}
|
||||
@@ -70,6 +67,7 @@ impl UiContext<Started> {
|
||||
Ok(UiInstance {
|
||||
inner: Arc::new(UiInstanceInner {
|
||||
host: self.inner.clone(),
|
||||
input: Mutex::new(input::InputState::default()),
|
||||
events: Mutex::new(events),
|
||||
queue,
|
||||
shutdown_complete: Mutex::new(shutdown_complete),
|
||||
@@ -143,6 +141,7 @@ pub struct UiInstance {
|
||||
|
||||
pub(crate) struct UiInstanceInner {
|
||||
host: Arc<HostHandle>,
|
||||
input: Mutex<input::InputState>,
|
||||
events: Mutex<Receiver<UiEvent>>,
|
||||
queue: events::EventQueue,
|
||||
shutdown_complete: Mutex<Receiver<()>>,
|
||||
@@ -153,7 +152,18 @@ impl UiInstance {
|
||||
pub fn send(&self, command: UiCommand) {
|
||||
let shared = &self.inner;
|
||||
match command {
|
||||
UiCommand::Input(event) => shared.host.send(HostControlMessage::Input(event)),
|
||||
UiCommand::Input(event) => {
|
||||
let events = {
|
||||
let Ok(mut input) = shared.input.lock() else {
|
||||
tracing::error!("Failed to lock the input state");
|
||||
return;
|
||||
};
|
||||
input::translate(&mut input, &event)
|
||||
};
|
||||
if !events.is_empty() {
|
||||
shared.host.send(HostControlMessage::Input(events));
|
||||
}
|
||||
}
|
||||
UiCommand::Resized { width, height } => shared.host.send(HostControlMessage::UpdateViewInfo(view::ViewInfoUpdate::Size { width, height })),
|
||||
UiCommand::ScaleChanged(scale) => shared.host.send(HostControlMessage::UpdateViewInfo(view::ViewInfoUpdate::Scale(scale))),
|
||||
UiCommand::Refresh => shared.host.send(HostControlMessage::RefreshViewInfo),
|
||||
@@ -210,7 +220,7 @@ impl Drop for UiInstanceInner {
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum UiCommand {
|
||||
Input(InputEvent),
|
||||
Input(winit::event::WindowEvent),
|
||||
Resized { width: u32, height: u32 },
|
||||
ScaleChanged(f64),
|
||||
Refresh,
|
||||
|
||||
@@ -99,7 +99,7 @@ enum ControlOutcome {
|
||||
fn control_loop(receiver: &IpcReceiver<HostControlMessage>, context: &CefContextHandle, sequence: &SequenceState) -> ControlOutcome {
|
||||
loop {
|
||||
match receiver.recv() {
|
||||
Ok(HostControlMessage::Input(event)) => context.process_input(event),
|
||||
Ok(HostControlMessage::Input(events)) => context.apply_input(events),
|
||||
Ok(HostControlMessage::UpdateViewInfo(update)) => context.update_view_info(update),
|
||||
Ok(HostControlMessage::RefreshViewInfo) => context.refresh_view_info(),
|
||||
Ok(HostControlMessage::SendWebMessage(message)) => context.send_web_message(message),
|
||||
|
||||
@@ -8,7 +8,7 @@ use crate::view::ViewInfoUpdate;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(crate) enum HostControlMessage {
|
||||
Input(InputEvent),
|
||||
Input(Vec<InputEvent>),
|
||||
UpdateViewInfo(ViewInfoUpdate),
|
||||
RefreshViewInfo,
|
||||
SendWebMessage(Vec<u8>),
|
||||
|
||||
@@ -1,18 +1,12 @@
|
||||
[package]
|
||||
name = "graphite-desktop-wrapper"
|
||||
version = "0.1.0"
|
||||
description = "Graphite Desktop Wrapper"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
|
||||
[features]
|
||||
gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
|
||||
|
||||
@@ -2,7 +2,7 @@ use graphite_editor::messages::clipboard::utility_types::ClipboardContentRaw;
|
||||
use graphite_editor::messages::prelude::*;
|
||||
|
||||
use super::DesktopWrapperMessageDispatcher;
|
||||
use super::messages::{DesktopFrontendMessage, DesktopWrapperMessage, EditorMessage, SaveFileDialogContext};
|
||||
use super::messages::{DesktopFrontendMessage, DesktopWrapperMessage, EditorMessage, OpenFileDialogContext, SaveFileDialogContext};
|
||||
|
||||
pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: DesktopWrapperMessage) {
|
||||
match message {
|
||||
@@ -15,14 +15,14 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
||||
DesktopWrapperMessage::Input(message) => {
|
||||
dispatcher.queue_editor_message(EditorMessage::InputPreprocessor(message));
|
||||
}
|
||||
DesktopWrapperMessage::IngestFile { path, content, action } => {
|
||||
dispatcher.queue_editor_message(IngestMessage::Ingest {
|
||||
data: content,
|
||||
action,
|
||||
mime_type: String::new(),
|
||||
path: Some(path),
|
||||
});
|
||||
}
|
||||
DesktopWrapperMessage::FileDialogResult { path, content, context } => match context {
|
||||
OpenFileDialogContext::Open => {
|
||||
dispatcher.queue_desktop_wrapper_message(DesktopWrapperMessage::OpenFile { path, content });
|
||||
}
|
||||
OpenFileDialogContext::Import => {
|
||||
dispatcher.queue_desktop_wrapper_message(DesktopWrapperMessage::ImportFile { path, content });
|
||||
}
|
||||
},
|
||||
DesktopWrapperMessage::SaveFileDialogResult { path, context } => match context {
|
||||
SaveFileDialogContext::Document { document_id, content } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::WriteFile { path: path.clone(), content });
|
||||
@@ -35,6 +35,14 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
||||
dispatcher.respond(DesktopFrontendMessage::WriteFile { path, content });
|
||||
}
|
||||
},
|
||||
DesktopWrapperMessage::OpenFile { path, content } => {
|
||||
let message = PortfolioMessage::OpenFile { path, content };
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
DesktopWrapperMessage::ImportFile { path, content } => {
|
||||
let message = PortfolioMessage::ImportFile { path, content };
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
DesktopWrapperMessage::PollNodeGraphEvaluation => dispatcher.poll_node_graph_evaluation(),
|
||||
DesktopWrapperMessage::UpdateMaximized { maximized } => {
|
||||
let message = FrontendMessage::UpdateMaximized { maximized };
|
||||
@@ -44,6 +52,10 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
||||
let message = FrontendMessage::UpdateFullscreen { fullscreen };
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
DesktopWrapperMessage::LoadDocumentContent { id, document } => {
|
||||
let message = PersistentStateMessage::LoadDocument { document_id: id, document };
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
DesktopWrapperMessage::LoadPersistedState { state } => {
|
||||
let message = PersistentStateMessage::LoadState { state };
|
||||
dispatcher.queue_editor_message(message);
|
||||
|
||||
@@ -3,23 +3,27 @@ use graphite_editor::messages::layout::utility_types::layout_widget::LayoutTarge
|
||||
use graphite_editor::messages::prelude::FrontendMessage;
|
||||
|
||||
use super::DesktopWrapperMessageDispatcher;
|
||||
use super::messages::{DesktopFrontendMessage, IngestAction, SaveFileDialogContext};
|
||||
use super::messages::{DesktopFrontendMessage, FileFilter, OpenFileDialogContext, SaveFileDialogContext};
|
||||
|
||||
pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: FrontendMessage) -> Option<FrontendMessage> {
|
||||
match message {
|
||||
FrontendMessage::RenderOverlays { context } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::UpdateOverlays(context.take_scene()));
|
||||
}
|
||||
FrontendMessage::TriggerBrowse { options, action } => {
|
||||
let title = match action {
|
||||
IngestAction::Open => "Open Document",
|
||||
IngestAction::Import => "Import File",
|
||||
_ => "Select File",
|
||||
};
|
||||
FrontendMessage::TriggerOpen => {
|
||||
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
|
||||
title: title.to_string(),
|
||||
options,
|
||||
action,
|
||||
title: "Open Document".to_string(),
|
||||
filters: vec![],
|
||||
multiple: true,
|
||||
context: OpenFileDialogContext::Open,
|
||||
});
|
||||
}
|
||||
FrontendMessage::TriggerImport => {
|
||||
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
|
||||
title: "Import File".to_string(),
|
||||
filters: vec![],
|
||||
multiple: false,
|
||||
context: OpenFileDialogContext::Import,
|
||||
});
|
||||
}
|
||||
FrontendMessage::TriggerSaveDocument {
|
||||
@@ -27,29 +31,32 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
name,
|
||||
path,
|
||||
folder,
|
||||
filters,
|
||||
content,
|
||||
} => {
|
||||
let content = content.into_vec();
|
||||
if let Some(path) = path {
|
||||
dispatcher.respond(DesktopFrontendMessage::WriteFile { path, content });
|
||||
} else {
|
||||
let extension = std::path::Path::new(&name).extension().and_then(|extension| extension.to_str()).unwrap_or("*").to_string();
|
||||
dispatcher.respond(DesktopFrontendMessage::SaveFileDialog {
|
||||
title: "Save Document".to_string(),
|
||||
default_filename: name,
|
||||
default_folder: folder,
|
||||
filters,
|
||||
filters: vec![FileFilter {
|
||||
name: "Graphite Document".to_string(),
|
||||
extensions: vec![extension],
|
||||
}],
|
||||
context: SaveFileDialogContext::Document { document_id, content },
|
||||
});
|
||||
}
|
||||
}
|
||||
FrontendMessage::TriggerSaveFile { name, folder, filters, content } => {
|
||||
FrontendMessage::TriggerSaveFile { name, folder, content } => {
|
||||
let content = content.into_vec();
|
||||
dispatcher.respond(DesktopFrontendMessage::SaveFileDialog {
|
||||
title: "Save File".to_string(),
|
||||
default_filename: name,
|
||||
default_folder: folder,
|
||||
filters,
|
||||
filters: Vec::new(),
|
||||
context: SaveFileDialogContext::File { content },
|
||||
});
|
||||
}
|
||||
@@ -69,6 +76,18 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
FrontendMessage::TriggerPersistenceWriteState { state } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteState { state });
|
||||
}
|
||||
FrontendMessage::TriggerPersistenceReadDocument { document_id } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PersistenceReadDocument { id: document_id });
|
||||
}
|
||||
FrontendMessage::TriggerPersistenceDeleteDocument { document_id } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PersistenceDeleteDocument { id: document_id });
|
||||
}
|
||||
FrontendMessage::TriggerPersistenceWriteDocument { document_id, document } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteDocument {
|
||||
id: document_id,
|
||||
document_serialized_content: document,
|
||||
});
|
||||
}
|
||||
FrontendMessage::TriggerOpenLaunchDocuments => {
|
||||
dispatcher.respond(DesktopFrontendMessage::OpenLaunchDocuments);
|
||||
}
|
||||
@@ -106,9 +125,6 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
FrontendMessage::WindowPointerLock => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PointerLock);
|
||||
}
|
||||
FrontendMessage::WindowUpdateDirectInput { enabled } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::WindowUpdateDirectInput { enabled });
|
||||
}
|
||||
FrontendMessage::WindowClose => {
|
||||
dispatcher.respond(DesktopFrontendMessage::WindowClose);
|
||||
}
|
||||
|
||||
@@ -10,8 +10,6 @@ use std::sync::Arc;
|
||||
|
||||
pub use graph_craft::application_io::resource::MmapResourceStorage;
|
||||
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
|
||||
pub use graphite_editor::document_store::{DocumentStore, FolderStore};
|
||||
pub use wgpu_executor::Texture;
|
||||
pub use wgpu_executor::WgpuBackends;
|
||||
pub use wgpu_executor::WgpuContext;
|
||||
pub use wgpu_executor::WgpuContextBuilder;
|
||||
@@ -33,7 +31,7 @@ pub struct 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")]
|
||||
let host = Host::Windows;
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -44,7 +42,7 @@ impl DesktopWrapper {
|
||||
let application_io = PlatformApplicationIo::new_with_context(wgpu_context);
|
||||
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,17 +52,21 @@ impl DesktopWrapper {
|
||||
executor.execute()
|
||||
}
|
||||
|
||||
pub fn set_completion_notifier(notifier: impl Fn() + Send + Sync + 'static) {
|
||||
graphite_editor::node_graph_executor::set_completion_notifier(Arc::new(notifier));
|
||||
}
|
||||
|
||||
pub async fn execute_node_graph() -> NodeGraphExecutionResult {
|
||||
let result = graphite_editor::node_graph_executor::run_node_graph().await;
|
||||
match result {
|
||||
(true, texture) => NodeGraphExecutionResult::HasRun(texture),
|
||||
(true, texture) => NodeGraphExecutionResult::HasRun(texture.map(Into::into)),
|
||||
(false, _) => NodeGraphExecutionResult::NotRun,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum NodeGraphExecutionResult {
|
||||
HasRun(Option<Texture>),
|
||||
HasRun(Option<std::sync::Arc<wgpu::Texture>>),
|
||||
NotRun,
|
||||
}
|
||||
|
||||
|
||||
@@ -44,10 +44,10 @@ impl<'a> DesktopWrapperMessageDispatcher<'a> {
|
||||
|
||||
pub(super) fn poll_node_graph_evaluation(&mut self) {
|
||||
let mut responses = VecDeque::new();
|
||||
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses)
|
||||
&& e != "No active document"
|
||||
{
|
||||
tracing::error!("Error polling node graph: {}", e);
|
||||
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses) {
|
||||
if e != "No active document" {
|
||||
tracing::error!("Error poling node graph: {}", e);
|
||||
}
|
||||
}
|
||||
while let Some(message) = responses.pop_front() {
|
||||
self.queue_editor_message(message);
|
||||
|
||||
@@ -3,10 +3,9 @@ use std::path::PathBuf;
|
||||
|
||||
pub(crate) use graphite_editor::messages::prelude::Message as EditorMessage;
|
||||
|
||||
pub use graphite_editor::messages::frontend::utility_types::{DocumentInfo, FileDialogOptions, FileFilter, PersistedState};
|
||||
pub use graphite_editor::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
|
||||
pub use graphite_editor::messages::input_mapper::utility_types::pointer::{EditorPointerState, MouseKeys, ScrollDelta};
|
||||
pub use graphite_editor::messages::portfolio::ingest::utility_types::IngestAction;
|
||||
pub use graphite_editor::messages::frontend::utility_types::{DocumentInfo, PersistedState};
|
||||
pub use graphite_editor::messages::input_mapper::utility_types::input_keyboard::{Key, ModifierKeys};
|
||||
pub use graphite_editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState as MouseState, EditorPosition as Position, MouseKeys};
|
||||
pub use graphite_editor::messages::prelude::DocumentId;
|
||||
pub use graphite_editor::messages::prelude::InputPreprocessorMessage as InputMessage;
|
||||
pub use graphite_editor::messages::prelude::PreferencesMessageHandler as Preferences;
|
||||
@@ -16,8 +15,9 @@ pub enum DesktopFrontendMessage {
|
||||
OpenLaunchDocuments,
|
||||
OpenFileDialog {
|
||||
title: String,
|
||||
options: FileDialogOptions,
|
||||
action: IngestAction,
|
||||
filters: Vec<FileFilter>,
|
||||
multiple: bool,
|
||||
context: OpenFileDialogContext,
|
||||
},
|
||||
SaveFileDialog {
|
||||
title: String,
|
||||
@@ -40,10 +40,14 @@ pub enum DesktopFrontendMessage {
|
||||
UpdateUIScale {
|
||||
scale: f64,
|
||||
},
|
||||
WindowUpdateDirectInput {
|
||||
enabled: bool,
|
||||
},
|
||||
UpdateOverlays(vello::Scene),
|
||||
PersistenceWriteDocument {
|
||||
id: DocumentId,
|
||||
document_serialized_content: String,
|
||||
},
|
||||
PersistenceDeleteDocument {
|
||||
id: DocumentId,
|
||||
},
|
||||
PersistenceWritePreferences {
|
||||
preferences: Preferences,
|
||||
},
|
||||
@@ -52,6 +56,9 @@ pub enum DesktopFrontendMessage {
|
||||
state: PersistedState,
|
||||
},
|
||||
PersistenceReadState,
|
||||
PersistenceReadDocument {
|
||||
id: DocumentId,
|
||||
},
|
||||
UpdateMenu {
|
||||
entries: Vec<MenuItem>,
|
||||
},
|
||||
@@ -77,11 +84,14 @@ pub enum DesktopWrapperMessage {
|
||||
FromWeb(Box<EditorMessage>),
|
||||
Wake,
|
||||
Input(InputMessage),
|
||||
IngestFile { path: PathBuf, content: Vec<u8>, action: IngestAction },
|
||||
FileDialogResult { path: PathBuf, content: Vec<u8>, context: OpenFileDialogContext },
|
||||
SaveFileDialogResult { path: PathBuf, context: SaveFileDialogContext },
|
||||
OpenFile { path: PathBuf, content: Vec<u8> },
|
||||
ImportFile { path: PathBuf, content: Vec<u8> },
|
||||
PollNodeGraphEvaluation,
|
||||
UpdateMaximized { maximized: bool },
|
||||
UpdateFullscreen { fullscreen: bool },
|
||||
LoadDocumentContent { id: DocumentId, document: String },
|
||||
LoadPersistedState { state: PersistedState },
|
||||
LoadPreferences { preferences: Preferences },
|
||||
MenuEvent { id: String },
|
||||
@@ -90,6 +100,17 @@ pub enum DesktopWrapperMessage {
|
||||
LoadThirdPartyLicenses { text: String },
|
||||
}
|
||||
|
||||
pub struct FileFilter {
|
||||
pub name: String,
|
||||
pub extensions: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum OpenFileDialogContext {
|
||||
Open,
|
||||
Import,
|
||||
}
|
||||
|
||||
pub enum SaveFileDialogContext {
|
||||
Document { document_id: DocumentId, content: Vec<u8> },
|
||||
File { content: Vec<u8> },
|
||||
|
||||
@@ -3,7 +3,7 @@ pub(crate) mod menu {
|
||||
use base64::engine::Engine;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64;
|
||||
|
||||
use graphite_editor::messages::input_mapper::utility_types::keyboard::{Key, LabeledKeyOrMouseMotion, LabeledShortcut};
|
||||
use graphite_editor::messages::input_mapper::utility_types::input_keyboard::{Key, LabeledKeyOrMouseMotion, LabeledShortcut};
|
||||
use graphite_editor::messages::input_mapper::utility_types::misc::ActionShortcut;
|
||||
use graphite_editor::messages::layout::LayoutMessage;
|
||||
use graphite_editor::messages::tool::tool_messages::tool_prelude::{Layout, LayoutGroup, LayoutTarget, MenuListEntry, Widget, WidgetId, WidgetRow};
|
||||
|
||||
@@ -1,18 +1,10 @@
|
||||
[package]
|
||||
name = "document-container"
|
||||
description = "Container abstraction for the on-disk side of the .gdd document format"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
@@ -40,7 +32,6 @@ web-sys = { workspace = true, features = [
|
||||
"FileSystemFileHandle",
|
||||
"FileSystemGetFileOptions",
|
||||
"FileSystemGetDirectoryOptions",
|
||||
"FileSystemRemoveOptions",
|
||||
"FileSystemHandle",
|
||||
"FileSystemHandleKind",
|
||||
"FileSystemWritableFileStream",
|
||||
|
||||
@@ -6,7 +6,6 @@ use std::fs::{self, OpenOptions};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct FolderBackend {
|
||||
root: PathBuf,
|
||||
}
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
use crate::{ByteHolder, Container, ContainerError, Result, validate_path, validate_prefix, with_trailing_slash};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::Mutex;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
#[derive(Default)]
|
||||
pub struct MemoryBackend {
|
||||
files: Arc<Mutex<HashMap<String, Vec<u8>>>>,
|
||||
files: Mutex<HashMap<String, Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl MemoryBackend {
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
use crate::{AsyncContainer, ByteHolder, ContainerError, Result, validate_path, validate_prefix, with_trailing_slash};
|
||||
use futures::channel::oneshot;
|
||||
use js_sys::Uint8Array;
|
||||
use std::cell::Cell;
|
||||
use std::collections::{HashSet, VecDeque};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use wasm_bindgen::JsCast;
|
||||
@@ -41,33 +40,6 @@ struct Inner {
|
||||
worker_active: bool,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static LAST_WRITE_FAILURE_ALERT: Cell<Option<f64>> = const { Cell::new(None) };
|
||||
}
|
||||
|
||||
fn report_write_error(operation: &str, path: &str, error: &JsValue) {
|
||||
if is_not_found(error) {
|
||||
log::warn!("OPFS {operation} on {path} dropped: the container no longer exists");
|
||||
return;
|
||||
}
|
||||
log::error!("OPFS {operation} failure on {path}:\n{error:?}");
|
||||
let now = js_sys::Date::now();
|
||||
// Debounce alerts to avoid spamming the user
|
||||
if LAST_WRITE_FAILURE_ALERT.get().is_some_and(|last| now - last < 60. * 1000.) {
|
||||
return;
|
||||
}
|
||||
LAST_WRITE_FAILURE_ALERT.set(Some(now));
|
||||
if let Some(window) = web_sys::window() {
|
||||
let message = format!(
|
||||
"Autosave is not working. Save your documents manually to avoid losing changes.\n\n\
|
||||
Please report it at https://github.com/GraphiteEditor/Graphite/issues/new and include this error:\n\n\
|
||||
{operation} {path}: {error:?}"
|
||||
);
|
||||
let _ = window.alert_with_message(&message);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct OpfsBackend {
|
||||
inner: Arc<Mutex<Inner>>,
|
||||
}
|
||||
@@ -105,6 +77,8 @@ impl OpfsBackend {
|
||||
guard.queue.push_back(Mutation::Barrier(sender));
|
||||
kick_worker(&self.inner, &mut guard);
|
||||
}
|
||||
// The sender is only dropped without sending if the worker is torn down mid-drain; either way
|
||||
// there is nothing left to wait for, so a receive error is treated as "already flushed".
|
||||
let _ = receiver.await;
|
||||
}
|
||||
}
|
||||
@@ -265,12 +239,12 @@ async fn drain_queue(inner: Arc<Mutex<Inner>>) {
|
||||
match mutation {
|
||||
Mutation::Write { path, bytes } => {
|
||||
if let Err(error) = write_file(&directory, &path, &bytes).await {
|
||||
report_write_error("write", &path, &error);
|
||||
log::error!("OPFS background write for {path} failed: {error:?}");
|
||||
}
|
||||
}
|
||||
Mutation::Append { path, bytes } => {
|
||||
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 } => {
|
||||
@@ -278,7 +252,7 @@ async fn drain_queue(inner: Arc<Mutex<Inner>>) {
|
||||
if let Err(error) = remove_file(&directory, &path).await
|
||||
&& !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.
|
||||
@@ -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
|
||||
/// segment. OPFS rejects directory names containing `/`, so a multi-segment path like
|
||||
/// `documents/<id>` must be descended one segment at a time rather than passed whole.
|
||||
async fn open_directory(directory_path: &str) -> std::result::Result<FileSystemDirectoryHandle, JsValue> {
|
||||
let 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()) {
|
||||
let options = FileSystemGetDirectoryOptions::new();
|
||||
@@ -304,37 +283,6 @@ async fn open_directory(directory_path: &str) -> std::result::Result<FileSystemD
|
||||
Ok(current)
|
||||
}
|
||||
|
||||
/// List the subdirectories directly under `directory_path`.
|
||||
pub async fn list_directories(directory_path: &str) -> Result<Vec<String>> {
|
||||
crate::validate_prefix(directory_path)?;
|
||||
let root = opfs_root().await.map_err(js_err)?;
|
||||
list_entries(&root, directory_path, EntryKind::Directory).await.map_err(|error| list_error(directory_path, error))
|
||||
}
|
||||
|
||||
/// Remove `directory_path` recursively.
|
||||
pub async fn remove_directory(directory_path: &str) -> Result<()> {
|
||||
validate_path(directory_path)?;
|
||||
let root = opfs_root().await.map_err(js_err)?;
|
||||
let removed = async {
|
||||
let (parent, name) = descend(&root, directory_path, false).await?;
|
||||
let options = web_sys::FileSystemRemoveOptions::new();
|
||||
options.set_recursive(true);
|
||||
JsFuture::from(parent.remove_entry_with_options(name, &options)).await
|
||||
}
|
||||
.await;
|
||||
|
||||
match removed {
|
||||
Ok(_) => Ok(()),
|
||||
Err(error) if is_not_found(&error) => Ok(()),
|
||||
Err(error) => Err(js_err(error)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn opfs_root() -> std::result::Result<FileSystemDirectoryHandle, JsValue> {
|
||||
let storage = web_sys::window().ok_or_else(|| JsValue::from_str("no window"))?.navigator().storage();
|
||||
JsFuture::from(storage.get_directory()).await?.dyn_into()
|
||||
}
|
||||
|
||||
/// Descend the `/`-separated path against `root` and return the directory handle plus the final segment.
|
||||
async fn descend<'a>(root: &FileSystemDirectoryHandle, relative: &'a str, create_dirs: bool) -> std::result::Result<(FileSystemDirectoryHandle, &'a str), JsValue> {
|
||||
let mut current = root.clone();
|
||||
@@ -525,7 +473,3 @@ fn list_error(prefix: &str, error: JsValue) -> ContainerError {
|
||||
js_err(error)
|
||||
}
|
||||
}
|
||||
|
||||
fn js_err(error: JsValue) -> ContainerError {
|
||||
ContainerError::Backend(format!("{error:?}"))
|
||||
}
|
||||
@@ -12,7 +12,6 @@
|
||||
|
||||
pub mod archive;
|
||||
pub mod backends;
|
||||
pub mod store;
|
||||
|
||||
pub enum ByteHolder {
|
||||
/// 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.
|
||||
/// `AnyContainer` is the workaround: `Gdd` holds one of these by value, and the `AsyncContainer`
|
||||
/// impl forwards to the active variant.
|
||||
#[derive(Clone)]
|
||||
pub enum AnyContainer {
|
||||
Memory(backends::memory::MemoryBackend),
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
|
||||
@@ -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();
|
||||
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"));
|
||||
}
|
||||
@@ -1,18 +1,10 @@
|
||||
[package]
|
||||
name = "document-format"
|
||||
description = "Typed handle for the .gdd document format, sitting over document-graph-storage and document-container"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
# Runtime bridge: the editor <-> storage conversion methods (stage/commit from a `NodeNetwork`,
|
||||
@@ -33,7 +25,7 @@ graphene-resource = { workspace = true }
|
||||
core-types = { workspace = true, optional = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
postcard = { workspace = true }
|
||||
rmp-serde = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
thiserror = "2.0"
|
||||
log = { workspace = true }
|
||||
|
||||
@@ -8,16 +8,18 @@ pub enum Codec {
|
||||
Json,
|
||||
/// Newline-delimited compact JSON, one value per line.
|
||||
JsonLines,
|
||||
/// A single postcard blob. `append` to a non-empty buffer errors.
|
||||
Postcard,
|
||||
/// Length-prefixed postcard frames: `[u32 big-endian length][postcard bytes]` per value.
|
||||
PostcardFrames,
|
||||
/// A single MessagePack blob. `append` to a non-empty buffer errors.
|
||||
MessagePack,
|
||||
/// Length-prefixed MessagePack frames: `[u32 big-endian length][MessagePack bytes]` per value.
|
||||
MessagePackFrames,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum CodecError {
|
||||
#[error("postcard error: {0}")]
|
||||
Postcard(#[from] postcard::Error),
|
||||
#[error("MessagePack encode error: {0}")]
|
||||
MessagePackEncode(#[from] rmp_serde::encode::Error),
|
||||
#[error("MessagePack decode error: {0}")]
|
||||
MessagePackDecode(#[from] rmp_serde::decode::Error),
|
||||
#[error("JSON error: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
#[error("frame length {0} exceeds u32")]
|
||||
@@ -39,8 +41,8 @@ impl Codec {
|
||||
match self {
|
||||
Codec::Json => "json",
|
||||
Codec::JsonLines => "jsonl",
|
||||
Codec::Postcard => "bin",
|
||||
Codec::PostcardFrames => "frames",
|
||||
Codec::MessagePack => "bin",
|
||||
Codec::MessagePackFrames => "frames",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,15 +62,15 @@ impl Codec {
|
||||
output.push(b'\n');
|
||||
Ok(())
|
||||
}
|
||||
Codec::Postcard => {
|
||||
Codec::MessagePack => {
|
||||
if !output.is_empty() {
|
||||
return Err(CodecError::SingleValueAlreadyWritten);
|
||||
}
|
||||
postcard::to_io(value, &mut *output)?;
|
||||
rmp_serde::encode::write(output, value)?;
|
||||
Ok(())
|
||||
}
|
||||
Codec::PostcardFrames => {
|
||||
let payload = postcard::to_stdvec(value)?;
|
||||
Codec::MessagePackFrames => {
|
||||
let payload = rmp_serde::to_vec(value)?;
|
||||
let length = u32::try_from(payload.len()).map_err(|_| CodecError::FrameTooLarge(payload.len()))?;
|
||||
output.extend_from_slice(&length.to_be_bytes());
|
||||
output.extend_from_slice(&payload);
|
||||
@@ -89,11 +91,11 @@ impl Codec {
|
||||
remaining: bytes,
|
||||
_marker: std::marker::PhantomData,
|
||||
}),
|
||||
Codec::Postcard => {
|
||||
let single = postcard::from_bytes::<T>(bytes).map_err(CodecError::from);
|
||||
Codec::MessagePack => {
|
||||
let single = rmp_serde::from_slice::<T>(bytes).map_err(CodecError::from);
|
||||
Box::new(std::iter::once(single))
|
||||
}
|
||||
Codec::PostcardFrames => Box::new(PostcardFrameIter {
|
||||
Codec::MessagePackFrames => Box::new(MessagePackFrameIter {
|
||||
remaining: bytes,
|
||||
_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],
|
||||
_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>;
|
||||
|
||||
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);
|
||||
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]
|
||||
fn postcard_round_trip_single() {
|
||||
fn message_pack_round_trip_single() {
|
||||
let frame = Frame { id: 99, label: "blob".into() };
|
||||
let bytes = Codec::Postcard.write_single(&frame).unwrap();
|
||||
let decoded: Frame = Codec::Postcard.read_single(&bytes).unwrap();
|
||||
let bytes = Codec::MessagePack.write_single(&frame).unwrap();
|
||||
let decoded: Frame = Codec::MessagePack.read_single(&bytes).unwrap();
|
||||
assert_eq!(decoded, frame);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postcard_append_to_non_empty_errors() {
|
||||
fn message_pack_append_to_non_empty_errors() {
|
||||
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:?}");
|
||||
}
|
||||
|
||||
/// A type-erased `serde_json::Value` round-trips through the binary codec: the property postcard
|
||||
/// could not satisfy (it raises `WontImplement` on self-describing values), which is why the
|
||||
/// resource/attribute deltas that carry `serde_json::Value` bodies need a self-describing codec.
|
||||
#[test]
|
||||
fn message_pack_round_trips_serde_json_value() {
|
||||
let value = serde_json::json!({ "kind": "embedded", "priority": 1.5, "tags": ["a", "b"] });
|
||||
let bytes = Codec::MessagePack.write_single(&value).unwrap();
|
||||
let decoded: serde_json::Value = Codec::MessagePack.read_single(&bytes).unwrap();
|
||||
assert_eq!(decoded, value);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_lines_round_trip_and_skip_blanks() {
|
||||
let frames = [Frame { id: 1, label: "alpha".into() }, Frame { id: 2, label: "beta".into() }];
|
||||
@@ -250,13 +263,13 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postcard_frames_round_trip() {
|
||||
fn message_pack_frames_round_trip() {
|
||||
let frames = frames();
|
||||
let mut buffer = Vec::new();
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -264,27 +277,27 @@ mod tests {
|
||||
/// deterministically (declared length exceeds the bytes that actually made it to disk) rather
|
||||
/// than decoding a partial value into a plausible-but-wrong one.
|
||||
#[test]
|
||||
fn postcard_frames_detect_truncation() {
|
||||
fn message_pack_frames_detect_truncation() {
|
||||
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);
|
||||
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:?}");
|
||||
}
|
||||
|
||||
/// A buffer whose first record's length prefix itself is incomplete (fewer than 4 bytes) is
|
||||
/// reported as a truncated prefix rather than mis-read as a zero-length frame.
|
||||
#[test]
|
||||
fn postcard_frames_detect_truncated_length_prefix() {
|
||||
fn message_pack_frames_detect_truncated_length_prefix() {
|
||||
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:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_single_then_read_with_iter_yields_one() {
|
||||
let frame = Frame { id: 5, label: "one".into() };
|
||||
for codec in [Codec::Json, Codec::JsonLines, Codec::Postcard, Codec::PostcardFrames] {
|
||||
for codec in [Codec::Json, Codec::JsonLines, Codec::MessagePack, Codec::MessagePackFrames] {
|
||||
let bytes = codec.write_single(&frame).unwrap();
|
||||
let collected: Vec<Frame> = codec.iter(&bytes).collect::<Result<_, _>>().unwrap();
|
||||
assert_eq!(collected, vec![Frame { id: 5, label: "one".into() }], "codec {codec:?}");
|
||||
@@ -302,7 +315,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
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();
|
||||
assert_eq!(unique.len(), exts.len(), "extensions collide: {exts:?}");
|
||||
}
|
||||
|
||||
@@ -35,9 +35,6 @@ pub enum Error {
|
||||
#[cfg(feature = "conversion")]
|
||||
#[error("commit error: {0}")]
|
||||
Commit(#[from] CommitError),
|
||||
/// The container has no manifest, cannot be opened.
|
||||
#[error("container has no manifest")]
|
||||
MissingManifest,
|
||||
/// The manifest's `format` field is not the `.gdd` magic, so this is not a `.gdd` document.
|
||||
#[error("not a .gdd document (manifest format = {found:?}, expected {expected:?})")]
|
||||
WrongFormat { found: String, expected: &'static str },
|
||||
|
||||
@@ -146,14 +146,10 @@ impl<L: Layout> Gdd<L> {
|
||||
// Carry the per-peer cursor + view settings so a `.gdd` reopened elsewhere restores the viewport.
|
||||
let session_state = SessionState {
|
||||
peer_id: self.session.peer(),
|
||||
user_id: self.session.user(),
|
||||
head_rev: self.session.head_rev(),
|
||||
last_broadcast_rev: self.session.last_broadcast_rev(),
|
||||
redo_stack: self.session.redo_stack().to_vec(),
|
||||
next_node_counter: self.session.next_node_counter(),
|
||||
last_hot_sequence: self.session.last_hot_sequence(),
|
||||
settled: self.session.settled_marks().clone(),
|
||||
clock: self.session.clock_counter(),
|
||||
view_settings: self.view_settings.clone(),
|
||||
network_view_settings: self.network_view_settings.clone(),
|
||||
};
|
||||
|
||||
+59
-49
@@ -6,6 +6,7 @@
|
||||
//!
|
||||
//! See the "On-disk container" section of `node-graph/rfcs/document-format.md` for the format spec.
|
||||
|
||||
use std::sync::Arc;
|
||||
// `Path` and `FolderBackend` are only used by the native-only path-based open/create, so they're
|
||||
// gated off wasm to avoid unused-import warnings.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
@@ -13,10 +14,10 @@ use std::path::Path;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
use document_container::backends::folder::FolderBackend;
|
||||
use document_container::{AnyContainer, AsyncContainer, ByteHolder};
|
||||
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
|
||||
#[cfg(feature = "conversion")]
|
||||
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")]
|
||||
use graphene_resource::LoadResource;
|
||||
use graphene_resource::ResourceHash;
|
||||
@@ -48,28 +49,30 @@ pub type GddV1 = Gdd<GddV1Layout>;
|
||||
pub const MANIFEST_CODEC: Codec = Codec::Json;
|
||||
|
||||
/// Working-copy codecs. The working copy lives in appdata, not under VCS — these defaults
|
||||
/// optimize for size and write cost. JSON/JSONL is opt-in via `ExportFormat::Folder` for users who
|
||||
/// want a diffable on-disk representation. Recorded in the manifest at create time and read back on
|
||||
/// open (see [`manifest::PayloadCodecs`]), so the persist path never probes the filesystem.
|
||||
/// optimize for size and write cost. MessagePack is self-describing, so it round-trips the
|
||||
/// type-erased `serde_json::Value` bodies that resource and attribute deltas carry (a non-self-
|
||||
/// describing format like postcard cannot). JSON/JSONL is opt-in via `ExportFormat::Folder` for
|
||||
/// users who want a diffable on-disk representation. Recorded in the manifest at create time and
|
||||
/// read back on open (see [`manifest::PayloadCodecs`]), so the persist path never probes the filesystem.
|
||||
pub const DEFAULT_SESSION_CODEC: Codec = Codec::Json;
|
||||
pub const DEFAULT_REGISTRY_CODEC: Codec = Codec::Postcard;
|
||||
pub const DEFAULT_HISTORY_CODEC: Codec = Codec::PostcardFrames;
|
||||
pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::PostcardFrames;
|
||||
pub const DEFAULT_REGISTRY_CODEC: Codec = Codec::MessagePack;
|
||||
pub const DEFAULT_HISTORY_CODEC: Codec = Codec::MessagePackFrames;
|
||||
pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::MessagePackFrames;
|
||||
|
||||
/// Editor-facing handle. Owns the `Session` and the working-copy container; mutations are mirrored
|
||||
/// to disk continuously (every retirement appends to the history file and re-snapshots the registry).
|
||||
///
|
||||
/// The per-edit persist path (`commit_from_runtime`, `apply_hot_op`, `retire`) is synchronous and
|
||||
/// read-free: the manifest is cached in memory (so payload codecs need no disk read), and writes go
|
||||
/// through the container's sync write surface. Only `open` / `export` are async, since they
|
||||
/// through the container's sync write surface. Only `open` / `create` / `export` are async, since they
|
||||
/// 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
|
||||
/// `Session` is cloned (a snapshot copy); the container is shared.
|
||||
#[derive(Clone)]
|
||||
pub struct Gdd<L: Layout = GddV1Layout> {
|
||||
pub(crate) session: Session,
|
||||
pub(crate) working: AnyContainer,
|
||||
pub(crate) working: Arc<AnyContainer>,
|
||||
pub(crate) layout: L,
|
||||
/// In-memory copy of the manifest, kept authoritative since `Gdd` is its sole writer. Holds the
|
||||
/// per-payload codecs so the persist path never probes the filesystem, keeping it fully read-free
|
||||
@@ -77,10 +80,10 @@ pub struct Gdd<L: Layout = GddV1Layout> {
|
||||
pub(crate) manifest: Manifest,
|
||||
/// Per-peer view settings (PTZ, rulers, etc.), persisted in `session.json` not the registry, so
|
||||
/// they stay out of the CRDT/history. Opaque to the storage layer; the editor owns the keys/values.
|
||||
pub(crate) view_settings: std::collections::BTreeMap<String, 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
|
||||
/// `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
|
||||
@@ -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
|
||||
/// 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 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`].
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::MissingManifest`] if the container holds no manifest, [`Error::WrongFormat`] / [`Error::UnsupportedVersion`]
|
||||
/// if it fails validation, plus the usual [`Error::Read`] / [`Error::Codec`] / [`Error::Crdt`] if a payload is malformed.
|
||||
/// [`Error::WrongFormat`] / [`Error::UnsupportedVersion`] if the manifest fails validation, plus
|
||||
/// the usual [`Error::Read`] / [`Error::Codec`] / [`Error::Crdt`] if a payload is malformed.
|
||||
pub async fn open_in(working: AnyContainer, layout: L) -> Result<Self, Error> {
|
||||
let manifest: Manifest = match io::read_single(&working, layout.manifest_basename(), MANIFEST_CODEC).await {
|
||||
Ok(manifest) => manifest,
|
||||
Err(io::ReadError::NotFound { .. }) => return Err(Error::MissingManifest),
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
let manifest: Manifest = io::read_single(&working, layout.manifest_basename(), MANIFEST_CODEC).await?;
|
||||
validate_manifest(&manifest)?;
|
||||
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 peer = session_state.peer_id;
|
||||
let user = session_state.user_id;
|
||||
let mut session = match (has_registry, has_history) {
|
||||
(true, true) => {
|
||||
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
|
||||
let history = load_history(&working, &layout, codecs.history).await?;
|
||||
Session::load(peer, 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) => {
|
||||
// Registry-only export: synthesize a history that reproduces this state.
|
||||
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
|
||||
Session::bootstrap_from_registry(peer, 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.
|
||||
@@ -161,15 +159,11 @@ impl<L: Layout> Gdd<L> {
|
||||
session.publish_up_to(rev);
|
||||
}
|
||||
|
||||
session.restore_hot_sequence(session_state.last_hot_sequence);
|
||||
session.restore_clock(session_state.clock);
|
||||
// Before the hot log replays, so a settled op in it is dropped rather than staged again.
|
||||
session.absorb_settled_marks(&session_state.settled);
|
||||
replay_hot_log(&working, &layout, codecs.hot_log, &mut session).await?;
|
||||
|
||||
Ok(Self {
|
||||
session,
|
||||
working,
|
||||
working: Arc::new(working),
|
||||
layout,
|
||||
manifest,
|
||||
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
|
||||
/// 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 codecs = manifest.codecs;
|
||||
io::write_single(&working, layout.manifest_basename(), MANIFEST_CODEC, &manifest)?;
|
||||
let session_state = SessionState {
|
||||
peer_id: peer,
|
||||
user_id: UserId(peer.0),
|
||||
..Default::default()
|
||||
};
|
||||
let session_state = SessionState { peer_id: peer, ..Default::default() };
|
||||
io::write_single(&working, layout.session_basename(), codecs.session, &session_state)?;
|
||||
|
||||
let session = Session::with_peer(peer);
|
||||
@@ -195,7 +185,7 @@ impl<L: Layout> Gdd<L> {
|
||||
|
||||
Ok(Self {
|
||||
session,
|
||||
working,
|
||||
working: Arc::new(working),
|
||||
layout,
|
||||
manifest,
|
||||
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).
|
||||
/// 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
|
||||
}
|
||||
|
||||
/// The per-network view settings read from `session.json` (node-graph nav + previewing), keyed by
|
||||
/// [`NetworkId`](document_graph_storage::NetworkId). Opaque `ui::nav::*` / `ui::previewing` blobs the editor decodes.
|
||||
pub fn network_view_settings(&self) -> &std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, 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
|
||||
}
|
||||
|
||||
@@ -295,20 +285,31 @@ impl<L: Layout> Gdd<L> {
|
||||
}
|
||||
|
||||
/// Drop the session and return the working-copy container + layout.
|
||||
/// Intended for test code that needs to reopen against the same container; panics if the container
|
||||
/// is still shared by a `Gdd` clone (tests don't clone before calling this).
|
||||
pub fn into_storage(self) -> (AnyContainer, L) {
|
||||
(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
|
||||
/// [`document_graph_storage::Declarations`] map, loading each `ProtoNode`'s bytes from `byte_store`
|
||||
/// (the global cache in the editor, the working-copy container for standalone). Covers history so
|
||||
/// the map can serve any undo/redo target. Cold-path (mount / open); async because resource loads are.
|
||||
/// Resolve the proto-node declarations referenced by the registry into a [`document_graph_storage::Declarations`]
|
||||
/// map, loading each `ProtoNode`'s bytes from `byte_store` (the global cache in the editor, the
|
||||
/// working-copy container for standalone). Only resources referenced by `Implementation::ProtoNode`
|
||||
/// are visited, so image/font resources are skipped. Cold-path (open / `to_runtime`); async
|
||||
/// because resource loads are.
|
||||
#[cfg(feature = "conversion")]
|
||||
pub async fn declarations(&self, byte_store: &dyn LoadResource) -> document_graph_storage::Declarations {
|
||||
use document_graph_storage::Implementation;
|
||||
|
||||
let registry = self.session.registry();
|
||||
let mut declarations = document_graph_storage::Declarations::new();
|
||||
|
||||
for (id, hash) in self.session.all_declaration_resources() {
|
||||
let Some(hash) = hash else {
|
||||
for node in registry.node_instances.values() {
|
||||
let Implementation::ProtoNode(id) = node.implementation() else { continue };
|
||||
if declarations.contains_key(id) {
|
||||
continue;
|
||||
}
|
||||
let Some(hash) = registry.resources.get(id).and_then(|entry| entry.hash) else {
|
||||
log::error!("Declaration resource {id} has no resolved hash; cannot load ProtoNode");
|
||||
continue;
|
||||
};
|
||||
@@ -318,7 +319,7 @@ impl<L: Layout> Gdd<L> {
|
||||
};
|
||||
match document_graph_storage::decode_declaration(resource.as_ref()) {
|
||||
Ok(proto) => {
|
||||
declarations.insert(id, proto);
|
||||
declarations.insert(*id, proto);
|
||||
}
|
||||
Err(error) => log::error!("Failed to deserialize ProtoNode for {id}: {error}"),
|
||||
}
|
||||
@@ -327,7 +328,16 @@ impl<L: Layout> Gdd<L> {
|
||||
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> {
|
||||
self.working.read(self.layout.legacy_path()).await.ok()
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
use document_container::AsyncContainer;
|
||||
#[cfg(feature = "conversion")]
|
||||
use document_graph_storage::NodeMetadataSource;
|
||||
use document_graph_storage::{HotOp, Rev, TimeStamp, Value};
|
||||
use document_graph_storage::{HotOp, Rev, TimeStamp};
|
||||
#[cfg(feature = "conversion")]
|
||||
use graphene_resource::ResourceStorage;
|
||||
|
||||
@@ -47,7 +47,7 @@ impl<L: Layout> Gdd<L> {
|
||||
/// declaration bytes. The working registry reflects the edit immediately, but nothing enters durable
|
||||
/// retired history until [`retire_pending_interaction`](Self::retire_pending_interaction). Staging on
|
||||
/// every edit while retiring only at interaction boundaries lets several edits coalesce into one retired
|
||||
/// interaction. Returns the decoded declarations the snapshot references, for the caller's cache.
|
||||
/// interaction.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::Commit`] if the runtime diff is rejected by the session. On an [`Error::Container`] /
|
||||
@@ -60,8 +60,8 @@ impl<L: Layout> Gdd<L> {
|
||||
metadata: &M,
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
byte_store: &dyn ResourceStorage,
|
||||
) -> Result<document_graph_storage::Declarations, Error> {
|
||||
let (hot_ops, conversion) = self.session.stage_from_runtime(network, metadata, resources)?;
|
||||
) -> Result<(), Error> {
|
||||
let (hot_ops, declaration_bytes) = self.session.stage_from_runtime(network, metadata, resources)?;
|
||||
|
||||
for hot_op in &hot_ops {
|
||||
self.append_hot_frame(hot_op)?;
|
||||
@@ -70,29 +70,6 @@ impl<L: Layout> Gdd<L> {
|
||||
// Persist proto-node declaration content to the byte store (the global cache in the editor,
|
||||
// the working-copy container for standalone export). Content-addressed, so re-storing
|
||||
// identical bytes on every commit is an idempotent no-op.
|
||||
for bytes in conversion.declaration_bytes.values() {
|
||||
byte_store.store(bytes);
|
||||
}
|
||||
Ok(conversion.declarations)
|
||||
}
|
||||
|
||||
/// Stage ops the caller built from what the editor recorded, rather than deriving them by converting
|
||||
/// the whole document and diffing it against the working registry.
|
||||
///
|
||||
/// Otherwise identical to [`stage_runtime_snapshot`](Self::stage_runtime_snapshot): each op becomes a
|
||||
/// hot frame, and the proto-node declaration bytes go to the byte store.
|
||||
#[cfg(feature = "conversion")]
|
||||
pub fn stage_constructed_ops(
|
||||
&mut self,
|
||||
ops: Vec<document_graph_storage::RegistryDelta>,
|
||||
declaration_bytes: &document_graph_storage::from_runtime::DeclarationBytes,
|
||||
byte_store: &dyn ResourceStorage,
|
||||
) -> Result<(), Error> {
|
||||
let hot_ops = self.session.stage_computed_ops(ops)?;
|
||||
|
||||
for hot_op in &hot_ops {
|
||||
self.append_hot_frame(hot_op)?;
|
||||
}
|
||||
for bytes in declaration_bytes.values() {
|
||||
byte_store.store(bytes);
|
||||
}
|
||||
@@ -173,7 +150,7 @@ impl<L: Layout> Gdd<L> {
|
||||
/// Unlike the per-interaction marker written inline at retire, this targets an already-written delta, so
|
||||
/// the whole history file is rewritten in topological order. O(history) — fine for occasional user
|
||||
/// labeling, not for per-interaction marking (which uses the inline path). No-op if `rev` is unknown.
|
||||
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: 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) {
|
||||
self.rewrite_history()?;
|
||||
}
|
||||
@@ -194,14 +171,10 @@ impl<L: Layout> Gdd<L> {
|
||||
fn persist_session_state(&mut self) -> Result<(), Error> {
|
||||
let state = SessionState {
|
||||
peer_id: self.session.peer(),
|
||||
user_id: self.session.user(),
|
||||
head_rev: self.session.head_rev(),
|
||||
last_broadcast_rev: self.session.last_broadcast_rev(),
|
||||
redo_stack: self.session.redo_stack().to_vec(),
|
||||
next_node_counter: self.session.next_node_counter(),
|
||||
last_hot_sequence: self.session.last_hot_sequence(),
|
||||
settled: self.session.settled_marks().clone(),
|
||||
clock: self.session.clock_counter(),
|
||||
view_settings: self.view_settings.clone(),
|
||||
network_view_settings: self.network_view_settings.clone(),
|
||||
};
|
||||
@@ -209,16 +182,18 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Re-snapshot the retired registry to `registry.bin`. `Session::load` trusts it to match the persisted `head`
|
||||
/// and replays the hot log on top, so it must hold no hot op, and any cursor move must re-persist it.
|
||||
/// Re-snapshot the materialized working registry to `registry.bin`. `Session::load` trusts the stored
|
||||
/// registry to match the persisted `head`, so any cursor move (undo/redo) that rewinds the working
|
||||
/// registry without retiring must re-persist it or a reopen would read a registry inconsistent with
|
||||
/// `head`. Synchronous and hot-path-safe (`write_non_blocking`).
|
||||
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(())
|
||||
}
|
||||
|
||||
/// Replace the per-peer view settings and persist them to `session.json`. Called by the editor when
|
||||
/// the viewport or a document-level toggle changes; never enters the registry, history, or CRDT.
|
||||
pub fn set_view_settings(&mut self, view_settings: std::collections::BTreeMap<String, 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.persist_session_state()
|
||||
}
|
||||
@@ -234,7 +209,7 @@ impl<L: Layout> Gdd<L> {
|
||||
/// enters the registry, history, or CRDT.
|
||||
pub fn set_network_view_settings(
|
||||
&mut self,
|
||||
network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, document_graph_storage::Value>>,
|
||||
network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>>,
|
||||
) -> Result<(), Error> {
|
||||
self.network_view_settings = network_view_settings;
|
||||
self.persist_session_state()
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
|
||||
use graphene_resource::ResourceFuture;
|
||||
@@ -38,7 +39,7 @@ impl<L: Layout> Gdd<L> {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub fn add_resource_from_path(&mut self, id: document_graph_storage::ResourceId, hash: ResourceHash, src: &Path) -> Result<(), Error> {
|
||||
let dest_path = self.layout.resource_path(&hash);
|
||||
if let AnyContainer::Folder(folder) = &self.working {
|
||||
if let AnyContainer::Folder(folder) = self.working.as_ref() {
|
||||
let full = folder.root().join(&dest_path);
|
||||
if let Some(parent) = full.parent() {
|
||||
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> {
|
||||
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//!
|
||||
//! Lives in `session.json`. Rewritten on retirement.
|
||||
|
||||
use document_graph_storage::{HotSequence, NetworkId, PeerId, Rev, SettledHotOps, UserId, Value};
|
||||
use document_graph_storage::{NetworkId, PeerId, Rev};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
@@ -15,17 +15,13 @@ pub struct SessionState {
|
||||
/// tiebreaking and minting peer-scoped IDs.
|
||||
#[serde(default)]
|
||||
pub peer_id: PeerId,
|
||||
/// The person using this device, which the peer registers as, so authorship and undo follow the person
|
||||
/// across the peer ids they accumulate.
|
||||
#[serde(default)]
|
||||
pub user_id: UserId,
|
||||
/// Local-chain cursor. Points at the most recently applied retired delta, or `None` on an empty
|
||||
/// document (no commits yet).
|
||||
#[serde(default)]
|
||||
pub head_rev: Option<Rev>,
|
||||
/// Published frontier: the latest retired commit broadcast to a peer. Commits after it are silently
|
||||
/// rewritable on undo; commits at or before it are published. `None` until broadcast transport lands.
|
||||
#[serde(default)]
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub last_broadcast_rev: Option<Rev>,
|
||||
/// Revs the user has undone past, so redo survives a reopen. (The legacy `VecDeque` redo history
|
||||
/// is not persisted, so within the shadow phase this is strictly more capable than the live editor.)
|
||||
@@ -35,24 +31,12 @@ pub struct SessionState {
|
||||
/// collide on minted IDs.
|
||||
#[serde(default)]
|
||||
pub next_node_counter: u64,
|
||||
/// The sequence of the last hot op this peer authored, feeding [`document_graph_storage::HotOp::sequence`], so a
|
||||
/// reopen never reuses a spent sequence.
|
||||
#[serde(default)]
|
||||
pub last_hot_sequence: HotSequence,
|
||||
/// Per-peer view settings (PTZ, rulers, overlays, snapping, panel collapse). Local to the viewer,
|
||||
/// so kept out of the CRDT/history. Editor owns the keys/values (opaque `ui::doc::*` blobs).
|
||||
#[serde(default)]
|
||||
pub view_settings: BTreeMap<String, Value>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub view_settings: BTreeMap<String, serde_json::Value>,
|
||||
/// Per-network view settings (node-graph nav + previewing), keyed by the stable storage [`NetworkId`].
|
||||
/// Per-peer like [`view_settings`](Self::view_settings); opaque `ui::nav::*` / `ui::previewing` blobs.
|
||||
#[serde(default)]
|
||||
pub network_view_settings: BTreeMap<NetworkId, BTreeMap<String, Value>>,
|
||||
/// Which hot ops are retired, so a late copy a peer re-sends after a reopen is dropped rather than retired a second
|
||||
/// time. About one sequence per author; runs only for ops in flight when saved.
|
||||
#[serde(default)]
|
||||
pub settled: SettledHotOps,
|
||||
/// The Lamport counter, so a reopen never mints a stamp already spent, even one no op in history or the hot log
|
||||
/// carries any more.
|
||||
#[serde(default)]
|
||||
pub clock: u64,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub network_view_settings: BTreeMap<NetworkId, BTreeMap<String, serde_json::Value>>,
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{Codec, Error, GddV1, GddV1Layout, Layout, Manifest, io, manifest};
|
||||
use document_graph_storage::{HotOp, HotSequence, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
|
||||
use document_graph_storage::{HotOp, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
|
||||
|
||||
fn empty_container() -> AnyContainer {
|
||||
AnyContainer::Memory(MemoryBackend::new())
|
||||
@@ -44,7 +44,7 @@ fn create_in_round_trips_empty_document() {
|
||||
futures::executor::block_on(async {
|
||||
let container = empty_container();
|
||||
|
||||
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()) {
|
||||
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()).await {
|
||||
Ok(gdd) => gdd,
|
||||
Err(error) => panic!("create_in failed: {error:?}"),
|
||||
};
|
||||
@@ -82,7 +82,9 @@ fn open_in_rejects_wrong_format_magic() {
|
||||
#[test]
|
||||
fn manifest_returns_what_create_in_wrote() {
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into()).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));
|
||||
|
||||
@@ -97,7 +99,9 @@ fn manifest_returns_what_create_in_wrote() {
|
||||
#[test]
|
||||
fn update_manifest_changes_visible_after_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).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())
|
||||
.unwrap_or_else(|error| panic!("update_manifest failed: {error:?}"));
|
||||
@@ -112,7 +116,9 @@ fn update_manifest_changes_visible_after_reopen() {
|
||||
#[test]
|
||||
fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).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
|
||||
// produces one network in the registry.
|
||||
@@ -122,7 +128,6 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: HotSequence(1),
|
||||
};
|
||||
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
|
||||
|
||||
@@ -138,7 +143,9 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
|
||||
#[test]
|
||||
fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).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).
|
||||
let early = HotOp {
|
||||
@@ -147,7 +154,6 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: HotSequence(1),
|
||||
};
|
||||
let late = HotOp {
|
||||
op: RegistryDelta::AddNetwork {
|
||||
@@ -155,7 +161,6 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 10, peer: PeerId(5) },
|
||||
sequence: HotSequence(2),
|
||||
};
|
||||
gdd.apply_hot_op(early).unwrap();
|
||||
gdd.apply_hot_op(late).unwrap();
|
||||
@@ -184,7 +189,9 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||
#[test]
|
||||
fn last_broadcast_rev_persists_across_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).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.
|
||||
let op = HotOp {
|
||||
@@ -193,7 +200,6 @@ fn last_broadcast_rev_persists_across_reopen() {
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: HotSequence(1),
|
||||
};
|
||||
gdd.apply_hot_op(op).unwrap();
|
||||
let retired = gdd.retire(TimeStamp { counter: 1, peer: PeerId(5) }).unwrap_or_else(|error| panic!("retire failed: {error:?}"));
|
||||
@@ -214,7 +220,9 @@ fn export_folder_round_trips_through_open() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xAB, "ed".into(), "std".into()).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 dest = dir.path().join("export");
|
||||
@@ -223,7 +231,7 @@ fn export_folder_round_trips_through_open() {
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
|
||||
|
||||
// Payloads keep the working-copy codecs: registry is 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("manifest.json").exists());
|
||||
assert!(dest.join("session.json").exists());
|
||||
@@ -242,7 +250,9 @@ fn export_zip_round_trips_via_deserialize() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), 0xCD, "ed".into(), "std".into()).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 dest = dir.path().join("doc.gdd.zip");
|
||||
@@ -267,7 +277,9 @@ fn export_rejects_invalid_options() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xEF, "ed".into(), "std".into()).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 dest = dir.path().join("nope");
|
||||
@@ -290,7 +302,9 @@ fn resource_round_trip_add_read_remove() {
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), 0xCAFE, "ed".into(), "std".into()).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 hash = ResourceHash::from(&payload[..]);
|
||||
@@ -320,7 +334,9 @@ fn resource_survives_reopen() {
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), 0xC0DE, "ed".into(), "std".into()).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 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.
|
||||
let working_dir = tempfile::tempdir().unwrap();
|
||||
let working = AnyContainer::Folder(FolderBackend::create(working_dir.path()).unwrap());
|
||||
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).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.
|
||||
let payload = b"external resource bytes";
|
||||
@@ -373,7 +391,9 @@ fn export_carries_resources() {
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), 0xBC, "ed".into(), "std".into()).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 hash = ResourceHash::from(&payload[..]);
|
||||
@@ -396,12 +416,14 @@ fn export_carries_resources() {
|
||||
#[test]
|
||||
fn embed_all_resources_materializes_link_only_resource() {
|
||||
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 graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), 0xF00D, "ed".into(), "std".into()).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
|
||||
// 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");
|
||||
assert_eq!(entry.hash, Some(hash));
|
||||
let embedded = to_value(&DataSource::Embedded).unwrap();
|
||||
let url = to_value(&DataSource::Url("https://example.com/r.bin".parse().unwrap())).unwrap();
|
||||
let embedded = serde_json::to_value(DataSource::Embedded).unwrap();
|
||||
let url = serde_json::to_value(DataSource::Url("https://example.com/r.bin".parse().unwrap())).unwrap();
|
||||
let 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");
|
||||
});
|
||||
@@ -466,7 +488,9 @@ fn export_materializes_embedded_resource_from_byte_store() {
|
||||
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), 0xBEEF, "ed".into(), "std".into()).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.
|
||||
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};
|
||||
|
||||
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 hash = graphene_resource::ResourceHash::from(&payload[..]);
|
||||
@@ -560,12 +586,14 @@ fn open_in_rejects_future_format_version() {
|
||||
#[test]
|
||||
fn create_in_records_default_codecs_in_manifest() {
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).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;
|
||||
assert_eq!(codecs.registry, Codec::Postcard);
|
||||
assert_eq!(codecs.history, Codec::PostcardFrames);
|
||||
assert_eq!(codecs.hot_log, Codec::PostcardFrames);
|
||||
assert_eq!(codecs.registry, Codec::MessagePack);
|
||||
assert_eq!(codecs.history, Codec::MessagePackFrames);
|
||||
assert_eq!(codecs.hot_log, Codec::MessagePackFrames);
|
||||
assert_eq!(codecs.session, Codec::Json);
|
||||
});
|
||||
}
|
||||
@@ -581,7 +609,9 @@ fn first_commit_registers_peer_and_survives_reopen() {
|
||||
use graphene_resource::ResourceRegistry;
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), 0xAB, "ed".into(), "std".into()).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 {
|
||||
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())
|
||||
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
|
||||
assert_eq!(
|
||||
gdd.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
|
||||
Some(UserId(21)),
|
||||
"first commit registers the peer"
|
||||
);
|
||||
assert_eq!(gdd.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "first commit registers the peer");
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
|
||||
assert_eq!(
|
||||
reopened.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
|
||||
Some(UserId(21)),
|
||||
"registration survives reopen"
|
||||
);
|
||||
assert_eq!(reopened.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "registration survives reopen");
|
||||
});
|
||||
}
|
||||
|
||||
@@ -623,7 +645,9 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
|
||||
futures::executor::block_on(async {
|
||||
use document_container::AsyncContainer;
|
||||
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).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 {
|
||||
op: RegistryDelta::AddNetwork {
|
||||
@@ -631,13 +655,12 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: HotSequence(1),
|
||||
};
|
||||
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
// Defaults: hot log is PostcardFrames (.frames), manifest is always JSON.
|
||||
assert!(working.exists(&io::path_for(layout.hot_log_basename(), Codec::PostcardFrames)).await);
|
||||
// Defaults: hot log is MessagePackFrames (.frames), manifest is always JSON.
|
||||
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);
|
||||
|
||||
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()
|
||||
};
|
||||
|
||||
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.
|
||||
let byte_store = HashMapResourceStorage::new();
|
||||
|
||||
@@ -1,108 +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 a_whole_document_stage_after_a_recorded_batch_stages_nothing_new() {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(21), 1, "ed".into(), "std".into()).unwrap();
|
||||
let store = HashMapResourceStorage::new();
|
||||
let resources = ResourceRegistry::new();
|
||||
gdd.stage_runtime_snapshot(&NodeNetwork::default(), &NoMetadata, &resources, &store)
|
||||
.expect("first whole-document stage");
|
||||
|
||||
let target = Registry::convert_from_runtime(&network_with_one_node(), &NoMetadata, &resources, PeerId(21)).unwrap();
|
||||
let ops = document_graph_storage::delta::compute_deltas(gdd.registry(), &target.registry);
|
||||
gdd.stage_constructed_ops(ops, &target.declaration_bytes, &store).expect("recorded batch");
|
||||
let hot_before = gdd.session().hot_log().len();
|
||||
|
||||
gdd.stage_runtime_snapshot(&network_with_one_node(), &NoMetadata, &resources, &store)
|
||||
.expect("the runtime already matches what was staged");
|
||||
assert_eq!(gdd.session().hot_log().len(), hot_before, "nothing new to stage");
|
||||
}
|
||||
|
||||
/// `registry.bin` is the retired snapshot the hot log replays onto, so an op still hot at save time must stay out of it.
|
||||
#[test]
|
||||
fn a_reopen_keeps_unretired_hot_ops_out_of_the_retired_snapshot() {
|
||||
use document_graph_storage::{AttributeDelta, HotOp, HotSequence, RegistryDelta, TimeStamp, Value};
|
||||
let set = |value: u32, counter: u64| HotOp {
|
||||
op: RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: AttributeDelta {
|
||||
key: "k".into(),
|
||||
value: Some(Value::from(serde_json::json!(value))),
|
||||
},
|
||||
},
|
||||
timestamp: TimeStamp { counter, peer: PeerId(22) },
|
||||
sequence: HotSequence(counter),
|
||||
};
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(22), 1, "ed".into(), "std".into()).unwrap();
|
||||
gdd.apply_hot_op(set(1, 1)).unwrap();
|
||||
gdd.apply_hot_op(set(2, 2)).unwrap();
|
||||
gdd.retire(TimeStamp { counter: 1, peer: PeerId(22) }).unwrap();
|
||||
|
||||
let retired = gdd.session().retired_registry().clone();
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.unwrap();
|
||||
assert!(reopened.session().retired_registry().value_equal(&retired), "the hot op leaked into the retired snapshot");
|
||||
assert_eq!(reopened.session().hot_log().len(), 1);
|
||||
});
|
||||
}
|
||||
|
||||
/// A reopen continues this peer's clock and run of hot op sequences, with ops still hot and after they all retired,
|
||||
/// since a reused sequence would let a peer's settled marks drop the new op.
|
||||
#[test]
|
||||
fn a_reopen_continues_the_hot_op_sequence() {
|
||||
use document_graph_storage::{AttributeDelta, RegistryDelta, Value};
|
||||
let set = |value: u32| RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: AttributeDelta {
|
||||
key: "k".into(),
|
||||
value: Some(Value::from(serde_json::json!(value))),
|
||||
},
|
||||
};
|
||||
// Stages one op and returns the sequence it got.
|
||||
fn stage(gdd: &mut GddV1, op: RegistryDelta) -> u64 {
|
||||
gdd.stage_constructed_ops(vec![op], &Default::default(), &HashMapResourceStorage::new()).unwrap();
|
||||
gdd.session().hot_log().last().unwrap().sequence.0
|
||||
}
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(23), 1, "ed".into(), "std".into()).unwrap();
|
||||
stage(&mut gdd, set(1));
|
||||
let up_to = gdd.session().hot_log().last().unwrap().timestamp;
|
||||
gdd.retire(up_to).unwrap();
|
||||
let last = stage(&mut gdd, set(2));
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
|
||||
assert_eq!(stage(&mut reopened, set(3)), last + 1);
|
||||
|
||||
let up_to = reopened.session().hot_log().last().unwrap().timestamp;
|
||||
reopened.retire(up_to).unwrap();
|
||||
let last = reopened.session().last_hot_sequence().0;
|
||||
let clock = reopened.session().clock_counter();
|
||||
let (working, layout) = reopened.into_storage();
|
||||
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
|
||||
assert_eq!(reopened.session().clock_counter(), clock, "the clock carries over");
|
||||
assert_eq!(stage(&mut reopened, set(4)), last + 1);
|
||||
});
|
||||
}
|
||||
@@ -1,18 +1,10 @@
|
||||
[package]
|
||||
name = "document-graph-storage"
|
||||
description = "Provides a delta based graph representation used in the Graphite file format"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
conversion = ["dep:graph-craft", "dep:core-types"]
|
||||
@@ -28,7 +20,7 @@ serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
blake3 = { workspace = true }
|
||||
rustc-hash = { workspace = true }
|
||||
postcard = { workspace = true }
|
||||
rmp-serde = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
graph-craft = { workspace = true, features = ["loading"] }
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::{TimeStamp, Value, ValueError, from_value, to_value};
|
||||
use crate::TimeStamp;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
@@ -8,54 +8,33 @@ use std::collections::BTreeMap;
|
||||
/// keys live on `Node.inputs_attributes[i]`; per-network keys live on `Network.attributes`.
|
||||
pub mod attr;
|
||||
|
||||
/// A type-erased attribute value paired with the timestamp at which it was last set. A deleted key
|
||||
/// stays as a stamped tombstone, so an older write loses in either arrival order; readers see it as absent.
|
||||
/// A type-erased attribute value paired with the timestamp at which it was last set.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AttributeValue {
|
||||
pub value: Value,
|
||||
pub struct Value {
|
||||
pub value: serde_json::Value,
|
||||
pub timestamp: TimeStamp,
|
||||
// No skipping: the registry is positional on disk.
|
||||
#[serde(default)]
|
||||
pub deleted: bool,
|
||||
}
|
||||
|
||||
impl AttributeValue {
|
||||
pub fn new(value: Value, timestamp: TimeStamp) -> Self {
|
||||
Self { value, timestamp, deleted: false }
|
||||
}
|
||||
|
||||
/// The tombstone of a key deleted at `timestamp`.
|
||||
pub fn deleted(timestamp: TimeStamp) -> Self {
|
||||
Self {
|
||||
value: Value::None,
|
||||
timestamp,
|
||||
deleted: true,
|
||||
}
|
||||
impl Value {
|
||||
pub fn new(value: serde_json::Value, timestamp: TimeStamp) -> Self {
|
||||
Self { value, timestamp }
|
||||
}
|
||||
}
|
||||
|
||||
/// Attribute maps. Each entity carries an `attributes_timestamp`: when its map was last written whole, by an
|
||||
/// addition or a whole-list input write. A key absent from the map is deleted as of that stamp, so an older
|
||||
/// write is dropped and an older tombstone is redundant.
|
||||
pub type Attributes = BTreeMap<String, AttributeValue>;
|
||||
|
||||
/// The live entries of an attribute map: every key that is not a tombstone.
|
||||
pub fn live(attributes: &Attributes) -> impl Iterator<Item = (&String, &AttributeValue)> {
|
||||
attributes.iter().filter(|(_, value)| !value.deleted)
|
||||
}
|
||||
pub type Attributes = BTreeMap<String, Value>;
|
||||
|
||||
/// Write helpers for `Attributes`.
|
||||
pub trait AttributesWrite {
|
||||
/// Inserts `value` under `key`.
|
||||
fn set(&mut self, key: &str, value: Value, timestamp: TimeStamp);
|
||||
/// Inserts a JSON value under `key`.
|
||||
fn set(&mut self, key: &str, value: serde_json::Value, timestamp: TimeStamp);
|
||||
|
||||
/// Serializes `value` and inserts it under `key`.
|
||||
fn set_serialized<T: serde::Serialize>(&mut self, key: &str, value: &T, timestamp: TimeStamp) -> Result<(), ValueError> {
|
||||
self.set(key, to_value(value)?, timestamp);
|
||||
fn set_serialized<T: serde::Serialize>(&mut self, key: &str, value: &T, timestamp: TimeStamp) -> Result<(), serde_json::Error> {
|
||||
self.set(key, serde_json::to_value(value)?, timestamp);
|
||||
Ok(())
|
||||
}
|
||||
/// Inserts only when `value != default`, so the read side falls back to the same default.
|
||||
fn set_if_not_default<T: serde::Serialize + PartialEq>(&mut self, key: &str, value: &T, default: &T, timestamp: TimeStamp) -> Result<(), ValueError> {
|
||||
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 {
|
||||
self.set_serialized(key, value, timestamp)?;
|
||||
}
|
||||
@@ -64,8 +43,8 @@ pub trait AttributesWrite {
|
||||
}
|
||||
|
||||
impl AttributesWrite for Attributes {
|
||||
fn set(&mut self, key: &str, value: Value, timestamp: TimeStamp) {
|
||||
self.insert(key.to_string(), AttributeValue::new(value, timestamp));
|
||||
fn set(&mut self, key: &str, value: serde_json::Value, timestamp: TimeStamp) {
|
||||
self.insert(key.to_string(), Value { value, timestamp });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,6 +66,6 @@ pub trait AttributesRead {
|
||||
|
||||
impl AttributesRead for Attributes {
|
||||
fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
|
||||
self.get(key).filter(|v| !v.deleted).and_then(|v| from_value(&v.value).ok())
|
||||
self.get(key).and_then(|v| serde_json::from_value(v.value.clone()).ok())
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
pub mod node {
|
||||
pub const CALL_ARGUMENT: &str = "call_argument";
|
||||
pub const CONTEXT_FEATURES: &str = "context_features";
|
||||
pub const VISIBLE: &str = "visible";
|
||||
pub const SKIP_DEDUPLICATION: &str = "skip_deduplication";
|
||||
pub const REFLECTION_METADATA: &str = "reflection_metadata";
|
||||
@@ -32,6 +31,7 @@ pub mod node {
|
||||
pub mod session {
|
||||
pub mod network {
|
||||
pub const PREVIEWING: &str = "ui::previewing";
|
||||
|
||||
// TODO: Remove these graph ui nav-specific attributes
|
||||
pub const NAV_PTZ: &str = "ui::nav::ptz";
|
||||
pub const NAV_TRANSFORM: &str = "ui::nav::transform";
|
||||
@@ -59,11 +59,6 @@ pub mod network {
|
||||
/// serialized blob so its shape can evolve (e.g. dropping the `Type`) without a model change. The
|
||||
/// node references use stable storage IDs, resolved back to runtime-local IDs on conversion.
|
||||
pub const SCOPE_INJECTIONS: &str = "scope_injections";
|
||||
|
||||
/// Whole-vec LWW of the display order of the network's pinned nodes, as stable storage IDs.
|
||||
/// Concurrent reorders do not merge, but the pinned set is already shared, and a shared set with
|
||||
/// per-peer ordering would diverge with no way to reconcile.
|
||||
pub const PINNED_ORDER: &str = "ui::pinned_order";
|
||||
}
|
||||
|
||||
pub mod delta {
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
use crate::{
|
||||
AttributeValue, Attributes, AttributesWrite, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Prior, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId,
|
||||
Value, attr, compute_rev,
|
||||
};
|
||||
use crate::{Attributes, AttributesWrite, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev};
|
||||
use graphene_resource::ResourceHash;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Content-addressed delta: `id` is `blake3_128(parents, author, timestamp, delta_type)`.
|
||||
///
|
||||
/// `reverse` is state-dependent undo bookkeeping (what the op overwrote, captured as it applied), so it's
|
||||
/// serialized for storage but excluded from the identity hash: two peers applying the same forward delta to
|
||||
/// different local states would otherwise compute different Revs for the same logical op.
|
||||
/// `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)]
|
||||
pub struct Delta {
|
||||
pub id: Rev,
|
||||
@@ -18,22 +16,16 @@ pub struct Delta {
|
||||
pub author: PeerId,
|
||||
pub timestamp: TimeStamp,
|
||||
pub kind: RegistryDelta,
|
||||
/// What every slot `kind` wrote held before it, stamps included, in write order. See [`Prior`].
|
||||
pub reverse: Vec<Prior>,
|
||||
pub reverse: RegistryDelta,
|
||||
/// Local, mutable annotations on this commit (interaction-end marker, future commit messages / labels).
|
||||
/// Deliberately excluded from `compute_rev`: relabeling a commit must not change its content-addressed
|
||||
/// identity, and two peers annotating the same op differently must still dedup to one `Rev`.
|
||||
#[serde(default)]
|
||||
#[serde(default, skip_serializing_if = "Attributes::is_empty")]
|
||||
pub attributes: Attributes,
|
||||
/// When the delta entered history, in Unix milliseconds by the clock of the peer that retired it; display only,
|
||||
/// and outside the rev like `attributes`. Zero means unrecorded, saving the tag byte an `Option` costs per delta;
|
||||
/// read it through [`retired_at`](Self::retired_at). Last, since the history codec is positional.
|
||||
#[serde(default)]
|
||||
pub(crate) retired_at_ms: u64,
|
||||
}
|
||||
|
||||
impl Delta {
|
||||
pub fn new(parent: Option<Rev>, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: Vec<Prior>) -> Self {
|
||||
pub fn new(parent: Option<Rev>, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: RegistryDelta) -> Self {
|
||||
let id = compute_rev(parent, author, timestamp, &kind);
|
||||
Self {
|
||||
id,
|
||||
@@ -43,7 +35,6 @@ impl Delta {
|
||||
kind,
|
||||
reverse,
|
||||
attributes: Attributes::default(),
|
||||
retired_at_ms: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,10 +52,9 @@ impl Delta {
|
||||
parent,
|
||||
author,
|
||||
timestamp,
|
||||
reverse: Vec::new(),
|
||||
reverse: kind.clone(),
|
||||
kind,
|
||||
attributes: Attributes::default(),
|
||||
retired_at_ms: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,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.
|
||||
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 {
|
||||
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == Value::Bool(true))
|
||||
}
|
||||
|
||||
/// When the delta entered history in wall-clock milliseconds, if the peer that retired it recorded it.
|
||||
pub fn retired_at(&self) -> Option<u64> {
|
||||
(self.retired_at_ms != 0).then_some(self.retired_at_ms)
|
||||
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == serde_json::Value::Bool(true))
|
||||
}
|
||||
|
||||
/// The content-addressed `Rev` this delta's identity fields hash to. Equals `id` for a delta built
|
||||
@@ -107,13 +92,14 @@ impl Delta {
|
||||
|
||||
/// Op payload. Timestamps live on the wrapping `Delta` — one per delta, applied to all LWW-eligible
|
||||
/// writes within. See `notes/document-format-collaboration.md`.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub enum RegistryDelta {
|
||||
AddNode {
|
||||
id: NodeId,
|
||||
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 {
|
||||
id: NodeId,
|
||||
snapshot: Node,
|
||||
@@ -123,25 +109,6 @@ pub enum RegistryDelta {
|
||||
index: u32,
|
||||
new_input: NodeInput,
|
||||
},
|
||||
/// A node's whole input list, for a change to the number or order of its slots that the
|
||||
/// index-addressed `ChangeNodeInput` cannot express. Assigns rather than merging: concurrent
|
||||
/// per-slot edits are lost, which is inherent to the indices themselves moving.
|
||||
///
|
||||
/// Touches only the inputs, leaving the node's attributes and implementation alone, so it composes
|
||||
/// with attribute ops on the same node instead of reverting them.
|
||||
SetNodeInputs {
|
||||
id: NodeId,
|
||||
inputs: Vec<InputSlot>,
|
||||
},
|
||||
/// A node's implementation, for swapping what it computes without rebuilding the node.
|
||||
///
|
||||
/// Removing and re-adding the node would express the same change, but would also clear every
|
||||
/// attribute it carries, so restating them would clobber whatever a concurrent peer wrote to the
|
||||
/// node's name, lock or pin.
|
||||
SetNodeImplementation {
|
||||
id: NodeId,
|
||||
implementation: Implementation,
|
||||
},
|
||||
ChangeNodeAttribute {
|
||||
id: NodeId,
|
||||
delta: AttributeDelta,
|
||||
@@ -166,12 +133,13 @@ pub enum RegistryDelta {
|
||||
id: NetworkId,
|
||||
network: Network,
|
||||
},
|
||||
/// `snapshot` is the network as removed; see [`RemoveNode`](Self::RemoveNode).
|
||||
/// `snapshot` lets the reverse delta rebuild without re-walking history.
|
||||
RemoveNetwork {
|
||||
id: NetworkId,
|
||||
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 {
|
||||
id: ResourceId,
|
||||
entry: ResourceEntry,
|
||||
@@ -193,15 +161,16 @@ pub enum RegistryDelta {
|
||||
AddSource {
|
||||
id: ResourceId,
|
||||
key: SourceKey,
|
||||
source: Value,
|
||||
source: serde_json::Value,
|
||||
},
|
||||
/// Remove one entry from a resource's source chain. LWW against the entry's timestamp.
|
||||
RemoveSource {
|
||||
id: ResourceId,
|
||||
key: SourceKey,
|
||||
},
|
||||
/// Registers a device's `PeerId` to the `UserId` behind it. LWW per peer, so a device that changes person
|
||||
/// registers again and the newest registration wins wherever it lands.
|
||||
/// 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 {
|
||||
peer: PeerId,
|
||||
user: UserId,
|
||||
@@ -216,52 +185,42 @@ pub enum RegistryDelta {
|
||||
Merge {
|
||||
extra_parents: Vec<Rev>,
|
||||
},
|
||||
/// The last op of its author's transaction. Changes nothing, and retirement drops it.
|
||||
EndTransaction,
|
||||
// Allow for future delta types without a model change
|
||||
Other(Value),
|
||||
Other(serde_json::Value),
|
||||
}
|
||||
|
||||
/// `value: None` means remove. The timestamp comes from the wrapping `Delta`.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct AttributeDelta {
|
||||
pub key: String,
|
||||
pub value: Option<Value>,
|
||||
pub value: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
/// Lands a single-key write. `floor` is the map's `attributes_timestamp`; see [`Attributes`]. A deletion
|
||||
/// leaves a tombstone.
|
||||
pub(crate) fn apply_attribute_delta(delta: AttributeDelta, timestamp: TimeStamp, attributes: &mut Attributes, floor: TimeStamp) {
|
||||
pub(crate) fn reverse_attribute_delta(delta: &AttributeDelta, attributes: &Attributes) -> AttributeDelta {
|
||||
AttributeDelta {
|
||||
key: delta.key.clone(),
|
||||
value: attributes.get(&delta.key).map(|previous| previous.value.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn apply_attribute_delta(delta: AttributeDelta, timestamp: TimeStamp, force: bool, attributes: &mut Attributes) {
|
||||
let AttributeDelta { key, value } = delta;
|
||||
let decided = attributes.get(&key).map_or(floor, |existing| existing.timestamp);
|
||||
if timestamp <= decided {
|
||||
return;
|
||||
}
|
||||
let entry = match value {
|
||||
Some(value) => AttributeValue::new(value, timestamp),
|
||||
None => AttributeValue::deleted(timestamp),
|
||||
};
|
||||
attributes.insert(key, entry);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_missing_retirement_time_costs_what_a_zero_costs_and_round_trips() {
|
||||
let base = Delta::new(None, PeerId(1), TimeStamp { counter: 1, peer: PeerId(1) }, RegistryDelta::EndTransaction, Vec::new());
|
||||
let mut stamped = base.clone();
|
||||
stamped.retired_at_ms = 1_790_000_000_000;
|
||||
|
||||
let bare_base = postcard::to_allocvec(&base).expect("encode");
|
||||
let bare_stamped = postcard::to_allocvec(&stamped).expect("encode");
|
||||
// Only the integer's varint differs: one byte for zero, six for today's milliseconds, no tag byte in either.
|
||||
assert_eq!(bare_stamped.len() - bare_base.len(), postcard::to_allocvec(&1_790_000_000_000u64).unwrap().len() - 1);
|
||||
|
||||
let decoded: Delta = postcard::from_bytes(&bare_stamped).expect("decode");
|
||||
assert_eq!(decoded.retired_at(), Some(1_790_000_000_000));
|
||||
let decoded: Delta = postcard::from_bytes(&bare_base).expect("decode");
|
||||
assert_eq!(decoded.retired_at(), None);
|
||||
match value {
|
||||
Some(value) => match attributes.entry(key) {
|
||||
std::collections::btree_map::Entry::Occupied(mut entry) => {
|
||||
if force || timestamp > entry.get().timestamp {
|
||||
entry.insert(Value { value, timestamp });
|
||||
}
|
||||
}
|
||||
std::collections::btree_map::Entry::Vacant(entry) => {
|
||||
entry.insert(Value { value, timestamp });
|
||||
}
|
||||
},
|
||||
None => {
|
||||
let should_remove = force || attributes.get(&key).is_none_or(|existing| timestamp > existing.timestamp);
|
||||
if should_remove {
|
||||
attributes.remove(&key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -166,14 +166,14 @@ fn diff_resource_entry(id: ResourceId, from: &ResourceEntry, to: &ResourceEntry,
|
||||
deltas.push(RegistryDelta::SetResourceHash { id, hash: to.hash });
|
||||
}
|
||||
|
||||
for (key, _) in from.live_sources() {
|
||||
for (key, _) in &from.sources {
|
||||
if to.source(key).is_none() {
|
||||
deltas.push(RegistryDelta::RemoveSource { id, key: *key });
|
||||
}
|
||||
}
|
||||
|
||||
// Compare source bodies only; the per-source timestamp is derived from the diff, not part of it.
|
||||
for (key, to_source) in to.live_sources() {
|
||||
for (key, to_source) in &to.sources {
|
||||
if from.source(key).is_none_or(|from_source| from_source.source != to_source.source) {
|
||||
deltas.push(RegistryDelta::AddSource {
|
||||
id,
|
||||
@@ -196,15 +196,15 @@ fn nodes_have_same_implementation(a: &Node, b: &Node) -> bool {
|
||||
fn compute_attribute_deltas(from: &crate::Attributes, to: &crate::Attributes) -> Vec<AttributeDelta> {
|
||||
let mut deltas = Vec::new();
|
||||
|
||||
for (key, _) in crate::attributes::live(from) {
|
||||
if to.get(key).is_none_or(|value| value.deleted) {
|
||||
for key in from.keys() {
|
||||
if !to.contains_key(key) {
|
||||
deltas.push(AttributeDelta { key: key.clone(), value: None });
|
||||
}
|
||||
}
|
||||
|
||||
// Compare by `value` only; the per-entry `timestamp` is derived from the diff, not part of it.
|
||||
for (key, to_value) in crate::attributes::live(to) {
|
||||
if from.get(key).is_none_or(|from_value| from_value.deleted || from_value.value != to_value.value) {
|
||||
for (key, to_value) in to {
|
||||
if from.get(key).is_none_or(|from_value| from_value.value != to_value.value) {
|
||||
deltas.push(AttributeDelta {
|
||||
key: key.clone(),
|
||||
value: Some(to_value.value.clone()),
|
||||
@@ -218,7 +218,7 @@ fn compute_attribute_deltas(from: &crate::Attributes, to: &crate::Attributes) ->
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{Attributes, ExportSlot, Network, Node, NodeInput, TimeStamp, Value};
|
||||
use crate::{Attributes, ExportSlot, Network, Node, NodeInput, TimeStamp};
|
||||
|
||||
#[test]
|
||||
fn test_compute_deltas_empty() {
|
||||
@@ -287,7 +287,6 @@ mod tests {
|
||||
input: NodeInput::Import { index: 0 },
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
attributes: Attributes::new(),
|
||||
attributes_timestamp: TimeStamp::ORIGIN,
|
||||
});
|
||||
|
||||
let deltas = compute_deltas(&from, &to);
|
||||
@@ -305,7 +304,11 @@ mod tests {
|
||||
from.networks.insert(NetworkId(0), Network::default());
|
||||
|
||||
let mut to = from.clone();
|
||||
to.networks.get_mut(&NetworkId(0)).unwrap().attributes.set("ui::nav::width", 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);
|
||||
assert_eq!(deltas.len(), 1, "a changed per-network attribute must emit one delta");
|
||||
@@ -338,10 +341,9 @@ mod tests {
|
||||
let stamp = |counter: u64| TimeStamp { counter, peer: crate::PeerId(0) };
|
||||
node.attributes.insert(
|
||||
"test".to_string(),
|
||||
crate::AttributeValue {
|
||||
value: Value::Str("old".into()),
|
||||
crate::Value {
|
||||
value: serde_json::json!("old"),
|
||||
timestamp: stamp(0),
|
||||
deleted: false,
|
||||
},
|
||||
);
|
||||
from.node_instances.insert(NodeId(42), node);
|
||||
@@ -349,10 +351,9 @@ mod tests {
|
||||
let mut to = from.clone();
|
||||
to.node_instances.get_mut(&NodeId(42)).unwrap().attributes.insert(
|
||||
"test".to_string(),
|
||||
crate::AttributeValue {
|
||||
value: Value::Str("new".into()),
|
||||
crate::Value {
|
||||
value: serde_json::json!("new"),
|
||||
timestamp: stamp(1),
|
||||
deleted: false,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -375,10 +376,9 @@ mod tests {
|
||||
let mut to = from.clone();
|
||||
to.attributes.insert(
|
||||
"doc::test_attribute".to_string(),
|
||||
crate::AttributeValue {
|
||||
value: Value::Str("value".into()),
|
||||
crate::Value {
|
||||
value: serde_json::json!("value"),
|
||||
timestamp: stamp(1),
|
||||
deleted: false,
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -1,29 +1,23 @@
|
||||
use std::collections::btree_map::Entry;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::hash::Hash;
|
||||
|
||||
use crate::{
|
||||
Attributes, CrdtError, Delta, ExportSlot, History, HotOp, HotSequence, Implementation, InputSlot, LamportClock, MAX_EXPORT_SLOTS, MAX_INPUT_SLOTS, Network, NetworkId, Node, NodeId, NodeInput,
|
||||
PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, Rev, SettledHotOps, SourceValue, TimeStamp, Tombstone, UserId, apply_attribute_delta,
|
||||
CrdtError, Delta, ExportSlot, History, HotOp, LamportClock, MAX_EXPORT_SLOTS, NetworkId, NodeId, NodeInput, PeerId, Registry, RegistryDelta, ResourceEntry, Rev, SourceValue, TimeStamp,
|
||||
apply_attribute_delta, reverse_attribute_delta,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Document {
|
||||
/// Working registry: retired state with the current hot ops applied on top. This is what live
|
||||
/// reads and `registry()` observe.
|
||||
/// reads and `registry()` observe, and what undo/redo force-apply against.
|
||||
pub(crate) working_registry: Registry,
|
||||
/// Live broadcast stream, applied to the `working_registry` on receive, GC'd at retirement.
|
||||
/// Persisted for crash recovery so in-flight unretired work survives editor restarts.
|
||||
pub(crate) hot_log: Vec<HotOp>,
|
||||
/// The stamps of the hot log's ops, so a re-announced op is recognised without a scan.
|
||||
pub(crate) hot_timestamps: HashSet<TimeStamp>,
|
||||
/// Which hot ops are retired into history, so a late copy is dropped;
|
||||
/// retired deltas keep no link back to their hot ops.
|
||||
pub(crate) settled: SettledHotOps,
|
||||
/// The registry as of the last retirement, with no un-retired hot ops applied. Retirement computes
|
||||
/// each delta's `reverse` against this (so LWW reverses capture the true pre-op value, not the
|
||||
/// hot-polluted working state) and advances it. It equals the working registry whenever the hot log is
|
||||
/// empty.
|
||||
/// hot-polluted working state) and advances it, stamping fields at the fresh `T_retire`. Kept equal
|
||||
/// to `registry` *by value* whenever the hot log is empty (undo/redo resync it after moving the
|
||||
/// cursor), but field timestamps can differ: retirement bumps the snapshot's to `T_retire` while the
|
||||
/// working registry keeps the staging-time timestamps. Benign while the local monotonic clock makes
|
||||
/// new edits win
|
||||
pub(crate) retired_snapshot: Registry,
|
||||
/// User's cursor in their local history chain. `None` on an empty document (no commits yet).
|
||||
pub(crate) head: Option<Rev>,
|
||||
@@ -34,129 +28,97 @@ pub struct Document {
|
||||
pub(crate) redo_stack: Vec<Rev>,
|
||||
pub(crate) clock: LamportClock,
|
||||
pub(crate) peer: PeerId,
|
||||
/// The person behind this peer; what `RegisterPeer` records for it.
|
||||
pub(crate) user: UserId,
|
||||
/// Latest retired commit on the local chain that a peer holds. Commits after it can be undone silently; commits up
|
||||
/// to it are published and stay. `None` means nothing published yet.
|
||||
/// Latest retired commit on the local chain that has been broadcast to at least one peer.
|
||||
/// Commits after this can be rewritten silently; commits at or before this are published
|
||||
/// and require forward reverse-delta ops to undo. `None` means nothing broadcast yet.
|
||||
pub(crate) last_broadcast_rev: Option<Rev>,
|
||||
/// Shared-monotonic counter feeding `next_node_id`. Bumped on every mint regardless of which
|
||||
/// peer is calling; collision avoidance comes from hashing `(self.peer, counter)`, so two peers
|
||||
/// reading the same counter still produce distinct IDs.
|
||||
pub(crate) next_node_counter: u64,
|
||||
/// Counts this peer's own hot ops, so each carries its position in a gap-free run. See [`HotOp::sequence`].
|
||||
pub(crate) last_hot_sequence: HotSequence,
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// An empty document for `peer`, at the origin of its clock.
|
||||
pub(crate) fn empty(peer: PeerId, user: UserId) -> Self {
|
||||
Self {
|
||||
working_registry: Registry::default(),
|
||||
retired_snapshot: Registry::default(),
|
||||
history: History::new(),
|
||||
hot_log: Vec::new(),
|
||||
hot_timestamps: HashSet::new(),
|
||||
settled: SettledHotOps::default(),
|
||||
head: None,
|
||||
redo_stack: Vec::new(),
|
||||
clock: LamportClock::new(peer),
|
||||
peer,
|
||||
user,
|
||||
last_broadcast_rev: None,
|
||||
next_node_counter: 0,
|
||||
last_hot_sequence: HotSequence::NONE,
|
||||
}
|
||||
}
|
||||
|
||||
/// Mint a fresh `NodeId` scoped to this document's peer. The 64-bit ID is `blake3(peer, counter)`
|
||||
/// truncated; the counter is shared across peers and persisted with the document.
|
||||
pub fn next_node_id(&mut self) -> NodeId {
|
||||
self.next_node_counter += 1;
|
||||
let mut hasher = blake3::Hasher::new();
|
||||
postcard::to_io(&(self.peer, self.next_node_counter), &mut hasher).expect("(PeerId, counter) must serialize");
|
||||
let digest = hasher.finalize();
|
||||
let bytes = rmp_serde::to_vec(&(self.peer, self.next_node_counter)).expect("(PeerId, counter) must serialize");
|
||||
let digest = blake3::hash(&bytes);
|
||||
let mut truncated = [0u8; 8];
|
||||
truncated.copy_from_slice(&digest.as_bytes()[..8]);
|
||||
NodeId(u64::from_le_bytes(truncated))
|
||||
}
|
||||
|
||||
/// Put back what a delta overwrote in the retired snapshot (silent-zone undo), leaving it as folding history up
|
||||
/// to the delta's parent would. The working registry follows: it is the same registry when nothing is hot.
|
||||
pub(crate) fn revert_delta(&mut self, delta: &Delta) {
|
||||
crate::prior::restore(&mut self.retired_snapshot, &delta.reverse);
|
||||
if self.hot_log.is_empty() {
|
||||
crate::prior::restore(&mut self.working_registry, &delta.reverse);
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
/// Apply a locally staged op: LWW into the registry, append to the hot log, leave history and `head`
|
||||
/// alone. Skips the retirement check, so staging never silently drops local work; outside callers use
|
||||
/// [`Session::apply_hot_op`](crate::Session::apply_hot_op).
|
||||
pub(crate) fn apply_hot_op(&mut self, hot_op: HotOp, mode: ApplyMode) -> Result<(), CrdtError> {
|
||||
self.apply_op_with(RegistryTarget::Working, hot_op.op.clone(), hot_op.timestamp, mode)?;
|
||||
self.hot_timestamps.insert(hot_op.timestamp);
|
||||
pub(crate) fn restore_network_from_history(&mut self, target: RegistryTarget, network_id: NetworkId) -> Result<(), CrdtError> {
|
||||
// Find the Delta whose forward op removed this network. Its `reverse` is `AddNetwork`,
|
||||
// which is what we want to re-apply.
|
||||
let delta = self
|
||||
.find_in_ancestry(|d| matches!(d.reverse, RegistryDelta::AddNetwork { id, .. } if id == network_id))
|
||||
.ok_or(CrdtError::NetworkNotInHistory(network_id))?;
|
||||
self.revert_delta(target, delta)
|
||||
}
|
||||
|
||||
/// Search every delta reachable from `head` (following all parents, including a merge's
|
||||
/// `extra_parents`) for the first matching `predicate`, breadth-first. Resurrection needs full
|
||||
/// ancestry reachability, so a node added only on a merged-in branch is still found.
|
||||
fn find_in_ancestry(&self, predicate: impl Fn(&Delta) -> bool) -> Option<Delta> {
|
||||
let mut queue: std::collections::VecDeque<Rev> = self.head.into_iter().collect();
|
||||
let mut seen: std::collections::HashSet<Rev> = self.head.into_iter().collect();
|
||||
while let Some(rev) = queue.pop_front() {
|
||||
let Some(delta) = self.history.get(rev) else { continue };
|
||||
if predicate(delta) {
|
||||
return Some(delta.clone());
|
||||
}
|
||||
for parent in delta.all_parents() {
|
||||
if seen.insert(parent) {
|
||||
queue.push_back(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Apply a delta's `reverse` as the new forward op (silent-zone undo). Force-applied: structural
|
||||
/// ops are idempotent, and LWW arms assign the reverse value unconditionally even though it carries
|
||||
/// the same timestamp as the forward op it undoes.
|
||||
pub(crate) fn revert_delta(&mut self, target: RegistryTarget, mut delta: Delta) -> Result<(), CrdtError> {
|
||||
for parent in delta.all_parents() {
|
||||
if !self.history.contains(parent) {
|
||||
return Err(CrdtError::NotFoundInHistory(parent));
|
||||
}
|
||||
}
|
||||
std::mem::swap(&mut delta.kind, &mut delta.reverse);
|
||||
self.apply_op_with(target, delta.kind, delta.timestamp, ApplyMode::Force)
|
||||
}
|
||||
|
||||
/// Apply a live broadcast op. Updates the registry via LWW and appends to the hot log.
|
||||
/// Doesn't touch history or `head` — hot ops are transient.
|
||||
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
|
||||
self.apply_op(hot_op.op.clone(), hot_op.timestamp)?;
|
||||
self.hot_log.push(hot_op);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Replay a hot op recovered from persisted state or received from a peer. Replaying one already
|
||||
/// reflected in the registry 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> {
|
||||
// Re-adding a settled op would leave a hot log entry no retirement will ever name.
|
||||
if self.settled.covers(hot_op.id()) {
|
||||
return Ok(());
|
||||
}
|
||||
// A re-announcement of a held op must not become a second copy.
|
||||
if self.hot_timestamps.contains(&hot_op.timestamp) {
|
||||
return Ok(());
|
||||
}
|
||||
// Our own ops raise the sequence counter too, should the persisted one lag behind the hot log.
|
||||
if hot_op.timestamp.peer == self.peer {
|
||||
self.last_hot_sequence = self.last_hot_sequence.max(hot_op.sequence);
|
||||
}
|
||||
|
||||
self.apply_op_idempotent(hot_op.op.clone(), hot_op.timestamp)?;
|
||||
self.hot_timestamps.insert(hot_op.timestamp);
|
||||
self.hot_log.push(hot_op);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Take on a peer's marks as well as this peer's. Returns whether a hot op was dropped.
|
||||
pub(crate) fn absorb_settled(&mut self, remote: &SettledHotOps) -> bool {
|
||||
self.settled.absorb(remote);
|
||||
self.drop_settled_hot_ops()
|
||||
}
|
||||
|
||||
/// Bring the stamp index back in line after the hot log was filtered as a whole.
|
||||
pub(crate) fn resync_hot_timestamps(&mut self) {
|
||||
self.hot_timestamps = self.hot_log.iter().map(|hot_op| hot_op.timestamp).collect();
|
||||
}
|
||||
|
||||
/// Re-derive the working registry as the retired snapshot plus every hot op, for a change that cannot
|
||||
/// be applied in place. O(N + L), for rare paths only.
|
||||
pub(crate) fn rebuild_working(&mut self) {
|
||||
self.working_registry = self.retired_snapshot.clone();
|
||||
for hot_op in std::mem::take(&mut self.hot_log) {
|
||||
// Nothing is deferred, so this cannot fail on a referent; don't strand the op over anything else.
|
||||
let _ = self.apply_op_idempotent(hot_op.op.clone(), hot_op.timestamp);
|
||||
self.hot_log.push(hot_op);
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop settled hot ops and re-derive the working registry without them; their effect comes back with their deltas.
|
||||
fn drop_settled_hot_ops(&mut self) -> bool {
|
||||
let before = self.hot_log.len();
|
||||
let settled = &self.settled;
|
||||
self.hot_log.retain(|hot_op| !settled.covers(hot_op.id()));
|
||||
let dropped = self.hot_log.len() != before;
|
||||
if dropped {
|
||||
self.resync_hot_timestamps();
|
||||
self.rebuild_working();
|
||||
}
|
||||
dropped
|
||||
}
|
||||
|
||||
/// Apply a retired commit and record it in history.
|
||||
/// Apply a retired commit. Idempotent on structural ops (AddNode/AddNetwork on existing
|
||||
/// targets, Remove on missing ones) since hot ops already produced the structural state.
|
||||
/// The point is to bump field timestamps to T_retire via the LWW arms.
|
||||
pub fn apply_delta(&mut self, delta: Delta) -> Result<(), CrdtError> {
|
||||
for parent in delta.all_parents() {
|
||||
if !self.history.contains(parent) {
|
||||
@@ -176,503 +138,296 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn registry_ref(&self, target: RegistryTarget) -> &Registry {
|
||||
fn registry_ref(&self, target: RegistryTarget) -> &Registry {
|
||||
match target {
|
||||
RegistryTarget::Working => &self.working_registry,
|
||||
RegistryTarget::Snapshot => &self.retired_snapshot,
|
||||
}
|
||||
}
|
||||
|
||||
/// A fresh local edit against the working registry; see [`ApplyMode::Live`].
|
||||
#[cfg(test)]
|
||||
/// New local/remote op against the working registry: add ops error on duplicate targets and
|
||||
/// `Change*` ops error on a missing target, while remove ops no-op when the target is already
|
||||
/// absent; LWW arms keep the newer-timestamp value (strict `>`). The common entry point for edits.
|
||||
pub(crate) fn apply_op(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
|
||||
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> {
|
||||
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Idempotent)
|
||||
}
|
||||
|
||||
/// Applies one op. Every field of the registry is last-writer-wins on a timestamp, whether an entity
|
||||
/// exists included, so the registry folds to the same values whatever order the ops land in:
|
||||
///
|
||||
/// - An addition writes every field of the entity at its stamp, and is evidence it exists from then.
|
||||
/// - A removal is evidence the entity does not exist from its stamp. Its content stays as a tombstone,
|
||||
/// and the removal's snapshot folds in like any other write.
|
||||
/// - A write, or a reference from another entity's op, is evidence the entity exists at its stamp, so it
|
||||
/// revives an older removal; an older write lands on the tombstone, for a later revival to see.
|
||||
/// - A write to an entity never seen lands on a placeholder until its addition arrives; see [`write()`].
|
||||
/// Silent-zone undo/redo rewind against the working registry: structural ops are idempotent, and
|
||||
/// LWW arms assign unconditionally. We own the single-writer chain here, so the precomputed reverse
|
||||
/// (undo) or forward (redo) value is authoritative even though its timestamp ties what it replaces.
|
||||
pub(crate) fn force_apply_op(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
|
||||
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Force)
|
||||
}
|
||||
|
||||
pub(crate) fn apply_op_with(&mut self, target: RegistryTarget, op: RegistryDelta, timestamp: TimeStamp, mode: ApplyMode) -> Result<(), CrdtError> {
|
||||
// Advance the local clock past every observed op, including ones that subsequently no-op or
|
||||
// error. Observation is about causality knowledge, not about whether the op took effect.
|
||||
self.clock.observe(timestamp);
|
||||
|
||||
let live = mode == ApplyMode::Live;
|
||||
// Structural ops skip (rather than error) on duplicate/missing targets when not a fresh edit;
|
||||
// LWW arms assign unconditionally only under `Force`.
|
||||
let idempotent = mode != ApplyMode::Live;
|
||||
let force = mode == ApplyMode::Force;
|
||||
|
||||
// Resurrect any concurrently-removed targets the op references before binding the registry
|
||||
// (resurrection re-borrows `self` via history), so the mutation below holds one `registry` ref.
|
||||
self.ensure_referenced_exist(target, &op)?;
|
||||
|
||||
let registry = self.registry_mut(target);
|
||||
match op {
|
||||
RegistryDelta::AddNode { id, node } => {
|
||||
if live && 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));
|
||||
}
|
||||
write_network(registry, node.network, timestamp, mode, |_| Ok(()))?;
|
||||
add(&mut registry.node_instances, &mut registry.removed_nodes, id, node, timestamp);
|
||||
registry.node_instances.insert(id, node);
|
||||
}
|
||||
RegistryDelta::RemoveNode { id, snapshot } => {
|
||||
remove(&mut registry.node_instances, &mut registry.removed_nodes, id, snapshot, timestamp);
|
||||
}
|
||||
RegistryDelta::SetNodeInputs { id, mut inputs } => {
|
||||
inputs.iter_mut().for_each(|slot| stamp_slot(slot, timestamp));
|
||||
let referenced: Vec<NodeId> = inputs
|
||||
.iter()
|
||||
.filter_map(|slot| match slot.input {
|
||||
NodeInput::Node { id, .. } => Some(id),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
ensure_seen(registry, &referenced, mode)?;
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
merge_inputs(node, inputs, timestamp);
|
||||
Ok(())
|
||||
})?;
|
||||
for referenced in referenced {
|
||||
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
|
||||
}
|
||||
RegistryDelta::RemoveNode { id, .. } => {
|
||||
registry.node_instances.remove(&id);
|
||||
}
|
||||
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
|
||||
let referenced = match new_input {
|
||||
NodeInput::Node { id, .. } => Some(id),
|
||||
_ => None,
|
||||
};
|
||||
ensure_seen(registry, referenced.as_slice(), mode)?;
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
let Some(input) = slot_for_write(node, index as usize, timestamp, mode)? else { return Ok(()) };
|
||||
if timestamp > input.timestamp {
|
||||
input.input = new_input;
|
||||
input.timestamp = timestamp;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
if let Some(referenced) = referenced {
|
||||
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
|
||||
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
let input = node.inputs.get_mut(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
|
||||
if force || timestamp > input.timestamp {
|
||||
input.input = new_input;
|
||||
input.timestamp = timestamp;
|
||||
}
|
||||
}
|
||||
RegistryDelta::SetNodeImplementation { id, implementation } => {
|
||||
ensure_seen(registry, &[id], mode)?;
|
||||
if let Implementation::Network(network) = implementation {
|
||||
write_network(registry, network, timestamp, mode, |_| Ok(()))?;
|
||||
}
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
if timestamp > node.implementation_timestamp {
|
||||
node.implementation = implementation;
|
||||
node.implementation_timestamp = timestamp;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
RegistryDelta::ChangeNodeAttribute { id, delta } => {
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
apply_attribute_delta(delta, timestamp, &mut node.attributes, node.attributes_timestamp);
|
||||
Ok(())
|
||||
})?;
|
||||
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
apply_attribute_delta(delta, timestamp, force, &mut node.attributes);
|
||||
}
|
||||
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => {
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
let Some(input) = slot_for_write(node, index as usize, timestamp, mode)? else { return Ok(()) };
|
||||
apply_attribute_delta(delta, timestamp, &mut input.attributes, input.attributes_timestamp);
|
||||
Ok(())
|
||||
})?;
|
||||
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
let input = node.inputs.get_mut(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
|
||||
apply_attribute_delta(delta, timestamp, force, &mut input.attributes);
|
||||
}
|
||||
RegistryDelta::SetNetworkExport { id, index, export } => {
|
||||
let referenced = match export {
|
||||
Some(NodeInput::Node { id, .. }) => Some(id),
|
||||
_ => None,
|
||||
};
|
||||
ensure_seen(registry, referenced.as_slice(), mode)?;
|
||||
write_network(registry, id, timestamp, mode, |net| {
|
||||
let slot_idx = index as usize;
|
||||
if slot_idx >= net.exports.len() {
|
||||
if slot_idx >= MAX_EXPORT_SLOTS {
|
||||
return Err(CrdtError::ExportSlotOutOfBounds(index));
|
||||
}
|
||||
net.exports.resize(slot_idx + 1, ExportSlot::default());
|
||||
}
|
||||
let net = registry.networks.get_mut(&id).ok_or(CrdtError::NetworkDoesNotExist(id))?;
|
||||
let slot_idx = index as usize;
|
||||
|
||||
let existing = &mut net.exports[slot_idx];
|
||||
if timestamp > existing.timestamp {
|
||||
existing.target = export;
|
||||
existing.timestamp = timestamp;
|
||||
if slot_idx >= net.exports.len() {
|
||||
if slot_idx >= MAX_EXPORT_SLOTS {
|
||||
return Err(CrdtError::ExportSlotOutOfBounds(index));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
if let Some(referenced) = referenced {
|
||||
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
|
||||
net.exports.resize(
|
||||
slot_idx + 1,
|
||||
ExportSlot {
|
||||
target: None,
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let existing = &mut net.exports[slot_idx];
|
||||
if force || timestamp > existing.timestamp {
|
||||
existing.target = export;
|
||||
existing.timestamp = timestamp;
|
||||
}
|
||||
}
|
||||
RegistryDelta::AddNetwork { id, network } => {
|
||||
if live && registry.networks.contains_key(&id) {
|
||||
RegistryDelta::AddNetwork { id, network: contents } => {
|
||||
if registry.networks.contains_key(&id) {
|
||||
if idempotent {
|
||||
return Ok(());
|
||||
}
|
||||
return Err(CrdtError::NetworkAlreadyExists(id));
|
||||
}
|
||||
add(&mut registry.networks, &mut registry.removed_networks, id, network, timestamp);
|
||||
registry.networks.insert(id, contents);
|
||||
}
|
||||
RegistryDelta::RemoveNetwork { id, snapshot } => {
|
||||
remove(&mut registry.networks, &mut registry.removed_networks, id, snapshot, timestamp);
|
||||
RegistryDelta::RemoveNetwork { id, .. } => {
|
||||
registry.networks.remove(&id);
|
||||
}
|
||||
RegistryDelta::ChangeNetworkAttribute { id, delta } => {
|
||||
write_network(registry, id, timestamp, mode, |net| {
|
||||
apply_attribute_delta(delta, timestamp, &mut net.attributes, net.attributes_timestamp);
|
||||
Ok(())
|
||||
})?;
|
||||
let net = registry.networks.get_mut(&id).ok_or(CrdtError::NetworkDoesNotExist(id))?;
|
||||
apply_attribute_delta(delta, timestamp, force, &mut net.attributes);
|
||||
}
|
||||
RegistryDelta::SetResourceHash { id, hash } => {
|
||||
upsert_resource(registry, id, timestamp, |entry| {
|
||||
if timestamp > entry.hash_timestamp {
|
||||
entry.hash = hash;
|
||||
entry.hash_timestamp = timestamp;
|
||||
}
|
||||
});
|
||||
}
|
||||
RegistryDelta::AddSource { id, key, source } => {
|
||||
upsert_resource(registry, id, timestamp, |entry| {
|
||||
let value = SourceValue { source, timestamp, deleted: false };
|
||||
entry.set_source(key, value);
|
||||
});
|
||||
}
|
||||
RegistryDelta::RemoveSource { id, key } => {
|
||||
// An upsert, so a removal for an entry never seen leaves a tombstone its addition loses to.
|
||||
upsert_resource(registry, id, timestamp, |entry| {
|
||||
entry.remove_source(&key, timestamp);
|
||||
});
|
||||
}
|
||||
RegistryDelta::AddResource { id, entry } => {
|
||||
add(&mut registry.resources, &mut registry.removed_resources, id, entry, timestamp);
|
||||
}
|
||||
RegistryDelta::RemoveResource { id, snapshot } => {
|
||||
remove(&mut registry.resources, &mut registry.removed_resources, id, snapshot, timestamp);
|
||||
}
|
||||
RegistryDelta::RegisterPeer { peer, user } => {
|
||||
// The newest registration of a device wins, whatever order they land in.
|
||||
if registry.peer_users.get(&peer).is_none_or(|existing| timestamp > existing.at) {
|
||||
registry.peer_users.insert(peer, PeerRegistration { user, at: timestamp });
|
||||
let entry = registry.resources.entry(id).or_default();
|
||||
if force || timestamp > entry.hash_timestamp {
|
||||
entry.hash = hash;
|
||||
entry.hash_timestamp = timestamp;
|
||||
}
|
||||
}
|
||||
RegistryDelta::AddSource { id, key, source } => {
|
||||
let entry = registry.resources.entry(id).or_default();
|
||||
let value = SourceValue { source, timestamp };
|
||||
if force { entry.force_set_source(key, value) } else { entry.set_source(key, value) }
|
||||
}
|
||||
RegistryDelta::RemoveSource { id, key } => {
|
||||
if let Some(entry) = registry.resources.get_mut(&id) {
|
||||
if force {
|
||||
entry.force_remove_source(&key);
|
||||
} else {
|
||||
entry.remove_source(&key, timestamp);
|
||||
}
|
||||
}
|
||||
}
|
||||
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 } => {
|
||||
apply_attribute_delta(delta, timestamp, &mut registry.attributes, TimeStamp::ORIGIN);
|
||||
apply_attribute_delta(delta, timestamp, force, &mut registry.attributes);
|
||||
}
|
||||
// Merge is a structural sync point only; it mutates no registry state.
|
||||
RegistryDelta::Merge { .. } | RegistryDelta::EndTransaction | RegistryDelta::Other(_) => {}
|
||||
RegistryDelta::Merge { .. } | RegistryDelta::Other(_) => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// An entity whose existence and every field are last-writer-wins on a timestamp.
|
||||
pub(crate) trait Presence: Sized {
|
||||
/// The newest stamp of an addition or a write: the latest evidence the entity exists.
|
||||
fn presence(&self) -> TimeStamp;
|
||||
fn set_presence(&mut self, at: TimeStamp);
|
||||
/// Stamps every field at `at`, the way an addition writes all of them.
|
||||
fn stamp_all(&mut self, at: TimeStamp);
|
||||
/// Folds `other` in, keeping whichever value of each field is newer.
|
||||
fn merge(&mut self, other: Self);
|
||||
/// Dead content for an entity nothing has added yet, for writes to land on until an addition comes.
|
||||
/// Every field is at the origin, so the addition's values win.
|
||||
fn placeholder() -> Self;
|
||||
}
|
||||
|
||||
impl Presence for Node {
|
||||
fn presence(&self) -> TimeStamp {
|
||||
self.presence
|
||||
}
|
||||
fn set_presence(&mut self, at: TimeStamp) {
|
||||
self.presence = at;
|
||||
}
|
||||
fn placeholder() -> Self {
|
||||
Node::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(0)), 0)
|
||||
}
|
||||
fn stamp_all(&mut self, at: TimeStamp) {
|
||||
self.presence = at;
|
||||
self.added = at;
|
||||
self.inputs_timestamp = at;
|
||||
self.implementation_timestamp = at;
|
||||
self.inputs.iter_mut().for_each(|slot| stamp_slot(slot, at));
|
||||
stamp_attributes(&mut self.attributes, &mut self.attributes_timestamp, at);
|
||||
}
|
||||
fn merge(&mut self, other: Self) {
|
||||
if other.added > self.added {
|
||||
self.network = other.network;
|
||||
self.added = other.added;
|
||||
}
|
||||
if other.implementation_timestamp > self.implementation_timestamp {
|
||||
self.implementation = other.implementation;
|
||||
self.implementation_timestamp = other.implementation_timestamp;
|
||||
}
|
||||
merge_inputs(self, other.inputs, other.inputs_timestamp);
|
||||
merge_attributes(&mut self.attributes, &mut self.attributes_timestamp, other.attributes, other.attributes_timestamp);
|
||||
self.presence = self.presence.max(other.presence);
|
||||
}
|
||||
}
|
||||
|
||||
impl Presence for Network {
|
||||
fn presence(&self) -> TimeStamp {
|
||||
self.presence
|
||||
}
|
||||
fn set_presence(&mut self, at: TimeStamp) {
|
||||
self.presence = at;
|
||||
}
|
||||
fn placeholder() -> Self {
|
||||
Network::default()
|
||||
}
|
||||
fn stamp_all(&mut self, at: TimeStamp) {
|
||||
self.presence = at;
|
||||
self.exports.iter_mut().for_each(|slot| slot.timestamp = at);
|
||||
stamp_attributes(&mut self.attributes, &mut self.attributes_timestamp, at);
|
||||
}
|
||||
fn merge(&mut self, other: Self) {
|
||||
let len = self.exports.len().max(other.exports.len());
|
||||
self.exports.resize_with(len, ExportSlot::default);
|
||||
for (slot, incoming) in self.exports.iter_mut().zip(other.exports) {
|
||||
if incoming.timestamp > slot.timestamp {
|
||||
*slot = incoming;
|
||||
/// 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)?;
|
||||
}
|
||||
}
|
||||
merge_attributes(&mut self.attributes, &mut self.attributes_timestamp, other.attributes, other.attributes_timestamp);
|
||||
self.presence = self.presence.max(other.presence);
|
||||
}
|
||||
}
|
||||
|
||||
impl Presence for ResourceEntry {
|
||||
fn presence(&self) -> TimeStamp {
|
||||
self.presence
|
||||
}
|
||||
fn set_presence(&mut self, at: TimeStamp) {
|
||||
self.presence = at;
|
||||
}
|
||||
fn placeholder() -> Self {
|
||||
ResourceEntry::default()
|
||||
}
|
||||
fn stamp_all(&mut self, at: TimeStamp) {
|
||||
self.presence = at;
|
||||
self.hash_timestamp = at;
|
||||
self.stamp_sources(at);
|
||||
}
|
||||
fn merge(&mut self, other: Self) {
|
||||
if other.hash_timestamp > self.hash_timestamp {
|
||||
self.hash = other.hash;
|
||||
self.hash_timestamp = other.hash_timestamp;
|
||||
}
|
||||
self.merge_sources(other.sources, other.sources_timestamp);
|
||||
self.presence = self.presence.max(other.presence);
|
||||
}
|
||||
}
|
||||
|
||||
fn stamp_slot(slot: &mut InputSlot, at: TimeStamp) {
|
||||
slot.timestamp = at;
|
||||
stamp_attributes(&mut slot.attributes, &mut slot.attributes_timestamp, at);
|
||||
}
|
||||
|
||||
/// Writes the map whole at `at`: the floor deletes every other key without a tombstone per key.
|
||||
fn stamp_attributes(attributes: &mut Attributes, floor: &mut TimeStamp, at: TimeStamp) {
|
||||
attributes.retain(|_, value| !value.deleted);
|
||||
attributes.values_mut().for_each(|value| value.timestamp = at);
|
||||
*floor = at;
|
||||
}
|
||||
|
||||
/// Folds `other` in key by key. A key only one map holds is dead when the other map's floor is newer, since
|
||||
/// that map was written whole after it; an entry stamped exactly at a floor was written by that whole-map
|
||||
/// write and survives. Where both hold a key, the newer entry wins.
|
||||
fn merge_attributes(attributes: &mut Attributes, floor: &mut TimeStamp, other: Attributes, other_floor: TimeStamp) {
|
||||
attributes.retain(|_, value| value.timestamp >= other_floor);
|
||||
for (key, value) in other {
|
||||
match attributes.entry(key) {
|
||||
Entry::Occupied(entry) if value.timestamp > entry.get().timestamp => *entry.into_mut() = value,
|
||||
Entry::Vacant(entry) if value.timestamp >= *floor => {
|
||||
entry.insert(value);
|
||||
RegistryDelta::ChangeNodeAttribute { id, .. } | RegistryDelta::ChangeNodeInputAttribute { id, .. } => self.ensure_node_exists(target, *id)?,
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: network, export: export_target, ..
|
||||
} => {
|
||||
if let Some(NodeInput::Node { id: referenced, .. }) = export_target {
|
||||
self.ensure_node_exists(target, *referenced)?;
|
||||
}
|
||||
self.ensure_network_exists(target, *network)?;
|
||||
}
|
||||
RegistryDelta::ChangeNetworkAttribute { id: network, .. } => self.ensure_network_exists(target, *network)?,
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
*floor = (*floor).max(other_floor);
|
||||
}
|
||||
|
||||
/// Folds an input list stamped `at` into the node's. The newer list decides the slot count, except that a
|
||||
/// slot written after that shape still exists, with the gap up to it filled by unset slots stamped by the
|
||||
/// shape. A slot both lists hold keeps its newer value, and its attributes fold key by key. A whole-list
|
||||
/// write and a per-slot write thus land the same in either order.
|
||||
fn merge_inputs(node: &mut Node, other: Vec<InputSlot>, at: TimeStamp) {
|
||||
let (mut newer, shape, older) = if at > node.inputs_timestamp {
|
||||
(other, at, std::mem::take(&mut node.inputs))
|
||||
} else {
|
||||
(std::mem::take(&mut node.inputs), node.inputs_timestamp, other)
|
||||
};
|
||||
for (index, incoming) in older.into_iter().enumerate() {
|
||||
if index >= newer.len() {
|
||||
if slot_newest(&incoming) <= shape {
|
||||
continue;
|
||||
fn ensure_node_exists(&mut self, target: RegistryTarget, node_id: NodeId) -> Result<(), CrdtError> {
|
||||
if !self.registry_ref(target).node_instances.contains_key(&node_id) {
|
||||
self.restore_node_from_history(target, node_id)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_network_exists(&mut self, target: RegistryTarget, network_id: NetworkId) -> Result<(), CrdtError> {
|
||||
if !self.registry_ref(target).networks.contains_key(&network_id) {
|
||||
self.restore_network_from_history(target, network_id)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Compute the inverse of `delta` against the registry named by `target`. Retirement passes
|
||||
/// [`RegistryTarget::Snapshot`] so LWW reverses (export target, inputs, attributes, resource hash)
|
||||
/// capture the true pre-op value rather than the hot-polluted working state.
|
||||
pub(crate) fn compute_reverse_delta(&self, target: RegistryTarget, delta: &RegistryDelta) -> Result<RegistryDelta, CrdtError> {
|
||||
let registry = self.registry_ref(target);
|
||||
Ok(match delta {
|
||||
RegistryDelta::AddNode { id, node } => RegistryDelta::RemoveNode { id: *id, snapshot: node.clone() },
|
||||
RegistryDelta::RemoveNode { id, snapshot } => RegistryDelta::AddNode { id: *id, node: snapshot.clone() },
|
||||
&RegistryDelta::ChangeNodeInput { id, index: input_idx, .. } => {
|
||||
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
let slot = node.inputs().get(input_idx as usize).ok_or(CrdtError::InputIndexOutOfBounds(input_idx as usize))?;
|
||||
RegistryDelta::ChangeNodeInput {
|
||||
id,
|
||||
index: input_idx,
|
||||
new_input: slot.input.clone(),
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
merge_attributes(&mut slot.attributes, &mut slot.attributes_timestamp, incoming.attributes, incoming.attributes_timestamp);
|
||||
}
|
||||
node.inputs = newer;
|
||||
node.inputs_timestamp = shape;
|
||||
}
|
||||
|
||||
/// The newest write the slot carries, its attributes included.
|
||||
fn slot_newest(slot: &InputSlot) -> TimeStamp {
|
||||
slot.attributes
|
||||
.values()
|
||||
.map(|value| value.timestamp)
|
||||
.fold(slot.timestamp.max(slot.attributes_timestamp), TimeStamp::max)
|
||||
}
|
||||
|
||||
/// The slot at `index` for a write at `at`. A slot past the end comes into being when the write is newer
|
||||
/// than the list's shape, as in [`merge_inputs`], and is `None` when the shape is newer. For a fresh local
|
||||
/// edit the index is out of bounds.
|
||||
fn slot_for_write(node: &mut Node, index: usize, at: TimeStamp, mode: ApplyMode) -> Result<Option<&mut InputSlot>, CrdtError> {
|
||||
if index >= node.inputs.len() {
|
||||
if index >= MAX_INPUT_SLOTS || mode == ApplyMode::Live {
|
||||
return Err(CrdtError::InputIndexOutOfBounds(index));
|
||||
}
|
||||
if at <= node.inputs_timestamp {
|
||||
return Ok(None);
|
||||
}
|
||||
let shape = node.inputs_timestamp;
|
||||
node.inputs.resize_with(index + 1, || InputSlot::unset(shape));
|
||||
}
|
||||
Ok(node.inputs.get_mut(index))
|
||||
}
|
||||
|
||||
/// The entity's content wherever it sits: live, or held by its tombstone.
|
||||
fn content_mut<'a, K: Hash + Eq + Copy, T>(live: &'a mut HashMap<K, T>, dead: &'a mut HashMap<K, Tombstone<T>>, id: K) -> Option<&'a mut T> {
|
||||
live.get_mut(&id).or_else(|| dead.get_mut(&id).map(|mark| &mut mark.content))
|
||||
}
|
||||
|
||||
/// Brings a removed entity back when its presence has grown past its removal. A placeholder stays dead
|
||||
/// whatever its presence.
|
||||
fn settle<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K) {
|
||||
if dead.get(&id).is_some_and(|mark| !mark.placeholder && mark.content.presence() > mark.at) {
|
||||
let mark = dead.remove(&id).expect("checked above");
|
||||
live.insert(id, mark.content);
|
||||
}
|
||||
}
|
||||
|
||||
/// Folds `content` into whatever is held under `id`, or holds it as new. Content comes from an addition or
|
||||
/// a removal's snapshot, so it proves the entity was added and a placeholder holding it stops being one.
|
||||
fn fold<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, content: T) {
|
||||
if let Some(mark) = dead.get_mut(&id).filter(|mark| mark.placeholder) {
|
||||
// The placeholder holds only early writes: they land on the real content as if the addition came first.
|
||||
let early = std::mem::replace(&mut mark.content, content);
|
||||
mark.content.merge(early);
|
||||
mark.placeholder = false;
|
||||
} else if let Some(existing) = content_mut(live, dead, id) {
|
||||
existing.merge(content);
|
||||
} else {
|
||||
live.insert(id, content);
|
||||
}
|
||||
settle(live, dead, id);
|
||||
}
|
||||
|
||||
/// An addition at `at`: every field of `content` is written at `at`, and the entity exists from then
|
||||
/// unless a newer removal holds it dead.
|
||||
fn add<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, mut content: T, at: TimeStamp) {
|
||||
content.stamp_all(at);
|
||||
fold(live, dead, id, content);
|
||||
}
|
||||
|
||||
/// A removal at `at`: the entity is dead from then unless a newer addition or write holds it live. The
|
||||
/// snapshot folds in first, so a removal of an entity never seen still lands and its addition loses when
|
||||
/// it arrives.
|
||||
fn remove<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, snapshot: T, at: TimeStamp) {
|
||||
fold(live, dead, id, snapshot);
|
||||
if let Some(mark) = dead.get_mut(&id) {
|
||||
mark.at = mark.at.max(at);
|
||||
} else if live.get(&id).is_some_and(|content| at > content.presence()) {
|
||||
let content = live.remove(&id).expect("checked above");
|
||||
dead.insert(id, Tombstone { content, at, placeholder: false });
|
||||
}
|
||||
}
|
||||
|
||||
/// A write at `at` to the entity under `id`, applied by `write` to its content wherever it sits. The
|
||||
/// write is evidence the entity exists at `at`, so it revives an older removal. A write to an entity
|
||||
/// never seen lands on a placeholder tombstone that stays dead until an addition folds into it, so ops
|
||||
/// land the same in any order and nothing is deferred. For a fresh local edit the entity is `missing()`.
|
||||
fn write<K: Hash + Eq + Copy, T: Presence>(
|
||||
live: &mut HashMap<K, T>,
|
||||
dead: &mut HashMap<K, Tombstone<T>>,
|
||||
id: K,
|
||||
at: TimeStamp,
|
||||
mode: ApplyMode,
|
||||
missing: impl FnOnce() -> CrdtError,
|
||||
write: impl FnOnce(&mut T) -> Result<(), CrdtError>,
|
||||
) -> Result<(), CrdtError> {
|
||||
let unseen = !live.contains_key(&id) && !dead.contains_key(&id);
|
||||
if unseen {
|
||||
if mode == ApplyMode::Live {
|
||||
return Err(missing());
|
||||
}
|
||||
dead.insert(
|
||||
id,
|
||||
Tombstone {
|
||||
content: T::placeholder(),
|
||||
at: TimeStamp::ORIGIN,
|
||||
placeholder: true,
|
||||
&RegistryDelta::ChangeNodeAttribute { id, ref delta } => {
|
||||
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
RegistryDelta::ChangeNodeAttribute {
|
||||
id,
|
||||
delta: reverse_attribute_delta(delta, node.attributes()),
|
||||
}
|
||||
}
|
||||
&RegistryDelta::ChangeNodeInputAttribute { id, index, ref delta } => {
|
||||
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
let input = node.inputs().get(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
|
||||
RegistryDelta::ChangeNodeInputAttribute {
|
||||
id,
|
||||
index,
|
||||
delta: reverse_attribute_delta(delta, &input.attributes),
|
||||
}
|
||||
}
|
||||
&RegistryDelta::SetNetworkExport { id, index, .. } => {
|
||||
// If the network is absent the forward op will resurrect it; the reverse is "set the export to None"
|
||||
// since pre-forward there was no export to point at.
|
||||
let export_target = registry.networks.get(&id).and_then(|net| net.exports.get(index as usize)).and_then(|s| s.target.clone());
|
||||
RegistryDelta::SetNetworkExport { id, index, export: export_target }
|
||||
}
|
||||
RegistryDelta::AddNetwork { id, network } => RegistryDelta::RemoveNetwork { id: *id, snapshot: network.clone() },
|
||||
&RegistryDelta::RemoveNetwork { id, ref snapshot } => RegistryDelta::AddNetwork { id, network: snapshot.clone() },
|
||||
&RegistryDelta::ChangeNetworkAttribute { id, ref delta } => {
|
||||
let current = registry.networks.get(&id).map(|net| &net.attributes).ok_or(CrdtError::NetworkDoesNotExist(id))?;
|
||||
RegistryDelta::ChangeNetworkAttribute {
|
||||
id,
|
||||
delta: reverse_attribute_delta(delta, current),
|
||||
}
|
||||
}
|
||||
RegistryDelta::ChangeDocumentAttribute { delta } => RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: reverse_attribute_delta(delta, ®istry.attributes),
|
||||
},
|
||||
);
|
||||
}
|
||||
let content = content_mut(live, dead, id).expect("held above");
|
||||
if let Err(error) = write(content) {
|
||||
// A rejected op changes nothing, so the placeholder made for it goes too.
|
||||
if unseen {
|
||||
dead.remove(&id);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
content.set_presence(content.presence().max(at));
|
||||
settle(live, dead, id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A fresh local edit cannot name a node never seen. Checked before an op's first write, so a refused op changes nothing.
|
||||
fn ensure_seen(registry: &Registry, ids: &[NodeId], mode: ApplyMode) -> Result<(), CrdtError> {
|
||||
let unseen = |id: &&NodeId| !registry.node_instances.contains_key(id) && !registry.removed_nodes.contains_key(id);
|
||||
match ids.iter().find(unseen) {
|
||||
Some(&id) if mode == ApplyMode::Live => Err(CrdtError::TargetNodeDoesNotExist(id)),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`write()`] to a node; with a no-op `f`, records a reference to it.
|
||||
fn write_node(registry: &mut Registry, id: NodeId, at: TimeStamp, mode: ApplyMode, f: impl FnOnce(&mut Node) -> Result<(), CrdtError>) -> Result<(), CrdtError> {
|
||||
write(&mut registry.node_instances, &mut registry.removed_nodes, id, at, mode, || CrdtError::TargetNodeDoesNotExist(id), f)
|
||||
}
|
||||
|
||||
fn write_network(registry: &mut Registry, id: NetworkId, at: TimeStamp, mode: ApplyMode, f: impl FnOnce(&mut Network) -> Result<(), CrdtError>) -> Result<(), CrdtError> {
|
||||
write(&mut registry.networks, &mut registry.removed_networks, id, at, mode, || CrdtError::NetworkDoesNotExist(id), f)
|
||||
}
|
||||
|
||||
/// Like [`write()`] for a resource, except that an entry never seen is created first, since single-field
|
||||
/// resource ops are upserts. Every other field starts at the origin, so a later addition fills them in.
|
||||
fn upsert_resource(registry: &mut Registry, id: ResourceId, at: TimeStamp, f: impl FnOnce(&mut ResourceEntry)) {
|
||||
if !registry.resources.contains_key(&id) && !registry.removed_resources.contains_key(&id) {
|
||||
registry.resources.insert(
|
||||
id,
|
||||
ResourceEntry {
|
||||
presence: at,
|
||||
..ResourceEntry::default()
|
||||
// Registrations are append-only and not user-undoable; reverse is the same op,
|
||||
// which applies as a no-op on the already-registered PeerId.
|
||||
&RegistryDelta::RegisterPeer { peer, user } => RegistryDelta::RegisterPeer { peer, user },
|
||||
&RegistryDelta::SetResourceHash { id, .. } => RegistryDelta::SetResourceHash {
|
||||
id,
|
||||
hash: registry.resources.get(&id).and_then(|entry| entry.hash),
|
||||
},
|
||||
);
|
||||
&RegistryDelta::AddSource { id, key, .. } => match registry.resources.get(&id).and_then(|entry| entry.source(&key)) {
|
||||
// The slot already held a source: undo restores it.
|
||||
Some(existing) => RegistryDelta::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: existing.source.clone(),
|
||||
},
|
||||
// The slot was empty: undo removes what this op added.
|
||||
None => RegistryDelta::RemoveSource { id, key },
|
||||
},
|
||||
&RegistryDelta::RemoveSource { id, key } => match registry.resources.get(&id).and_then(|entry| entry.source(&key)) {
|
||||
Some(existing) => RegistryDelta::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: existing.source.clone(),
|
||||
},
|
||||
// Nothing to restore; reverse is a no-op removal.
|
||||
None => RegistryDelta::RemoveSource { id, key },
|
||||
},
|
||||
&RegistryDelta::AddResource { id, .. } => match registry.resources.get(&id) {
|
||||
// Overwrote an existing entry: undo restores it.
|
||||
Some(existing) => RegistryDelta::AddResource { id, entry: existing.clone() },
|
||||
// Created a new entry: undo removes what this op added (snapshot is empty since there was nothing prior).
|
||||
None => RegistryDelta::RemoveResource {
|
||||
id,
|
||||
snapshot: ResourceEntry::default(),
|
||||
},
|
||||
},
|
||||
&RegistryDelta::RemoveResource { id, .. } => {
|
||||
let snapshot = registry.resources.get(&id).cloned().unwrap_or_default();
|
||||
RegistryDelta::AddResource { id, entry: snapshot }
|
||||
}
|
||||
RegistryDelta::Merge { extra_parents } => RegistryDelta::Merge { extra_parents: extra_parents.clone() },
|
||||
&RegistryDelta::Other(_) => RegistryDelta::Other(serde_json::Value::Null),
|
||||
})
|
||||
}
|
||||
let entry = content_mut(&mut registry.resources, &mut registry.removed_resources, id).expect("held above");
|
||||
f(entry);
|
||||
entry.set_presence(entry.presence().max(at));
|
||||
settle(&mut registry.resources, &mut registry.removed_resources, id);
|
||||
}
|
||||
|
||||
/// Which of a [`Document`]'s two registries an apply targets: the working copy (retired state plus
|
||||
@@ -684,12 +439,13 @@ pub(crate) enum RegistryTarget {
|
||||
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)]
|
||||
pub(crate) enum ApplyMode {
|
||||
/// A fresh local edit: adding what exists, or writing to what was never seen, is an error, since a local
|
||||
/// edit cannot mean either.
|
||||
/// Fresh local/remote edit: structural ops error on duplicate/missing targets; LWW uses 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,
|
||||
/// Silent-zone undo/redo rewind: structural ops are idempotent and LWW arms assign unconditionally.
|
||||
Force,
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use core_types::Context;
|
||||
use core_types::context::ContextDependencies;
|
||||
use core_types::uuid::NodeId as RuntimeNodeId;
|
||||
use graph_craft::concrete;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
@@ -10,12 +9,9 @@ use serde::Serialize;
|
||||
|
||||
use crate::attr::*;
|
||||
use crate::metadata_source::{NoMetadata, NodeMetadataSource};
|
||||
use crate::{
|
||||
AttributesWrite, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ProtoNode, ROOT_NETWORK, Registry, ResourceHash, ResourceId, TimeStamp, Value,
|
||||
ValueError, from_value, to_value,
|
||||
};
|
||||
use crate::{AttributesWrite, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ProtoNode, ROOT_NETWORK, Registry, ResourceHash, ResourceId, TimeStamp};
|
||||
|
||||
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:?}"))
|
||||
}
|
||||
|
||||
@@ -43,7 +39,7 @@ impl NodePath {
|
||||
}
|
||||
|
||||
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 mut truncated = [0u8; 8];
|
||||
truncated.copy_from_slice(&digest.as_bytes()[..8]);
|
||||
@@ -55,7 +51,7 @@ impl NodePath {
|
||||
/// depending on traversal order. A domain tag keeps it from colliding with this node's own
|
||||
/// `to_global_id`. The root network is `ROOT_NETWORK` and never goes through here.
|
||||
fn owned_network_id(&self, peer: PeerId) -> NetworkId {
|
||||
let bytes = 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 mut truncated = [0u8; 8];
|
||||
truncated.copy_from_slice(&digest.as_bytes()[..8]);
|
||||
@@ -63,34 +59,6 @@ impl NodePath {
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves a node's storage identity: the identity the metadata source holds for it where there is
|
||||
/// one, and a hash of its location otherwise. Every place a node is named goes through here, so a
|
||||
/// node's own registry key and every reference to it agree.
|
||||
///
|
||||
/// A held identity travels with the node, so moving it between networks keeps it. A hashed one is
|
||||
/// derived from the node's place in the tree, so it changes when the node moves; it stands in for a
|
||||
/// node no source names, such as one in a network that has never been stored.
|
||||
pub(crate) struct NodeIds<'a, M: NodeMetadataSource + ?Sized> {
|
||||
pub(crate) metadata: Option<&'a M>,
|
||||
pub(crate) metadata_path: &'a [RuntimeNodeId],
|
||||
pub(crate) peer: PeerId,
|
||||
}
|
||||
|
||||
impl<M: NodeMetadataSource + ?Sized> Clone for NodeIds<'_, M> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
impl<M: NodeMetadataSource + ?Sized> Copy for NodeIds<'_, M> {}
|
||||
|
||||
impl<M: NodeMetadataSource + ?Sized> NodeIds<'_, M> {
|
||||
fn resolve(&self, path: &NodePath, local_id: RuntimeNodeId) -> NodeId {
|
||||
self.metadata
|
||||
.and_then(|metadata| metadata.storage_node_id(self.metadata_path, local_id))
|
||||
.unwrap_or_else(|| path.to_global_id(self.peer))
|
||||
}
|
||||
}
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ConversionError {
|
||||
#[error("Failed to serialize value: {0}")]
|
||||
@@ -120,29 +88,45 @@ impl TryFrom<&NodeNetwork> for Registry {
|
||||
pub type DeclarationBytes = HashMap<ResourceHash, Vec<u8>>;
|
||||
|
||||
/// A `from_runtime` conversion result: the reference-only [`Registry`] plus the proto-node
|
||||
/// declarations it extracted, as bytes keyed by content hash (for the caller's byte store) and as
|
||||
/// decoded [`ProtoNode`]s keyed by id (for the caller's declaration cache).
|
||||
/// declaration *bytes* it extracted, keyed by content hash. `document-graph-storage` doesn't own a byte
|
||||
/// store, so the caller (the `Gdd`) persists these into its content store; the registry only holds
|
||||
/// the `ResourceId`/`ResourceHash` references.
|
||||
pub struct RuntimeConversion {
|
||||
pub registry: Registry,
|
||||
pub declaration_bytes: DeclarationBytes,
|
||||
pub declarations: crate::Declarations,
|
||||
/// Each network's runtime `metadata_path` mapped to its stable storage `NetworkId`, for associating
|
||||
/// per-network, per-peer view state (`session.json`) without re-deriving ids.
|
||||
pub network_ids: HashMap<Vec<RuntimeNodeId>, NetworkId>,
|
||||
}
|
||||
|
||||
/// Encode a [`ProtoNode`] declaration to its content-addressed bytes: through the self-describing
|
||||
/// [`Value`] (so serde aliases keep working and the on-disk shape stays migratable), then postcard.
|
||||
/// Paired with [`decode_declaration`].
|
||||
impl RuntimeConversion {
|
||||
/// Rebuild the [`Declarations`](crate::Declarations) map (`ResourceId` → [`ProtoNode`]) from the
|
||||
/// extracted bytes, for callers that keep the bytes in hand instead of routing them through a
|
||||
/// byte store (tests, the round-trip CLI). Editor/`Gdd` paths persist the bytes and resolve via
|
||||
/// their byte store instead.
|
||||
pub fn declarations(&self) -> Result<crate::Declarations, ConversionError> {
|
||||
self.declaration_bytes
|
||||
.iter()
|
||||
.map(|(hash, bytes)| {
|
||||
let proto = decode_declaration(bytes).map_err(|error| ConversionError::SerializationError(format!("declaration {hash}: {error}")))?;
|
||||
Ok((ResourceId::from_hash(hash), proto))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode a [`ProtoNode`] declaration to its content-addressed bytes: through a self-describing
|
||||
/// `serde_json::Value` (so serde aliases keep working and the on-disk shape stays migratable), then
|
||||
/// rmp-serialized (which encodes the intermediate `Value` compactly). Paired with [`decode_declaration`].
|
||||
pub fn encode_declaration(proto: &ProtoNode) -> Result<Vec<u8>, String> {
|
||||
let value = to_value(proto).map_err(|error| error.to_string())?;
|
||||
postcard::to_stdvec(&value).map_err(|error| error.to_string())
|
||||
let value = serde_json::to_value(proto).map_err(|error| error.to_string())?;
|
||||
rmp_serde::to_vec(&value).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
/// Decode a [`ProtoNode`] declaration from the bytes [`encode_declaration`] produced.
|
||||
pub fn decode_declaration(bytes: &[u8]) -> Result<ProtoNode, String> {
|
||||
let value: Value = postcard::from_bytes(bytes).map_err(|error| error.to_string())?;
|
||||
from_value(&value).map_err(|error| error.to_string())
|
||||
let value: serde_json::Value = rmp_serde::from_slice(bytes).map_err(|error| error.to_string())?;
|
||||
serde_json::from_value(value).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
impl Registry {
|
||||
@@ -164,7 +148,6 @@ impl Registry {
|
||||
let mut ctx = ConversionContext {
|
||||
declaration_ids: HashMap::new(),
|
||||
declaration_bytes: HashMap::new(),
|
||||
declarations: HashMap::new(),
|
||||
network_ids: HashMap::new(),
|
||||
metadata,
|
||||
peer,
|
||||
@@ -183,7 +166,6 @@ impl Registry {
|
||||
Ok(RuntimeConversion {
|
||||
registry,
|
||||
declaration_bytes: ctx.declaration_bytes,
|
||||
declarations: ctx.declarations,
|
||||
network_ids: ctx.network_ids,
|
||||
})
|
||||
}
|
||||
@@ -192,49 +174,40 @@ impl Registry {
|
||||
/// Snapshot the runtime [`ResourceRegistry`](graphene_resource::ResourceRegistry) into the storage
|
||||
/// [`ResourceStore`](crate::ResourceStore). Each source's chain position becomes a fractional
|
||||
/// [`Priority`](crate::Priority) (index-as-priority preserves order); the `DataSource` body is
|
||||
/// stored type-erased as [`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.
|
||||
fn convert_resources(resources: &graphene_resource::ResourceRegistry, referenced: &std::collections::HashSet<ResourceId>, peer: PeerId, registry: &mut Registry) -> Result<(), ConversionError> {
|
||||
for id in resources.ids() {
|
||||
if !referenced.contains(&id) {
|
||||
continue;
|
||||
}
|
||||
if let Some(entry) = convert_resource_entry(resources, id, peer)? {
|
||||
registry.resources.insert(id, entry);
|
||||
let Some(info) = resources.info(&id) else { continue };
|
||||
|
||||
let mut entry = crate::ResourceEntry {
|
||||
hash: info.hash.copied(),
|
||||
hash_timestamp: TimeStamp::ORIGIN,
|
||||
..Default::default()
|
||||
};
|
||||
for (position, source) in info.sources.iter().enumerate() {
|
||||
let key = crate::SourceKey {
|
||||
priority: crate::Priority::new(position as f64).expect("enumerate index is finite"),
|
||||
peer,
|
||||
};
|
||||
let body = serde_json::to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
|
||||
entry.set_source(
|
||||
key,
|
||||
crate::SourceValue {
|
||||
source: body,
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
registry.resources.insert(id, entry);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Snapshot one runtime resource into a storage entry, or `None` if the runtime has no such resource.
|
||||
pub fn convert_resource_entry(resources: &graphene_resource::ResourceRegistry, id: ResourceId, peer: PeerId) -> Result<Option<crate::ResourceEntry>, ConversionError> {
|
||||
let Some(info) = resources.info(&id) else { return Ok(None) };
|
||||
|
||||
let mut entry = crate::ResourceEntry {
|
||||
hash: info.hash.copied(),
|
||||
hash_timestamp: TimeStamp::ORIGIN,
|
||||
..Default::default()
|
||||
};
|
||||
for (position, source) in info.sources.iter().enumerate() {
|
||||
let key = crate::SourceKey {
|
||||
priority: crate::Priority::new(position as f64).expect("enumerate index is finite"),
|
||||
peer,
|
||||
};
|
||||
let body = to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
|
||||
// Built rather than written: the chain is put in place as converted, floor and all at the origin.
|
||||
entry.force_set_source(
|
||||
key,
|
||||
crate::SourceValue {
|
||||
source: body,
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
deleted: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Ok(Some(entry))
|
||||
}
|
||||
|
||||
/// Collect the `ResourceId`s referenced by `TaggedValue::Resource` inputs anywhere in the network
|
||||
/// (recursively through nested networks). These are the resources the document actually uses; the
|
||||
/// runtime cache may hold more (history-retained orphans) that shouldn't be snapshotted into storage.
|
||||
@@ -280,8 +253,6 @@ struct ConversionContext<'m, M: NodeMetadataSource + ?Sized> {
|
||||
declaration_ids: HashMap<String, ResourceId>,
|
||||
/// Extracted declaration content keyed by hash, handed back for the caller's byte store.
|
||||
declaration_bytes: DeclarationBytes,
|
||||
/// The same declarations decoded, keyed by id, handed back for the caller's declaration cache.
|
||||
declarations: crate::Declarations,
|
||||
/// Maps each network's runtime `metadata_path` to its stable storage `NetworkId`, so the caller can
|
||||
/// associate per-network, per-peer view state (in `session.json`) with networks without re-deriving ids.
|
||||
network_ids: HashMap<Vec<RuntimeNodeId>, NetworkId>,
|
||||
@@ -289,20 +260,6 @@ struct ConversionContext<'m, M: NodeMetadataSource + ?Sized> {
|
||||
peer: PeerId,
|
||||
}
|
||||
|
||||
impl<'m, M: NodeMetadataSource + ?Sized> ConversionContext<'m, M> {
|
||||
/// The identity resolver for nodes addressed inside the network at `metadata_path`.
|
||||
fn ids<'a>(&self, metadata_path: &'a [RuntimeNodeId]) -> NodeIds<'a, M>
|
||||
where
|
||||
'm: 'a,
|
||||
{
|
||||
NodeIds {
|
||||
metadata: Some(self.metadata),
|
||||
metadata_path,
|
||||
peer: self.peer,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_network<M: NodeMetadataSource + ?Sized>(
|
||||
node_network: &NodeNetwork,
|
||||
network_id: NetworkId,
|
||||
@@ -313,7 +270,7 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
|
||||
) -> Result<(), ConversionError> {
|
||||
for (runtime_node_id, doc_node) in &node_network.nodes {
|
||||
let node_path = child_path(parent_path, network_id, *runtime_node_id);
|
||||
let global_id = ctx.ids(metadata_path).resolve(&node_path, *runtime_node_id);
|
||||
let global_id = node_path.to_global_id(ctx.peer);
|
||||
|
||||
let location = NodeLocation {
|
||||
network_id,
|
||||
@@ -321,8 +278,8 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
|
||||
metadata_path,
|
||||
runtime_node_id: *runtime_node_id,
|
||||
};
|
||||
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);
|
||||
let mut node = convert_node(doc_node, location, registry, ctx)?;
|
||||
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(runtime_node_id.0), TimeStamp::ORIGIN);
|
||||
registry.node_instances.insert(global_id, node);
|
||||
}
|
||||
|
||||
@@ -331,25 +288,17 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
|
||||
.iter()
|
||||
.map(|export| {
|
||||
Ok(ExportSlot {
|
||||
target: Some(convert_input(export, parent_path, network_id, ctx.ids(metadata_path))?),
|
||||
target: Some(convert_input(export, parent_path, network_id, ctx.peer)?),
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>, ConversionError>>()?;
|
||||
|
||||
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_scope_injections(&mut attributes, node_network, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
|
||||
write_ui_network_attributes(&mut attributes, ctx.metadata, metadata_path, TimeStamp::ORIGIN)?;
|
||||
write_scope_injections(&mut attributes, node_network, parent_path, network_id, ctx.peer, TimeStamp::ORIGIN)?;
|
||||
|
||||
registry.networks.insert(
|
||||
network_id,
|
||||
Network {
|
||||
presence: TimeStamp::ORIGIN,
|
||||
exports,
|
||||
attributes,
|
||||
attributes_timestamp: TimeStamp::ORIGIN,
|
||||
},
|
||||
);
|
||||
registry.networks.insert(network_id, Network { exports, attributes });
|
||||
ctx.network_ids.insert(metadata_path.to_vec(), network_id);
|
||||
|
||||
Ok(())
|
||||
@@ -358,12 +307,12 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
|
||||
/// Serialize a network's `scope_injections` onto its attributes as one whole-map LWW blob, remapping
|
||||
/// each runtime-local node reference to its stable storage global ID so the reference survives a
|
||||
/// round trip even if runtime IDs are later reshuffled.
|
||||
fn write_scope_injections<M: NodeMetadataSource + ?Sized>(
|
||||
fn write_scope_injections(
|
||||
attributes: &mut crate::Attributes,
|
||||
node_network: &NodeNetwork,
|
||||
parent_path: Option<&NodePath>,
|
||||
network_id: NetworkId,
|
||||
ids: NodeIds<'_, M>,
|
||||
peer: PeerId,
|
||||
timestamp: TimeStamp,
|
||||
) -> Result<(), ConversionError> {
|
||||
if node_network.scope_injections.is_empty() {
|
||||
@@ -374,7 +323,7 @@ fn write_scope_injections<M: NodeMetadataSource + ?Sized>(
|
||||
.scope_injections
|
||||
.iter()
|
||||
.map(|(key, (runtime_id, ty))| {
|
||||
let storage_id = ids.resolve(&child_path(parent_path, network_id, *runtime_id), *runtime_id);
|
||||
let storage_id = child_path(parent_path, network_id, *runtime_id).to_global_id(peer);
|
||||
(key.clone(), (storage_id, ty.clone()))
|
||||
})
|
||||
.collect();
|
||||
@@ -401,13 +350,7 @@ struct NodeLocation<'a> {
|
||||
runtime_node_id: RuntimeNodeId,
|
||||
}
|
||||
|
||||
fn convert_node<M: NodeMetadataSource + ?Sized>(
|
||||
doc_node: &DocumentNode,
|
||||
location: NodeLocation<'_>,
|
||||
registry: &mut Registry,
|
||||
ctx: &mut ConversionContext<'_, M>,
|
||||
recurse: bool,
|
||||
) -> Result<Node, ConversionError> {
|
||||
fn convert_node<M: NodeMetadataSource + ?Sized>(doc_node: &DocumentNode, location: NodeLocation<'_>, registry: &mut Registry, ctx: &mut ConversionContext<'_, M>) -> Result<Node, ConversionError> {
|
||||
let NodeLocation {
|
||||
network_id,
|
||||
parent_path,
|
||||
@@ -424,10 +367,9 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
|
||||
write_ui_input_attributes(&mut input_attrs, ctx.metadata, metadata_path, runtime_node_id, input_index, timestamp)?;
|
||||
|
||||
inputs.push(InputSlot {
|
||||
input: convert_input(input, parent_path, network_id, ctx.ids(metadata_path))?,
|
||||
input: convert_input(input, parent_path, network_id, ctx.peer)?,
|
||||
timestamp,
|
||||
attributes: input_attrs,
|
||||
attributes_timestamp: timestamp,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -440,16 +382,13 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
|
||||
} else {
|
||||
metadata_path
|
||||
};
|
||||
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)?;
|
||||
|
||||
// Defaults match `DocumentNode::default()`; `to_runtime` rehydrates absent keys from the same defaults.
|
||||
let mut attributes = crate::Attributes::new();
|
||||
attributes
|
||||
.set_if_not_default(node::CALL_ARGUMENT, &doc_node.call_argument, &concrete!(Context), timestamp)
|
||||
.map_err(map_serialization_error(node::CALL_ARGUMENT))?;
|
||||
attributes
|
||||
.set_if_not_default(node::CONTEXT_FEATURES, &doc_node.context_features, &ContextDependencies::default(), timestamp)
|
||||
.map_err(map_serialization_error(node::CONTEXT_FEATURES))?;
|
||||
attributes
|
||||
.set_if_not_default(node::VISIBLE, &doc_node.visible, &true, timestamp)
|
||||
.map_err(map_serialization_error(node::VISIBLE))?;
|
||||
@@ -460,58 +399,13 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
|
||||
write_ui_attributes(&mut attributes, ctx.metadata, metadata_path, runtime_node_id, timestamp)?;
|
||||
|
||||
Ok(Node {
|
||||
presence: timestamp,
|
||||
added: timestamp,
|
||||
inputs_timestamp: timestamp,
|
||||
implementation,
|
||||
implementation_timestamp: timestamp,
|
||||
inputs,
|
||||
attributes,
|
||||
attributes_timestamp: timestamp,
|
||||
network: network_id,
|
||||
})
|
||||
}
|
||||
|
||||
/// The `call_argument` attribute write for a node, cleared when the value is the default that
|
||||
/// `to_runtime` rehydrates an absent key from. For staging paths that encode this field alone.
|
||||
pub fn encode_call_argument(call_argument: &core_types::Type) -> Result<crate::AttributeDelta, ConversionError> {
|
||||
encode_if_not_default(node::CALL_ARGUMENT, call_argument, &concrete!(Context))
|
||||
}
|
||||
|
||||
/// The `context_features` attribute write, cleared at its default like [`encode_call_argument`].
|
||||
pub fn encode_context_features(context_features: &ContextDependencies) -> Result<crate::AttributeDelta, ConversionError> {
|
||||
encode_if_not_default(node::CONTEXT_FEATURES, context_features, &ContextDependencies::default())
|
||||
}
|
||||
|
||||
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))?) };
|
||||
|
||||
Ok(crate::AttributeDelta { key: key.to_string(), value })
|
||||
}
|
||||
|
||||
/// Public form of the node ui-attribute encoding, for staging paths that encode single nodes.
|
||||
pub fn encode_node_ui_attributes<M: NodeMetadataSource + ?Sized>(
|
||||
attributes: &mut crate::Attributes,
|
||||
metadata: &M,
|
||||
metadata_path: &[RuntimeNodeId],
|
||||
runtime_node_id: RuntimeNodeId,
|
||||
timestamp: TimeStamp,
|
||||
) -> Result<(), ConversionError> {
|
||||
write_ui_attributes(attributes, metadata, metadata_path, runtime_node_id, timestamp)
|
||||
}
|
||||
|
||||
/// Public form of the per-input ui-attribute encoding, matching `encode_node_ui_attributes`.
|
||||
pub fn encode_input_ui_attributes<M: NodeMetadataSource + ?Sized>(
|
||||
attributes: &mut crate::Attributes,
|
||||
metadata: &M,
|
||||
metadata_path: &[RuntimeNodeId],
|
||||
runtime_node_id: RuntimeNodeId,
|
||||
input_index: usize,
|
||||
timestamp: TimeStamp,
|
||||
) -> Result<(), ConversionError> {
|
||||
write_ui_input_attributes(attributes, metadata, metadata_path, runtime_node_id, input_index, timestamp)
|
||||
}
|
||||
|
||||
fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
|
||||
attributes: &mut crate::Attributes,
|
||||
metadata: &M,
|
||||
@@ -532,14 +426,14 @@ fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
|
||||
(node::ui::PINNED, metadata.pinned(metadata_path, runtime_node_id)),
|
||||
] {
|
||||
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)
|
||||
&& !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.
|
||||
@@ -553,34 +447,9 @@ fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Node references here are remapped to stable storage IDs for the same reason `write_scope_injections`
|
||||
/// does it: a runtime ID is not stable across a round trip.
|
||||
fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
|
||||
attributes: &mut crate::Attributes,
|
||||
node_network: &NodeNetwork,
|
||||
network_path: &[RuntimeNodeId],
|
||||
parent_path: Option<&NodePath>,
|
||||
network_id: NetworkId,
|
||||
ids: NodeIds<'_, M>,
|
||||
timestamp: TimeStamp,
|
||||
) -> Result<(), ConversionError> {
|
||||
// The same source the IDs resolve through, so a network's attributes and the nodes they name agree.
|
||||
let Some(metadata) = ids.metadata else { return Ok(()) };
|
||||
fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(attributes: &mut crate::Attributes, metadata: &M, network_path: &[RuntimeNodeId], timestamp: TimeStamp) -> Result<(), ConversionError> {
|
||||
if let Some(reference) = metadata.reference(network_path) {
|
||||
attributes.set(node::ui::REFERENCE, Value::Str(reference.to_string()), timestamp);
|
||||
}
|
||||
|
||||
let to_storage_id = |runtime_id: RuntimeNodeId| ids.resolve(&child_path(parent_path, network_id, runtime_id), runtime_id);
|
||||
|
||||
// Only nodes the converted network still holds: the read side drops a stored ID it cannot find, so
|
||||
// persisting one for a node deleted or reparented elsewhere would leave stored state disagreeing with
|
||||
// what a peer converting the same input produces.
|
||||
let pinned_order: Vec<_> = metadata.pinned_order(network_path).into_iter().filter(|pinned| node_network.nodes.contains_key(pinned)).collect();
|
||||
if !pinned_order.is_empty() {
|
||||
let stored: Vec<NodeId> = pinned_order.into_iter().map(to_storage_id).collect();
|
||||
attributes
|
||||
.set_serialized(network::PINNED_ORDER, &stored, timestamp)
|
||||
.map_err(map_serialization_error(network::PINNED_ORDER))?;
|
||||
attributes.set(node::ui::REFERENCE, serde_json::Value::String(reference.to_string()), timestamp);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -598,7 +467,7 @@ fn write_ui_input_attributes<M: NodeMetadataSource + ?Sized>(
|
||||
) -> Result<(), ConversionError> {
|
||||
let non_empty_string = |key: &'static str, value: Option<&str>, attributes: &mut crate::Attributes| {
|
||||
if let Some(value) = value.filter(|s| !s.is_empty()) {
|
||||
attributes.set(key, Value::Str(value.to_string()), timestamp);
|
||||
attributes.set(key, serde_json::Value::String(value.to_string()), timestamp);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -613,14 +482,14 @@ fn write_ui_input_attributes<M: NodeMetadataSource + ?Sized>(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn convert_input<M: NodeMetadataSource + ?Sized>(input: &GraphCraftNodeInput, parent_path: Option<&NodePath>, network_id: NetworkId, ids: NodeIds<'_, M>) -> Result<NodeInput, ConversionError> {
|
||||
fn convert_input(input: &GraphCraftNodeInput, parent_path: Option<&NodePath>, network_id: NetworkId, peer: PeerId) -> Result<NodeInput, ConversionError> {
|
||||
Ok(match input {
|
||||
GraphCraftNodeInput::Node { node_id, output_index } => NodeInput::Node {
|
||||
id: ids.resolve(&child_path(parent_path, network_id, *node_id), *node_id),
|
||||
id: child_path(parent_path, network_id, *node_id).to_global_id(peer),
|
||||
index: (*output_index).try_into().map_err(|_| ConversionError::IndexOverflow(*output_index))?,
|
||||
},
|
||||
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 }
|
||||
}
|
||||
GraphCraftNodeInput::Scope(s) => NodeInput::Scope(s.clone()),
|
||||
@@ -633,9 +502,7 @@ fn convert_input<M: NodeMetadataSource + ?Sized>(input: &GraphCraftNodeInput, pa
|
||||
})
|
||||
}
|
||||
|
||||
/// The non-ui attributes a slot carries, derived from the input itself: the declared type of an
|
||||
/// import, and a reflection node's metadata.
|
||||
pub fn convert_input_attributes(input: &GraphCraftNodeInput) -> Result<crate::Attributes, ConversionError> {
|
||||
fn convert_input_attributes(input: &GraphCraftNodeInput) -> Result<crate::Attributes, ConversionError> {
|
||||
let mut attributes = crate::Attributes::new();
|
||||
let timestamp = TimeStamp::ORIGIN;
|
||||
|
||||
@@ -662,7 +529,6 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
|
||||
child_metadata_path: &[RuntimeNodeId],
|
||||
registry: &mut Registry,
|
||||
ctx: &mut ConversionContext<'_, M>,
|
||||
recurse: bool,
|
||||
) -> Result<Implementation, ConversionError> {
|
||||
Ok(match implementation {
|
||||
DocumentNodeImplementation::ProtoNode(identifier) => {
|
||||
@@ -685,7 +551,6 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
|
||||
|
||||
register_declaration_resource(registry, id, hash, ctx.peer);
|
||||
ctx.declaration_bytes.insert(hash, bytes);
|
||||
ctx.declarations.insert(id, proto);
|
||||
ctx.declaration_ids.insert(identifier_str, id);
|
||||
|
||||
Implementation::ProtoNode(id)
|
||||
@@ -695,186 +560,10 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
|
||||
// `to_runtime` -> `from_runtime` round trip reproduces the same `NetworkId` (and thus the
|
||||
// same node-path hashes underneath it).
|
||||
let nested_network_id = current_node_path.owned_network_id(ctx.peer);
|
||||
if recurse {
|
||||
convert_network(nested_network, nested_network_id, Some(current_node_path), child_metadata_path, registry, ctx)?;
|
||||
}
|
||||
convert_network(nested_network, nested_network_id, Some(current_node_path), child_metadata_path, registry, ctx)?;
|
||||
Implementation::Network(nested_network_id)
|
||||
}
|
||||
// TODO: Support Extract in the Registry format.
|
||||
DocumentNodeImplementation::Extract => return Err(ConversionError::UnsupportedImplementation),
|
||||
})
|
||||
}
|
||||
|
||||
/// Derives the storage IDs for entities addressed by runtime network paths, resolving each through
|
||||
/// the same [`NodeIds`] a whole-document conversion uses so scoped and whole-document conversions agree.
|
||||
pub struct PathResolver<'m> {
|
||||
metadata: Option<&'m dyn NodeMetadataSource>,
|
||||
peer: PeerId,
|
||||
}
|
||||
|
||||
impl<'m> PathResolver<'m> {
|
||||
/// Without a metadata source every node falls back to a hash of its location, which only matches a
|
||||
/// whole-document conversion while no node has a stored identity.
|
||||
pub fn new(metadata: Option<&'m dyn NodeMetadataSource>, peer: PeerId) -> Self {
|
||||
Self { metadata, peer }
|
||||
}
|
||||
|
||||
/// The storage `NetworkId` of the network at `local_path` (`ROOT_NETWORK` for the empty path).
|
||||
pub fn network_id(&self, local_path: &[RuntimeNodeId]) -> NetworkId {
|
||||
match self.owner_path(local_path) {
|
||||
None => ROOT_NETWORK,
|
||||
Some(owner) => owner.owned_network_id(self.peer),
|
||||
}
|
||||
}
|
||||
|
||||
/// The storage `NodeId` of the node with `local_id` inside the network at `local_path`.
|
||||
pub fn node_id(&self, local_path: &[RuntimeNodeId], local_id: RuntimeNodeId) -> NodeId {
|
||||
let owner = self.owner_path(local_path);
|
||||
self.ids(local_path).resolve(&child_path(owner.as_ref(), self.network_id(local_path), local_id), local_id)
|
||||
}
|
||||
|
||||
/// Converts one runtime input inside the network at `local_path` to its storage form, resolving
|
||||
/// node references to their storage IDs.
|
||||
pub fn convert_input_at(&self, input: &GraphCraftNodeInput, local_path: &[RuntimeNodeId]) -> Result<NodeInput, ConversionError> {
|
||||
let owner = self.owner_path(local_path);
|
||||
convert_input(input, owner.as_ref(), self.network_id(local_path), self.ids(local_path))
|
||||
}
|
||||
|
||||
/// The identity resolver for nodes addressed inside the network at `local_path`.
|
||||
fn ids<'a>(&self, local_path: &'a [RuntimeNodeId]) -> NodeIds<'a, dyn NodeMetadataSource + 'm>
|
||||
where
|
||||
'm: 'a,
|
||||
{
|
||||
NodeIds {
|
||||
metadata: self.metadata,
|
||||
metadata_path: local_path,
|
||||
peer: self.peer,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `NodePath` of the node owning the network at `local_path`, or `None` for the root network.
|
||||
fn owner_path(&self, local_path: &[RuntimeNodeId]) -> Option<NodePath> {
|
||||
let mut owner: Option<NodePath> = None;
|
||||
for &local_id in local_path {
|
||||
let network_id = match &owner {
|
||||
None => ROOT_NETWORK,
|
||||
Some(owner) => owner.owned_network_id(self.peer),
|
||||
};
|
||||
owner = Some(child_path(owner.as_ref(), network_id, local_id));
|
||||
}
|
||||
owner
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a chosen subset of runtime entities into a scratch [`Registry`] through the same
|
||||
/// encoders as a whole-document conversion, so staging can derive deltas for just those entities.
|
||||
pub struct ScopedConversion<'m> {
|
||||
ctx: ConversionContext<'m, dyn NodeMetadataSource + 'm>,
|
||||
resolver: PathResolver<'m>,
|
||||
}
|
||||
|
||||
impl<'m> ScopedConversion<'m> {
|
||||
pub fn new(metadata: &'m dyn NodeMetadataSource, peer: PeerId) -> Self {
|
||||
Self {
|
||||
ctx: ConversionContext {
|
||||
declaration_ids: HashMap::new(),
|
||||
declaration_bytes: HashMap::new(),
|
||||
declarations: HashMap::new(),
|
||||
network_ids: HashMap::new(),
|
||||
metadata,
|
||||
peer,
|
||||
},
|
||||
resolver: PathResolver::new(Some(metadata), peer),
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts the node with `local_id` in the network at `local_path` into `registry` under its
|
||||
/// stable IDs. `recurse` also converts the contents of any nested network the node implements;
|
||||
/// without it only the node itself is converted, with its nested network referenced by ID.
|
||||
pub fn convert_node_at(&mut self, registry: &mut Registry, local_path: &[RuntimeNodeId], local_id: RuntimeNodeId, doc_node: &DocumentNode, recurse: bool) -> Result<(), ConversionError> {
|
||||
let owner_path = self.resolver.owner_path(local_path);
|
||||
let location = NodeLocation {
|
||||
network_id: self.resolver.network_id(local_path),
|
||||
parent_path: owner_path.as_ref(),
|
||||
metadata_path: local_path,
|
||||
runtime_node_id: local_id,
|
||||
};
|
||||
|
||||
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);
|
||||
registry.node_instances.insert(self.resolver.node_id(local_path, local_id), node);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Converts the entry of the network at `local_path` (its export slots and network-level
|
||||
/// attributes, not its nodes) into `registry`.
|
||||
pub fn convert_network_entry_at(&mut self, registry: &mut Registry, local_path: &[RuntimeNodeId], node_network: &NodeNetwork) -> Result<(), ConversionError> {
|
||||
let owner_path = self.resolver.owner_path(local_path);
|
||||
let network_id = self.resolver.network_id(local_path);
|
||||
|
||||
let exports = node_network
|
||||
.exports
|
||||
.iter()
|
||||
.map(|export| {
|
||||
Ok(ExportSlot {
|
||||
target: Some(convert_input(export, owner_path.as_ref(), network_id, self.ctx.ids(local_path))?),
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>, ConversionError>>()?;
|
||||
|
||||
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_scope_injections(&mut attributes, node_network, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
|
||||
|
||||
registry.networks.insert(
|
||||
network_id,
|
||||
Network {
|
||||
presence: TimeStamp::ORIGIN,
|
||||
exports,
|
||||
attributes,
|
||||
attributes_timestamp: TimeStamp::ORIGIN,
|
||||
},
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The extracted proto-node declarations: the bytes for the caller's byte store, and the same
|
||||
/// declarations decoded for its declaration cache.
|
||||
pub fn finish(self) -> (DeclarationBytes, crate::Declarations) {
|
||||
(self.ctx.declaration_bytes, self.ctx.declarations)
|
||||
}
|
||||
}
|
||||
|
||||
/// The `TaggedValue::Resource` IDs referenced by a stored node's value inputs.
|
||||
///
|
||||
/// Peeks at the externally-tagged serde shape (`{"Resource": <id>}`) rather than deserializing the
|
||||
/// whole `TaggedValue`, which can be arbitrarily large. `resource_ref_shape_matches_serde` asserts
|
||||
/// this stays in lockstep with the real serialization.
|
||||
pub fn node_value_resource_refs(node: &Node) -> impl Iterator<Item = ResourceId> + '_ {
|
||||
node.inputs.iter().filter_map(|slot| value_resource_ref(&slot.input))
|
||||
}
|
||||
|
||||
/// The `TaggedValue::Resource` ID referenced by a stored value input, if any.
|
||||
pub fn value_resource_ref(input: &NodeInput) -> Option<ResourceId> {
|
||||
match input {
|
||||
NodeInput::Value { value: Value::Object(fields), .. } => match fields.as_slice() {
|
||||
[(key, id)] if key == "Resource" => from_value(id).ok(),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod resource_ref_shape {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn resource_ref_shape_matches_serde() {
|
||||
let id = ResourceId::from_hash(&ResourceHash::from(b"shape test".as_slice()));
|
||||
let value = to_value(&TaggedValue::Resource(id)).expect("TaggedValue::Resource serializes");
|
||||
let parsed = value_resource_ref(&NodeInput::Value { value, exposed: false });
|
||||
assert_eq!(parsed, Some(id), "The shape peek in node_value_resource_refs must match TaggedValue's serde form");
|
||||
}
|
||||
}
|
||||
@@ -3,26 +3,21 @@
|
||||
//! [`History`] owns the deltas in topological order (every parent precedes its children) plus an
|
||||
//! index from [`Rev`] to position for O(1) lookup. The order is a valid replay order, so it is what
|
||||
//! gets serialized to the on-disk history file and what [`crate::Session::replay_from_history`]
|
||||
//! consumes. Appending a commit keeps the order; deltas arriving out of it are put back by
|
||||
//! a canonical sort.
|
||||
//! consumes. Retired commits have a single writer in every regime (solo editing, or leader-ordered
|
||||
//! collaboration where the leader serializes retired commits), so appending preserves the order by
|
||||
//! construction. The only operation that introduces out-of-order deltas is [`merge`](History::merge),
|
||||
//! which re-sorts the combined set into the canonical order to restore the invariant.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::{AttributesWrite, 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)]
|
||||
pub struct History {
|
||||
/// Deltas in topological order. Mutated only via [`push`](Self::push).
|
||||
deltas: Vec<Delta>,
|
||||
/// `Rev` to its position in `deltas`. Kept in sync with `deltas` by every mutator.
|
||||
index: HashMap<Rev, usize>,
|
||||
/// Every rev some delta names as a parent.
|
||||
referenced: HashSet<Rev>,
|
||||
/// Deltas no other delta names as a parent.
|
||||
tips: HashSet<Rev>,
|
||||
/// Content hashes the deltas name, from resource additions and removals.
|
||||
resource_hashes: HashSet<ResourceHash>,
|
||||
}
|
||||
|
||||
impl History {
|
||||
@@ -32,9 +27,8 @@ impl History {
|
||||
|
||||
/// Build from deltas already in topological order (the on-disk load path), indexing them in place.
|
||||
pub fn from_ordered(deltas: Vec<Delta>) -> Self {
|
||||
let mut history = Self::default();
|
||||
deltas.into_iter().for_each(|delta| history.push(delta));
|
||||
history
|
||||
let index = deltas.iter().enumerate().map(|(position, delta)| (delta.id, position)).collect();
|
||||
Self { deltas, index }
|
||||
}
|
||||
|
||||
pub fn get(&self, rev: Rev) -> Option<&Delta> {
|
||||
@@ -45,11 +39,6 @@ impl History {
|
||||
self.index.contains_key(&rev)
|
||||
}
|
||||
|
||||
/// The content hashes named by any resource addition or removal in history.
|
||||
pub fn resource_hashes(&self) -> &HashSet<ResourceHash> {
|
||||
&self.resource_hashes
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.deltas.len()
|
||||
}
|
||||
@@ -62,22 +51,10 @@ impl History {
|
||||
/// (idempotent re-apply) overwrites the existing entry in place rather than appending, so the
|
||||
/// order and index are unchanged.
|
||||
pub fn push(&mut self, delta: Delta) {
|
||||
match &delta.kind {
|
||||
RegistryDelta::AddResource { entry, .. } => self.resource_hashes.extend(entry.hash),
|
||||
RegistryDelta::RemoveResource { snapshot, .. } => self.resource_hashes.extend(snapshot.hash),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(&position) = self.index.get(&delta.id) {
|
||||
self.deltas[position] = delta;
|
||||
return;
|
||||
}
|
||||
for parent in delta.all_parents() {
|
||||
self.referenced.insert(parent);
|
||||
self.tips.remove(&parent);
|
||||
}
|
||||
if !self.referenced.contains(&delta.id) {
|
||||
self.tips.insert(delta.id);
|
||||
}
|
||||
self.index.insert(delta.id, self.deltas.len());
|
||||
self.deltas.push(delta);
|
||||
}
|
||||
@@ -87,24 +64,66 @@ impl History {
|
||||
self.deltas.iter()
|
||||
}
|
||||
|
||||
/// `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());
|
||||
/// Absorb `incoming` (dedup by `Rev`) and canonically re-sort the whole combined history.
|
||||
///
|
||||
/// The sort is deterministic (topological, ties broken by `Rev`), so two peers that absorb the same
|
||||
/// delta set produce byte-identical history, not merely two different valid orderings. This is the
|
||||
/// history-convergence mechanism: arrival order is erased. Callers update the registry separately
|
||||
/// (LWW apply is commutative, so the registry converges regardless of order).
|
||||
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) {
|
||||
for delta in incoming {
|
||||
self.push(delta);
|
||||
}
|
||||
self.canonical_sort();
|
||||
}
|
||||
|
||||
/// Re-order `deltas` into the canonical topological order and rebuild the index: parents precede
|
||||
/// children, and among deltas whose parents are all emitted the lowest `Rev` goes first. O(V + E).
|
||||
fn canonical_sort(&mut self) {
|
||||
// Unsatisfied in-history parent count per delta, plus reverse edges to decrement as parents emit.
|
||||
let mut pending_parents: HashMap<Rev, usize> = HashMap::with_capacity(self.deltas.len());
|
||||
let mut children: HashMap<Rev, Vec<Rev>> = HashMap::new();
|
||||
for delta in &self.deltas {
|
||||
let in_history_parents = delta.all_parents().filter(|parent| self.index.contains_key(parent)).count();
|
||||
pending_parents.insert(delta.id, in_history_parents);
|
||||
for parent in delta.all_parents() {
|
||||
if self.index.contains_key(&parent) {
|
||||
children.entry(parent).or_default().push(delta.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Ready set as a min-heap on `Rev` (via `Reverse`) so ties resolve deterministically.
|
||||
let mut ready: std::collections::BinaryHeap<std::cmp::Reverse<Rev>> = pending_parents.iter().filter(|(_, count)| **count == 0).map(|(rev, _)| std::cmp::Reverse(*rev)).collect();
|
||||
|
||||
let mut order: Vec<Rev> = Vec::with_capacity(self.deltas.len());
|
||||
while let Some(std::cmp::Reverse(rev)) = ready.pop() {
|
||||
order.push(rev);
|
||||
for child in children.get(&rev).into_iter().flatten() {
|
||||
let count = pending_parents.get_mut(child).expect("child is in history");
|
||||
*count -= 1;
|
||||
if *count == 0 {
|
||||
ready.push(std::cmp::Reverse(*child));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// `order` is a permutation of the existing revs, so reorder `deltas` to match and rebuild the index.
|
||||
let mut by_rev: HashMap<Rev, Delta> = self.deltas.drain(..).map(|delta| (delta.id, delta)).collect();
|
||||
self.index.clear();
|
||||
for (position, rev) in order.iter().enumerate() {
|
||||
if let Some(delta) = by_rev.remove(rev) {
|
||||
self.index.insert(*rev, position);
|
||||
self.deltas.push(delta);
|
||||
}
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
/// The current tips: revs that no other delta lists as a parent (the divergent heads). A linear
|
||||
/// history has exactly one tip; concurrent branches have several. Sorted ascending for determinism.
|
||||
pub fn tips(&self) -> Vec<Rev> {
|
||||
let 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
|
||||
}
|
||||
@@ -123,7 +142,7 @@ impl History {
|
||||
|
||||
/// Set a local annotation attribute (e.g. a commit message) on a retired delta in place. Excluded
|
||||
/// from the delta's `Rev`, so identity and the index are unchanged. Returns whether the delta was found.
|
||||
pub fn annotate(&mut self, rev: Rev, key: &str, value: 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) {
|
||||
Some(&position) => {
|
||||
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
|
||||
/// slot index forcing an unbounded `exports` allocation.
|
||||
pub(crate) const MAX_EXPORT_SLOTS: usize = 1 << 16;
|
||||
/// A per-slot write can bring a slot past the end of the list into being, so it is capped the same way.
|
||||
pub(crate) const MAX_INPUT_SLOTS: usize = 1 << 16;
|
||||
|
||||
/// Per-device identity. Stable per `(device, document)`. Used for CRDT tiebreaking and `NodeId`
|
||||
/// scoping. Globally unique across all peers ever in a document.
|
||||
@@ -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();
|
||||
parents.sort_unstable();
|
||||
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);
|
||||
let digest = hasher.finalize();
|
||||
|
||||
@@ -7,11 +7,9 @@ pub mod document;
|
||||
pub mod history;
|
||||
pub mod ids;
|
||||
pub mod model;
|
||||
mod prior;
|
||||
pub mod registry;
|
||||
pub mod resources;
|
||||
pub mod session;
|
||||
pub mod value;
|
||||
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub mod from_runtime;
|
||||
@@ -26,17 +24,12 @@ pub use document::*;
|
||||
pub use history::History;
|
||||
pub use ids::*;
|
||||
pub use model::*;
|
||||
pub use prior::{NetworkField, NodeField, Prior};
|
||||
pub use registry::*;
|
||||
pub use resources::*;
|
||||
pub use session::*;
|
||||
pub use value::{Value, ValueError, from_value, to_value};
|
||||
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub use from_runtime::{
|
||||
PathResolver, RuntimeConversion, ScopedConversion, convert_input_attributes, convert_resource_entry, decode_declaration, encode_declaration, encode_input_ui_attributes, encode_node_ui_attributes,
|
||||
node_value_resource_refs, value_resource_ref,
|
||||
};
|
||||
pub use from_runtime::{RuntimeConversion, decode_declaration, encode_declaration};
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position};
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
@@ -44,7 +37,6 @@ pub use to_runtime::Declarations;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
mod bookkeeping;
|
||||
mod crdt;
|
||||
mod round_trip;
|
||||
}
|
||||
@@ -8,17 +8,11 @@ use std::collections::HashMap;
|
||||
|
||||
use core_types::uuid::NodeId as RuntimeNodeId;
|
||||
|
||||
use crate::Value;
|
||||
|
||||
/// One node's editor-side metadata, produced by `Registry::to_runtime_with_metadata`. One entry per
|
||||
/// node, since every node carries an identity to restore even when it carries no `ui::*` attribute.
|
||||
/// One node's editor-side metadata, produced by `Registry::to_runtime_with_metadata`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct NodeMetadataEntry {
|
||||
pub network_path: Vec<RuntimeNodeId>,
|
||||
pub local_id: RuntimeNodeId,
|
||||
/// The node's storage identity. Restoring it pins the node to this identity, so a later conversion
|
||||
/// keeps it instead of re-deriving one from the node's location.
|
||||
pub storage_id: crate::NodeId,
|
||||
pub position: Option<Position>,
|
||||
pub is_layer: bool,
|
||||
pub display_name: Option<String>,
|
||||
@@ -30,7 +24,19 @@ pub struct NodeMetadataEntry {
|
||||
pub output_names: Vec<String>,
|
||||
}
|
||||
|
||||
/// Per-network metadata. Separate from `NodeMetadataEntry` since these are
|
||||
impl NodeMetadataEntry {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.position.is_none()
|
||||
&& !self.is_layer
|
||||
&& self.display_name.is_none()
|
||||
&& !self.locked
|
||||
&& !self.pinned
|
||||
&& self.output_names.is_empty()
|
||||
&& self.input_metadata.iter().all(InputMetadataEntry::is_empty)
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-network metadata (navigation, previewing). Separate from `NodeMetadataEntry` since these are
|
||||
/// properties of a network, not of any node.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct NetworkMetadataEntry {
|
||||
@@ -38,12 +44,16 @@ pub struct NetworkMetadataEntry {
|
||||
/// Empty = root network.
|
||||
pub network_path: Vec<RuntimeNodeId>,
|
||||
/// 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.
|
||||
/// (node-graph nav + previewing, in `session.json`) with a network across reparenting.
|
||||
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>,
|
||||
/// The display order of the network's pinned nodes.
|
||||
pub pinned_order: Vec<RuntimeNodeId>,
|
||||
}
|
||||
|
||||
impl NetworkMetadataEntry {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.reference.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-input editor metadata. Mirrors `InputPersistentMetadata` but wraps strings in `Option` so
|
||||
@@ -54,11 +64,17 @@ pub struct InputMetadataEntry {
|
||||
pub input_description: Option<String>,
|
||||
pub widget_override: Option<String>,
|
||||
/// Reassembled from `ui::input_data::<sub_key>` attributes.
|
||||
pub input_data: HashMap<String, Value>,
|
||||
pub input_data: HashMap<String, serde_json::Value>,
|
||||
}
|
||||
|
||||
impl InputMetadataEntry {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.input_name.is_none() && self.input_description.is_none() && self.widget_override.is_none() && self.input_data.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
fn position(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Option<Position> {
|
||||
None
|
||||
@@ -90,25 +106,13 @@ pub trait NodeMetadataSource {
|
||||
None
|
||||
}
|
||||
/// Returns owned to stay object-safe. Each entry is stored as `ui::input_data::<key>` for per-key LWW.
|
||||
fn input_data(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId, _input_index: usize) -> HashMap<String, Value> {
|
||||
fn input_data(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId, _input_index: usize) -> HashMap<String, serde_json::Value> {
|
||||
HashMap::new()
|
||||
}
|
||||
|
||||
/// The storage identity this node is pinned to, if it has one. A node the source does not name
|
||||
/// falls back to a hash of its location.
|
||||
fn storage_node_id(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Option<crate::NodeId> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The definition the network was instantiated from, if it still names one.
|
||||
fn reference(&self, _network_path: &[RuntimeNodeId]) -> Option<&str> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The display order of the network's pinned nodes.
|
||||
fn pinned_order(&self, _network_path: &[RuntimeNodeId]) -> Vec<RuntimeNodeId> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// No-op metadata source. Use when there's nothing to attach (synthetic networks, CLI tools).
|
||||
|
||||
@@ -1,30 +1,12 @@
|
||||
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 std::borrow::Cow;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Node {
|
||||
/// The latest addition or write, so a concurrent removal resolves by last-writer-wins rather than
|
||||
/// arrival order. See [`Registry::removed_nodes`](crate::Registry::removed_nodes).
|
||||
#[serde(default)]
|
||||
pub(crate) presence: TimeStamp,
|
||||
/// When the node was last added, which decides its network between concurrent additions of one id.
|
||||
#[serde(default)]
|
||||
pub(crate) added: TimeStamp,
|
||||
/// When the input list last changed shape, so whole-list and per-slot writes resolve the same in either
|
||||
/// order: the list follows the newer write, and a slot both lists held keeps its newer value.
|
||||
#[serde(default)]
|
||||
pub(crate) inputs_timestamp: TimeStamp,
|
||||
pub(crate) implementation: Implementation,
|
||||
/// When the implementation was last written, so a swap resolves by last-writer-wins rather than by
|
||||
/// the order ops happen to arrive in. Absent from documents written before swaps were expressible.
|
||||
#[serde(default)]
|
||||
pub(crate) implementation_timestamp: TimeStamp,
|
||||
pub(crate) inputs: Vec<InputSlot>,
|
||||
pub(crate) attributes: Attributes,
|
||||
/// When `attributes` was last written whole; see [`Attributes`].
|
||||
#[serde(default)]
|
||||
pub(crate) attributes_timestamp: TimeStamp,
|
||||
pub(crate) network: NetworkId,
|
||||
}
|
||||
|
||||
@@ -61,26 +43,14 @@ impl Node {
|
||||
attributes_value_equal(&self.attributes, &other.attributes)
|
||||
}
|
||||
|
||||
/// A node in `network` whose `inputs` slots are unset, for a caller that fills them in with
|
||||
/// `ChangeNodeInput`. The slot count is fixed at creation, since changing an input addresses a
|
||||
/// slot by position.
|
||||
pub fn new(network: NetworkId, implementation: Implementation, inputs: usize) -> Self {
|
||||
Self {
|
||||
presence: TimeStamp::ORIGIN,
|
||||
added: TimeStamp::ORIGIN,
|
||||
inputs_timestamp: TimeStamp::ORIGIN,
|
||||
implementation,
|
||||
implementation_timestamp: TimeStamp::ORIGIN,
|
||||
inputs: vec![InputSlot::unset(TimeStamp::ORIGIN); inputs],
|
||||
attributes: Attributes::new(),
|
||||
attributes_timestamp: TimeStamp::ORIGIN,
|
||||
network,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn dummy() -> Self {
|
||||
Self::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::new()), 0)
|
||||
Self {
|
||||
implementation: Implementation::ProtoNode(ResourceId::new()),
|
||||
inputs: vec![],
|
||||
attributes: Attributes::new(),
|
||||
network: crate::ROOT_NETWORK,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,26 +61,6 @@ pub struct InputSlot {
|
||||
pub input: NodeInput,
|
||||
pub timestamp: TimeStamp,
|
||||
pub attributes: Attributes,
|
||||
/// When `attributes` was last written whole; see [`Attributes`].
|
||||
#[serde(default)]
|
||||
pub attributes_timestamp: TimeStamp,
|
||||
}
|
||||
|
||||
impl InputSlot {
|
||||
/// A slot holding nothing, stamped `at`.
|
||||
pub fn unset(at: TimeStamp) -> Self {
|
||||
// `to_runtime` reads this back as a `TaggedValue`, whose unit `None` variant encodes as this string.
|
||||
// Pinned by `unset_input_slot_deserializes_as_tagged_value_none`.
|
||||
Self {
|
||||
input: NodeInput::Value {
|
||||
value: Value::Str("None".to_string()),
|
||||
exposed: false,
|
||||
},
|
||||
timestamp: at,
|
||||
attributes: Attributes::new(),
|
||||
attributes_timestamp: at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -120,7 +70,7 @@ pub enum NodeInput {
|
||||
index: u32,
|
||||
},
|
||||
Value {
|
||||
value: Value,
|
||||
value: serde_json::Value,
|
||||
exposed: bool,
|
||||
},
|
||||
Scope(Cow<'static, str>),
|
||||
@@ -142,16 +92,10 @@ pub enum Implementation {
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Network {
|
||||
/// The latest addition or write; see [`Node::presence`](crate::Node).
|
||||
#[serde(default)]
|
||||
pub(crate) presence: TimeStamp,
|
||||
pub exports: Vec<ExportSlot>,
|
||||
/// Per-network `ui::*` state (navigation, previewing). Separate from `Node.attributes` so
|
||||
/// view-state edits LWW independently.
|
||||
pub attributes: Attributes,
|
||||
/// When `attributes` was last written whole; see [`Attributes`].
|
||||
#[serde(default)]
|
||||
pub attributes_timestamp: TimeStamp,
|
||||
}
|
||||
|
||||
impl Network {
|
||||
@@ -176,7 +120,7 @@ impl Network {
|
||||
|
||||
/// One positional export slot. `target == None` marks an empty/removed slot. Timestamp drives LWW
|
||||
/// on concurrent `SetExport` ops.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ExportSlot {
|
||||
pub target: Option<NodeInput>,
|
||||
pub timestamp: TimeStamp,
|
||||
@@ -210,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
|
||||
/// the same network without that slot, so the soak oracle doesn't false-report drift.
|
||||
#[test]
|
||||
|
||||
@@ -1,304 +0,0 @@
|
||||
use crate::{
|
||||
AttributeValue, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, TimeStamp,
|
||||
Tombstone,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::hash::Hash;
|
||||
|
||||
/// What a slot held before a delta wrote it, with its own stamps. Undo puts these back as they were, bypassing
|
||||
/// LWW, so the registry is again exactly what folding history up to the delta's parent gives. Never sent or
|
||||
/// applied as an op.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum Prior {
|
||||
/// The whole entity, live or tombstoned. `None, None` means it didn't exist, so undoing an addition leaves no
|
||||
/// tombstone behind.
|
||||
Node {
|
||||
id: NodeId,
|
||||
live: Option<Node>,
|
||||
removed: Option<Tombstone<Node>>,
|
||||
},
|
||||
Network {
|
||||
id: NetworkId,
|
||||
live: Option<Network>,
|
||||
removed: Option<Tombstone<Network>>,
|
||||
},
|
||||
Resource {
|
||||
id: ResourceId,
|
||||
live: Option<ResourceEntry>,
|
||||
removed: Option<Tombstone<ResourceEntry>>,
|
||||
},
|
||||
/// One field of a live node, and the node's presence, which every write moves.
|
||||
NodeField {
|
||||
id: NodeId,
|
||||
presence: TimeStamp,
|
||||
field: NodeField,
|
||||
},
|
||||
/// One field of a live network, and its presence.
|
||||
NetworkField {
|
||||
id: NetworkId,
|
||||
presence: TimeStamp,
|
||||
field: NetworkField,
|
||||
},
|
||||
DocumentAttribute {
|
||||
key: String,
|
||||
previous: Option<AttributeValue>,
|
||||
},
|
||||
PeerUser {
|
||||
peer: PeerId,
|
||||
previous: Option<PeerRegistration>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum NodeField {
|
||||
/// Only the presence moved, by a reference from another entity's op.
|
||||
Presence,
|
||||
Attribute {
|
||||
key: String,
|
||||
previous: Option<AttributeValue>,
|
||||
},
|
||||
Input {
|
||||
index: u32,
|
||||
previous: InputSlot,
|
||||
},
|
||||
InputAttribute {
|
||||
index: u32,
|
||||
key: String,
|
||||
previous: Option<AttributeValue>,
|
||||
},
|
||||
Inputs {
|
||||
previous: Vec<InputSlot>,
|
||||
inputs_timestamp: TimeStamp,
|
||||
},
|
||||
Implementation {
|
||||
previous: Implementation,
|
||||
implementation_timestamp: TimeStamp,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum NetworkField {
|
||||
/// Only the presence moved, by a node added to or implemented by it.
|
||||
Presence,
|
||||
Attribute {
|
||||
key: String,
|
||||
previous: Option<AttributeValue>,
|
||||
},
|
||||
Exports {
|
||||
previous: Vec<ExportSlot>,
|
||||
},
|
||||
}
|
||||
|
||||
/// What `op` is about to write in `registry`, in write order. Taken before the op applies.
|
||||
pub(crate) fn capture(registry: &Registry, op: &RegistryDelta) -> Vec<Prior> {
|
||||
let mut priors = Vec::new();
|
||||
let node_input = |input: &NodeInput| match input {
|
||||
NodeInput::Node { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
};
|
||||
match op {
|
||||
RegistryDelta::AddNode { id, node } => {
|
||||
priors.push(network_field(registry, node.network, |_| NetworkField::Presence));
|
||||
priors.push(whole_node(registry, *id));
|
||||
}
|
||||
RegistryDelta::RemoveNode { id, .. } => priors.push(whole_node(registry, *id)),
|
||||
RegistryDelta::SetNodeInputs { id, inputs } => {
|
||||
priors.push(node_field(registry, *id, |node| NodeField::Inputs {
|
||||
previous: node.inputs.clone(),
|
||||
inputs_timestamp: node.inputs_timestamp,
|
||||
}));
|
||||
priors.extend(
|
||||
inputs
|
||||
.iter()
|
||||
.filter_map(|slot| node_input(&slot.input))
|
||||
.map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)),
|
||||
);
|
||||
}
|
||||
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
|
||||
priors.push(node_field(registry, *id, |node| {
|
||||
input_field(node, *index, |slot| NodeField::Input {
|
||||
index: *index,
|
||||
previous: slot.clone(),
|
||||
})
|
||||
}));
|
||||
priors.extend(node_input(new_input).map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)));
|
||||
}
|
||||
RegistryDelta::SetNodeImplementation { id, implementation } => {
|
||||
if let Implementation::Network(network) = implementation {
|
||||
priors.push(network_field(registry, *network, |_| NetworkField::Presence));
|
||||
}
|
||||
priors.push(node_field(registry, *id, |node| NodeField::Implementation {
|
||||
previous: node.implementation.clone(),
|
||||
implementation_timestamp: node.implementation_timestamp,
|
||||
}));
|
||||
}
|
||||
RegistryDelta::ChangeNodeAttribute { id, delta } => priors.push(node_field(registry, *id, |node| NodeField::Attribute {
|
||||
key: delta.key.clone(),
|
||||
previous: node.attributes.get(&delta.key).cloned(),
|
||||
})),
|
||||
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => priors.push(node_field(registry, *id, |node| {
|
||||
input_field(node, *index, |slot| NodeField::InputAttribute {
|
||||
index: *index,
|
||||
key: delta.key.clone(),
|
||||
previous: slot.attributes.get(&delta.key).cloned(),
|
||||
})
|
||||
})),
|
||||
RegistryDelta::SetNetworkExport { id, export, .. } => {
|
||||
priors.push(network_field(registry, *id, |network| NetworkField::Exports { previous: network.exports.clone() }));
|
||||
priors.extend(export.as_ref().and_then(node_input).map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)));
|
||||
}
|
||||
RegistryDelta::AddNetwork { id, .. } | RegistryDelta::RemoveNetwork { id, .. } => priors.push(whole_network(registry, *id)),
|
||||
RegistryDelta::ChangeNetworkAttribute { id, delta } => {
|
||||
priors.push(network_field(registry, *id, |network| NetworkField::Attribute {
|
||||
key: delta.key.clone(),
|
||||
previous: network.attributes.get(&delta.key).cloned(),
|
||||
}));
|
||||
}
|
||||
RegistryDelta::AddResource { id, .. }
|
||||
| RegistryDelta::RemoveResource { id, .. }
|
||||
| RegistryDelta::SetResourceHash { id, .. }
|
||||
| RegistryDelta::AddSource { id, .. }
|
||||
| RegistryDelta::RemoveSource { id, .. } => priors.push(Prior::Resource {
|
||||
id: *id,
|
||||
live: registry.resources.get(id).cloned(),
|
||||
removed: registry.removed_resources.get(id).cloned(),
|
||||
}),
|
||||
RegistryDelta::RegisterPeer { peer, .. } => priors.push(Prior::PeerUser {
|
||||
peer: *peer,
|
||||
previous: registry.peer_users.get(peer).copied(),
|
||||
}),
|
||||
RegistryDelta::ChangeDocumentAttribute { delta } => priors.push(Prior::DocumentAttribute {
|
||||
key: delta.key.clone(),
|
||||
previous: registry.attributes.get(&delta.key).cloned(),
|
||||
}),
|
||||
RegistryDelta::Merge { .. } | RegistryDelta::EndTransaction | RegistryDelta::Other(_) => {}
|
||||
}
|
||||
priors
|
||||
}
|
||||
|
||||
/// Puts back what `priors` recorded, newest write first.
|
||||
pub(crate) fn restore(registry: &mut Registry, priors: &[Prior]) {
|
||||
for prior in priors.iter().rev() {
|
||||
match prior {
|
||||
Prior::Node { id, live, removed } => put_whole(&mut registry.node_instances, &mut registry.removed_nodes, *id, live.as_ref(), removed.as_ref()),
|
||||
Prior::Network { id, live, removed } => put_whole(&mut registry.networks, &mut registry.removed_networks, *id, live.as_ref(), removed.as_ref()),
|
||||
Prior::Resource { id, live, removed } => put_whole(&mut registry.resources, &mut registry.removed_resources, *id, live.as_ref(), removed.as_ref()),
|
||||
Prior::NodeField { id, presence, field } => {
|
||||
let Some(node) = registry.node_instances.get_mut(id) else {
|
||||
debug_assert!(false, "a field prior is taken from a live node, which the later priors put back");
|
||||
continue;
|
||||
};
|
||||
node.presence = *presence;
|
||||
match field {
|
||||
NodeField::Presence => {}
|
||||
NodeField::Attribute { key, previous } => put_attribute(&mut node.attributes, key, previous.as_ref()),
|
||||
NodeField::Input { index, previous } => {
|
||||
if let Some(slot) = node.inputs.get_mut(*index as usize) {
|
||||
*slot = previous.clone();
|
||||
}
|
||||
}
|
||||
NodeField::InputAttribute { index, key, previous } => {
|
||||
if let Some(slot) = node.inputs.get_mut(*index as usize) {
|
||||
put_attribute(&mut slot.attributes, key, previous.as_ref());
|
||||
}
|
||||
}
|
||||
NodeField::Inputs { previous, inputs_timestamp } => {
|
||||
node.inputs = previous.clone();
|
||||
node.inputs_timestamp = *inputs_timestamp;
|
||||
}
|
||||
NodeField::Implementation { previous, implementation_timestamp } => {
|
||||
node.implementation = previous.clone();
|
||||
node.implementation_timestamp = *implementation_timestamp;
|
||||
}
|
||||
}
|
||||
}
|
||||
Prior::NetworkField { id, presence, field } => {
|
||||
let Some(network) = registry.networks.get_mut(id) else {
|
||||
debug_assert!(false, "a field prior is taken from a live network, which the later priors put back");
|
||||
continue;
|
||||
};
|
||||
network.presence = *presence;
|
||||
match field {
|
||||
NetworkField::Presence => {}
|
||||
NetworkField::Attribute { key, previous } => put_attribute(&mut network.attributes, key, previous.as_ref()),
|
||||
NetworkField::Exports { previous } => network.exports = previous.clone(),
|
||||
}
|
||||
}
|
||||
Prior::DocumentAttribute { key, previous } => put_attribute(&mut registry.attributes, key, previous.as_ref()),
|
||||
Prior::PeerUser { peer, previous } => match previous {
|
||||
Some(registration) => _ = registry.peer_users.insert(*peer, *registration),
|
||||
None => _ = registry.peer_users.remove(peer),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn whole_node(registry: &Registry, id: NodeId) -> Prior {
|
||||
Prior::Node {
|
||||
id,
|
||||
live: registry.node_instances.get(&id).cloned(),
|
||||
removed: registry.removed_nodes.get(&id).cloned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn whole_network(registry: &Registry, id: NetworkId) -> Prior {
|
||||
Prior::Network {
|
||||
id,
|
||||
live: registry.networks.get(&id).cloned(),
|
||||
removed: registry.removed_networks.get(&id).cloned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// One field of a live node; anything else, a write that lands on a tombstone or a placeholder, records the
|
||||
/// whole entity.
|
||||
fn node_field(registry: &Registry, id: NodeId, field: impl FnOnce(&Node) -> NodeField) -> Prior {
|
||||
match registry.node_instances.get(&id) {
|
||||
Some(node) => Prior::NodeField {
|
||||
id,
|
||||
presence: node.presence,
|
||||
field: field(node),
|
||||
},
|
||||
None => whole_node(registry, id),
|
||||
}
|
||||
}
|
||||
|
||||
fn network_field(registry: &Registry, id: NetworkId, field: impl FnOnce(&Network) -> NetworkField) -> Prior {
|
||||
match registry.networks.get(&id) {
|
||||
Some(network) => Prior::NetworkField {
|
||||
id,
|
||||
presence: network.presence,
|
||||
field: field(network),
|
||||
},
|
||||
None => whole_network(registry, id),
|
||||
}
|
||||
}
|
||||
|
||||
/// A write to one slot, or to the whole list when the slot doesn't exist yet, since writing past the end grows it.
|
||||
fn input_field(node: &Node, index: u32, field: impl FnOnce(&InputSlot) -> NodeField) -> NodeField {
|
||||
match node.inputs.get(index as usize) {
|
||||
Some(slot) => field(slot),
|
||||
None => NodeField::Inputs {
|
||||
previous: node.inputs.clone(),
|
||||
inputs_timestamp: node.inputs_timestamp,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn put_whole<K: Hash + Eq + Copy, T: Clone>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, was_live: Option<&T>, was_removed: Option<&Tombstone<T>>) {
|
||||
match was_live {
|
||||
Some(content) => _ = live.insert(id, content.clone()),
|
||||
None => _ = live.remove(&id),
|
||||
}
|
||||
match was_removed {
|
||||
Some(mark) => _ = dead.insert(id, mark.clone()),
|
||||
None => _ = dead.remove(&id),
|
||||
}
|
||||
}
|
||||
|
||||
fn put_attribute(attributes: &mut crate::Attributes, key: &str, previous: Option<&AttributeValue>) {
|
||||
match previous {
|
||||
Some(value) => _ = attributes.insert(key.to_string(), value.clone()),
|
||||
None => _ = attributes.remove(key),
|
||||
}
|
||||
}
|
||||
@@ -1,13 +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 std::collections::HashMap;
|
||||
|
||||
/// The live document: what exists and what it holds.
|
||||
///
|
||||
/// Every field is last-writer-wins on a timestamp, including whether an entity exists, so the registry
|
||||
/// depends on the set of ops applied and not their order. A removed entity keeps a tombstone stamped with
|
||||
/// the removal: an op stamped earlier is dropped in either arrival order, and one stamped later revives the
|
||||
/// entity from it. The live maps hold only what exists.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Registry {
|
||||
pub node_instances: HashMap<NodeId, Node>,
|
||||
@@ -15,55 +9,13 @@ pub struct Registry {
|
||||
/// Content-addressable resources (images, fonts, eventually proto-node declarations) referenced
|
||||
/// by `ResourceId`. See [`ResourceStore`].
|
||||
pub resources: ResourceStore,
|
||||
/// Which person each device is, registered via `RegistryDelta::RegisterPeer` by a device's first
|
||||
/// contribution and whenever its user changes. Lets undo and history authorship scope by person across
|
||||
/// the peer ids one person accumulates.
|
||||
pub peer_users: HashMap<PeerId, PeerRegistration>,
|
||||
/// Append-only mapping from per-device `PeerId` to per-human `UserId`.
|
||||
/// Registered by each device's first contribution via `RegistryDelta::RegisterPeer`.
|
||||
pub peer_users: HashMap<PeerId, UserId>,
|
||||
pub attributes: Attributes,
|
||||
/// Tombstones of removed nodes, so an op on one is ordered against its removal whichever arrives first.
|
||||
#[serde(default)]
|
||||
pub removed_nodes: HashMap<NodeId, Tombstone<Node>>,
|
||||
/// Tombstones of removed networks; see [`removed_nodes`](Self::removed_nodes).
|
||||
#[serde(default)]
|
||||
pub removed_networks: HashMap<NetworkId, Tombstone<Network>>,
|
||||
/// Tombstones of removed resources; see [`removed_nodes`](Self::removed_nodes).
|
||||
#[serde(default)]
|
||||
pub removed_resources: HashMap<ResourceId, Tombstone<ResourceEntry>>,
|
||||
}
|
||||
|
||||
/// A device's registration to a person, and when it was made.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PeerRegistration {
|
||||
pub user: UserId,
|
||||
pub at: TimeStamp,
|
||||
}
|
||||
|
||||
/// A removed entity: its content, for reviving it, and when it was removed, for ordering later-arriving
|
||||
/// ops against the removal.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Tombstone<T> {
|
||||
pub content: T,
|
||||
pub at: TimeStamp,
|
||||
/// Nothing has added the entity yet, so it stays dead until an addition folds in; the content only holds
|
||||
/// writes that arrived ahead of it. See [`Registry::removed_nodes`].
|
||||
#[serde(default)]
|
||||
pub placeholder: bool,
|
||||
}
|
||||
|
||||
impl Registry {
|
||||
/// The node under `id`, live or as it was when removed. For a reference to a node the runtime cannot
|
||||
/// hold, which still needs the id the node had there.
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub(crate) fn node_or_removed(&self, id: NodeId) -> Option<&Node> {
|
||||
self.node_instances.get(&id).or_else(|| self.removed_nodes.get(&id).map(|mark| &mark.content))
|
||||
}
|
||||
|
||||
/// The network under `id`, live or as it was when removed.
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub(crate) fn network_or_removed(&self, id: NetworkId) -> Option<&Network> {
|
||||
self.networks.get(&id).or_else(|| self.removed_networks.get(&id).map(|mark| &mark.content))
|
||||
}
|
||||
|
||||
/// True if both registries agree on every value-bearing field, ignoring per-slot and
|
||||
/// per-attribute timestamps. Mirrors `compute_deltas`'s value-only semantics, so unchanged
|
||||
/// state at a stamped slot doesn't count as drift. `peer_users` is excluded: it isn't diffed by
|
||||
@@ -133,10 +85,10 @@ impl Registry {
|
||||
}
|
||||
|
||||
pub(crate) fn attributes_value_equal(a: &Attributes, b: &Attributes) -> bool {
|
||||
if crate::attributes::live(a).count() != crate::attributes::live(b).count() {
|
||||
if a.len() != b.len() {
|
||||
return false;
|
||||
}
|
||||
crate::attributes::live(a).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
|
||||
@@ -148,8 +100,8 @@ pub(crate) fn resources_value_equal(a: &ResourceStore, b: &ResourceStore) -> boo
|
||||
a.iter().all(|(id, entry)| {
|
||||
b.get(id).is_some_and(|other| {
|
||||
entry.hash == other.hash
|
||||
&& entry.live_sources().count() == other.live_sources().count()
|
||||
&& entry.live_sources().all(|(key, value)| other.source(key).is_some_and(|other_value| value.source == other_value.source))
|
||||
&& entry.sources.len() == other.sources.len()
|
||||
&& entry.sources.iter().all(|(key, value)| other.source(key).is_some_and(|other_value| value.source == other_value.source))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::{PeerId, TimeStamp, Value, from_value, to_value};
|
||||
use crate::{PeerId, TimeStamp};
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
@@ -11,28 +11,13 @@ pub struct SourceKey {
|
||||
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
|
||||
/// committing to a Rust enum; `timestamp` drives LWW on re-setting this same entry.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct SourceValue {
|
||||
pub source: Value,
|
||||
pub source: serde_json::Value,
|
||||
pub timestamp: TimeStamp,
|
||||
/// A removed source stays as a stamped tombstone, so an older addition loses in either arrival order;
|
||||
/// readers see it as absent.
|
||||
#[serde(default)]
|
||||
pub deleted: bool,
|
||||
}
|
||||
|
||||
impl SourceValue {
|
||||
/// The tombstone of a source removed at `timestamp`.
|
||||
pub fn deleted(timestamp: TimeStamp) -> Self {
|
||||
Self {
|
||||
source: Value::None,
|
||||
timestamp,
|
||||
deleted: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A single content-addressable resource: an ordered, conflict-mergeable chain of fallback sources
|
||||
@@ -41,13 +26,8 @@ impl SourceValue {
|
||||
/// resource agree by construction, since the hash is content-derived).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
|
||||
pub struct ResourceEntry {
|
||||
/// The latest addition or write; see [`Node::presence`](crate::Node).
|
||||
pub(crate) presence: TimeStamp,
|
||||
/// Fallback chain kept sorted by `SourceKey`, so iteration yields highest-priority first.
|
||||
pub sources: Vec<(SourceKey, SourceValue)>,
|
||||
/// When `sources` was last written whole, by an addition of the entry. A key the chain does not hold is
|
||||
/// deleted as of then, as with [`Attributes`](crate::Attributes).
|
||||
pub sources_timestamp: TimeStamp,
|
||||
pub hash: Option<ResourceHash>,
|
||||
pub hash_timestamp: TimeStamp,
|
||||
}
|
||||
@@ -59,22 +39,12 @@ impl<'de> Deserialize<'de> for ResourceEntry {
|
||||
// collapse any duplicate keys, keeping the higher-timestamp value (LWW).
|
||||
#[derive(Deserialize)]
|
||||
struct Raw {
|
||||
#[serde(default)]
|
||||
presence: TimeStamp,
|
||||
sources: Vec<(SourceKey, SourceValue)>,
|
||||
#[serde(default)]
|
||||
sources_timestamp: TimeStamp,
|
||||
hash: Option<ResourceHash>,
|
||||
hash_timestamp: TimeStamp,
|
||||
}
|
||||
|
||||
let Raw {
|
||||
presence,
|
||||
mut sources,
|
||||
sources_timestamp,
|
||||
hash,
|
||||
hash_timestamp,
|
||||
} = Raw::deserialize(deserializer)?;
|
||||
let Raw { mut sources, hash, hash_timestamp } = Raw::deserialize(deserializer)?;
|
||||
sources.sort_by_key(|(a, _)| *a);
|
||||
sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| {
|
||||
// `dedup_by` keeps the first of each run; sorting is stable, so resolve duplicates by LWW.
|
||||
@@ -87,13 +57,7 @@ impl<'de> Deserialize<'de> for ResourceEntry {
|
||||
true
|
||||
});
|
||||
|
||||
Ok(Self {
|
||||
presence,
|
||||
sources,
|
||||
sources_timestamp,
|
||||
hash,
|
||||
hash_timestamp,
|
||||
})
|
||||
Ok(Self { sources, hash, hash_timestamp })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,107 +66,82 @@ impl ResourceEntry {
|
||||
/// source entry and the resolved hash carry `timestamp` so later LWW writes order against it.
|
||||
/// The bytes themselves are persisted separately by the caller's byte store.
|
||||
pub fn embedded(hash: ResourceHash, peer: PeerId, timestamp: TimeStamp) -> Self {
|
||||
let embedded = 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 sources = vec![(
|
||||
SourceKey { priority, peer },
|
||||
SourceValue {
|
||||
source: embedded,
|
||||
timestamp,
|
||||
deleted: false,
|
||||
},
|
||||
)];
|
||||
let sources = vec![(SourceKey { priority, peer }, SourceValue { source: embedded, timestamp })];
|
||||
|
||||
Self {
|
||||
presence: timestamp,
|
||||
sources,
|
||||
sources_timestamp: timestamp,
|
||||
hash: Some(hash),
|
||||
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> {
|
||||
self.find(key).ok().map(|index| &self.sources[index].1).filter(|value| !value.deleted)
|
||||
}
|
||||
|
||||
/// The live sources in precedence order, tombstones skipped.
|
||||
pub(crate) fn live_sources(&self) -> impl Iterator<Item = (&SourceKey, &SourceValue)> {
|
||||
self.sources.iter().filter(|(_, value)| !value.deleted).map(|(key, value)| (key, value))
|
||||
}
|
||||
|
||||
fn find(&self, key: &SourceKey) -> Result<usize, usize> {
|
||||
self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key))
|
||||
}
|
||||
|
||||
/// The stamp that decides a write to `key`: its entry's, tombstone included, or the chain's floor.
|
||||
fn decided(&self, key: &SourceKey) -> TimeStamp {
|
||||
self.find(key).map_or(self.sources_timestamp, |index| self.sources[index].1.timestamp)
|
||||
}
|
||||
|
||||
fn put(&mut self, key: SourceKey, value: SourceValue) {
|
||||
match self.find(&key) {
|
||||
Ok(index) => self.sources[index].1 = value,
|
||||
Err(index) => self.sources.insert(index, (key, value)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the chain whole at `at`: the floor deletes every other key without a tombstone per key.
|
||||
pub(crate) fn stamp_sources(&mut self, at: TimeStamp) {
|
||||
self.sources.retain(|(_, value)| !value.deleted);
|
||||
self.sources.iter_mut().for_each(|(_, value)| value.timestamp = at);
|
||||
self.sources_timestamp = at;
|
||||
}
|
||||
|
||||
/// Folds another chain in key by key, the way attribute maps merge: a key only one chain holds is
|
||||
/// dead when the other chain's floor is newer than it, and the newer entry wins where both hold a key.
|
||||
pub(crate) fn merge_sources(&mut self, other: Vec<(SourceKey, SourceValue)>, other_floor: TimeStamp) {
|
||||
self.sources.retain(|(_, value)| value.timestamp >= other_floor);
|
||||
for (key, value) in other {
|
||||
match self.find(&key) {
|
||||
Ok(index) if value.timestamp > self.sources[index].1.timestamp => self.sources[index].1 = value,
|
||||
Err(index) if value.timestamp >= self.sources_timestamp => self.sources.insert(index, (key, value)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
self.sources_timestamp = self.sources_timestamp.max(other_floor);
|
||||
self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)).ok().map(|index| &self.sources[index].1)
|
||||
}
|
||||
|
||||
/// Insert or LWW-overwrite the entry at `key`. A re-set at an existing key wins only if `value`'s
|
||||
/// timestamp is strictly newer; a fresh key is inserted in sorted position.
|
||||
pub fn set_source(&mut self, key: SourceKey, value: SourceValue) {
|
||||
if value.timestamp > self.decided(&key) {
|
||||
self.put(key, value);
|
||||
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)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Like [`set_source`](Self::set_source) but assigns unconditionally, for building an entry.
|
||||
/// Like [`set_source`](Self::set_source) but assigns unconditionally (silent-zone rewind), where the
|
||||
/// precomputed reverse/forward value is authoritative even if its timestamp ties what it replaces.
|
||||
pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) {
|
||||
self.put(key, value);
|
||||
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
|
||||
Ok(index) => self.sources[index].1 = value,
|
||||
Err(index) => self.sources.insert(index, (key, value)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove the source at `key` if what decides it is strictly older than `timestamp` (LWW), leaving a
|
||||
/// tombstone. Returns whether the removal landed.
|
||||
/// Remove the entry at `key` if its timestamp is strictly older than `timestamp` (LWW). Returns
|
||||
/// whether anything was removed.
|
||||
pub fn remove_source(&mut self, key: &SourceKey, timestamp: TimeStamp) -> bool {
|
||||
if timestamp <= self.decided(key) {
|
||||
return false;
|
||||
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)) {
|
||||
Ok(index) if timestamp > self.sources[index].1.timestamp => {
|
||||
self.sources.remove(index);
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Like [`remove_source`](Self::remove_source) but removes unconditionally (silent-zone rewind).
|
||||
pub fn force_remove_source(&mut self, key: &SourceKey) -> bool {
|
||||
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)) {
|
||||
Ok(index) => {
|
||||
self.sources.remove(index);
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
self.put(*key, SourceValue::deleted(timestamp));
|
||||
true
|
||||
}
|
||||
|
||||
/// True if the chain already carries a `DataSource::Embedded` source. Decodes each source body into
|
||||
/// `DataSource` so a shape change in the serialized form can't slip an embedded source past detection.
|
||||
pub fn has_embedded_source(&self) -> bool {
|
||||
self.live_sources()
|
||||
.any(|(_, value)| matches!(from_value::<graphene_resource::DataSource>(&value.source), Ok(graphene_resource::DataSource::Embedded)))
|
||||
self.sources.iter().any(|(_, value)| {
|
||||
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
|
||||
/// highest-precedence fallback.
|
||||
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 {
|
||||
priority: Priority::new(min_priority - 1.).expect("finite priority minus one is finite"),
|
||||
peer,
|
||||
@@ -286,15 +225,15 @@ mod tests {
|
||||
}
|
||||
|
||||
/// Deserialization routes through `Priority::new`, so a non-finite value on disk is rejected rather
|
||||
/// than silently producing an unsound map key. 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.
|
||||
#[test]
|
||||
fn priority_deserialize_validates_finiteness() {
|
||||
let finite = postcard::to_stdvec(&3.5_f64).unwrap();
|
||||
assert!(postcard::from_bytes::<Priority>(&finite).is_ok());
|
||||
let finite = rmp_serde::to_vec(&3.5_f64).unwrap();
|
||||
assert!(rmp_serde::from_slice::<Priority>(&finite).is_ok());
|
||||
|
||||
let non_finite = postcard::to_stdvec(&f64::INFINITY).unwrap();
|
||||
assert!(postcard::from_bytes::<Priority>(&non_finite).is_err(), "a non-finite priority on disk must be rejected");
|
||||
let non_finite = rmp_serde::to_vec(&f64::INFINITY).unwrap();
|
||||
assert!(rmp_serde::from_slice::<Priority>(&non_finite).is_err(), "a non-finite priority on disk must be rejected");
|
||||
}
|
||||
|
||||
/// `ResourceEntry`'s accessors rely on `sources` being sorted by `SourceKey`. Deserializing an
|
||||
@@ -309,23 +248,20 @@ mod tests {
|
||||
peer: PeerId(1),
|
||||
},
|
||||
SourceValue {
|
||||
source: Value::Float(priority),
|
||||
source: serde_json::json!(priority),
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
deleted: false,
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
// Build a deliberately unsorted chain as a literal (bypassing the sorted-insert API), then round-trip it through `Value`.
|
||||
let unsorted = ResourceEntry {
|
||||
presence: TimeStamp::ORIGIN,
|
||||
sources_timestamp: TimeStamp::ORIGIN,
|
||||
sources: vec![source(2.), source(0.), source(1.)],
|
||||
hash: None,
|
||||
hash_timestamp: TimeStamp::ORIGIN,
|
||||
};
|
||||
// Serialize a deliberately unsorted chain through the raw shape, then deserialize as `ResourceEntry`.
|
||||
let unsorted = serde_json::json!({
|
||||
"sources": [source(2.), source(0.), source(1.)],
|
||||
"hash": null,
|
||||
"hash_timestamp": TimeStamp::ORIGIN,
|
||||
});
|
||||
|
||||
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();
|
||||
assert_eq!(priorities, vec![0., 1., 2.], "sources must be sorted by SourceKey after deserialization");
|
||||
}
|
||||
@@ -342,23 +278,20 @@ mod tests {
|
||||
(
|
||||
key,
|
||||
SourceValue {
|
||||
source: Value::Str(body.into()),
|
||||
source: serde_json::json!(body),
|
||||
timestamp: TimeStamp { counter, peer: PeerId(1) },
|
||||
deleted: false,
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
let with_duplicates = ResourceEntry {
|
||||
presence: TimeStamp::ORIGIN,
|
||||
sources_timestamp: TimeStamp::ORIGIN,
|
||||
sources: vec![entry(5, "newer"), entry(1, "older")],
|
||||
hash: None,
|
||||
hash_timestamp: TimeStamp::ORIGIN,
|
||||
};
|
||||
let with_duplicates = serde_json::json!({
|
||||
"sources": [entry(5, "newer"), entry(1, "older")],
|
||||
"hash": null,
|
||||
"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[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;
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
use crate::from_runtime;
|
||||
use crate::{
|
||||
ApplyMode, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId, Value, to_value,
|
||||
};
|
||||
use crate::{ApplyMode, Delta, Document, History, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId};
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
@@ -29,17 +27,22 @@ impl Session {
|
||||
Self::with_peer(PeerId(core_types::uuid::generate_uuid()))
|
||||
}
|
||||
|
||||
/// A session for `peer` standing for itself as a person. For tests and tools without a stored identity;
|
||||
/// a working copy wants [`with_identity`](Self::with_identity).
|
||||
/// Construct a session bound to a specific `PeerId`. Used by tests; production code wants
|
||||
/// `Session::new`.
|
||||
pub fn with_peer(peer: PeerId) -> Self {
|
||||
Self::with_identity(peer, UserId(peer.0))
|
||||
}
|
||||
|
||||
/// A session for device `peer` used by person `user`. The user is what the peer's registration records,
|
||||
/// and what undo and history authorship scope by.
|
||||
pub fn with_identity(peer: PeerId, user: UserId) -> Self {
|
||||
Self {
|
||||
document: Document::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(),
|
||||
}
|
||||
}
|
||||
@@ -48,22 +51,6 @@ impl Session {
|
||||
self.document.peer
|
||||
}
|
||||
|
||||
pub fn user(&self) -> UserId {
|
||||
self.document.user
|
||||
}
|
||||
|
||||
/// The person a peer is registered to, if its registration has landed here.
|
||||
pub fn user_of(&self, peer: PeerId) -> Option<UserId> {
|
||||
let registered = || self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user);
|
||||
(peer == self.document.peer).then_some(self.document.user).or_else(registered)
|
||||
}
|
||||
|
||||
/// Whether `peer` is this person: this device, or another registered to the same user. Undo in a
|
||||
/// session scopes by this, so a fresh copy of a document still undoes what its user did from another.
|
||||
pub fn is_mine(&self, peer: PeerId) -> bool {
|
||||
self.user_of(peer) == Some(self.document.user)
|
||||
}
|
||||
|
||||
pub fn registry(&self) -> &Registry {
|
||||
&self.document.working_registry
|
||||
}
|
||||
@@ -77,7 +64,8 @@ impl Session {
|
||||
/// Diff the current registry against a fresh conversion of `network`, then commit each emitted
|
||||
/// op as its own `Delta` on the local chain. One `clock.tick()` per op (strictly causal within
|
||||
/// a commit). Returns the new `Rev`s in commit order (empty if nothing changed) plus the
|
||||
/// 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
|
||||
/// pushed onto the hot log. The caller persists the returned hot frames and then calls `retire`
|
||||
@@ -88,11 +76,11 @@ impl Session {
|
||||
network: &graph_craft::document::NodeNetwork,
|
||||
metadata: &M,
|
||||
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 ops = crate::delta::compute_deltas(&self.document.working_registry, &conversion.registry);
|
||||
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
|
||||
@@ -117,7 +105,7 @@ impl Session {
|
||||
/// Used on a throwaway session clone at export time so the exported registry and history agree;
|
||||
/// callers must guarantee the bytes are available in the export's resource store.
|
||||
pub fn embed_resource_sources(&mut self, ids: impl IntoIterator<Item = ResourceId>) -> Result<Vec<Rev>, CrdtError> {
|
||||
let embedded = 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();
|
||||
for id in ids {
|
||||
@@ -141,57 +129,31 @@ impl Session {
|
||||
Ok(revs)
|
||||
}
|
||||
|
||||
/// Stages ops computed outside the session (an incremental runtime projection) as hot ops, the
|
||||
/// same way `stage_from_runtime` stages a diff's ops.
|
||||
pub fn stage_computed_ops(&mut self, ops: Vec<RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
self.stage_ops(ops)
|
||||
}
|
||||
|
||||
/// Apply each op as a hot op with a freshly-ticked timestamp, returning the staged frames in
|
||||
/// order. Each tick is strictly later than the last, so the final frame carries the latest
|
||||
/// timestamp, which is what the caller passes to `retire`.
|
||||
///
|
||||
/// The peer's first contribution is preceded by a `RegisterPeer` op, so the device's
|
||||
/// `PeerId → UserId` mapping is established (and, under causal delivery, observed by other peers)
|
||||
/// before any of its edits. A no-op batch doesn't register, since registration rides a real edit.
|
||||
pub(crate) fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
// A batch is staged whole or not at all: a refused op takes back the ones before it, which reached nothing yet.
|
||||
/// before any of its edits. A no-op batch doesn't register — registration rides a real edit.
|
||||
fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
let mut pending: Vec<RegistryDelta> = ops.into_iter().collect();
|
||||
if pending.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let (peer, user) = (self.document.peer, self.document.user);
|
||||
if self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user) != Some(user) {
|
||||
pending.insert(0, RegistryDelta::RegisterPeer { peer, user });
|
||||
if !self.document.working_registry.peer_users.contains_key(&self.document.peer) {
|
||||
let user = UserId(self.document.peer.0);
|
||||
pending.insert(0, RegistryDelta::RegisterPeer { peer: self.document.peer, user });
|
||||
}
|
||||
|
||||
// Reusing a sequence would let retirement marks drop the new op, so a batch that would run past the end is refused whole.
|
||||
if self.document.last_hot_sequence.0.checked_add(pending.len() as u64).is_none() {
|
||||
return Err(CrdtError::SequencesExhausted);
|
||||
}
|
||||
|
||||
let sequence_before = self.document.last_hot_sequence;
|
||||
let mut staged = Vec::with_capacity(pending.len());
|
||||
for op in pending {
|
||||
let sequence = HotSequence(self.document.last_hot_sequence.0 + 1);
|
||||
let hot_op = HotOp {
|
||||
op,
|
||||
timestamp: self.document.clock.tick(),
|
||||
sequence,
|
||||
};
|
||||
if let Err(error) = self.document.apply_hot_op(hot_op.clone(), ApplyMode::Live) {
|
||||
// The run continues where it was, so no sequence goes unused.
|
||||
self.document.last_hot_sequence = sequence_before;
|
||||
if !staged.is_empty() {
|
||||
let taken: HashSet<HotOpId> = staged.iter().map(HotOp::id).collect();
|
||||
self.document.hot_log.retain(|hot_op| !taken.contains(&hot_op.id()));
|
||||
self.document.resync_hot_timestamps();
|
||||
self.document.rebuild_working();
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
self.document.last_hot_sequence = sequence;
|
||||
self.document.apply_hot_op(hot_op.clone())?;
|
||||
staged.push(hot_op);
|
||||
}
|
||||
Ok(staged)
|
||||
@@ -199,26 +161,19 @@ impl Session {
|
||||
|
||||
/// Wrap each op as a `Delta`, apply it, and chain it onto the local history. One tick per op.
|
||||
///
|
||||
/// Operates on the *retired snapshot*: each `reverse` is captured from it and the forward op applied to it, so
|
||||
/// the reverse holds the true pre-op state rather than the hot-polluted working state. The
|
||||
/// Operates on the *retired snapshot*: reverses are computed against and forward ops applied to it,
|
||||
/// so each `reverse` captures the true pre-op value rather than the hot-polluted working state. The
|
||||
/// working registry already reflects these ops (they were staged as hot ops before retirement, or
|
||||
/// equal the snapshot when there are none), so it is left untouched.
|
||||
///
|
||||
/// `idempotent`: pass `true` when the snapshot already reflects the op (retirement of an already-
|
||||
/// applied hot op) so duplicate structural inserts no-op rather than error.
|
||||
fn commit_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>, idempotent: bool) -> Result<Vec<Rev>, CrdtError> {
|
||||
self.commit_ops_authored_at(ops.into_iter().map(|op| (op, None)), idempotent)
|
||||
}
|
||||
|
||||
/// [`commit_ops`](Self::commit_ops) for ops authored elsewhere, paired with the timestamp they were
|
||||
/// authored at (`None` to mint one). The delta's timestamp is what the registry resolves LWW on, so
|
||||
/// retirement passes the op's own.
|
||||
fn commit_ops_authored_at(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Option<TimeStamp>)>, idempotent: bool) -> Result<Vec<Rev>, CrdtError> {
|
||||
let target = RegistryTarget::Snapshot;
|
||||
let ops = ops.into_iter();
|
||||
let mut produced = Vec::with_capacity(ops.size_hint().0);
|
||||
|
||||
for (op, 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
|
||||
// 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.
|
||||
@@ -226,10 +181,10 @@ impl Session {
|
||||
self.document.redo_stack.clear();
|
||||
}
|
||||
|
||||
let reverse = crate::prior::capture(self.document.registry_ref(target), &op);
|
||||
let timestamp = authored_at.unwrap_or_else(|| self.document.clock.tick());
|
||||
let reverse = self.document.compute_reverse_delta(target, &op)?;
|
||||
let timestamp = self.document.clock.tick();
|
||||
let parent = self.document.head;
|
||||
let author = timestamp.peer;
|
||||
let author = self.document.peer;
|
||||
|
||||
let delta = Delta::new(parent, author, timestamp, op, reverse);
|
||||
let rev = delta.id;
|
||||
@@ -253,7 +208,7 @@ impl Session {
|
||||
/// Wrap an already-materialized snapshot. Trusts `registry` to match `history`; advances the
|
||||
/// clock past every observed timestamp but does not re-apply ops. `history` is taken in on-disk
|
||||
/// (topological) order.
|
||||
pub fn load(peer: PeerId, 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);
|
||||
for delta in &history {
|
||||
clock.observe(delta.timestamp);
|
||||
@@ -266,11 +221,13 @@ impl Session {
|
||||
retired_snapshot: registry.clone(),
|
||||
working_registry: registry,
|
||||
history: History::from_ordered(history),
|
||||
hot_log: Vec::new(),
|
||||
head,
|
||||
redo_stack,
|
||||
clock,
|
||||
peer,
|
||||
last_broadcast_rev: None,
|
||||
next_node_counter,
|
||||
..Document::empty(peer, user)
|
||||
},
|
||||
remote_tips: HashMap::new(),
|
||||
}
|
||||
@@ -278,8 +235,8 @@ impl Session {
|
||||
|
||||
/// Rebuild the registry from scratch by applying every delta in causal order.
|
||||
/// `deltas` must be in causal order (every parent before its children).
|
||||
pub fn replay_from_history(peer: PeerId, user: UserId, deltas: impl IntoIterator<Item = Delta>, next_node_counter: u64) -> Result<Self, CrdtError> {
|
||||
let mut session = Self::with_identity(peer, user);
|
||||
pub fn replay_from_history(peer: PeerId, deltas: impl IntoIterator<Item = Delta>, next_node_counter: u64) -> Result<Self, CrdtError> {
|
||||
let mut session = Self::with_peer(peer);
|
||||
session.document.next_node_counter = next_node_counter;
|
||||
|
||||
for delta in deltas {
|
||||
@@ -294,21 +251,9 @@ impl Session {
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
/// Apply a hot op from another peer. Idempotent, and a no-op for one history already covers: a late
|
||||
/// delivery must not put a retired op back in the hot log.
|
||||
/// Apply a hot op without going through the broadcast stream.
|
||||
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
|
||||
self.document.replay_hot_op(hot_op)
|
||||
}
|
||||
|
||||
/// Which hot ops are done with, for a peer catching up and for persisting. See [`SettledHotOps`].
|
||||
pub fn settled_marks(&self) -> &SettledHotOps {
|
||||
&self.document.settled
|
||||
}
|
||||
|
||||
/// Take on a peer's marks, or this peer's persisted ones: whatever they cover that the hot log still holds is
|
||||
/// dropped, and the working registry re-derived without it.
|
||||
pub fn absorb_settled_marks(&mut self, remote: &SettledHotOps) {
|
||||
self.document.absorb_settled(remote);
|
||||
self.document.apply_hot_op(hot_op)
|
||||
}
|
||||
|
||||
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
|
||||
@@ -317,52 +262,57 @@ impl Session {
|
||||
self.document.replay_hot_op(hot_op)
|
||||
}
|
||||
|
||||
/// The retired snapshot as history alone produces it, independent of arrival order and the hot log.
|
||||
/// Folded over `head`'s ancestry only: an undone delta stays in the DAG for redo to find, and folding
|
||||
/// all of history would restore work the user undid.
|
||||
pub fn snapshot_from_history(&self) -> Result<Registry, CrdtError> {
|
||||
// Every op lands the same whatever order it arrives in, so applying each once is the fold.
|
||||
let reachable = self.document.history.ancestors(self.document.head);
|
||||
let mut scratch = Document::empty(self.document.peer, self.document.user);
|
||||
for delta in self.document.history.iter().filter(|delta| reachable.contains(&delta.id)) {
|
||||
scratch.apply_op_with(RegistryTarget::Working, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
|
||||
/// Integrate `incoming` retired deltas from another branch and emit a [`RegistryDelta::Merge`]
|
||||
/// joining the resulting tips, returning the new merge `Rev` (or `None` if `incoming` adds nothing).
|
||||
/// Applies each incoming op to the registry, then hands the set to [`History::merge`]. Incoming
|
||||
/// deltas must arrive in causal order.
|
||||
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) -> Result<Option<Rev>, CrdtError> {
|
||||
let mut absorbed: Vec<Delta> = Vec::new();
|
||||
for delta in incoming {
|
||||
if self.document.history.contains(delta.id) {
|
||||
continue;
|
||||
}
|
||||
self.document.apply_op_idempotent(delta.kind.clone(), delta.timestamp)?;
|
||||
absorbed.push(delta);
|
||||
}
|
||||
Ok(scratch.working_registry)
|
||||
if absorbed.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
self.document.history.merge(absorbed);
|
||||
let tips = self.document.history.tips();
|
||||
let timestamp = self.document.clock.tick();
|
||||
let merge = Delta::merge(tips, self.document.peer, timestamp);
|
||||
let merge_rev = merge.id;
|
||||
// The merge's parents are the current tips, so it sorts last: `push` preserves the canonical
|
||||
// order without re-sorting the whole history.
|
||||
self.document.history.push(merge);
|
||||
self.document.head = Some(merge_rev);
|
||||
|
||||
// Merge runs with an empty hot log; keep the retired snapshot in step with the working registry.
|
||||
self.document.retired_snapshot = self.document.working_registry.clone();
|
||||
Ok(Some(merge_rev))
|
||||
}
|
||||
|
||||
pub fn history_len(&self) -> usize {
|
||||
self.document.history.len()
|
||||
}
|
||||
|
||||
/// The hot ops stamped at or before `up_to`, which [`retire`](Self::retire) drains. Sent with the deltas,
|
||||
/// since a lagging op can arrive below the cutoff afterwards.
|
||||
pub fn hot_ops_up_to(&self, up_to: TimeStamp) -> Vec<HotOpId> {
|
||||
self.document.hot_log.iter().filter(|hot_op| hot_op.timestamp <= up_to).map(HotOp::id).collect()
|
||||
}
|
||||
|
||||
/// Promote the given hot ops into retired deltas, in hot-log order, each keeping the timestamp it was
|
||||
/// authored at. Markers commit nothing. Ops not in the log are ignored.
|
||||
/// Promote hot ops with timestamp `≤ up_to` into retired deltas, re-applied with fresh
|
||||
/// retirement timestamps so LWW arms bump field timestamps to `T_retire`.
|
||||
///
|
||||
/// One retired delta per hot op.
|
||||
pub fn retire_hot_ops(&mut self, ids: &[HotOpId]) -> Result<Vec<Rev>, CrdtError> {
|
||||
let wanted: HashSet<HotOpId> = ids.iter().copied().collect();
|
||||
let (drained, kept): (Vec<HotOp>, Vec<HotOp>) = self.document.hot_log.drain(..).partition(|hot_op| wanted.contains(&hot_op.id()));
|
||||
self.document.hot_log = kept;
|
||||
self.document.resync_hot_timestamps();
|
||||
self.document.settled.extend(drained.iter().map(HotOp::id));
|
||||
|
||||
let ops = drained
|
||||
.into_iter()
|
||||
.filter(|hot_op| !matches!(hot_op.op, RegistryDelta::EndTransaction))
|
||||
.map(|hot_op| (hot_op.op, Some(hot_op.timestamp)));
|
||||
self.commit_ops_authored_at(ops, true)
|
||||
}
|
||||
|
||||
/// Promote every hot op stamped at or before `up_to`, whatever its author.
|
||||
/// Today: one retired delta per hot op. Coarsening is a future step.
|
||||
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, CrdtError> {
|
||||
let ids = self.hot_ops_up_to(up_to);
|
||||
self.retire_hot_ops(&ids)
|
||||
let mut drained = Vec::new();
|
||||
let mut remaining = Vec::with_capacity(self.document.hot_log.len());
|
||||
for hot_op in self.document.hot_log.drain(..) {
|
||||
if hot_op.timestamp <= up_to {
|
||||
drained.push(hot_op);
|
||||
} else {
|
||||
remaining.push(hot_op);
|
||||
}
|
||||
}
|
||||
self.document.hot_log = remaining;
|
||||
|
||||
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.
|
||||
/// Called once per interaction by the editor-facing commit path (not by resource/internal commits).
|
||||
pub fn mark_interaction_end(&mut self, rev: Rev) {
|
||||
@@ -373,36 +323,38 @@ impl Session {
|
||||
/// Low-level: set a local annotation attribute (e.g. a commit message) on a retired delta in place.
|
||||
/// Excluded from the delta's content-addressed `Rev`, so identity is unchanged. Returns whether the
|
||||
/// delta was found. The `Gdd` layer re-persists the affected history frame after calling this.
|
||||
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: Value) -> bool {
|
||||
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: serde_json::Value) -> bool {
|
||||
let timestamp = self.document.clock.tick();
|
||||
self.document.history.annotate(rev, key, value, timestamp)
|
||||
}
|
||||
|
||||
/// Whether the interaction at `head` can be undone in the silent zone: it is this user's own, holds no merge, and
|
||||
/// nothing in it was published, since rewinding a step peers hold would diverge from them. The document's first
|
||||
/// interaction is not undoable, as opening a document starts with an empty undo history.
|
||||
/// Whether there is a retired commit at `head` that can be undone in the silent zone (a commit
|
||||
/// after `last_broadcast_rev`). `head == 0` is the empty history; published commits aren't
|
||||
/// silently undoable (that needs a forward reverse-delta op, deferred until transport lands).
|
||||
///
|
||||
/// The earliest interaction (the document's loaded/created base) is *not* undoable: undoing it would
|
||||
/// rewind into the pre-base state, which legacy never offers (opening a document gives an empty undo
|
||||
/// history). We detect "head is on the earliest interaction" by walking `head`'s interaction back along
|
||||
/// first-parents and checking whether it bottoms out at the root with no earlier interaction boundary to
|
||||
/// land on. If so, there is nothing before this interaction to undo to, so undo is disabled.
|
||||
pub fn can_undo(&self) -> bool {
|
||||
self.document.head.is_some_and(|head| self.interaction_start_parent(head, true).is_some())
|
||||
let Some(head) = self.document.head else { return false };
|
||||
if self.document.last_broadcast_rev == Some(head) {
|
||||
return false;
|
||||
}
|
||||
self.interaction_start_parent(head).is_some()
|
||||
}
|
||||
|
||||
/// The rev the cursor rests on once the interaction ending at `end` is undone: the parent where the previous
|
||||
/// interaction ended, a merge, or another user's delta begins. `None` when `end` is a merge, the interaction starts
|
||||
/// at the root, or, for a `silent` undo, it is not this user's or holds a published delta.
|
||||
fn interaction_start_parent(&self, end: Rev, silent: bool) -> Option<Rev> {
|
||||
let history = &self.document.history;
|
||||
let mut current = history.get(end)?;
|
||||
let user = self.user_of(current.author);
|
||||
if matches!(current.kind, RegistryDelta::Merge { .. }) || (silent && user != Some(self.document.user)) {
|
||||
return None;
|
||||
}
|
||||
let boundary = |delta: &Delta| delta.is_interaction_end() || matches!(delta.kind, RegistryDelta::Merge { .. }) || self.user_of(delta.author) != user;
|
||||
/// Walk the interaction containing `rev` back along first-parents to its first delta, returning the
|
||||
/// rev the cursor would rest on after undoing this interaction, or `None` if that is the root (the
|
||||
/// earliest interaction, which is not undoable). Mirrors the boundary condition in [`undo`](Self::undo):
|
||||
/// stop when the parent is an `interaction_end` boundary or the root.
|
||||
fn interaction_start_parent(&self, rev: Rev) -> Option<Rev> {
|
||||
let mut current = rev;
|
||||
loop {
|
||||
if silent && self.document.last_broadcast_rev == Some(current.id) {
|
||||
return None;
|
||||
}
|
||||
let parent = history.get(current.parent?)?;
|
||||
if boundary(parent) {
|
||||
return Some(parent.id);
|
||||
let parent = self.document.history.get(current)?.parent?;
|
||||
if self.document.history.get(parent).is_some_and(|d| d.is_interaction_end()) {
|
||||
return Some(parent);
|
||||
}
|
||||
current = parent;
|
||||
}
|
||||
@@ -412,22 +364,37 @@ impl Session {
|
||||
!self.document.redo_stack.is_empty()
|
||||
}
|
||||
|
||||
/// Silent-zone undo of one interaction: put back what its deltas overwrote, newest first, until `head` rests where it
|
||||
/// began (see [`can_undo`](Self::can_undo)). Its `head` rev goes on the redo stack; the DAG is not rewritten.
|
||||
/// Silent-zone undo of one *interaction*: revert deltas walking `head` back along first-parents until
|
||||
/// it reaches the previous interaction boundary (a delta marked `interaction_end`) or the empty root. One
|
||||
/// interaction spans several deltas (one `commit_from_runtime` batch), so undo reverts the whole run,
|
||||
/// not a single delta — matching the legacy per-interaction undo granularity. The undone interaction's
|
||||
/// `head` rev is pushed onto the redo stack. Reflog semantics: the DAG is never rewritten.
|
||||
pub fn undo(&mut self) -> Result<Rev, CrdtError> {
|
||||
if !self.can_undo() {
|
||||
return Err(CrdtError::NothingToUndo);
|
||||
}
|
||||
let checkpoint = self.document.head.ok_or(CrdtError::NothingToUndo)?;
|
||||
let base = self.interaction_start_parent(checkpoint, true).ok_or(CrdtError::NothingToUndo)?;
|
||||
|
||||
while let Some(rev) = self.document.head.filter(|&rev| rev != base) {
|
||||
// Revert this interaction's last delta, then keep going back until `head` rests on the previous
|
||||
// interaction's boundary (its `interaction_end` delta) or the root.
|
||||
loop {
|
||||
let rev = self.document.head.ok_or(CrdtError::NothingToUndo)?;
|
||||
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
|
||||
self.document.revert_delta(&delta);
|
||||
self.document.head = delta.parent;
|
||||
let parent = delta.parent;
|
||||
|
||||
self.document.revert_delta(RegistryTarget::Working, delta)?;
|
||||
self.document.head = parent;
|
||||
|
||||
match parent {
|
||||
None => break,
|
||||
Some(parent) if self.document.history.get(parent).is_some_and(|d| d.is_interaction_end()) => break,
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
// With ops hot, working is the rewound snapshot plus them.
|
||||
if !self.document.hot_log.is_empty() {
|
||||
self.document.rebuild_working();
|
||||
}
|
||||
// Undo runs with an empty hot log, so keep the retired snapshot in lockstep with the rewound
|
||||
// working registry (the next interaction's reverses are computed against it).
|
||||
self.document.retired_snapshot = self.document.working_registry.clone();
|
||||
self.document.redo_stack.push(checkpoint);
|
||||
Ok(checkpoint)
|
||||
}
|
||||
@@ -447,28 +414,23 @@ impl Session {
|
||||
forward.push(delta);
|
||||
}
|
||||
|
||||
// Undo left the snapshot exactly at the fold up to `head`, so applying the deltas as retirement did folds
|
||||
// them in again, a newer write merged in before them still winning over theirs.
|
||||
let hot = !self.document.hot_log.is_empty();
|
||||
// Force-apply so each forward value wins the LWW tie against the reverse that undo force-applied
|
||||
// at the same timestamp. Symmetric with `revert_delta`.
|
||||
for delta in forward.into_iter().rev() {
|
||||
self.document.apply_op_with(RegistryTarget::Snapshot, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
|
||||
if !hot {
|
||||
self.document.apply_op_with(RegistryTarget::Working, delta.kind, delta.timestamp, ApplyMode::Idempotent)?;
|
||||
}
|
||||
}
|
||||
if hot {
|
||||
self.document.rebuild_working();
|
||||
self.document.force_apply_op(delta.kind.clone(), delta.timestamp)?;
|
||||
}
|
||||
self.document.head = Some(checkpoint);
|
||||
|
||||
// Redo runs with an empty hot log; keep the retired snapshot in lockstep with the working registry.
|
||||
self.document.retired_snapshot = self.document.working_registry.clone();
|
||||
Ok(checkpoint)
|
||||
}
|
||||
|
||||
/// Build a synthetic linear history whose replay reproduces `registry`. Each op gets a
|
||||
/// freshly-ticked clock timestamp and chains to the previous op's `Rev`.
|
||||
pub fn bootstrap_from_registry(peer: PeerId, 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 mut session = Self::with_identity(peer, user);
|
||||
let mut session = Self::with_peer(peer);
|
||||
session.commit_ops(ops, false)?;
|
||||
// No hot ops on this path, so the working registry must mirror the freshly-built snapshot.
|
||||
session.document.working_registry = session.document.retired_snapshot.clone();
|
||||
@@ -499,42 +461,16 @@ impl Session {
|
||||
/// bytes. Walks current resources plus each delta's `AddResource`/`RemoveResource` snapshot.
|
||||
pub fn all_referenced_resource_hashes(&self) -> HashSet<ResourceHash> {
|
||||
let mut hashes: HashSet<ResourceHash> = self.document.working_registry.resources.values().filter_map(|entry| entry.hash).collect();
|
||||
hashes.extend(self.document.history.resource_hashes());
|
||||
hashes
|
||||
}
|
||||
|
||||
/// Every proto-node declaration resource referenced by the current registry or anywhere in history,
|
||||
/// with its content hash, or `None` where the hash never resolved.
|
||||
pub fn all_declaration_resources(&self) -> HashMap<ResourceId, Option<ResourceHash>> {
|
||||
let registry = &self.document.working_registry;
|
||||
|
||||
let mut hashes: HashMap<ResourceId, ResourceHash> = registry.resources.iter().filter_map(|(id, entry)| Some((*id, entry.hash?))).collect();
|
||||
for delta in self.document.history.iter() {
|
||||
match &delta.kind {
|
||||
RegistryDelta::AddResource { id, entry } => hashes.extend(entry.hash.map(|hash| (*id, hash))),
|
||||
RegistryDelta::RemoveResource { id, snapshot } => hashes.extend(snapshot.hash.map(|hash| (*id, hash))),
|
||||
RegistryDelta::SetResourceHash { id, hash: Some(hash) } => {
|
||||
hashes.insert(*id, *hash);
|
||||
}
|
||||
RegistryDelta::AddResource { entry, .. } => hashes.extend(entry.hash),
|
||||
RegistryDelta::RemoveResource { snapshot, .. } => hashes.extend(snapshot.hash),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let current_nodes = registry.node_instances.values();
|
||||
let historic_nodes = self.document.history.iter().filter_map(|delta| match &delta.kind {
|
||||
RegistryDelta::AddNode { node, .. } => Some(node),
|
||||
RegistryDelta::RemoveNode { snapshot, .. } => Some(snapshot),
|
||||
_ => None,
|
||||
});
|
||||
|
||||
current_nodes
|
||||
.chain(historic_nodes)
|
||||
.filter_map(|node| match node.implementation() {
|
||||
Implementation::ProtoNode(id) => Some(*id),
|
||||
Implementation::Network(_) => None,
|
||||
})
|
||||
.map(|id| (id, hashes.get(&id).copied()))
|
||||
.collect()
|
||||
hashes
|
||||
}
|
||||
|
||||
pub fn hot_log(&self) -> &[HotOp] {
|
||||
@@ -565,7 +501,7 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Test-only: commit a single op as a retired delta on the local chain, returning the result so a
|
||||
/// test can observe a failure (e.g. `NotFoundInHistory`).
|
||||
/// test can observe a resurrection failure (e.g. `NotFoundInHistory`).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn commit_op_for_test(&mut self, op: RegistryDelta) -> Result<(), CrdtError> {
|
||||
self.commit_ops(std::iter::once(op), false).map(|_| ())
|
||||
@@ -578,29 +514,6 @@ impl Session {
|
||||
pub fn next_node_counter(&self) -> u64 {
|
||||
self.document.next_node_counter
|
||||
}
|
||||
|
||||
/// The sequence of the last hot op this peer authored, which is how many it has. Carried across a reload, so no
|
||||
/// sequence is spent twice.
|
||||
pub fn last_hot_sequence(&self) -> HotSequence {
|
||||
self.document.last_hot_sequence
|
||||
}
|
||||
|
||||
/// The Lamport counter, persisted so a reopen never mints a stamp it already spent, even one no op in history or
|
||||
/// the hot log carries any more.
|
||||
pub fn clock_counter(&self) -> u64 {
|
||||
self.document.clock.counter
|
||||
}
|
||||
|
||||
/// Continue the Lamport clock after a load. Raises only, like observing an op.
|
||||
pub fn restore_clock(&mut self, counter: u64) {
|
||||
self.document.clock.counter = self.document.clock.counter.max(counter);
|
||||
}
|
||||
|
||||
/// Restore the authored-op count after a load, keeping a fresh op off a spent sequence. Raises only:
|
||||
/// replaying a persisted hot log afterwards cannot lower it.
|
||||
pub fn restore_hot_sequence(&mut self, sequence: HotSequence) {
|
||||
self.document.last_hot_sequence = self.document.last_hot_sequence.max(sequence);
|
||||
}
|
||||
}
|
||||
|
||||
/// Errors from `Session::commit_from_runtime`.
|
||||
@@ -626,122 +539,10 @@ impl Default for Session {
|
||||
pub struct HotOp {
|
||||
pub op: RegistryDelta,
|
||||
pub timestamp: TimeStamp,
|
||||
/// Position in its author's run. See [`HotSequence`].
|
||||
pub sequence: HotSequence,
|
||||
}
|
||||
|
||||
impl HotOp {
|
||||
/// Identifies the op in the settled marks, which track a contiguous prefix per author.
|
||||
pub fn id(&self) -> HotOpId {
|
||||
HotOpId {
|
||||
peer: self.timestamp.peer,
|
||||
sequence: self.sequence,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Position in one author's run of hot ops, counting from 1 with no gaps. Kept apart from the Lamport
|
||||
/// counter, which skips on observing a higher remote timestamp and so cannot bound a contiguous prefix.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct HotSequence(pub u64);
|
||||
|
||||
impl HotSequence {
|
||||
/// Before this author has written anything, covering no op.
|
||||
pub const NONE: Self = Self(0);
|
||||
|
||||
/// The position after this one, for adjacency. Saturates: a run ending at the last position has no successor.
|
||||
pub fn next(self) -> Self {
|
||||
Self(self.0.saturating_add(1))
|
||||
}
|
||||
}
|
||||
|
||||
/// One hot op's author and position in its run. Retirement names promoted ops by these, which tells a
|
||||
/// receiver which prefix history covers.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct HotOpId {
|
||||
pub peer: PeerId,
|
||||
pub sequence: HotSequence,
|
||||
}
|
||||
|
||||
/// Which hot ops are retired into history: `settled_up_to` is each author's gap-free prefix, and `settled_beyond`
|
||||
/// the settled ops past it. Gaps exist only while ops are in flight, so an author collapses to its prefix. Replicated and persisted, so a
|
||||
/// late copy of a settled op is dropped wherever it lands.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SettledHotOps {
|
||||
pub settled_up_to: HashMap<PeerId, HotSequence>,
|
||||
/// Settled ops past their author's prefix, as inclusive runs, one per gap in flight.
|
||||
pub settled_beyond: HashMap<PeerId, Vec<(HotSequence, HotSequence)>>,
|
||||
}
|
||||
|
||||
/// Sort and coalesce runs, joining any that touch or abut.
|
||||
fn coalesce(runs: &mut Vec<(HotSequence, HotSequence)>) {
|
||||
runs.sort_unstable();
|
||||
runs.dedup_by(|(start, end), (_, last_end)| {
|
||||
let joins = *start <= last_end.next();
|
||||
if joins {
|
||||
*last_end = (*last_end).max(*end);
|
||||
}
|
||||
joins
|
||||
});
|
||||
}
|
||||
|
||||
impl SettledHotOps {
|
||||
/// Whether history already holds this hot op.
|
||||
pub fn covers(&self, id: HotOpId) -> bool {
|
||||
self.settled_up_to.get(&id.peer).is_some_and(|&through| id.sequence <= through)
|
||||
|| self
|
||||
.settled_beyond
|
||||
.get(&id.peer)
|
||||
.is_some_and(|runs| runs.iter().any(|&(start, end)| (start..=end).contains(&id.sequence)))
|
||||
}
|
||||
|
||||
/// Take on `remote`'s coverage as well as this one's.
|
||||
pub(crate) fn absorb(&mut self, remote: &Self) {
|
||||
for (&peer, &remote_through) in &remote.settled_up_to {
|
||||
let through = self.settled_up_to.entry(peer).or_default();
|
||||
*through = (*through).max(remote_through);
|
||||
}
|
||||
for (&peer, runs) in &remote.settled_beyond {
|
||||
self.settled_beyond.entry(peer).or_default().extend(runs.iter().copied());
|
||||
}
|
||||
self.compact();
|
||||
}
|
||||
|
||||
/// Record newly settled ops.
|
||||
pub fn extend(&mut self, retired: impl IntoIterator<Item = HotOpId>) {
|
||||
for id in retired {
|
||||
self.settled_beyond.entry(id.peer).or_default().push((id.sequence, id.sequence));
|
||||
}
|
||||
self.compact();
|
||||
}
|
||||
|
||||
/// Fold runs that continue their author's prefix into `settled_up_to`, leaving only those past a gap.
|
||||
fn compact(&mut self) {
|
||||
for (&peer, runs) in &mut self.settled_beyond {
|
||||
coalesce(runs);
|
||||
let mut through = self.settled_up_to.get(&peer).copied().unwrap_or(HotSequence::NONE);
|
||||
let joined = runs.iter().take_while(|&&(start, end)| {
|
||||
let joins = start <= through.next();
|
||||
if joins {
|
||||
through = through.max(end);
|
||||
}
|
||||
joins
|
||||
});
|
||||
let joined = joined.count();
|
||||
runs.drain(..joined);
|
||||
if through != HotSequence::NONE {
|
||||
self.settled_up_to.insert(peer, through);
|
||||
}
|
||||
}
|
||||
self.settled_beyond.retain(|_, runs| !runs.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum CrdtError {
|
||||
#[error("This peer has authored every hot op sequence there is")]
|
||||
SequencesExhausted,
|
||||
#[error("Target node {0} does not exist")]
|
||||
TargetNodeDoesNotExist(NodeId),
|
||||
#[error("Network {0} does not exist")]
|
||||
@@ -752,6 +553,10 @@ pub enum CrdtError {
|
||||
ExportSlotOutOfBounds(u32),
|
||||
#[error("Delta {0} not found in history")]
|
||||
NotFoundInHistory(Rev),
|
||||
#[error("No history entry resurrects node {0}")]
|
||||
NodeNotInHistory(NodeId),
|
||||
#[error("No history entry resurrects network {0}")]
|
||||
NetworkNotInHistory(NetworkId),
|
||||
#[error("Nothing to undo")]
|
||||
NothingToUndo,
|
||||
#[error("Nothing to redo")]
|
||||
@@ -760,6 +565,9 @@ pub enum CrdtError {
|
||||
NodeAlreadyExists(NodeId),
|
||||
#[error("Network {0} already exists")]
|
||||
NetworkAlreadyExists(NetworkId),
|
||||
/// PeerId is already registered to a different UserId.
|
||||
#[error("Peer {0:?} is already registered to a different user")]
|
||||
PeerRegistrationConflict(PeerId),
|
||||
#[error("Delta stored under {stored} hashes to {expected}")]
|
||||
RevMismatch { stored: Rev, expected: Rev },
|
||||
}
|
||||
@@ -1,165 +0,0 @@
|
||||
use crate::{AttributeDelta, CrdtError, HotOpId, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, RegistryDelta, Session, UserId, Value};
|
||||
|
||||
pub(super) fn set_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: AttributeDelta {
|
||||
key: key.to_string(),
|
||||
value: Some(Value::from(serde_json::json!(value))),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn add_network(id: u64) -> RegistryDelta {
|
||||
RegistryDelta::AddNetwork {
|
||||
id: NetworkId(id),
|
||||
network: Network::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Retirement takes the ops under the cutoff in any log order: every op commutes, so the snapshot folds to
|
||||
/// the working registry's values with a later-stamped op left hot.
|
||||
#[test]
|
||||
fn retirement_takes_the_ops_under_the_cutoff_in_any_applied_order() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
// A guest's late-stamped op sits ahead of an earlier-stamped one: the log is in arrival order, stamps
|
||||
// are the authors' clocks.
|
||||
let hot = |op, counter, peer| crate::HotOp {
|
||||
op,
|
||||
timestamp: crate::TimeStamp { counter, peer: PeerId(peer) },
|
||||
sequence: crate::HotSequence(1),
|
||||
};
|
||||
let (late, own) = (hot(add_network(9), 50, 2), hot(set_attribute("x", 1), 20, 3));
|
||||
host.apply_hot_op(late.clone()).expect("the late-stamped op lands first");
|
||||
host.apply_hot_op(own.clone()).expect("the earlier-stamped op lands second");
|
||||
assert_eq!(host.hot_ops_up_to(own.timestamp).len(), 1, "only the op under the cutoff retires");
|
||||
|
||||
host.retire(own.timestamp).expect("retire");
|
||||
assert_eq!(host.hot_log().len(), 1, "the later-stamped op stays hot");
|
||||
assert!(!host.retired_registry().networks.contains_key(&NetworkId(9)));
|
||||
assert!(host.registry().networks.contains_key(&NetworkId(9)));
|
||||
assert!(host.retired_registry().attributes.get("x").is_some_and(|value| !value.deleted));
|
||||
|
||||
host.retire(late.timestamp).expect("retire the rest");
|
||||
assert!(host.hot_log().is_empty());
|
||||
assert!(host.registry().value_equal(host.retired_registry()));
|
||||
}
|
||||
|
||||
/// A device's registration to a person is a write like any other: a later one replaces it, and a peer that
|
||||
/// receives the two in the other order ends up with the same mapping.
|
||||
#[test]
|
||||
fn a_peers_registration_is_the_newest_by_stamp_whatever_order_it_lands() {
|
||||
// Registration rides the staging path, so the steps go through the hot log and retire.
|
||||
fn stage_and_retire(session: &mut Session, op: RegistryDelta) {
|
||||
let hot = session.stage_ops([op]).expect("stage");
|
||||
let ids: Vec<crate::HotOpId> = hot.iter().map(crate::HotOp::id).collect();
|
||||
session.retire_hot_ops(&ids).expect("retire");
|
||||
}
|
||||
let mut device = Session::with_identity(PeerId(1), UserId(10));
|
||||
stage_and_retire(&mut device, set_attribute("first", 1));
|
||||
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(10));
|
||||
|
||||
// The person at the device changes: the next batch registers again, and the newer registration wins.
|
||||
device.document.user = UserId(20);
|
||||
stage_and_retire(&mut device, set_attribute("second", 2));
|
||||
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(20));
|
||||
let registrations = device.history().filter(|delta| matches!(delta.kind, RegistryDelta::RegisterPeer { .. })).count();
|
||||
assert_eq!(registrations, 2, "one registration per person the device stood for");
|
||||
|
||||
let mut other = Session::with_peer(PeerId(2));
|
||||
for delta in device.cloned_deltas().into_iter().rev() {
|
||||
other.document.apply_op_idempotent(delta.kind, delta.timestamp).unwrap();
|
||||
}
|
||||
assert_eq!(other.user_of(PeerId(1)), Some(UserId(20)), "the newest registration wins in any order");
|
||||
assert_eq!(other.user_of(PeerId(3)), None, "a peer never registered has no user");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_batch_past_the_last_sequence_is_refused_whole() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
session.restore_hot_sequence(crate::HotSequence(u64::MAX - 1));
|
||||
assert!(matches!(session.stage_ops([set_attribute("k", 1)]), Err(crate::CrdtError::SequencesExhausted)));
|
||||
assert!(session.hot_log().is_empty());
|
||||
}
|
||||
|
||||
/// The settled marks carry over a reopen, so a late copy of a retired op is dropped rather than retired again.
|
||||
#[test]
|
||||
fn a_reopened_session_drops_a_late_copy_of_a_retired_op() {
|
||||
let op = crate::HotOp {
|
||||
op: set_attribute("k", 1),
|
||||
timestamp: crate::TimeStamp { counter: 3, peer: PeerId(2) },
|
||||
sequence: crate::HotSequence(1),
|
||||
};
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
host.apply_hot_op(op.clone()).unwrap();
|
||||
host.retire(op.timestamp).unwrap();
|
||||
|
||||
let mut reopened = Session::load(PeerId(1), UserId(1), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
|
||||
reopened.absorb_settled_marks(host.settled_marks());
|
||||
reopened.apply_hot_op(op.clone()).unwrap();
|
||||
assert!(reopened.hot_log().is_empty());
|
||||
assert!(reopened.retire(op.timestamp).unwrap().is_empty());
|
||||
assert_eq!(reopened.history_len(), host.history_len());
|
||||
}
|
||||
|
||||
/// A local op naming a node never seen is refused before it writes anything, its target included, so the working
|
||||
/// registry stays the snapshot plus the hot log.
|
||||
#[test]
|
||||
fn a_refused_local_op_leaves_the_working_registry_unchanged() {
|
||||
let mut s = Session::with_peer(PeerId(1));
|
||||
let node = Node::new(NetworkId(1), Implementation::Network(NetworkId(1)), 1);
|
||||
s.stage_ops([
|
||||
RegistryDelta::AddNetwork {
|
||||
id: NetworkId(1),
|
||||
network: Network::default(),
|
||||
},
|
||||
RegistryDelta::AddNode { id: NodeId(1), node },
|
||||
])
|
||||
.unwrap();
|
||||
let before = s.registry().clone();
|
||||
|
||||
let refused = s.stage_ops([RegistryDelta::ChangeNodeInput {
|
||||
id: NodeId(1),
|
||||
index: 0,
|
||||
new_input: NodeInput::Node { id: NodeId(404), index: 0 },
|
||||
}]);
|
||||
assert!(matches!(refused, Err(CrdtError::TargetNodeDoesNotExist(_))));
|
||||
assert_eq!(s.registry(), &before, "the refused op's write to node 1 stayed in the working registry");
|
||||
}
|
||||
|
||||
/// A batch refused partway stages nothing: the caller only gets the error, so ops left staged would never be persisted
|
||||
/// or sent.
|
||||
#[test]
|
||||
fn a_refused_batch_stages_nothing() {
|
||||
let mut s = Session::with_peer(PeerId(1));
|
||||
s.stage_ops([RegistryDelta::AddNetwork {
|
||||
id: NetworkId(1),
|
||||
network: Network::default(),
|
||||
}])
|
||||
.unwrap();
|
||||
let hot_before = s.hot_log().len();
|
||||
let refused = s.stage_ops([
|
||||
set_attribute("lands", 1),
|
||||
RegistryDelta::ChangeNodeInput {
|
||||
id: NodeId(404),
|
||||
index: 0,
|
||||
new_input: NodeInput::Value {
|
||||
value: Value::from(serde_json::json!(1)),
|
||||
exposed: false,
|
||||
},
|
||||
},
|
||||
]);
|
||||
assert!(refused.is_err());
|
||||
assert_eq!(s.hot_log().len(), hot_before, "a refused batch stages nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settled_marks_round_trip_through_json() {
|
||||
let mut marks = crate::SettledHotOps::default();
|
||||
let id = |peer: u64, sequence: u64| HotOpId {
|
||||
peer: PeerId(peer),
|
||||
sequence: crate::HotSequence(sequence),
|
||||
};
|
||||
marks.extend([id(1, 1), id(1, 2), id(1, 5), id(u64::MAX, 3)]);
|
||||
let json = serde_json::to_string(&marks).unwrap();
|
||||
assert_eq!(serde_json::from_str::<crate::SettledHotOps>(&json).unwrap(), marks);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -7,23 +7,27 @@ use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput,
|
||||
use graph_craft::graphene_compiler::Compiler;
|
||||
use graph_craft::{ProtoNodeIdentifier, Type, concrete};
|
||||
|
||||
use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry, from_value};
|
||||
use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry};
|
||||
|
||||
/// Helper function to verify a NodeNetwork can be compiled successfully.
|
||||
/// Note: This only works for complete networks with all inputs resolved.
|
||||
/// Test networks with Import inputs will fail compilation (which is expected).
|
||||
fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
|
||||
let compiler = Compiler {};
|
||||
compiler.compile_single(network.clone()).map_err(|e| format!("Compilation failed: {:?}", e))?;
|
||||
compiler
|
||||
.compile_single(network.clone(), &graph_craft::proto::Registry::new())
|
||||
.map_err(|e| format!("Compilation failed: {:?}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Convert a runtime network to a storage `Registry`, returning the declarations alongside it.
|
||||
/// Proto-node declaration content is no longer stored in the registry (it lives in a byte store);
|
||||
/// these tests have no byte store, so they keep the extracted `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) {
|
||||
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
|
||||
@@ -244,11 +248,6 @@ fn test_nested_network_flattening() {
|
||||
#[test]
|
||||
fn test_metadata_preservation() {
|
||||
// Create a network with nodes that have non-default metadata
|
||||
let context_features = ContextDependencies {
|
||||
extract: core_types::context::ContextFeatures::FOOTPRINT | core_types::context::ContextFeatures::REAL_TIME,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
@@ -258,7 +257,6 @@ fn test_metadata_preservation() {
|
||||
inputs: vec![NodeInput::import(concrete!(f64), 0), NodeInput::import(Type::Generic(Cow::Borrowed("T")), 1)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::NodeWithMetadata")),
|
||||
call_argument: concrete!(String),
|
||||
context_features,
|
||||
visible: false, // Non-default value
|
||||
skip_deduplication: true, // Non-default value
|
||||
..Default::default()
|
||||
@@ -292,8 +290,12 @@ fn test_metadata_preservation() {
|
||||
let conv_node_1 = converted.nodes.get(&NodeId(1)).unwrap();
|
||||
assert_eq!(orig_node_1.call_argument, conv_node_1.call_argument, "call_argument for node 1 should be preserved");
|
||||
|
||||
// Verify context_features is preserved
|
||||
assert_eq!(orig_node_0.context_features, conv_node_0.context_features, "context_features should be preserved");
|
||||
// Verify context_features is not stored
|
||||
assert_eq!(
|
||||
conv_node_0.context_features,
|
||||
ContextDependencies::default(),
|
||||
"context_features should resolve at compile, not round-trip"
|
||||
);
|
||||
|
||||
// Verify visible is preserved
|
||||
assert_eq!(orig_node_0.visible, conv_node_0.visible, "visible should be preserved");
|
||||
@@ -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 declarations = conversion.declarations;
|
||||
let declarations = conversion.declarations().expect("rebuild declarations");
|
||||
let registry = conversion.registry;
|
||||
|
||||
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");
|
||||
|
||||
// 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())]);
|
||||
|
||||
// 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");
|
||||
}
|
||||
|
||||
/// A node-input `TaggedValue::Number` must survive the storage round-trip bit-exact. Inputs are stored
|
||||
/// type-erased as a `Value`, so this guards against any precision loss in the f64
|
||||
/// -> Value -> f64 path for a value with a full 17-significant-digit mantissa.
|
||||
/// A node-input `TaggedValue::F64` must survive the storage round-trip bit-exact. Inputs are stored as a
|
||||
/// self-describing `serde_json::Value` (encoded with the registry's MessagePack codec), so this guards
|
||||
/// against any precision loss in the f64 -> serde_json::Number -> f64 path for a value with a full
|
||||
/// 17-significant-digit mantissa.
|
||||
#[test]
|
||||
fn node_input_f64_round_trips_bit_exact() {
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
@@ -622,7 +625,7 @@ fn node_input_f64_round_trips_bit_exact() {
|
||||
nodes: [(
|
||||
NodeId(0),
|
||||
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")),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -639,8 +642,8 @@ fn node_input_f64_round_trips_bit_exact() {
|
||||
let NodeInput::Value { tagged_value, .. } = input else {
|
||||
panic!("expected a value input, got {input:?}")
|
||||
};
|
||||
let TaggedValue::Number(actual) = &**tagged_value else {
|
||||
panic!("expected Number, got {:?}", tagged_value)
|
||||
let TaggedValue::F64(actual) = &**tagged_value else {
|
||||
panic!("expected F64, got {:?}", tagged_value)
|
||||
};
|
||||
|
||||
assert_eq!(actual.to_bits(), precise.to_bits(), "f64 node input drifted: {actual} != {precise}");
|
||||
@@ -658,7 +661,7 @@ fn duplicate_runtime_node_id_is_rejected() {
|
||||
|
||||
// Force both root-network nodes onto the same runtime ID.
|
||||
for node in registry.node_instances.values_mut() {
|
||||
node.attributes.set(crate::attr::node::ORIGINAL_NODE_ID, 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");
|
||||
@@ -757,28 +760,18 @@ fn cyclic_network_reference_is_rejected() {
|
||||
registry.node_instances.insert(
|
||||
crate::NodeId(0),
|
||||
Node {
|
||||
presence: Default::default(),
|
||||
added: Default::default(),
|
||||
inputs_timestamp: Default::default(),
|
||||
implementation: Implementation::Network(child_network_id),
|
||||
implementation_timestamp: Default::default(),
|
||||
inputs: Vec::new(),
|
||||
attributes: crate::Attributes::default(),
|
||||
attributes_timestamp: Default::default(),
|
||||
network: crate::ROOT_NETWORK,
|
||||
},
|
||||
);
|
||||
registry.node_instances.insert(
|
||||
crate::NodeId(1),
|
||||
Node {
|
||||
presence: Default::default(),
|
||||
added: Default::default(),
|
||||
inputs_timestamp: Default::default(),
|
||||
implementation: Implementation::Network(crate::ROOT_NETWORK),
|
||||
implementation_timestamp: Default::default(),
|
||||
inputs: Vec::new(),
|
||||
attributes: crate::Attributes::default(),
|
||||
attributes_timestamp: Default::default(),
|
||||
network: child_network_id,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -10,7 +10,7 @@ use rustc_hash::{FxHashMap, FxHashSet};
|
||||
|
||||
use crate::attr::*;
|
||||
use crate::metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry};
|
||||
use crate::{AttributesRead, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId, Value, from_value};
|
||||
use crate::{AttributesRead, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ConversionError {
|
||||
@@ -38,8 +38,7 @@ pub enum ConversionError {
|
||||
pub type Declarations = std::collections::HashMap<ResourceId, ProtoNode>;
|
||||
|
||||
impl Registry {
|
||||
/// Returns the network plus one metadata entry per node, since every node carries an identity to
|
||||
/// restore even when it has no `ui::*` attribute.
|
||||
/// Returns the network plus per-node metadata entries (one per node carrying any `ui::*` attribute).
|
||||
pub fn to_runtime_with_metadata(&self, declarations: &Declarations) -> Result<(NodeNetwork, Vec<NodeMetadataEntry>), ConversionError> {
|
||||
let (network, node_entries, _) = self.to_runtime_with_full_metadata(declarations)?;
|
||||
Ok((network, node_entries))
|
||||
@@ -51,7 +50,19 @@ impl Registry {
|
||||
let mut node_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
|
||||
// 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
|
||||
/// `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
|
||||
/// `from_runtime`.
|
||||
pub fn to_resource_registry(&self) -> Result<graphene_resource::ResourceRegistry, ConversionError> {
|
||||
let mut registry = graphene_resource::ResourceRegistry::new();
|
||||
|
||||
for (id, entry) in &self.resources {
|
||||
for (_, source) in entry.live_sources() {
|
||||
let decoded: graphene_resource::DataSource = from_value(&source.source).map_err(|error| ConversionError::DeserializationError(error.to_string()))?;
|
||||
for (_, source) in &entry.sources {
|
||||
let decoded: graphene_resource::DataSource = serde_json::from_value(source.source.clone()).map_err(|error| ConversionError::DeserializationError(error.to_string()))?;
|
||||
registry.push_source_back(id, decoded);
|
||||
}
|
||||
if let Some(hash) = entry.hash {
|
||||
@@ -92,26 +103,6 @@ struct ConversionContext<'a> {
|
||||
nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &'a Node)>>,
|
||||
}
|
||||
|
||||
impl<'a> ConversionContext<'a> {
|
||||
fn new(registry: &'a Registry, declarations: &'a Declarations) -> Self {
|
||||
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
|
||||
for (&global_id, node) in ®istry.node_instances {
|
||||
nodes_by_network.entry(node.network).or_default().push((global_id, node));
|
||||
}
|
||||
Self {
|
||||
registry,
|
||||
declarations,
|
||||
nodes_by_network,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The id the node had in the runtime it was converted from, kept as an attribute so a conversion back
|
||||
/// lands it under the id the editor's metadata is keyed by.
|
||||
fn runtime_node_id(global_id: NodeId, node: &Node) -> RuntimeNodeId {
|
||||
RuntimeNodeId(node.attributes.get_typed(node::ORIGINAL_NODE_ID).unwrap_or(global_id.0))
|
||||
}
|
||||
|
||||
/// Converts a single network. Recurses through `Implementation::Network` owning nodes.
|
||||
///
|
||||
/// **ID remapping:** Registry uses globally hashed IDs; runtime networks need local IDs. We pull
|
||||
@@ -174,19 +165,21 @@ fn convert_network(
|
||||
node_collector: &mut Option<Vec<NodeMetadataEntry>>,
|
||||
network_collector: &mut Option<Vec<NetworkMetadataEntry>>,
|
||||
) -> 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() {
|
||||
collector.push(extract_network_metadata(context.registry, &network.attributes, metadata_path, network_id));
|
||||
collector.push(extract_network_metadata(&network.attributes, metadata_path, network_id));
|
||||
}
|
||||
|
||||
let mut nodes: FxHashMap<RuntimeNodeId, DocumentNode> = FxHashMap::default();
|
||||
for &(global_id, node) in context.nodes_by_network.get(&network_id).map(Vec::as_slice).unwrap_or_default() {
|
||||
let runtime_id = runtime_node_id(global_id, node);
|
||||
let local_id = runtime_id.0;
|
||||
let local_id = node.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(global_id.0);
|
||||
let runtime_id = RuntimeNodeId(local_id);
|
||||
|
||||
if let Some(collector) = node_collector.as_mut() {
|
||||
collector.push(extract_ui_metadata(node, global_id, metadata_path, runtime_id));
|
||||
if let Some(collector) = node_collector.as_mut()
|
||||
&& let Some(entry) = extract_ui_metadata(node, metadata_path, runtime_id)
|
||||
{
|
||||
collector.push(entry);
|
||||
}
|
||||
|
||||
let doc_node = convert_node(context, node, metadata_path, runtime_id, node_collector, network_collector)?;
|
||||
@@ -240,15 +233,16 @@ 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()
|
||||
}
|
||||
|
||||
/// Emitted for every node, since `storage_id` is worth restoring even where no `ui::*` attribute is.
|
||||
/// `input_metadata` is always sized to match `node.inputs.len()` for a strict slot-by-slot rebuild;
|
||||
/// empty slots use `InputMetadataEntry::default()`.
|
||||
fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[RuntimeNodeId], local_id: RuntimeNodeId) -> NodeMetadataEntry {
|
||||
/// Returns `None` when the node has no `ui::*` attributes at all so callers don't end up with
|
||||
/// empty entries for unconverted-from-runtime nodes. `input_metadata` is always sized to match
|
||||
/// `node.inputs.len()` for a strict slot-by-slot rebuild; empty slots use `InputMetadataEntry::default()`.
|
||||
fn extract_ui_metadata(node: &crate::Node, network_path: &[RuntimeNodeId], local_id: RuntimeNodeId) -> Option<NodeMetadataEntry> {
|
||||
let position: Option<Position> = node.attributes.get_typed(node::ui::POSITION);
|
||||
let is_layer = node.attributes.get_or(node::ui::IS_LAYER, false);
|
||||
let display_name: Option<String> = node.attributes.get_typed(node::ui::DISPLAY_NAME);
|
||||
@@ -258,10 +252,9 @@ fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[R
|
||||
|
||||
let input_metadata: Vec<InputMetadataEntry> = node.inputs.iter().map(|slot| &slot.attributes).map(extract_input_metadata).collect();
|
||||
|
||||
NodeMetadataEntry {
|
||||
let entry = NodeMetadataEntry {
|
||||
network_path: network_path.to_vec(),
|
||||
local_id,
|
||||
storage_id,
|
||||
position,
|
||||
is_layer,
|
||||
display_name,
|
||||
@@ -269,36 +262,22 @@ fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[R
|
||||
pinned,
|
||||
input_metadata,
|
||||
output_names,
|
||||
}
|
||||
};
|
||||
(!entry.is_empty()).then_some(entry)
|
||||
}
|
||||
|
||||
/// Node references stored here are storage IDs, resolved back to runtime-local IDs the way
|
||||
/// `read_scope_injections` does. A reference to a node that is no longer in this network is dropped
|
||||
/// rather than failing the conversion: a pinned node can have been deleted.
|
||||
fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes, network_path: &[RuntimeNodeId], network_id: NetworkId) -> NetworkMetadataEntry {
|
||||
let to_runtime_id = |storage_id: NodeId| {
|
||||
let node = registry.node_instances.get(&storage_id).filter(|node| node.network == network_id)?;
|
||||
Some(runtime_node_id(storage_id, node))
|
||||
};
|
||||
|
||||
let pinned_order = attributes
|
||||
.get_typed::<Vec<NodeId>>(network::PINNED_ORDER)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter_map(to_runtime_id)
|
||||
.collect();
|
||||
|
||||
fn extract_network_metadata(attributes: &crate::Attributes, network_path: &[RuntimeNodeId], network_id: NetworkId) -> NetworkMetadataEntry {
|
||||
NetworkMetadataEntry {
|
||||
network_path: network_path.to_vec(),
|
||||
network_id,
|
||||
reference: attributes.get_typed(node::ui::REFERENCE),
|
||||
pinned_order,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reassembles `input_data` by scanning every attribute under `ui::input_data::` and stripping the prefix.
|
||||
fn extract_input_metadata(attributes: &crate::Attributes) -> InputMetadataEntry {
|
||||
let input_data: HashMap<String, Value> = crate::attributes::live(attributes)
|
||||
let input_data: HashMap<String, serde_json::Value> = attributes
|
||||
.iter()
|
||||
.filter_map(|(key, value)| key.strip_prefix(node::input::ui::DATA_PREFIX).map(|sub_key| (sub_key.to_owned(), value.value.clone())))
|
||||
.collect();
|
||||
|
||||
@@ -331,8 +310,8 @@ fn convert_node(
|
||||
implementation: convert_implementation(context, &node.implementation, metadata_path, runtime_node_id, node_collector, network_collector)?,
|
||||
visible: node.attributes.get_or(node::VISIBLE, true),
|
||||
skip_deduplication: node.attributes.get_or(node::SKIP_DEDUPLICATION, false),
|
||||
context_features: node.attributes.get_or_default(node::CONTEXT_FEATURES),
|
||||
// Regenerated during compilation; not stored.
|
||||
context_features: Default::default(),
|
||||
original_location: Default::default(),
|
||||
})
|
||||
}
|
||||
@@ -340,9 +319,7 @@ fn convert_node(
|
||||
fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput, input_attributes: &crate::Attributes) -> Result<GraphCraftNodeInput, ConversionError> {
|
||||
Ok(match input {
|
||||
NodeInput::Node { id: node_id, index: output_index } => {
|
||||
// A node removed concurrently keeps its id, as the editor holds a dangling input; only a node
|
||||
// never seen has no id to map to.
|
||||
let referenced = registry.node_or_removed(*node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
|
||||
let referenced = registry.node_instances.get(node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
|
||||
|
||||
// Runtime references are local to one network. A cross-network reference would remap to a
|
||||
// local ID that doesn't exist in the current runtime network, so reject it.
|
||||
@@ -353,13 +330,14 @@ fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput,
|
||||
});
|
||||
}
|
||||
|
||||
let local_id = referenced.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(node_id.0);
|
||||
GraphCraftNodeInput::Node {
|
||||
node_id: runtime_node_id(*node_id, referenced),
|
||||
node_id: RuntimeNodeId(local_id),
|
||||
output_index: *output_index as usize,
|
||||
}
|
||||
}
|
||||
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 {
|
||||
tagged_value: MemoHash::new(tagged_value),
|
||||
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]);
|
||||
}
|
||||
}
|
||||
+9
-15
@@ -1,17 +1,14 @@
|
||||
[package]
|
||||
name = "graphite-editor"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
publish = false
|
||||
version = "0.0.0"
|
||||
rust-version = "1.88"
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
edition = "2024"
|
||||
readme = "../README.md"
|
||||
homepage = "https://graphite.art"
|
||||
repository = "https://github.com/GraphiteEditor/Graphite"
|
||||
license = "Apache-2.0"
|
||||
|
||||
[features]
|
||||
default = ["gpu"]
|
||||
@@ -47,7 +44,6 @@ tsify = { workspace = true }
|
||||
dyn-any = { workspace = true }
|
||||
num_enum = { workspace = true }
|
||||
usvg = { workspace = true }
|
||||
simplecss = { workspace = true }
|
||||
once_cell = { workspace = true }
|
||||
web-sys = { workspace = true }
|
||||
vello = { workspace = true }
|
||||
@@ -75,5 +71,3 @@ wasm-bindgen-futures = { workspace = true }
|
||||
# Workspace dependencies
|
||||
env_logger = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
core-types = { workspace = true }
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
use std::env;
|
||||
use std::process::Command;
|
||||
|
||||
const GRAPHITE_RELEASE_SERIES: &str = "Alpha 5";
|
||||
const GRAPHITE_RELEASE_SERIES: &str = "Alpha 4";
|
||||
|
||||
fn main() {
|
||||
// Instruct Cargo to rerun this build script if any of these environment variables change.
|
||||
|
||||
@@ -14,14 +14,14 @@ impl Editor {
|
||||
environment: Environment,
|
||||
uuid_random_seed: u64,
|
||||
resource_storage: Arc<dyn ResourceStorage>,
|
||||
document_store: Arc<dyn document_container::store::DocumentStore>,
|
||||
working_copy_root: Option<std::path::PathBuf>,
|
||||
mut application_io: PlatformApplicationIo,
|
||||
wake: Wake,
|
||||
) -> Self {
|
||||
ENVIRONMENT.set(environment).expect("Editor shoud only be initialized once");
|
||||
graphene_std::uuid::set_uuid_seed(uuid_random_seed);
|
||||
|
||||
let mut dispatcher = Dispatcher::new(resource_storage, document_store);
|
||||
let mut dispatcher = Dispatcher::new(resource_storage, working_copy_root);
|
||||
dispatcher.message_handlers.future_message_handler.set_wake(wake);
|
||||
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
|
||||
crate::node_graph_executor::replace_application_io(application_io);
|
||||
|
||||
@@ -135,9 +135,7 @@ pub const LINE_ROTATE_SNAP_ANGLE: f64 = 15.;
|
||||
|
||||
// BRUSH TOOL
|
||||
pub const BRUSH_SIZE_CHANGE_KEYBOARD: f64 = 5.;
|
||||
pub const BRUSH_SIZE_DEFAULT: f64 = 40.;
|
||||
pub const BRUSH_HARDNESS_DEFAULT: f64 = 0.;
|
||||
pub const BRUSH_FLOW_DEFAULT: f64 = 100.;
|
||||
pub const DEFAULT_BRUSH_SIZE: f64 = 20.;
|
||||
|
||||
// EYEDROPPER TOOL
|
||||
pub const EYEDROPPER_PREVIEW_AREA_RESOLUTION: u32 = 11;
|
||||
@@ -193,9 +191,5 @@ pub const UI_SCALE_DEFAULT: f64 = 1.;
|
||||
pub const UI_SCALE_MIN: f64 = 0.5;
|
||||
pub const UI_SCALE_MAX: f64 = 3.;
|
||||
|
||||
// DIALOGS
|
||||
pub const MAX_UNSAVED_DOCUMENTS_IN_DIALOG: usize = 5;
|
||||
pub const MAX_DOCUMENT_NAME_LENGTH_IN_DIALOG: usize = 60;
|
||||
|
||||
// ACTIONS
|
||||
pub const BLEND_COUNT_PER_LAYER: usize = 10;
|
||||
+17
-20
@@ -36,7 +36,7 @@ pub struct DispatcherMessageHandlers {
|
||||
pub(crate) portfolio_message_handler: PortfolioMessageHandler,
|
||||
preferences_message_handler: PreferencesMessageHandler,
|
||||
pub(crate) resource_storage_message_handler: ResourceStorageMessageHandler,
|
||||
pub(crate) tool_message_handler: ToolMessageHandler,
|
||||
tool_message_handler: ToolMessageHandler,
|
||||
viewport_message_handler: ViewportMessageHandler,
|
||||
}
|
||||
|
||||
@@ -89,19 +89,15 @@ const DEBUG_MESSAGE_BLOCK_LIST: &[MessageDiscriminant] = &[
|
||||
const DEBUG_MESSAGE_ENDING_BLOCK_LIST: &[&str] = &["PointerMove", "PointerOutsideViewport", "Overlays", "Draw", "CurrentTime", "Time"];
|
||||
|
||||
impl Dispatcher {
|
||||
pub fn new(resource_storage: Arc<dyn ResourceStorage>, 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();
|
||||
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
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self {
|
||||
let mut s = Self::new(
|
||||
Arc::new(graph_craft::application_io::resource::HashMapResourceStorage::new()),
|
||||
Arc::new(document_container::store::MemoryStore::default()),
|
||||
);
|
||||
let mut s = Self::default();
|
||||
s.message_handlers.portfolio_message_handler = PortfolioMessageHandler::with_executor(executor);
|
||||
s
|
||||
}
|
||||
@@ -269,8 +265,8 @@ impl Dispatcher {
|
||||
Message::MenuBar(message) => {
|
||||
let menu_bar_message_handler = &mut self.message_handlers.menu_bar_message_handler;
|
||||
|
||||
menu_bar_message_handler.focus_document = self.message_handlers.portfolio_message_handler.workspace.panel_layout.focus_document;
|
||||
let layout = &self.message_handlers.portfolio_message_handler.workspace.panel_layout;
|
||||
menu_bar_message_handler.focus_document = self.message_handlers.portfolio_message_handler.workspace_panel_layout.focus_document;
|
||||
let layout = &self.message_handlers.portfolio_message_handler.workspace_panel_layout;
|
||||
menu_bar_message_handler.data_panel_open = layout.is_panel_present(PanelType::Data);
|
||||
menu_bar_message_handler.layers_panel_open = layout.is_panel_present(PanelType::Layers);
|
||||
menu_bar_message_handler.properties_panel_open = layout.is_panel_present(PanelType::Properties);
|
||||
@@ -430,7 +426,6 @@ impl Dispatcher {
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::messages::portfolio::ingest::utility_types::IngestAction;
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
|
||||
#[tokio::test]
|
||||
@@ -482,11 +477,9 @@ mod test {
|
||||
"Demo artwork '{document_name}' has more than 1 line (remember to open and re-save it in Graphite)",
|
||||
);
|
||||
|
||||
let responses = editor.editor.handle_message(IngestMessage::Ingest {
|
||||
data: document_serialized_content.into_bytes(),
|
||||
action: IngestAction::Open,
|
||||
mime_type: String::new(),
|
||||
path: Some(file_name.into()),
|
||||
let responses = editor.editor.handle_message(PortfolioMessage::OpenFile {
|
||||
path: file_name.into(),
|
||||
content: document_serialized_content.bytes().collect(),
|
||||
});
|
||||
|
||||
// Check if the graph renders
|
||||
@@ -499,11 +492,15 @@ mod test {
|
||||
if let FrontendMessage::UpdateLayout {
|
||||
layout_target: LayoutTarget::DialogColumn1,
|
||||
diff,
|
||||
} = response && let DiffUpdate::Layout(sub_layout) = &diff[0].new_value
|
||||
&& let LayoutGroup::Row(WidgetRow { widgets }) = &sub_layout.0[0]
|
||||
&& let Widget::TextLabel(TextLabel { value, .. }) = &*widgets[0].widget
|
||||
} = response
|
||||
{
|
||||
print_problem_to_terminal_on_failure(value);
|
||||
if let DiffUpdate::Layout(sub_layout) = &diff[0].new_value {
|
||||
if let LayoutGroup::Row(WidgetRow { widgets }) = &sub_layout.0[0] {
|
||||
if let Widget::TextLabel(TextLabel { value, .. }) = &*widgets[0].widget {
|
||||
print_problem_to_terminal_on_failure(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,5 +19,3 @@ pub mod node_graph_executor;
|
||||
pub mod test_utils;
|
||||
pub mod utility_traits;
|
||||
pub mod utility_types;
|
||||
|
||||
pub use document_container::store as document_store;
|
||||
@@ -5,7 +5,6 @@ use crate::messages::prelude::*;
|
||||
pub enum AppWindowMessage {
|
||||
PointerLock,
|
||||
PointerLockMove { x: f64, y: f64 },
|
||||
DirectInput { enabled: bool },
|
||||
Restart,
|
||||
Close,
|
||||
Minimize,
|
||||
|
||||
Loaded 100 of 607 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user