Compare commits

...
Author SHA1 Message Date
Keavon Chambers 41e589bb9a Rework the assign transform nodes to apply per-instance and fix rotation for Copy to Points parity 2026-06-28 12:49:29 -07:00
Timon 51adb6ea1f WIP 2026-06-28 12:40:21 -07:00
Dennis Kobert a979ccd5bd Add document-format RFC draft (#4264)
* Add document-format RFC draft

* Align document-format RFC with graph-storage implementation

* Update writing style

* Recharacterize resource source chain as LWW-element-set, not add-wins OR-set

* Add Rev identity rationale framed against Git, plus patch-id future item

* Correct RFC inaccuracies found in implementation audit

* Mark unimplemented retirement coarsening and leader election as future; fix resurrection mechanism

* Add hot-log to the on-disk payload list in the architecture diagram
2026-06-28 19:05:30 +00:00
Keavon Chambers fa27d53b98 Add a Vite plugin to auto-prefix -webkit-user-select so it's not so often forgotten (#4288)
* Add a Vite plugin to auto-prefix -webkit-user-select so it's not so often forgotten

* Enforce a property boundary on the left
2026-06-28 00:20:26 -07:00
Keavon Chambers cc465d6f2a Fix the 'Separate Subpaths' node dropping a layer's transform when it has no subpaths (#4289)
Fix the Separate Subpaths node dropping a layer's transform when it has no subpaths
2026-06-27 23:42:25 -07:00
Timon 21bf290013 Hide node parameters connected to a NodeInput::Scope in the Properties panel (#4284)
Hide inputs connected to a scope in properties panel
2026-06-26 09:48:14 +00:00
TimonandJames Lindsay 684496109a Fix a previewed node's dashed output wire appearing at the wrong position (#4282)
* Fix node graph connection to export in wrong place

Co-authored-by: James Lindsay <[email protected]>

* Review

---------

Co-authored-by: James Lindsay <[email protected]>
2026-06-26 09:43:00 +00:00
Timon f3faefd460 Snap overlays to device instead of UI pixels on web (#4281)
Snap overlays to physical instead of logical pixels on web
2026-06-25 09:04:36 +00:00
Timon 6fb6e83d68 Desktop: Prefer Vulkan as the WGPU backend on Linux (#4270)
* Manual wgpu adapter selection

* Fall back to remaining adapters when the preferred one fails to initialize
2026-06-25 00:09:39 +00:00
Keavon Chambers ebbbb6bd1b Fix the Shift-drag alignment guide anchoring to the prior selection instead of the dragged layer (#4278) 2026-06-23 02:28:06 -07:00
Dennis Kobert 03c33dc784 Fix error from running cargo check with a system global Cargo config.toml rustflags override (#4277)
Fix error caused by running cargo check in the workspace
2026-06-23 09:09:19 +00:00
jneemandKeavon Chambers 57ee2b00ca Bump linesweeper to 0.4 (#4273)
* Bump linesweeper to 0.4

* Avoid crash if there's an indexing bug

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-06-23 00:15:55 +00:00
Keavon Chambers 1158d93bb4 Migrate legacy gradients via an isolated measurement pre-pass (#4268)
* Migrate legacy gradients via an isolated measurement pre-pass

Convert legacy bounding-box-relative Fill::Gradient values to absolute
space on document load by measuring each fill's evaluated geometry,
rather than walking each layer's primary flow. The pre-pass scans the
whole root network so fills on secondary branches (e.g. a Copy to Points
instance) and fills in hidden, disabled, or orphaned branches are all
found, redirecting the document export to each fill in turn to force its
branch to evaluate and reading its geometry back from the inspect result.

With every legacy gradient converted before any render, the legacy
bounding-box render path is removed: the ATTR_GRADIENT_LEGACY marker, the
renderer's legacy brush branch, and fill_to_graphic_list's bbox bake all
go away. Gradients nested inside subgraph node networks are out of scope
and warned about.

* Address review: harden gradient migration against stalls and document switches

- Advance the queue on dispatch early returns (missing export or channel
  send error) so a failure can't leave the migration permanently stuck
  with the document unable to render.
- Tag the migration with its DocumentId: cancel-and-restart when a
  different document's migration is requested, and only apply a
  measurement to the active document's in-progress migration, so
  switching documents mid-migration can't stall or cross-apply.

* Remove nested network non-migration warning

* Cleanup

* Also add migrations for Fill node backup colors

* Apply migrations to the demo art
2026-06-22 16:59:22 -07:00
Keavon Chambers c1fa8ba8da Move NumberInput.svelte input processing from JS to Rust (#4274)
* Move NumberInput.svelte input processing from JS to Rust

* Fix edge cases
2026-06-22 14:57:11 -07:00
TimonandKeavon Chambers f798b48b83 Move branding and package install into cargo-run (#4266)
* Move branding asset fetch into cargo-run

* Move frontend npm install into cargo-run

* Rename branding::ensure to branding::setup

* Wording nits

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-06-22 20:21:46 +00:00
Keavon Chambers b286e89746 Make the Pen tool's preview segment follow the cursor during a G/R/S handle transform (#4269) 2026-06-22 01:37:23 -07:00
Timon d753ce26f7 Make the cargo-run tool auto-install its wasm-opt build dependency (#4256)
* Allow auto downloading wasm-opt

* Fix for mac

* Review
2026-06-21 20:17:54 +00:00
TimonandKeavon Chambers a72ac39059 Replace the dev server's wasm-pack, cargo-watch, and concurrently tools with custom cargo-run tooling (#4254)
Replace wasm-pack, cargo-watch and concurrently with custom build tooling

Co-authored-by: Keavon Chambers <[email protected]>
2026-06-21 12:48:31 -07:00
Keavon Chambers 1f05000238 Exclude viewport zoom from influencing scale in the Transform node set by the drawing tools (#4260)
* Keep viewport zoom out of drawing tools' Transform node

* Simplify window-aligned transform helpers and fix spline DragStop fallback
2026-06-21 12:09:21 -07:00
Dennis Kobert b45cc312dd Add support for opening GDD documents from the CLI (#4262)
* Wire document-format into graphene-cli

* Support loading both legacy and new graphite files in the cli

* Address PR review: propagate CLI errors and use dyn resolver

* Fix CLI network wrap + preprocessor ordering

* Cleanup preprocessor

* Remove unused import
2026-06-21 18:17:01 +02:00
88 changed files with 2767 additions and 1200 deletions

No files matched your search

+3 -3
View File
@@ -1,8 +1,8 @@
[build]
# Keep `--cfg=web_sys_unstable_apis` here so the wasm wrapper crates build with the same web-sys API signatures (e.g. `put_image_data`/`get_image_data` taking `i32` rather than `f64`) on both native test builds and the wasm target. Cargo applies `[build]` rustflags only when no target-specific rustflags table matches, so the wasm-specific list below must continue to include this cfg.
# Keep `--cfg=web_sys_unstable_apis` here so the wasm wrapper crates build with the same web-sys API signatures (e.g. `put_image_data`/`get_image_data` taking `i32` rather than `f64`) on both native and the wasm target.
[target.'cfg(not(target_family = "wasm"))']
rustflags = ["--cfg=web_sys_unstable_apis"]
[target.wasm32-unknown-unknown]
[target.'cfg(target_family = "wasm")']
rustflags = [
# Currently disabled because of https://github.com/GraphiteEditor/Graphite/issues/1262
# The current simd implementation leads to undefined behavior
+1 -1
View File
@@ -6,7 +6,7 @@
},
"ghcr.io/devcontainers/features/node:1": {}
},
"onCreateCommand": "cargo install cargo-watch wasm-pack cargo-about && cargo install -f [email protected]",
"onCreateCommand": "cargo install cargo-about && cargo install -f [email protected]",
"customizations": {
"vscode": {
// NOTE: Keep this in sync with `.vscode/extensions.json`
+28 -12
View File
@@ -58,6 +58,8 @@ jobs:
RUSTC_WRAPPER: /usr/bin/sccache
CARGO_INCREMENTAL: 0
SCCACHE_DIR: /var/lib/github-actions/.cache
WASM_BINDGEN_CLI_VERSION: "0.2.121"
BINARYEN_VERSION: "130"
steps:
- name: 📥 Clone repository
uses: actions/checkout@v6
@@ -65,19 +67,11 @@ jobs:
repository: ${{ inputs.checkout_repo || github.repository }}
ref: ${{ inputs.checkout_ref || '' }}
- name: 🗑 Clear wasm-bindgen cache
run: rm -r ~/.cache/.wasm-pack || true
- name: 🟢 Install Node.js
uses: actions/setup-node@v6
with:
node-version-file: .nvmrc
- name: 🚧 Install build dependencies
run: |
cd frontend
npm run setup
- name: 🦀 Install Rust
uses: actions-rust-lang/setup-rust-toolchain@v1
with:
@@ -87,6 +81,19 @@ jobs:
rustflags: ""
target: wasm32-unknown-unknown
- name: 🚧 Install wasm-bindgen-cli and Binaryen wasm-opt
run: |
if ! wasm-bindgen --version 2>/dev/null | grep -qF "$WASM_BINDGEN_CLI_VERSION"; then
cargo install -f "wasm-bindgen-cli@$WASM_BINDGEN_CLI_VERSION"
fi
BINARYEN_DIR="$HOME/.cache/binaryen-version_$BINARYEN_VERSION"
if [ ! -x "$BINARYEN_DIR/bin/wasm-opt" ]; then
mkdir -p "$BINARYEN_DIR"
curl -sSfL "https://github.com/WebAssembly/binaryen/releases/download/version_$BINARYEN_VERSION/binaryen-version_$BINARYEN_VERSION-x86_64-linux.tar.gz" | tar xz -C "$BINARYEN_DIR" --strip-components=1
fi
echo "$BINARYEN_DIR/bin" >> "$GITHUB_PATH"
- name: 🔀 Choose production deployment environment and insert template
id: production-env
if: github.event_name == 'push'
@@ -294,6 +301,7 @@ jobs:
env:
WASM_BINDGEN_CLI_VERSION: "0.2.121"
BINARYEN_VERSION: "130"
steps:
- name: 📥 Clone repository
@@ -341,13 +349,15 @@ jobs:
winget install --id LLVM.LLVM -e --accept-package-agreements --accept-source-agreements
winget install --id Kitware.CMake -e --accept-package-agreements --accept-source-agreements
winget install --id OpenSSL.OpenSSL -e --accept-package-agreements --accept-source-agreements
winget install --id WebAssembly.Binaryen -e --accept-package-agreements --accept-source-agreements
winget install --id GnuWin32.PkgConfig -e --accept-package-agreements --accept-source-agreements
"OPENSSL_DIR=C:\Program Files\OpenSSL-Win64" | Out-File -FilePath $env:GITHUB_ENV -Append
"PKG_CONFIG_PATH=C:\Program Files\OpenSSL-Win64\lib\pkgconfig" | Out-File -FilePath $env:GITHUB_ENV -Append
cargo binstall --no-confirm --force wasm-pack
curl.exe -sSfL -o "$env:RUNNER_TEMP\binaryen.tar.gz" "https://github.com/WebAssembly/binaryen/releases/download/version_$env:BINARYEN_VERSION/binaryen-version_$env:BINARYEN_VERSION-x86_64-windows.tar.gz"
tar -xzf "$env:RUNNER_TEMP\binaryen.tar.gz" -C $env:RUNNER_TEMP
"$env:RUNNER_TEMP\binaryen-version_$env:BINARYEN_VERSION\bin" | Out-File -FilePath $env:GITHUB_PATH -Append
cargo binstall --no-confirm --force cargo-about
cargo binstall --no-confirm --force "wasm-bindgen-cli@$env:WASM_BINDGEN_CLI_VERSION"
@@ -485,6 +495,7 @@ jobs:
env:
WASM_BINDGEN_CLI_VERSION: "0.2.121"
BINARYEN_VERSION: "130"
steps:
- name: 📥 Clone repository
@@ -529,7 +540,6 @@ jobs:
brew install \
pkg-config \
openssl@3 \
binaryen \
llvm \
cargo-binstall
@@ -537,7 +547,13 @@ jobs:
echo "PKG_CONFIG_PATH=$(brew --prefix openssl@3)/lib/pkgconfig" >> $GITHUB_ENV
echo "$(brew --prefix llvm)/bin" >> $GITHUB_PATH
cargo binstall --no-confirm --force wasm-pack
BINARYEN_DIR="$HOME/.cache/binaryen-version_$BINARYEN_VERSION"
if [ ! -x "$BINARYEN_DIR/bin/wasm-opt" ]; then
mkdir -p "$BINARYEN_DIR"
curl -sSfL "https://github.com/WebAssembly/binaryen/releases/download/version_$BINARYEN_VERSION/binaryen-version_$BINARYEN_VERSION-arm64-macos.tar.gz" | tar xz -C "$BINARYEN_DIR" --strip-components=1
fi
echo "$BINARYEN_DIR/bin" >> "$GITHUB_PATH"
cargo binstall --no-confirm --force cargo-about
cargo binstall --no-confirm --force "wasm-bindgen-cli@${WASM_BINDGEN_CLI_VERSION}"
-2
View File
@@ -30,7 +30,6 @@ pkgs.mkShell (
pkgs.nodejs
pkgs.binaryen
pkgs.wasm-bindgen-cli_0_2_121
pkgs.wasm-pack
pkgs.cargo-about
pkgs.rustc
@@ -41,7 +40,6 @@ pkgs.mkShell (
pkgs.git
pkgs.cargo-watch
pkgs.cargo-nextest
pkgs.cargo-expand
+1 -3
View File
@@ -84,7 +84,6 @@ deps.crane.lib.buildPackage (
pkgs.nodejs
pkgs.binaryen
pkgs.wasm-bindgen-cli_0_2_121
pkgs.wasm-pack
pkgs.cargo-about
pkgs.removeReferencesTo
pkgs.importNpmLock.npmConfigHook
@@ -94,7 +93,6 @@ deps.crane.lib.buildPackage (
npmRoot = "${info.src}/frontend";
};
npmRoot = "frontend";
npmConfigScript = "setup";
makeCacheWritable = true;
env = {
@@ -111,7 +109,7 @@ deps.crane.lib.buildPackage (
'';
preBuild = ''
# Prevent `package-installer.js` from trying to update npm dependencies
# Prevent `cargo-run`'s frontend setup from trying to update npm dependencies
touch -r frontend/package-lock.json -d '+1 year' frontend/node_modules/.install-timestamp
export HOME="$TMPDIR"
Generated
+237 -47
View File
@@ -209,9 +209,9 @@ checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
[[package]]
name = "aws-lc-rs"
version = "1.16.2"
version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a054912289d18629dc78375ba2c3726a3afe3ff71b4edba9dedfca0e3446d1fc"
checksum = "d9a7b350e3bb1767102698302bc37256cbd48422809984b98d292c40e2579aa9"
dependencies = [
"aws-lc-sys",
"zeroize",
@@ -219,9 +219,9 @@ dependencies = [
[[package]]
name = "aws-lc-sys"
version = "0.39.0"
version = "0.37.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa7e52a4c5c547c741610a2c6f123f3881e409b714cd27e6798ef020c514f0a"
checksum = "b092fe214090261288111db7a2b2c2118e5a7f30dc2569f1732c4069a6840549"
dependencies = [
"cc",
"cmake",
@@ -354,7 +354,7 @@ version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
dependencies = [
"objc2 0.6.4",
"objc2 0.6.3",
]
[[package]]
@@ -421,9 +421,9 @@ checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
[[package]]
name = "bytes"
version = "1.11.1"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"
[[package]]
name = "bzip2"
@@ -505,9 +505,31 @@ dependencies = [
name = "cargo-run"
version = "0.0.0"
dependencies = [
"duct",
"semver",
"thiserror 2.0.18",
]
[[package]]
name = "cargo-run-internal-download"
version = "0.0.0"
dependencies = [
"cargo-run",
"flate2",
"sha2",
"tar",
"ureq",
]
[[package]]
name = "cargo-run-internal-watch"
version = "0.0.0"
dependencies = [
"cargo-run",
"notify",
"notify-debouncer-full",
]
[[package]]
name = "cargo-util-schemas"
version = "0.8.2"
@@ -582,7 +604,7 @@ dependencies = [
"clap",
"libc",
"libloading 0.9.0",
"objc2 0.6.4",
"objc2 0.6.3",
"objc2-foundation 0.3.2",
"objc2-io-surface",
"objc2-metal 0.3.2",
@@ -1120,9 +1142,9 @@ checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
[[package]]
name = "deranged"
version = "0.5.8"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
checksum = "9c9e6a11ca8224451684bc0d7d5a7adbf8f2fd6887261a1cfc3c0432f9d4068e"
dependencies = [
"powerfmt",
]
@@ -1213,7 +1235,7 @@ dependencies = [
"bitflags 2.11.0",
"block2 0.6.2",
"libc",
"objc2 0.6.4",
"objc2 0.6.3",
]
[[package]]
@@ -1335,6 +1357,18 @@ dependencies = [
"dtoa",
]
[[package]]
name = "duct"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e66e9c0c03d094e1a0ba1be130b849034aa80c3a2ab8ee94316bc809f3fa684"
dependencies = [
"libc",
"os_pipe",
"shared_child",
"shared_thread",
]
[[package]]
name = "dunce"
version = "1.0.5"
@@ -1514,6 +1548,15 @@ dependencies = [
"log",
]
[[package]]
name = "file-id"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1fc6a637b6dc58414714eddd9170ff187ecb0933d4c7024d1abbd23a3cc26e9"
dependencies = [
"windows-sys 0.60.2",
]
[[package]]
name = "filetime"
version = "0.2.26"
@@ -1637,6 +1680,15 @@ version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
[[package]]
name = "fsevent-sys"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2"
dependencies = [
"libc",
]
[[package]]
name = "futf"
version = "0.1.5"
@@ -1994,6 +2046,8 @@ version = "0.1.0"
dependencies = [
"chrono",
"clap",
"document-container",
"document-format",
"fern",
"futures",
"graph-craft",
@@ -2142,7 +2196,7 @@ dependencies = [
"interprocess",
"lzma-rust2",
"muda",
"objc2 0.6.4",
"objc2 0.6.3",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"open",
@@ -2241,6 +2295,7 @@ dependencies = [
"js-sys",
"kurbo",
"log",
"math-parser",
"num_enum",
"once_cell",
"preprocessor",
@@ -2283,7 +2338,6 @@ dependencies = [
"graphite-editor",
"js-sys",
"log",
"math-parser",
"node-macro",
"ron",
"serde",
@@ -2788,11 +2842,28 @@ dependencies = [
[[package]]
name = "indoc"
version = "2.0.7"
version = "2.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706"
checksum = "f4c7245a08504955605670dbf141fceab975f15ca21570696aebe9d2e71576bd"
[[package]]
name = "inotify"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "533e68a5842e734946fe159fb03fc9bbbb254f590dd0d8ad321ae5ff7beca2c1"
dependencies = [
"rustversion",
"bitflags 2.11.0",
"inotify-sys",
"libc",
]
[[package]]
name = "inotify-sys"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e05c02b5e89bff3b946cedeca278abc628fe811e604f027c45a8aa3cf793d0eb"
dependencies = [
"libc",
]
[[package]]
@@ -2990,6 +3061,26 @@ version = "3.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc"
[[package]]
name = "kqueue"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "273c0752728918e0ac4976f2b275b6fefb9ecd400585dec929419f3844cd87b5"
dependencies = [
"kqueue-sys",
"libc",
]
[[package]]
name = "kqueue-sys"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087"
dependencies = [
"bitflags 2.11.0",
"libc",
]
[[package]]
name = "kurbo"
version = "0.13.1"
@@ -3075,9 +3166,9 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "linesweeper"
version = "0.3.0"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8421b276e96af0ace5f3d8d2d165d0dea07fe764d2fe94ec06bb1acaf8a1e759"
checksum = "9c19728333c060c6569a53c9a0e56c4be0df52cb4e6e07a8fbe16084cecce769"
dependencies = [
"arrayvec",
"kurbo",
@@ -3255,6 +3346,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78bed444cc8a2160f01cbcf811ef18cac863ad68ae8ca62092e8db51d51c761c"
dependencies = [
"libc",
"log",
"wasi 0.11.1+wasi-snapshot-preview1",
"windows-sys 0.59.0",
]
@@ -3282,7 +3374,7 @@ dependencies = [
"crossbeam-channel",
"dpi",
"keyboard-types",
"objc2 0.6.4",
"objc2 0.6.3",
"objc2-app-kit 0.3.2",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
@@ -3431,6 +3523,46 @@ dependencies = [
"syn 2.0.106",
]
[[package]]
name = "notify"
version = "8.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d3d07927151ff8575b7087f245456e549fea62edf0ec4e565a5ee50c8402bc3"
dependencies = [
"bitflags 2.11.0",
"fsevent-sys",
"inotify",
"kqueue",
"libc",
"log",
"mio",
"notify-types",
"walkdir",
"windows-sys 0.60.2",
]
[[package]]
name = "notify-debouncer-full"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c02b49179cfebc9932238d04d6079912d26de0379328872846118a0fa0dbb302"
dependencies = [
"file-id",
"log",
"notify",
"notify-types",
"walkdir",
]
[[package]]
name = "notify-types"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42b8cfee0e339a0337359f3c88165702ac6e600dc01c0cc9579a92d62b08477a"
dependencies = [
"bitflags 2.11.0",
]
[[package]]
name = "nu-ansi-term"
version = "0.50.1"
@@ -3451,9 +3583,9 @@ dependencies = [
[[package]]
name = "num-conv"
version = "0.2.0"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf97ec579c3c42f953ef76dbf8d55ac91fb219dde70e49aa4a6b7d74e9919050"
checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9"
[[package]]
name = "num-derive"
@@ -3525,9 +3657,9 @@ dependencies = [
[[package]]
name = "objc2"
version = "0.6.4"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f"
checksum = "b7c2599ce0ec54857b29ce62166b0ed9b4f6f1a70ccc9a71165b6154caca8c05"
dependencies = [
"objc2-encode",
]
@@ -3556,7 +3688,7 @@ checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"
dependencies = [
"bitflags 2.11.0",
"block2 0.6.2",
"objc2 0.6.4",
"objc2 0.6.3",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
]
@@ -3582,7 +3714,7 @@ dependencies = [
"bitflags 2.11.0",
"block2 0.6.2",
"dispatch2",
"objc2 0.6.4",
"objc2 0.6.3",
]
[[package]]
@@ -3646,7 +3778,7 @@ dependencies = [
"bitflags 2.11.0",
"block2 0.6.2",
"libc",
"objc2 0.6.4",
"objc2 0.6.3",
"objc2-core-foundation",
]
@@ -3658,7 +3790,7 @@ checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"
dependencies = [
"bitflags 2.11.0",
"libc",
"objc2 0.6.4",
"objc2 0.6.3",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
]
@@ -3684,7 +3816,7 @@ dependencies = [
"bitflags 2.11.0",
"block2 0.6.2",
"dispatch2",
"objc2 0.6.4",
"objc2 0.6.3",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
"objc2-io-surface",
@@ -3710,7 +3842,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"
dependencies = [
"bitflags 2.11.0",
"objc2 0.6.4",
"objc2 0.6.3",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
"objc2-metal 0.3.2",
@@ -3723,7 +3855,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22"
dependencies = [
"bitflags 2.11.0",
"objc2 0.6.4",
"objc2 0.6.3",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
]
@@ -3805,6 +3937,16 @@ dependencies = [
"num-traits",
]
[[package]]
name = "os_pipe"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.61.2",
]
[[package]]
name = "owned_ttf_parser"
version = "0.25.1"
@@ -4500,7 +4642,7 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135"
dependencies = [
"objc2 0.6.4",
"objc2 0.6.3",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
"objc2-quartz-core 0.3.2",
@@ -4699,7 +4841,7 @@ dependencies = [
"js-sys",
"libc",
"log",
"objc2 0.6.4",
"objc2 0.6.3",
"objc2-app-kit 0.3.2",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
@@ -4843,9 +4985,9 @@ dependencies = [
[[package]]
name = "rustls"
version = "0.23.37"
version = "0.23.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "758025cb5fccfd3bc2fd74708fd4682be41d99e5dff73c377c0646c6012c73a4"
checksum = "c0ebcbd2f03de0fc1122ad9bb24b127a5a6cd51d72604a3f3c50ac459762b6cc"
dependencies = [
"aws-lc-rs",
"log",
@@ -4917,9 +5059,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"
[[package]]
name = "rustls-webpki"
version = "0.103.10"
version = "0.103.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df33b2b81ac578cabaf06b89b0631153a3f416b0a886e8a7a1707fb51abbd1ef"
checksum = "0a17884ae0c1b773f1ccd2bd4a8c72f16da897310a98b0e84bf349ad5ead92fc"
dependencies = [
"aws-lc-rs",
"ring",
@@ -5205,12 +5347,60 @@ dependencies = [
"lazy_static",
]
[[package]]
name = "shared_child"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e362d9935bc50f019969e2f9ecd66786612daae13e8f277be7bfb66e8bed3f7"
dependencies = [
"libc",
"sigchld",
"windows-sys 0.60.2",
]
[[package]]
name = "shared_thread"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52b86057fcb5423f5018e331ac04623e32d6b5ce85e33300f92c79a1973928b0"
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "sigchld"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47106eded3c154e70176fc83df9737335c94ce22f821c32d17ed1db1f83badb1"
dependencies = [
"libc",
"os_pipe",
"signal-hook",
]
[[package]]
name = "signal-hook"
version = "0.3.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"
dependencies = [
"libc",
"signal-hook-registry",
]
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
dependencies = [
"errno",
"libc",
]
[[package]]
name = "simd-adler32"
version = "0.3.7"
@@ -5702,30 +5892,30 @@ dependencies = [
[[package]]
name = "time"
version = "0.3.47"
version = "0.3.41"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c"
checksum = "8a7619e19bc266e0f9c5e6686659d394bc57973859340060a69221e57dbc0c40"
dependencies = [
"deranged",
"itoa",
"num-conv",
"powerfmt",
"serde_core",
"serde",
"time-core",
"time-macros",
]
[[package]]
name = "time-core"
version = "0.1.8"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca"
checksum = "c9e9a38711f559d9e3ce1cdb06dd7c5b8ea546bc90052da6d06bb76da74bb07c"
[[package]]
name = "time-macros"
version = "0.2.27"
version = "0.2.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215"
checksum = "3526739392ec93fd8b359c8e98514cb3e8e021beb4e5f597b00a0221f8ed8a49"
dependencies = [
"num-conv",
"time-core",
@@ -6784,7 +6974,7 @@ dependencies = [
"log",
"naga",
"ndk-sys",
"objc2 0.6.4",
"objc2 0.6.3",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
"objc2-metal 0.3.2",
@@ -7390,7 +7580,7 @@ dependencies = [
"block2 0.6.2",
"dispatch2",
"dpi",
"objc2 0.6.4",
"objc2 0.6.3",
"objc2-app-kit 0.3.2",
"objc2-core-foundation",
"objc2-core-graphics",
@@ -7409,7 +7599,7 @@ version = "0.30.12"
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
dependencies = [
"memmap2 0.9.10",
"objc2 0.6.4",
"objc2 0.6.3",
"objc2-core-foundation",
"smol_str",
"tracing",
@@ -7457,7 +7647,7 @@ dependencies = [
"block2 0.6.2",
"dispatch2",
"dpi",
"objc2 0.6.4",
"objc2 0.6.3",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
"objc2-ui-kit",
+4 -3
View File
@@ -7,8 +7,8 @@ members = [
"desktop/platform/linux",
"desktop/platform/mac",
"desktop/platform/win",
"document/container",
"document/graph-storage",
"document/container",
"document/document-format",
"editor",
"frontend/wrapper",
@@ -27,6 +27,7 @@ members = [
"node-graph/preprocessor",
"proc-macros",
"tools/cargo-run",
"tools/cargo-run/internal/*",
"tools/crate-hierarchy-viz",
"tools/third-party-licenses",
"tools/editor-message-tree",
@@ -106,6 +107,7 @@ rustc-hash = "2.0"
bytemuck = { version = "1.13", features = ["derive", "min_const_generics"] }
serde = { version = "1.0", features = ["derive", "rc"] }
serde_json = "1.0"
rmp-serde = "1.3"
serde_bytes = "0.11"
serde-wasm-bindgen = "0.6"
reqwest = { version = "0.13", features = ["blocking", "json"] }
@@ -172,7 +174,6 @@ color = "0.3"
# Linebender ecosystem (END)
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
rand_chacha = "0.9"
rmp-serde = "1.3"
glam = { version = "0.32.1", default-features = false, features = [
"nostd-libm",
"scalar-math",
@@ -227,7 +228,7 @@ 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"
linesweeper = "0.3"
linesweeper = "0.4"
smallvec = "1.13.2"
zip = { version = "8", default-features = false }
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Fill":{"Solid":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"FillGradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}]},"gradient_type":"Linear","start":[0.09778450863315612,0.7264556766766779],"end":[0.09778450863315612,0.3634234796342139],"spread_method":"Pad"}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1789832635968548900,{"inputs":[{"Node":{"node_id":1924303400883620400,"output_index"Line 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":{"Fill":{"Solid":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"FillGradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}]},"gradient_type":"Linear","start":[9.606221358397944,-69.72678572415595],"end":[9.606221358397944,-162.2641409381776],"spread_method":"Pad","absolute":true,"transform":[1.0,0.0,0.0,1.0,0.0,0.0]}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1789832635968548900,{"inputs":[{"NLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183952488591282082,{"inputs":[{"Node":{"node_id":17965270694495451178,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,-6.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exportsLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183952488591282082,{"inputs":[{"Node":{"node_id":17965270694495451178,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,-6.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exportsLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Fill":{"Solid":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"FillGradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]},"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5],"spread_method":"Pad"}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::artboard::Artboard>"}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":4}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"NoLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Fill":{"Solid":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"FillGradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]},"gradient_type":"Linear","start":[-10.0,0.0],"end":[10.0,0.0],"spread_method":"Pad","absolute":true,"transform":[1.0,0.0,0.0,1.0,0.0,0.0]}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::artboard::Artboard>"}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":4}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"FillGradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]},"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5],"spread_method":"Pad"}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNodLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"FillGradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]},"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5],"spread_method":"Pad","absolute":true,"transform":[1.0,0.0,0.0,1.0,0.0,0.0]}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::contLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":6559102076450693000,"output_index":0}},{"Value":{"tagged_value":{"Fill":{"Gradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]},"gradient_type":"Radial","start":[0.4915209831246563,0.36613756613756576],"end":[0.49551110871305326,0.9947089947089944],"spread_method":"Pad"}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"FillGradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]},"gradient_type":"Radial","start":[0.4915209831246563,0.36613756613756576],"end":[0.49551110871305326,0.9947089947089944],"spread_method":"Pad"}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.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":{"Fill":{"Gradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]},"gradient_type":"Radial","start":[-0.22577926355610423,34.981204988590605],"end":[-0.11953019835323353,66.53737705977504],"spread_method":"Pad","absolute":true,"transform":[0.0033669629737862325,-0.9999943317641021,0.9999943317641021,0.0033669629737862325,-35.2060257800042,34.63764658282962]}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"FillGradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]},"gradient_type":"Radial","start":[-0.22577926355610423,34.981204988590605],"end":[-0.11953019835323353,66.53737705977504],"spread_method":"Pad","absolute":true,"transform":[0.0033669629737862325,-0.9999943317641021,0.9999943317641021,0.0033669629737862325,-35.2060257800042,34.63764658282962]}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Fill":{"Solid":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"FillGradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]},"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5],"spread_method":"Pad"}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedCoLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Fill":{"Solid":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"FillGradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]},"gradient_type":"Linear","start":[604.9565968314213,108.54930650815423],"end":[607.1269623532997,108.54930650815423],"spread_method":"Pad","absolute":true,"transform":[1.0,0.0,0.0,1.0,0.0,0.0]}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_indLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scLine truncated
+8 -10
View File
@@ -1,20 +1,18 @@
use crate::wrapper::{WgpuContext, WgpuContextBuilder, WgpuFeatures};
pub(super) async fn create_wgpu_context() -> WgpuContext {
let wgpu_context_builder = WgpuContextBuilder::new().with_features(WgpuFeatures::IMMEDIATES);
let mut wgpu_context_builder = WgpuContextBuilder::new().with_features(WgpuFeatures::IMMEDIATES);
// TODO: make this configurable via cli flags instead
if let Some(index) = std::env::var("GRAPHITE_WGPU_ADAPTER").ok().and_then(|s| s.parse().ok()) {
tracing::info!("Overriding WGPU adapter selection with adapter index {index}");
wgpu_context_builder = wgpu_context_builder.with_selection(index);
}
// TODO: add a cli flag to list adapters and exit instead of always printing
println!("\nAvailable WGPU adapters:\n{}", wgpu_context_builder.available_adapters_fmt().await);
// TODO: make this configurable via cli flags instead
let wgpu_context = match std::env::var("GRAPHITE_WGPU_ADAPTER").ok().and_then(|s| s.parse().ok()) {
None => wgpu_context_builder.build().await,
Some(adapter_index) => {
tracing::info!("Overriding WGPU adapter selection with adapter index {adapter_index}");
wgpu_context_builder.build_with_adapter_selection(|_| Some(adapter_index)).await
}
}
.expect("Failed to create WGPU context");
let wgpu_context = wgpu_context_builder.build().await.expect("Failed to create WGPU context");
// TODO: add a cli flag to list adapters and exit instead of always printing
println!("Using WGPU adapter: {:?}", wgpu_context.adapter.get_info());
+1
View File
@@ -8,6 +8,7 @@ use std::sync::Arc;
pub use graph_craft::application_io::resource::MmapResourceStorage;
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
pub use wgpu_executor::WgpuBackends;
pub use wgpu_executor::WgpuContext;
pub use wgpu_executor::WgpuContextBuilder;
pub use wgpu_executor::WgpuExecutor;
+1
View File
@@ -23,6 +23,7 @@ graphene-hash = { workspace = true }
interpreted-executor = { workspace = true }
graphene-std = { workspace = true } # NOTE: `core-types` should not be added here because `graphene-std` re-exports its contents
preprocessor = { workspace = true }
math-parser = { workspace = true }
# Workspace dependencies
js-sys = { workspace = true }
@@ -310,11 +310,25 @@ impl LayoutMessageHandler {
let callback_message = (number_input.on_update.callback)(number_input);
responses.add(callback_message);
}
// TODO: This crashes when the cursor is in a text box, such as in the Text node, and the transform node is clicked (https://github.com/GraphiteEditor/Graphite/issues/1761)
Value::String(str) => match str.as_str() {
"Increment" => responses.add((number_input.increment_callback_increase.callback)(number_input)),
"Decrement" => responses.add((number_input.increment_callback_decrease.callback)(number_input)),
_ => panic!("Invalid string found when updating `NumberInput`"),
// A text-field commit sends the user's raw entry as a math expression to evaluate and validate.
Value::String(expression) => {
let Some(evaluated) = evaluate_and_validate_number_input(&expression, number_input) else { return };
// Skip the update (and its history transaction) when the value is unchanged, since the network interface would short-circuit it anyway.
if number_input.value == Some(evaluated) {
return;
}
// Snapshot the pre-change state for undo via `on_commit`, then apply the new value via `on_update`.
responses.add((number_input.on_commit.callback)(&()));
number_input.value = Some(evaluated);
responses.add((number_input.on_update.callback)(number_input));
}
// The increment arrows send `{ "increment": "Increase" | "Decrease" }` to invoke the backend's directional step callback.
Value::Object(ref command) => match command.get("increment").and_then(Value::as_str) {
Some("Increase") => responses.add((number_input.increment_callback_increase.callback)(number_input)),
Some("Decrease") => responses.add((number_input.increment_callback_decrease.callback)(number_input)),
_ => error!("NumberInput received an unrecognized command: {value:?}"),
},
_ => {}
},
@@ -524,3 +538,32 @@ fn populate_computed_display_fields(layout: &mut Layout) {
}
}
}
/// Evaluates a math expression committed in a `NumberInput`'s text field, then clamps and rounds it to the widget's constraints.
/// Returns `None` if the expression fails to parse, fails to evaluate, or yields a non-real number (such as `sqrt(-1)`).
fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInput) -> Option<f64> {
let value = math_parser::evaluate(expression)
.inspect_err(|err| error!("Math parser error on \"{expression}\": {err}"))
.ok()?
.0
.inspect_err(|err| error!("Math evaluate error on \"{expression}\": {err}"))
.ok()?;
let real = value.as_real()?;
if real.is_nan() {
return None;
}
let mut validated = real;
if let Some(min) = number_input.min {
validated = validated.max(min);
}
if let Some(max) = number_input.max {
validated = validated.min(max);
}
if number_input.is_integer {
validated = validated.round();
}
Some(validated)
}
@@ -225,8 +225,6 @@ pub enum DocumentMessage {
UpdateClickTargets {
click_targets: HashMap<NodeId, Vec<Arc<ClickTarget>>>,
},
// TODO: Eventually remove this document upgrade code
MigrateLegacyGradients,
UpdateOutlines {
outlines: HashMap<NodeId, Vec<Arc<ClickTarget>>>,
},
@@ -1372,38 +1372,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
.collect();
self.network_interface.update_click_targets(layer_click_targets);
}
// TODO: Eventually remove this document upgrade code
DocumentMessage::MigrateLegacyGradients => {
if self.pending_gradient_migration {
self.pending_gradient_migration = false;
// Read each layer's legacy gradient and compute its absolute form from the now-available local bounds
let layers: Vec<_> = self.metadata().all_layers().collect();
let conversions: Vec<(NodeId, Fill)> = layers
.into_iter()
.filter_map(|layer| {
let gradient = graph_modification_utils::get_gradient(layer, &self.network_interface)?;
if gradient.absolute {
return None;
}
let fill_node_id = graph_modification_utils::get_fill_node_id(layer, &self.network_interface)?;
let bounds = self.metadata().nonzero_bounding_box(layer);
let bounding_box = DAffine2::from_scale_angle_translation(bounds[1] - bounds[0], 0., bounds[0]);
let layer_transform = self.metadata().upstream_transform(layer.to_node());
Some((fill_node_id, Fill::Gradient(gradient.to_absolute(bounding_box, layer_transform))))
})
.collect();
let converted_any = !conversions.is_empty();
for (fill_node_id, fill) in conversions {
self.network_interface
.set_input(&InputConnector::node(fill_node_id, 1), NodeInput::value(TaggedValue::Fill(fill), false), &[]);
}
if converted_any {
responses.add(NodeGraphMessage::RunDocumentGraph);
}
}
}
DocumentMessage::UpdateOutlines { outlines } => {
let layer_outlines = outlines
.into_iter()
@@ -2281,6 +2281,14 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
} else {
let number_of_inputs = context.network_interface.number_of_inputs(&node_id, context.selection_network_path);
for input_index in 1..number_of_inputs {
// Hide inputs that are connected to a scope
if let Some(NodeInput::Scope(_)) = context
.network_interface
.input_from_connector(&InputConnector::node(node_id, input_index), context.selection_network_path)
{
continue;
}
let row = context.call_widget_override(&node_id, input_index).unwrap_or_else(|| {
let Some(implementation) = context.network_interface.implementation(&node_id, context.selection_network_path) else {
log::error!("Could not get implementation for node {node_id}");
@@ -230,10 +230,12 @@ impl OverlayContext {
}
self.render_context.begin_path();
self.render_context.move_to(polygon.last().unwrap().x.round() - 0.5, polygon.last().unwrap().y.round() - 0.5);
let last = self.snap_to_physical_pixel_center(*polygon.last().unwrap());
self.render_context.move_to(last.x, last.y);
for point in polygon {
self.render_context.line_to(point.x.round() - 0.5, point.y.round() - 0.5);
let p = self.snap_to_physical_pixel_center(*point);
self.render_context.line_to(p.x, p.y);
}
if let Some(color_fill) = color_fill {
@@ -286,8 +288,8 @@ impl OverlayContext {
.ok();
}
let start = start.round() - DVec2::splat(0.5);
let end = end.round() - DVec2::splat(0.5);
let start = self.snap_to_physical_pixel_center(start);
let end = self.snap_to_physical_pixel_center(end);
self.render_context.begin_path();
self.render_context.move_to(start.x, start.y);
@@ -328,7 +330,7 @@ impl OverlayContext {
dash_offset: Option<f64>,
) {
let color_stroke = color_stroke.unwrap_or(COLOR_OVERLAY_BLUE);
let center = center.round();
let center = self.snap_to_physical_pixel(center);
self.start_dpi_aware_transform();
@@ -397,7 +399,7 @@ impl OverlayContext {
transform: Option<DAffine2>,
) {
let color_stroke = color_stroke.unwrap_or(COLOR_OVERLAY_BLUE);
let position = position.round();
let position = self.snap_to_physical_pixel(position);
self.start_dpi_aware_transform();
@@ -455,7 +457,7 @@ impl OverlayContext {
pub fn manipulator_handle(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
self.start_dpi_aware_transform();
let position = position.round() - DVec2::splat(0.5);
let position = self.snap_to_physical_pixel_center(position);
self.render_context.begin_path();
self.render_context
@@ -553,7 +555,7 @@ impl OverlayContext {
pub fn hover_manipulator_handle(&mut self, position: DVec2, selected: bool) {
self.start_dpi_aware_transform();
let position = position.round() - DVec2::splat(0.5);
let position = self.snap_to_physical_pixel_center(position);
self.render_context.begin_path();
self.render_context
@@ -622,7 +624,7 @@ impl OverlayContext {
let color_fill = color_fill.unwrap_or(COLOR_OVERLAY_WHITE);
let color_stroke = color_stroke.unwrap_or(COLOR_OVERLAY_BLUE);
let position = position.round() - DVec2::splat(0.5);
let position = self.snap_to_physical_pixel_center(position);
let corner = position - DVec2::splat(size) / 2.;
self.start_dpi_aware_transform();
@@ -642,7 +644,7 @@ impl OverlayContext {
let size = 1.;
let color_fill = color.unwrap_or(COLOR_OVERLAY_WHITE);
let position = position.round() - DVec2::splat(0.5);
let position = self.snap_to_physical_pixel_center(position);
let corner = position - DVec2::splat(size) / 2.;
self.start_dpi_aware_transform();
@@ -727,7 +729,7 @@ impl OverlayContext {
self.start_dpi_aware_transform();
let center = compass_center.round() - DVec2::splat(0.5);
let center = self.snap_to_physical_pixel_center(compass_center);
// Save the old line width to restore it later
let old_line_width = self.render_context.line_width();
@@ -781,7 +783,7 @@ impl OverlayContext {
pub fn pivot(&mut self, position: DVec2, angle: f64) {
let uv = DVec2::from_angle(angle);
let (x, y) = (position.round() - DVec2::splat(0.5)).into();
let (x, y) = self.snap_to_physical_pixel_center(position).into();
self.start_dpi_aware_transform();
@@ -816,7 +818,7 @@ impl OverlayContext {
}
pub fn dowel_pin(&mut self, position: DVec2, angle: f64, color: Option<&str>) {
let (x, y) = (position.round() - DVec2::splat(0.5)).into();
let (x, y) = self.snap_to_physical_pixel_center(position).into();
let color = color.unwrap_or(COLOR_OVERLAY_YELLOW_DULL);
self.start_dpi_aware_transform();
@@ -941,29 +943,30 @@ impl OverlayContext {
};
let start_point = transform.transform_point2(point_to_dvec2(first.start()));
let start_point = self.snap_to_physical_pixel(start_point);
self.render_context.move_to(start_point.x, start_point.y);
for curve in curves {
match curve {
PathSeg::Line(line) => {
let a = transform.transform_point2(point_to_dvec2(line.p1));
let a = a.round() - DVec2::splat(0.5);
let a = self.snap_to_physical_pixel_center(a);
self.render_context.line_to(a.x, a.y);
}
PathSeg::Quad(quad_bez) => {
let a = transform.transform_point2(point_to_dvec2(quad_bez.p1));
let b = transform.transform_point2(point_to_dvec2(quad_bez.p2));
let a = a.round() - DVec2::splat(0.5);
let b = b.round() - DVec2::splat(0.5);
let a = self.snap_to_physical_pixel_center(a);
let b = self.snap_to_physical_pixel_center(b);
self.render_context.quadratic_curve_to(a.x, a.y, b.x, b.y);
}
PathSeg::Cubic(cubic_bez) => {
let a = transform.transform_point2(point_to_dvec2(cubic_bez.p1));
let b = transform.transform_point2(point_to_dvec2(cubic_bez.p2));
let c = transform.transform_point2(point_to_dvec2(cubic_bez.p3));
let a = a.round() - DVec2::splat(0.5);
let b = b.round() - DVec2::splat(0.5);
let c = c.round() - DVec2::splat(0.5);
let a = self.snap_to_physical_pixel_center(a);
let b = self.snap_to_physical_pixel_center(b);
let c = self.snap_to_physical_pixel_center(c);
self.render_context.bezier_curve_to(a.x, a.y, b.x, b.y, c.x, c.y);
}
}
@@ -1110,6 +1113,22 @@ impl OverlayContext {
self.line(quad.bottom_left(), quad.bottom_right(), None, None);
}
}
fn snap_to_physical_pixel(&self, p: DVec2) -> DVec2 {
let s = self.viewport.scale();
if !s.is_finite() || s <= 0.0 {
return p.round();
}
(p * s).round() / s
}
fn snap_to_physical_pixel_center(&self, p: DVec2) -> DVec2 {
let s = self.viewport.scale();
if !s.is_finite() || s <= 0.0 {
return p.round() - DVec2::splat(0.5);
}
self.snap_to_physical_pixel(p) - DVec2::splat(0.5 / s)
}
}
pub enum Pivot {
@@ -4239,6 +4239,10 @@ impl NodeNetworkInterface {
}
NodeTypePersistentMetadata::Node(_) => {}
}
// Altering an export may move the connectors meaning the ports must be refreshed.
if matches!(input_connector, InputConnector::Export(_)) {
self.unload_import_export_ports(network_path);
}
self.unload_upstream_node_click_targets(vec![*upstream_node_id], network_path);
self.unload_stack_dependents(network_path);
self.try_set_upstream_to_chain(input_connector, network_path);
@@ -5,6 +5,7 @@ use crate::messages::portfolio::document::node_graph::document_node_definitions:
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeTemplate, OutputConnector};
use crate::messages::prelude::DocumentMessageHandler;
use crate::messages::tool::common_functionality::graph_modification_utils;
use glam::{DVec2, IVec2};
use graph_craft::application_io::resource::{DataSource, Resource, ResourceHash, ResourceId};
use graph_craft::descriptor;
@@ -1121,8 +1122,8 @@ pub fn document_migration_replace_resources_referenced_by_hash(document_serializ
pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_node_definitions_on_open: bool) {
document.network_interface.migrate_path_modify_node();
// Legacy `Fill::Gradient`s are converted to absolute by the deferred migration pass once the first graph run yields geometry bounds
document.pending_gradient_migration = true;
// Legacy `Fill::Gradient`s are converted to absolute by the deferred migration pre-pass that measures each fill's geometry
document.pending_gradient_migration = !graph_modification_utils::legacy_gradient_fill_nodes(&document.network_interface).is_empty();
let network = document.network_interface.document_network().clone();
@@ -1621,6 +1621,13 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
// Use exact physical dimensions from browser (via ResizeObserver's devicePixelContentBoxSize)
let physical_resolution = viewport.size().to_physical().into_dvec2().round().as_uvec2();
// TODO: Eventually remove this document upgrade code
// A freshly-opened document with legacy gradients runs a one-time measurement pre-pass instead of rendering, until every gradient is converted to absolute space
if document.pending_gradient_migration {
self.executor.drive_gradient_migration(document, document_id, physical_resolution, scale, responses);
return;
}
// TODO: Remove this when we do the SVG rendering with a separate library on desktop, thus avoiding a need for the hole punch.
// TODO: See #3796. There is a second instance of this todo comment and code block (be sure to remove both).
#[cfg(not(target_family = "wasm"))]
@@ -1999,7 +2006,7 @@ impl PortfolioMessageHandler {
return Err("No active document".to_string());
};
let result = self.executor.poll_node_graph_evaluation(active_document, responses);
let result = self.executor.poll_node_graph_evaluation(active_document, document_id, responses);
if result.is_err() {
let error = r#"
<rect x="50%" y="50%" width="460" height="100" transform="translate(-230 -50)" rx="4" fill="var(--color-warning-yellow)" />
@@ -3,7 +3,7 @@ use crate::messages::portfolio::document::node_graph::document_node_definitions:
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeNetworkInterface, NodeTemplate};
use crate::messages::prelude::*;
use glam::DVec2;
use glam::{DAffine2, DVec2};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graph_craft::{ProtoNodeIdentifier, concrete};
@@ -319,6 +319,60 @@ pub fn get_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkI
Some(gradient.clone())
}
// TODO: Eventually remove this document upgrade code
/// The legacy bounding-box-relative gradient (`absolute == false`) in a "Fill" node's active `fill` input, if any.
fn legacy_active_gradient_in_fill_node(fill_node_id: NodeId, network_interface: &NodeNetworkInterface) -> Option<Gradient> {
let node = network_interface.document_network().nodes.get(&fill_node_id)?;
let TaggedValue::Fill(Fill::Gradient(gradient)) = node.inputs.get(graphene_std::vector::fill::FillInput::<Fill>::INDEX)?.as_value()? else {
return None;
};
(!gradient.absolute).then(|| gradient.clone())
}
// TODO: Eventually remove this document upgrade code
/// The legacy bounding-box-relative gradient (`absolute == false`) stashed in a "Fill" node's `_backup_gradient` input, if any.
/// The backup is inert until the fill is toggled back to a gradient, at which point it becomes the active fill, so it needs converting too.
fn legacy_backup_gradient_in_fill_node(fill_node_id: NodeId, network_interface: &NodeNetworkInterface) -> Option<Gradient> {
let node = network_interface.document_network().nodes.get(&fill_node_id)?;
let TaggedValue::FillGradient(gradient) = node.inputs.get(graphene_std::vector::fill::BackupGradientInput::INDEX)?.as_value()? else {
return None;
};
(!gradient.absolute).then(|| gradient.clone())
}
// TODO: Eventually remove this document upgrade code
/// Convert a "Fill" node's legacy gradients (the active `fill` and/or the stashed `_backup_gradient`) to absolute space using
/// the geometry's measured bounding box, writing each back in place. The active fill is written as a `Fill`, the backup as a bare `FillGradient`.
pub fn migrate_fill_node_gradients_to_absolute(fill_node_id: NodeId, network_interface: &mut NodeNetworkInterface, bounding_box: DAffine2, layer_transform: DAffine2) {
if let Some(gradient) = legacy_active_gradient_in_fill_node(fill_node_id, network_interface) {
let absolute = gradient.to_absolute(bounding_box, layer_transform);
let input = InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::<Fill>::INDEX);
network_interface.set_input(&input, NodeInput::value(TaggedValue::Fill(Fill::Gradient(absolute)), false), &[]);
}
if let Some(gradient) = legacy_backup_gradient_in_fill_node(fill_node_id, network_interface) {
let absolute = gradient.to_absolute(bounding_box, layer_transform);
let input = InputConnector::node(fill_node_id, graphene_std::vector::fill::BackupGradientInput::INDEX);
network_interface.set_input(&input, NodeInput::value(TaggedValue::FillGradient(absolute), false), &[]);
}
}
// TODO: Eventually remove this document upgrade code
/// Find every root-network "Fill" node holding a legacy bounding-box-relative gradient, either as its active `fill` or as its `_backup_gradient`.
///
/// Scans the document network structurally instead of walking each layer's primary flow, so it also catches fills on
/// secondary inputs and in hidden, disabled, or orphaned branches. Fills nested inside subgraph node networks are skipped.
pub fn legacy_gradient_fill_nodes(network_interface: &NodeNetworkInterface) -> Vec<NodeId> {
let fill_identifier = DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER);
network_interface
.document_network()
.nodes
.keys()
.copied()
.filter(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&fill_identifier))
.filter(|&node_id| legacy_active_gradient_in_fill_node(node_id, network_interface).is_some() || legacy_backup_gradient_in_fill_node(node_id, network_interface).is_some())
.collect()
}
/// Get the gradient stops of a layer, if any.
pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<GradientStops> {
let gradient_value_node = network_interface.document_network().nodes.get(&get_upstream_gradient_value_node_id(layer, network_interface)?)?;
@@ -181,3 +181,44 @@ impl Resize {
self.layer = None;
}
}
/// The viewport zoom factor, taken from the document-to-viewport transform so it accounts for zoom snapping and canvas flipping.
/// Divide a viewport-space measurement by this to convert it to document units.
pub fn viewport_zoom(document: &DocumentMessageHandler) -> f64 {
document.metadata().document_to_viewport.matrix2.determinant().abs().sqrt()
}
/// The viewport-space transform for a freshly drawn layer placed at `viewport_position`: window-aligned, so it is just the zoom (no tilt or flip).
/// Routing it through [`TransformIn::Viewport`] yields a document-space layer transform that counter-rotates the tilt/flip with the zoom left out.
/// `aspect` is an optional unitless local-frame stretch (e.g. for polygons and stars); pass [`DVec2::ONE`] for none.
pub fn window_aligned_transform(document: &DocumentMessageHandler, viewport_position: DVec2, aspect: DVec2) -> DAffine2 {
DAffine2::from_scale_angle_translation(viewport_zoom(document) * aspect, 0., viewport_position)
}
/// [`TransformSet`](GraphOperationMessage::TransformSet) applying [`window_aligned_transform`] to a freshly drawn layer, via
/// [`TransformIn::Viewport`] so the parent transform is resolved at execution time (also correct when the placement is deferred until after the graph runs).
pub fn window_aligned_transform_set(document: &DocumentMessageHandler, layer: LayerNodeIdentifier, viewport_position: DVec2, aspect: DVec2) -> Message {
GraphOperationMessage::TransformSet {
layer,
transform: window_aligned_transform(document, viewport_position, aspect),
transform_in: TransformIn::Viewport,
skip_rerender: false,
}
.into()
}
/// [`TransformSet`](GraphOperationMessage::TransformSet) placing a freshly drawn path-like layer (Pen, Freehand, Spline, Line, Arrow) at
/// `viewport_position` with only a translation: the drawn geometry holds the shape (including tilt), so the Transform node stays a pure document-space offset.
pub fn translation_transform_set(document: &DocumentMessageHandler, layer: LayerNodeIdentifier, viewport_position: DVec2) -> Message {
// Same orientation/scale as the document-to-viewport transform, but translated to land the layer's origin at the drawn viewport position.
let mut transform = document.metadata().document_to_viewport;
transform.translation = viewport_position;
GraphOperationMessage::TransformSet {
layer,
transform,
transform_in: TransformIn::Viewport,
skip_rerender: false,
}
.into()
}
@@ -1,6 +1,5 @@
use super::shape_utility::ShapeToolModifierKey;
use super::*;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeTemplate};
@@ -9,7 +8,6 @@ use crate::messages::tool::common_functionality::gizmos::shape_gizmos::sweep_ang
use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::common_functionality::shapes::shape_utility::{ShapeGizmoHandler, arc_outline};
use crate::messages::tool::tool_messages::tool_prelude::*;
use glam::DAffine2;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::vector::misc::ArcType;
@@ -159,29 +157,26 @@ impl Arc {
};
let dimensions = (start - end).abs();
let mut scale = DVec2::ONE;
let mut aspect = DVec2::ONE;
let radius: f64;
// We keep the smaller dimension's scale at 1 and scale the other dimension accordingly
if dimensions.x > dimensions.y {
scale.x = dimensions.x / dimensions.y;
aspect.x = dimensions.x / dimensions.y;
radius = dimensions.y / 2.;
} else {
scale.y = dimensions.y / dimensions.x;
aspect.y = dimensions.y / dimensions.x;
radius = dimensions.x / 2.;
}
let radius = radius / viewport_zoom(document);
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, 1),
input: NodeInput::value(TaggedValue::F64(radius), false),
});
responses.add(GraphOperationMessage::TransformSet {
layer,
transform: DAffine2::from_scale_angle_translation(scale, 0., start.midpoint(end)),
transform_in: TransformIn::Viewport,
skip_rerender: false,
});
responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), aspect));
}
}
}
@@ -1,15 +1,14 @@
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeTemplate};
use crate::messages::tool::common_functionality::gizmos::shape_gizmos::circle_arc_radius_handle::{RadiusHandle, RadiusHandleState};
use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::common_functionality::resize::{viewport_zoom, window_aligned_transform_set};
use crate::messages::tool::common_functionality::shape_editor::ShapeState;
use crate::messages::tool::common_functionality::shapes::shape_utility::{ShapeGizmoHandler, ShapeToolModifierKey};
use crate::messages::tool::tool_messages::shape_tool::ShapeToolData;
use crate::messages::tool::tool_messages::tool_prelude::*;
use glam::DAffine2;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
@@ -101,7 +100,7 @@ impl Circle {
return;
};
let dimensions = (start - end).abs();
let dimensions = ((start - end) / viewport_zoom(document)).abs();
// We keep the smaller dimension's scale at 1 and scale the other dimension accordingly
let radius: f64 = if dimensions.x > dimensions.y { dimensions.y / 2. } else { dimensions.x / 2. };
@@ -111,11 +110,6 @@ impl Circle {
input: NodeInput::value(TaggedValue::F64(radius), false),
});
responses.add(GraphOperationMessage::TransformSet {
layer,
transform: DAffine2::from_scale_angle_translation(DVec2::ONE, 0., start.midpoint(end)),
transform_in: TransformIn::Viewport,
skip_rerender: false,
});
responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), DVec2::ONE));
}
}
@@ -1,12 +1,10 @@
use super::shape_utility::ShapeToolModifierKey;
use super::*;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeTemplate};
use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::tool_messages::tool_prelude::*;
use glam::DAffine2;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use std::collections::VecDeque;
@@ -36,20 +34,17 @@ impl Ellipse {
return;
};
let radius = ((start - end) / 2. / viewport_zoom(document)).abs();
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, 1),
input: NodeInput::value(TaggedValue::F64(((start.x - end.x) / 2.).abs()), false),
input: NodeInput::value(TaggedValue::F64(radius.x), false),
});
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, 2),
input: NodeInput::value(TaggedValue::F64(((start.y - end.y) / 2.).abs()), false),
});
responses.add(GraphOperationMessage::TransformSet {
layer,
transform: DAffine2::from_translation(start.midpoint(end)),
transform_in: TransformIn::Viewport,
skip_rerender: false,
input: NodeInput::value(TaggedValue::F64(radius.y), false),
});
responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), DVec2::ONE));
}
}
}
@@ -1,6 +1,5 @@
use super::shape_utility::ShapeToolModifierKey;
use super::*;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
@@ -10,7 +9,6 @@ use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::common_functionality::shape_editor::ShapeState;
use crate::messages::tool::common_functionality::shapes::shape_utility::ShapeGizmoHandler;
use crate::messages::tool::tool_messages::tool_prelude::*;
use glam::DAffine2;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::NodeInputDecleration;
@@ -117,6 +115,8 @@ impl Grid {
let (translation, dimensions, angle) = calculate_grid_params(start, end, is_isometric, ipp.keyboard.key(center), ipp.keyboard.key(lock_ratio));
let dimensions = dimensions / viewport_zoom(document);
// Set dimensions/spacing
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, SpacingInput::<f64>::INDEX),
@@ -132,12 +132,7 @@ impl Grid {
}
// Set transform
responses.add(GraphOperationMessage::TransformSet {
layer,
transform: DAffine2::from_scale_angle_translation(DVec2::ONE, 0., translation),
transform_in: TransformIn::Viewport,
skip_rerender: false,
});
responses.add(window_aligned_transform_set(document, layer, translation, DVec2::ONE));
}
}
@@ -10,6 +10,7 @@ pub mod shape_utility;
pub mod spiral_shape;
pub mod star_shape;
pub use super::resize::{viewport_zoom, window_aligned_transform_set};
pub use super::shapes::arrow_shape::Arrow;
pub use super::shapes::ellipse_shape::Ellipse;
pub use super::shapes::line_shape::{Line, LineEnd};
@@ -1,6 +1,5 @@
use super::shape_utility::{ShapeToolModifierKey, update_radius_sign};
use super::*;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type};
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
@@ -12,7 +11,6 @@ use crate::messages::tool::common_functionality::shape_editor::ShapeState;
use crate::messages::tool::common_functionality::shapes::shape_utility::{ShapeGizmoHandler, polygon_outline};
use crate::messages::tool::tool_messages::shape_tool::ShapeOptionsUpdate;
use crate::messages::tool::tool_messages::tool_prelude::*;
use glam::DAffine2;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use std::collections::VecDeque;
@@ -132,16 +130,18 @@ impl Polygon {
let dimensions = (start - end).abs();
// We keep the smaller dimension's scale at 1 and scale the other dimension accordingly
let mut scale = DVec2::ONE;
let mut aspect = DVec2::ONE;
let radius;
if dimensions.x > dimensions.y {
scale.x = dimensions.x / dimensions.y;
aspect.x = dimensions.x / dimensions.y;
radius = dimensions.y / 2.;
} else {
scale.y = dimensions.y / dimensions.x;
aspect.y = dimensions.y / dimensions.x;
radius = dimensions.x / 2.;
}
let radius = radius / viewport_zoom(document);
let Some(node_id) = graph_modification_utils::get_polygon_id(layer, &document.network_interface) else {
return;
};
@@ -151,12 +151,7 @@ impl Polygon {
input: NodeInput::value(TaggedValue::F64(radius), false),
});
responses.add(GraphOperationMessage::TransformSet {
layer,
transform: DAffine2::from_scale_angle_translation(scale, 0., (start + end) / 2.),
transform_in: TransformIn::Viewport,
skip_rerender: false,
});
responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), aspect));
}
}
@@ -1,12 +1,10 @@
use super::shape_utility::ShapeToolModifierKey;
use super::*;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeTemplate};
use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::tool_messages::tool_prelude::*;
use glam::DAffine2;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use std::collections::VecDeque;
@@ -36,20 +34,17 @@ impl Rectangle {
return;
};
let size = ((start - end) / viewport_zoom(document)).abs();
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, 1),
input: NodeInput::value(TaggedValue::F64((start.x - end.x).abs()), false),
input: NodeInput::value(TaggedValue::F64(size.x), false),
});
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, 2),
input: NodeInput::value(TaggedValue::F64((start.y - end.y).abs()), false),
});
responses.add(GraphOperationMessage::TransformSet {
layer,
transform: DAffine2::from_translation(start.midpoint(end)),
transform_in: TransformIn::Viewport,
skip_rerender: false,
input: NodeInput::value(TaggedValue::F64(size.y), false),
});
responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), DVec2::ONE));
}
}
}
@@ -1,6 +1,5 @@
use super::*;
use crate::messages::frontend::utility_types::MouseCursorIcon;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type};
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
@@ -135,7 +134,7 @@ impl Spiral {
let snapped_viewport_point = document.metadata().document_to_viewport.transform_point2(snapped.snapped_point_document);
shape_tool_data.data.snap_manager.update_indicator(snapped);
let dragged_distance = (viewport_drag_start - snapped_viewport_point).length();
let dragged_distance = (viewport_drag_start - snapped_viewport_point).length() / viewport_zoom(document);
let Some(node_id) = graph_modification_utils::get_spiral_id(layer, &document.network_interface) else {
return;
@@ -155,12 +154,7 @@ impl Spiral {
SpiralType::Logarithmic => (dragged_distance).max(0.1),
};
responses.add(GraphOperationMessage::TransformSet {
layer,
transform: DAffine2::from_scale_angle_translation(DVec2::ONE, 0., viewport_drag_start),
transform_in: TransformIn::Viewport,
skip_rerender: false,
});
responses.add(window_aligned_transform_set(document, layer, viewport_drag_start, DVec2::ONE));
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, OuterRadiusInput::INDEX),
@@ -1,6 +1,5 @@
use super::shape_utility::{ShapeToolModifierKey, update_radius_sign};
use super::*;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type};
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
@@ -12,7 +11,6 @@ use crate::messages::tool::common_functionality::shape_editor::ShapeState;
use crate::messages::tool::common_functionality::shapes::shape_utility::{ShapeGizmoHandler, star_outline};
use crate::messages::tool::tool_messages::tool_prelude::*;
use core::f64;
use glam::DAffine2;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use std::collections::VecDeque;
@@ -137,16 +135,18 @@ impl Star {
let dimensions = (start - end).abs();
// We keep the smaller dimension's scale at 1 and scale the other dimension accordingly
let mut scale = DVec2::ONE;
let mut aspect = DVec2::ONE;
let radius: f64;
if dimensions.x > dimensions.y {
scale.x = dimensions.x / dimensions.y;
aspect.x = dimensions.x / dimensions.y;
radius = dimensions.y / 2.;
} else {
scale.y = dimensions.y / dimensions.x;
aspect.y = dimensions.y / dimensions.x;
radius = dimensions.x / 2.;
}
let radius = radius / viewport_zoom(document);
let Some(node_id) = graph_modification_utils::get_star_id(layer, &document.network_interface) else {
return;
};
@@ -161,12 +161,7 @@ impl Star {
input: NodeInput::value(TaggedValue::F64(radius / 2.), false),
});
responses.add(GraphOperationMessage::TransformSet {
layer,
transform: DAffine2::from_scale_angle_translation(scale, 0., (start + end) / 2.),
transform_in: TransformIn::Viewport,
skip_rerender: false,
});
responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), aspect));
}
}
}
@@ -1,5 +1,4 @@
use super::tool_prelude::*;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
use crate::messages::portfolio::document::overlays::utility_functions::path_endpoint_overlays;
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
@@ -9,6 +8,7 @@ use crate::messages::tool::common_functionality::color_selector::{
sync_drawing_state,
};
use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::common_functionality::resize::translation_transform_set;
use crate::messages::tool::common_functionality::stroke_options::{StrokeOptionsUpdate, apply_stroke_option, create_stroke_options_popover_widget};
use crate::messages::tool::common_functionality::utility_functions::should_extend;
use glam::DVec2;
@@ -309,16 +309,7 @@ impl Fsm for FreehandToolFsmState {
// Position the layer at the initial mouse position via Transform
responses.add(DeferMessage::AfterGraphRun {
messages: vec![
GraphOperationMessage::TransformSet {
layer,
transform: DAffine2::from_translation(input.mouse.position),
transform_in: TransformIn::Viewport,
skip_rerender: false,
}
.into(),
NodeGraphMessage::RunDocumentGraph.into(),
],
messages: vec![translation_transform_set(document, layer, input.mouse.position), NodeGraphMessage::RunDocumentGraph.into()],
});
FreehandToolFsmState::Drawing
@@ -337,7 +328,7 @@ impl Fsm for FreehandToolFsmState {
tool_data.new_layer_viewport_start = None;
}
let position = if let Some(start) = tool_data.new_layer_viewport_start {
input.mouse.position - start
document.metadata().document_to_viewport.inverse().transform_vector2(input.mouse.position - start)
} else {
transform.inverse().transform_point2(input.mouse.position)
};
@@ -1,7 +1,6 @@
use super::tool_prelude::*;
use crate::consts::{COLOR_OVERLAY_BLUE, COLOR_OVERLAY_BLUE_05, HIDE_HANDLE_DISTANCE, LINE_ROTATE_SNAP_ANGLE, SEGMENT_OVERLAY_SIZE};
use crate::messages::input_mapper::utility_types::input_mouse::MouseKeys;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
use crate::messages::portfolio::document::overlays::utility_functions::path_overlays;
use crate::messages::portfolio::document::overlays::utility_types::{DrawHandles, OverlayContext};
@@ -12,6 +11,7 @@ use crate::messages::tool::common_functionality::color_selector::{
sync_drawing_state,
};
use crate::messages::tool::common_functionality::graph_modification_utils::{self, merge_layers};
use crate::messages::tool::common_functionality::resize::translation_transform_set;
use crate::messages::tool::common_functionality::shape_editor::ShapeState;
use crate::messages::tool::common_functionality::snapping::{SnapCache, SnapCandidatePoint, SnapConstraint, SnapData, SnapManager, SnapTypeConfiguration};
use crate::messages::tool::common_functionality::stroke_options::{StrokeOptionsUpdate, apply_stroke_option, create_stroke_options_popover_widget};
@@ -1373,13 +1373,7 @@ impl PenToolData {
// Defer the transform setup and point insertion until after the layer is created
responses.add(DeferMessage::AfterGraphRun {
messages: vec![
GraphOperationMessage::TransformSet {
layer,
transform: DAffine2::from_translation(viewport_vec),
transform_in: TransformIn::Viewport,
skip_rerender: false,
}
.into(),
translation_transform_set(document, layer, viewport_vec),
GraphOperationMessage::Vector {
layer,
modification_type: VectorModificationType::InsertPoint { id, position: DVec2::ZERO },
@@ -1601,6 +1595,9 @@ impl Fsm for PenToolFsmState {
let vector = document.network_interface.compute_modified_vector(layer);
let Some(vector) = vector else { return PenToolFsmState::GRSHandle };
// Keep the preview segment's endpoint tracking the cursor while the outgoing handle is transformed by the GRS operation
tool_data.place_anchor(SnapData::new(document, input, viewport), transform, input.mouse.position, responses);
if let Some(latest_pt) = tool_data.latest_point_mut() {
let layer_space_to_viewport = document.metadata().transform_to_viewport(layer);
let final_pos = layer_space_to_viewport.inverse().transform_point2(final_position);
@@ -512,7 +512,6 @@ struct SelectToolData {
selected_layers_changed: bool,
snap_candidates: Vec<SnapCandidatePoint>,
auto_panning: AutoPanning,
drag_start_center: ViewportPosition,
}
impl SelectToolData {
@@ -529,6 +528,15 @@ impl SelectToolData {
}
}
/// The center of the combined viewport-space bounding box of the layers currently being dragged.
fn dragging_layers_center(&self, document: &DocumentMessageHandler) -> Option<ViewportPosition> {
self.layers_dragging
.iter()
.filter_map(|&layer| document.metadata().bounding_box_viewport(layer).map(Rect::from_box))
.reduce(Rect::combine_bounds)
.map(|bounds| bounds.center())
}
pub fn selection_quad(&self) -> Quad {
let bbox = self.selection_box();
Quad::from_box(bbox)
@@ -1021,7 +1029,18 @@ impl Fsm for SelectToolFsmState {
let angle = -mouse_position.angle_to(DVec2::X);
let snapped_angle = (angle / snap_resolution).round() * snap_resolution;
let origin = tool_data.drag_start_center;
// Anchor the guide to the dragged layers' center at the moment the drag began. It's computed live (rather than
// snapshotted at drag start) so it stays correct as the layers move and the viewport auto-pans: their current
// center minus the drag displacement recovers the start center in the present viewport frame. Sourcing it from
// the layers being dragged (not the prior selection's pivot) is what keeps it on the layer actually grabbed.
let origin = if matches!(self, Self::Dragging { .. }) {
tool_data
.dragging_layers_center(document)
.map(|center| center - (tool_data.drag_current - tool_data.drag_start))
.unwrap_or_else(|| tool_data.pivot_gizmo().position(document))
} else {
tool_data.pivot_gizmo().position(document)
};
let viewport_diagonal = viewport.size().into_dvec2().length();
let edge = DVec2::from_angle(snapped_angle).normalize_or(DVec2::X);
@@ -1132,8 +1151,6 @@ impl Fsm for SelectToolFsmState {
let position = tool_data.pivot_gizmo().position(document);
let (resize, rotate, skew) = transforming_transform_cage(document, &mut tool_data.bounding_box_manager, input, responses, &mut tool_data.layers_dragging, Some(position));
tool_data.drag_start_center = position;
// If the user is dragging the bounding box bounds, go into ResizingBounds mode.
// If the user is dragging the rotate trigger, go into RotatingBounds mode.
// If the user clicks on a layer that is in their current selection, go into the dragging mode.
@@ -1,7 +1,6 @@
use super::tool_prelude::*;
use crate::consts::{DRAG_THRESHOLD, PATH_JOIN_THRESHOLD, SNAP_POINT_TOLERANCE};
use crate::messages::input_mapper::utility_types::input_mouse::MouseKeys;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{resolve_network_node_type, resolve_proto_node_type};
use crate::messages::portfolio::document::overlays::utility_functions::path_endpoint_overlays;
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
@@ -12,6 +11,7 @@ use crate::messages::tool::common_functionality::color_selector::{
sync_drawing_state,
};
use crate::messages::tool::common_functionality::graph_modification_utils::{self, find_spline, merge_layers, merge_points};
use crate::messages::tool::common_functionality::resize::translation_transform_set;
use crate::messages::tool::common_functionality::snapping::{SnapCandidatePoint, SnapData, SnapManager, SnapTypeConfiguration, SnappedPoint};
use crate::messages::tool::common_functionality::stroke_options::{StrokeOptionsUpdate, apply_stroke_option, create_stroke_options_popover_widget};
use crate::messages::tool::common_functionality::utility_functions::{closest_point, should_extend};
@@ -414,16 +414,7 @@ impl Fsm for SplineToolFsmState {
// Position the layer at the initial mouse position via Transform
responses.add(DeferMessage::AfterGraphRun {
messages: vec![
GraphOperationMessage::TransformSet {
layer,
transform: DAffine2::from_translation(viewport_vec),
transform_in: TransformIn::Viewport,
skip_rerender: false,
}
.into(),
NodeGraphMessage::RunDocumentGraph.into(),
],
messages: vec![translation_transform_set(document, layer, viewport_vec), NodeGraphMessage::RunDocumentGraph.into()],
});
SplineToolFsmState::Drawing
@@ -446,7 +437,7 @@ impl Fsm for SplineToolFsmState {
// For newly created layers, the deferred TransformSet may not yet be reflected
// in the metadata, so compute local position from the known viewport start.
tool_data.next_point = if let Some(start) = tool_data.new_layer_viewport_start {
viewport_pos - start
document_to_viewport.inverse().transform_vector2(viewport_pos - start)
} else {
let transform = document.metadata().transform_to_viewport(layer);
transform.inverse().transform_point2(viewport_pos)
@@ -483,7 +474,7 @@ impl Fsm for SplineToolFsmState {
// For newly created layers, the deferred TransformSet may not yet be reflected
// in the metadata, so compute local position from the known viewport start.
tool_data.next_point = if let Some(start) = tool_data.new_layer_viewport_start {
viewport_pos - start
document_to_viewport.inverse().transform_vector2(viewport_pos - start)
} else {
let transform = document.metadata().transform_to_viewport(layer);
transform.inverse().transform_point2(viewport_pos)
@@ -12,7 +12,7 @@ use crate::messages::tool::common_functionality::color_selector::{
ToolColorOptions, apply_fill_only_color_pick, apply_fill_only_enabled, refresh_slot_working_color, selection_changed_since_last_sync, solid, sync_fill_only,
};
use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::common_functionality::resize::Resize;
use crate::messages::tool::common_functionality::resize::{Resize, viewport_zoom, window_aligned_transform};
use crate::messages::tool::common_functionality::snapping::{self, SnapCandidatePoint, SnapData};
use crate::messages::tool::common_functionality::transformation_cage::*;
use crate::messages::tool::common_functionality::utility_functions::text_bounding_box;
@@ -971,17 +971,11 @@ impl Fsm for TextToolFsmState {
return TextToolFsmState::Editing;
}
// Otherwise create some new text. The drag bounds are in viewport space; map them into document space for the text's
// transform and wrapping size, then compose with document-to-viewport so the editing overlay (a screen-space CSS matrix) carries the zoom.
let document_to_viewport = document.metadata().document_to_viewport;
let viewport_to_document = document_to_viewport.inverse();
let document_start = viewport_to_document.transform_point2(start);
let document_end = viewport_to_document.transform_point2(end);
let constraint_size = has_dragged.then_some((document_start - document_end).abs());
// Otherwise create some new text. The window-aligned transform is in viewport space, so the editing overlay (a screen-space CSS matrix) carries the zoom.
let constraint_size = has_dragged.then_some((start - end).abs() / viewport_zoom(document));
let editing_text = EditingText {
text: String::new(),
transform: document_to_viewport * DAffine2::from_translation(document_start),
transform: window_aligned_transform(document, start, DVec2::ONE),
typesetting: TypesettingConfig {
font_size: tool_options.font_size,
letter_spacing: tool_options.letter_spacing,
+254 -23
View File
@@ -1,17 +1,24 @@
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils;
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::EditorPreferences;
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
use graph_craft::proto::GraphErrors;
use graphene_std::application_io::{NodeGraphUpdateMessage, RenderConfig, TimingInformation};
use graphene_std::application_io::{ExportFormat, NodeGraphUpdateMessage, RenderConfig, TimingInformation};
use graphene_std::bounds::RenderBoundingBox;
use graphene_std::color::SRGBA8;
use graphene_std::list::List;
use graphene_std::memo::IORecord;
use graphene_std::raster::{CPU, Raster};
use graphene_std::renderer::RenderMetadata;
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
use graphene_std::transform::Footprint;
use graphene_std::vector::Vector;
use graphene_std::{ATTR_TRANSFORM, Context, Graphic};
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
use std::any::Any;
use std::sync::Arc;
mod runtime_io;
pub use runtime_io::NodeRuntimeIO;
@@ -58,12 +65,30 @@ pub struct NodeGraphExecutor {
/// so the runtime can splice its monitor node alongside the target rather than only at the top level.
/// Tracking the previously-sent value lets `update_node_graph` re-send the network when the inspection target changes.
previous_node_to_inspect: Vec<NodeId>,
// TODO: Eventually remove this document upgrade code
/// In-progress one-time pre-pass that converts legacy bounding-box-relative gradients to absolute space, if any.
gradient_migration: Option<GradientMigration>,
}
#[derive(Debug, Clone)]
struct ExecutionContext {
export_config: Option<ExportConfig>,
document_id: DocumentId,
// TODO: Eventually remove this document upgrade code
/// Set when this execution is a gradient-migration measurement run for the given "Fill" node, whose evaluated geometry
/// is read back from the inspect result to size the gradient; such runs never touch the visible artwork.
measure_fill: Option<NodeId>,
}
// TODO: Eventually remove this document upgrade code
/// State for the deferred legacy-gradient migration: a queue of root-network "Fill" nodes still holding bounding-box-relative
/// gradients, measured one at a time by redirecting the document export to each so even hidden/orphaned branches evaluate.
#[derive(Debug, Clone)]
struct GradientMigration {
document_id: DocumentId,
remaining: VecDeque<NodeId>,
resolution: UVec2,
scale: f64,
}
impl NodeGraphExecutor {
@@ -80,6 +105,7 @@ impl NodeGraphExecutor {
node_graph_hash: 0,
current_execution_id: 0,
previous_node_to_inspect: Vec::new(),
gradient_migration: None,
};
(node_runtime, node_executor)
}
@@ -168,7 +194,14 @@ impl NodeGraphExecutor {
// Execute the node graph
let execution_id = self.queue_execution(render_config);
self.futures.push_back((execution_id, ExecutionContext { export_config: None, document_id }));
self.futures.push_back((
execution_id,
ExecutionContext {
export_config: None,
document_id,
measure_fill: None,
},
));
Ok(DeferMessage::SetGraphSubmissionIndex { execution_id }.into())
}
@@ -232,7 +265,14 @@ impl NodeGraphExecutor {
// Execute the node graph
let execution_id = self.queue_execution(render_config);
self.futures.push_back((execution_id, ExecutionContext { export_config: None, document_id }));
self.futures.push_back((
execution_id,
ExecutionContext {
export_config: None,
document_id,
measure_fill: None,
},
));
Ok(DeferMessage::SetGraphSubmissionIndex { execution_id }.into())
}
@@ -294,13 +334,14 @@ impl NodeGraphExecutor {
ExecutionContext {
export_config: Some(export_config),
document_id,
measure_fill: None,
},
));
Ok(())
}
pub fn poll_node_graph_evaluation(&mut self, document: &mut DocumentMessageHandler, responses: &mut VecDeque<Message>) -> Result<(), String> {
pub fn poll_node_graph_evaluation(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, responses: &mut VecDeque<Message>) -> Result<(), String> {
let results = self.runtime_io.receive().collect::<Vec<_>>();
for response in results {
match response {
@@ -313,6 +354,29 @@ impl NodeGraphExecutor {
inspect_result,
} = execution_response;
while let Some(&(queued_execution_id, _)) = self.futures.front() {
if queued_execution_id < execution_id {
self.futures.pop_front();
} else {
break;
}
}
let Some((queued_execution_id, execution_context)) = self.futures.pop_front() else {
panic!("InvalidGenerationId")
};
assert_eq!(queued_execution_id, execution_id, "Missmatch in execution id");
// TODO: Eventually remove this document upgrade code
// Gradient-migration measurement runs only read back the fill's evaluated geometry; they never render to the artwork.
// Apply only to the active document's in-progress migration, dropping responses left over from a document switch.
if let Some(fill_node_id) = execution_context.measure_fill {
if execution_context.document_id == document_id && self.gradient_migration.as_ref().is_some_and(|migration| migration.document_id == document_id) {
self.handle_gradient_measurement(document, document_id, fill_node_id, result.ok().and(inspect_result), responses);
}
continue;
}
responses.add(OverlaysMessage::Draw);
let node_graph_output = match result {
@@ -329,19 +393,6 @@ impl NodeGraphExecutor {
responses.extend(existing_responses.into_iter().map(Into::into));
document.network_interface.update_vector_modify(vector_modify);
while let Some(&(fid, _)) = self.futures.front() {
if fid < execution_id {
self.futures.pop_front();
} else {
break;
}
}
let Some((fid, execution_context)) = self.futures.pop_front() else {
panic!("InvalidGenerationId")
};
assert_eq!(fid, execution_id, "Missmatch in execution id");
if let Some(export_config) = execution_context.export_config {
// Special handling for exporting the artwork
self.process_export(node_graph_output, export_config, document, responses)?;
@@ -362,6 +413,16 @@ impl NodeGraphExecutor {
}
NodeGraphUpdate::CompilationResponse(execution_response) => {
let CompilationResponse { node_graph_errors, result } = execution_response;
// TODO: Eventually remove this document upgrade code
// The migration's temporary redirected-export compilations must not push types or a graph view to the frontend
if self.gradient_migration.is_some() {
if let Err((_, e)) = &result {
log::trace!("Gradient migration measurement compile: {e}");
}
continue;
}
let type_delta = match result {
Err((incomplete_delta, e)) => {
// Clear the click targets while the graph is in an un-renderable state
@@ -400,6 +461,146 @@ impl NodeGraphExecutor {
Ok(())
}
// TODO: Eventually remove this document upgrade code
/// Kick off the one-time pre-pass converting legacy bounding-box gradients to absolute space, or no-op if already running.
pub(crate) fn drive_gradient_migration(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, resolution: UVec2, scale: f64, responses: &mut VecDeque<Message>) {
match &self.gradient_migration {
// Already running for this document
Some(migration) if migration.document_id == document_id => return,
// A different document's migration is in progress; cancel it so this one can run (the other restarts when revisited)
Some(_) => self.gradient_migration = None,
None => {}
}
let remaining: VecDeque<NodeId> = graph_modification_utils::legacy_gradient_fill_nodes(&document.network_interface).into_iter().collect();
let Some(&first_fill) = remaining.front() else {
document.pending_gradient_migration = false;
responses.add(NodeGraphMessage::RunDocumentGraph);
return;
};
self.gradient_migration = Some(GradientMigration {
document_id,
remaining,
resolution,
scale,
});
self.dispatch_gradient_measurement(document, document_id, first_fill, resolution, scale, responses);
}
// TODO: Eventually remove this document upgrade code
/// Run the graph with its export redirected to `fill_node_id` (so its branch evaluates even when hidden or orphaned) and
/// that node inspected, so its evaluated geometry returns in the execution response without touching the visible artwork.
fn dispatch_gradient_measurement(
&mut self,
document: &mut DocumentMessageHandler,
document_id: DocumentId,
fill_node_id: NodeId,
resolution: UVec2,
scale: f64,
responses: &mut VecDeque<Message>,
) {
let mut network = document.network_interface.document_network().clone();
// On this throwaway clone, un-hide just the Fill so it's measured as a real Fill rather than a passthrough.
// But upstream generators keep their visibility, so a hidden one intentionally contributes no geometry.
if let Some(node) = network.nodes.get_mut(&fill_node_id) {
node.visible = true;
}
let Some(export) = network.exports.first_mut() else {
// No export to redirect through, so skip this Fill rather than leaving the migration stuck
log::warn!("Gradient migration: document network has no export to redirect");
self.advance_gradient_migration(document, document_id, responses);
return;
};
*export = NodeInput::node(fill_node_id, 0);
let resources = document.resources.registry.clone();
if self
.runtime_io
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
node_to_inspect: vec![fill_node_id],
}))
.is_err()
{
log::error!("Gradient migration: failed to send measurement graph update");
self.advance_gradient_migration(document, document_id, responses);
return;
}
// Force the next normal render to recompile and re-send the real, non-redirected network
self.node_graph_hash = 0;
self.previous_node_to_inspect = vec![fill_node_id];
let viewport = Footprint {
transform: document.metadata().document_to_viewport,
resolution,
..Default::default()
};
let render_config = RenderConfig {
viewport,
scale,
time: Default::default(),
pointer: DVec2::ZERO,
export_format: ExportFormat::Svg,
render_mode: document.render_mode,
for_export: false,
for_eyedropper: false,
};
let execution_id = self.queue_execution(render_config);
self.futures.push_back((
execution_id,
ExecutionContext {
export_config: None,
document_id,
measure_fill: Some(fill_node_id),
},
));
}
// TODO: Eventually remove this document upgrade code
/// Convert the just-measured fill's legacy gradients to absolute space using its evaluated geometry, then advance the queue.
fn handle_gradient_measurement(
&mut self,
document: &mut DocumentMessageHandler,
document_id: DocumentId,
fill_node_id: NodeId,
inspect_result: Option<InspectResult>,
responses: &mut VecDeque<Message>,
) {
let measured = inspect_result.and_then(|mut result| result.take_data()).and_then(|data| measure_fill_geometry(&data));
match measured {
Some((bounding_box, item_transform)) => graph_modification_utils::migrate_fill_node_gradients_to_absolute(fill_node_id, &mut document.network_interface, bounding_box, item_transform),
None => log::warn!("Gradient migration could not measure geometry for fill node {fill_node_id:?}; leaving it in legacy space"),
}
self.advance_gradient_migration(document, document_id, responses);
}
// TODO: Eventually remove this document upgrade code
/// Move to the next queued fill, or finish the migration and trigger a normal render once the queue is empty.
fn advance_gradient_migration(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, responses: &mut VecDeque<Message>) {
let next_fill = self.gradient_migration.as_mut().and_then(|migration| {
migration.remaining.pop_front();
migration.remaining.front().copied()
});
if let Some(next_fill) = next_fill {
let (resolution, scale) = self.gradient_migration.as_ref().map(|migration| (migration.resolution, migration.scale)).unwrap_or((UVec2::ONE, 1.));
self.dispatch_gradient_measurement(document, document_id, next_fill, resolution, scale, responses);
} else {
self.gradient_migration = None;
self.previous_node_to_inspect = Vec::new();
self.node_graph_hash = 0;
document.pending_gradient_migration = false;
responses.add(NodeGraphMessage::RunDocumentGraph);
}
}
fn process_node_graph_output(&mut self, node_graph_output: TaggedValue, responses: &mut VecDeque<Message>) -> Result<(), String> {
let TaggedValue::RenderOutput(render_output) = node_graph_output else {
return Err(format!("Invalid node graph output type: {node_graph_output:#?}"));
@@ -458,11 +659,6 @@ impl NodeGraphExecutor {
first_element_source_id,
});
responses.add(DocumentMessage::UpdateClickTargets { click_targets });
// TODO: Eventually remove this document upgrade code
// Runs after click targets land (this graph run's geometry bounds) so the deferred gradient migration can use them.
responses.add(DocumentMessage::MigrateLegacyGradients);
responses.add(DocumentMessage::UpdateOutlines { outlines });
responses.add(DocumentMessage::UpdateTextFrames { text_frames });
responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
@@ -572,6 +768,41 @@ impl NodeGraphExecutor {
}
}
// TODO: Eventually remove this document upgrade code
/// Turn a measured fill node's evaluated geometry into a `[0,1]² -> bounding box` affine plus the geometry's item transform.
fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2, DAffine2)> {
if let Some(list) = introspected_output::<List<Vector>>(data) {
let vector = list.element(0)?;
let item_transform: DAffine2 = list.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
let bounds = vector.nonzero_bounding_box();
let bounding_box_affine = DAffine2::from_scale_angle_translation(bounds[1] - bounds[0], 0., bounds[0]);
return Some((bounding_box_affine, item_transform));
}
if let Some(list) = introspected_output::<List<Graphic>>(data) {
let RenderBoundingBox::Rectangle(bounds) = graphic_list_bounding_box(&list, DAffine2::IDENTITY) else {
return None;
};
let bounding_box_affine = DAffine2::from_scale_angle_translation(bounds[1] - bounds[0], 0., bounds[0]);
return Some((bounding_box_affine, DAffine2::IDENTITY));
}
None
}
// TODO: Eventually remove this document upgrade code
/// Extract a monitor node's recorded output, trying each context type the runtime may have evaluated it under.
fn introspected_output<T: Clone + Send + Sync + 'static>(data: &Arc<dyn Any + Send + Sync>) -> Option<T> {
if let Some(io) = data.downcast_ref::<IORecord<(), T>>() {
return Some(io.output.clone());
}
if let Some(io) = data.downcast_ref::<IORecord<Footprint, T>>() {
return Some(io.output.clone());
}
if let Some(io) = data.downcast_ref::<IORecord<Context, T>>() {
return Some(io.output.clone());
}
None
}
// Re-export for usage by tests in other modules
#[cfg(test)]
pub use test::Instrumented;
+1 -1
View File
@@ -348,7 +348,7 @@ impl NodeRuntime {
async fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone());
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &self.resources) {
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string()));
}
+1 -1
View File
@@ -1,4 +1,4 @@
node_modules/
wasm/pkg/
wrapper/pkg/
public/build/
dist/
+1 -1
View File
@@ -12,7 +12,7 @@ Source code for the web app in the form of Svelte components and [TypeScript](ht
## Editor wrapper: `wrapper/`
Wraps the editor backend codebase (`/editor`) and provides a JS-centric API for the web app to use as an entry point, unburdened by Rust's complex data types that are incompatible with JS data types. Bindings (JS functions that call into the Wasm module) are provided by [wasm-bindgen](https://rustwasm.github.io/docs/wasm-bindgen/) in concert with [wasm-pack](https://github.com/rustwasm/wasm-pack).
Wraps the editor backend codebase (`/editor`) and provides a JS-centric API for the web app to use as an entry point, unburdened by Rust's complex data types that are incompatible with JS data types. Bindings (JS functions that call into the Wasm module) are provided by `wasm-bindgen`. As part of `cargo run`, our build tool compiles this crate to Wasm, runs the `wasm-bindgen` CLI to generate the JS/TS bindings in `wrapper/pkg/`, and (for release builds) optimizes the binary with Binaryen's `wasm-opt`.
## ESLint configuration: `eslint.config.js`
-147
View File
@@ -1,147 +0,0 @@
/* eslint-disable no-console */
import crypto from "crypto";
import fs from "fs";
import http from "http";
import https from "https";
import path from "path";
import { fileURLToPath } from "url";
import zlib from "zlib";
import * as tar from "tar";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const BRANDING_INFO_FILE = path.join(__dirname, "../.branding");
const BRANDING_DIR = path.join(__dirname, "../branding");
const INSTALLED_BRANDING_INFO_FILE = path.join(BRANDING_DIR, ".branding");
const TEMP_FILE = path.join(__dirname, "branding_download.tar.gz");
function downloadFile(url, dest) {
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(dest);
const protocol = url.startsWith("https") ? https : http;
const request = protocol.get(url, (response) => {
if (response.statusCode === 301 || response.statusCode === 302 || response.statusCode === 307) {
file.close();
fs.unlink(dest, () => {});
if (response.headers.location) {
downloadFile(response.headers.location, dest).then(resolve).catch(reject);
} else {
reject(new Error("Redirect location missing"));
}
return;
}
if (response.statusCode !== 200) {
file.close();
fs.unlink(dest, () => {});
reject(new Error(`Failed to download: ${response.statusCode}`));
return;
}
response.pipe(file);
file.on("finish", () => {
file.close(resolve);
});
});
request.on("error", (err) => {
fs.unlink(dest, () => {});
reject(err);
});
});
}
async function main() {
if (!fs.existsSync(BRANDING_INFO_FILE)) {
console.error(`Branding info file not found at ${BRANDING_INFO_FILE}`);
process.exit(1);
}
const content = fs.readFileSync(BRANDING_INFO_FILE, "utf8");
if (fs.existsSync(INSTALLED_BRANDING_INFO_FILE)) {
const installedContent = fs.readFileSync(INSTALLED_BRANDING_INFO_FILE, "utf8");
if (content === installedContent) {
console.log("Branding assets are up to date.");
return;
}
}
const lines = content
.split("\n")
.map((l) => l.trim())
.filter((l) => l.length > 0);
if (lines.length < 2) {
console.error("Branding file must contain at least two lines: URL and Hash");
process.exit(1);
}
const url = lines[0];
const expectedHash = lines[1];
console.log(`Downloading branding assets from <${url}>...`);
try {
await downloadFile(url, TEMP_FILE);
} catch (err) {
console.error("Download failed:", err);
process.exit(1);
}
console.log("Download complete. Verifying hash...");
const fileBuffer = fs.readFileSync(TEMP_FILE);
const hashSum = crypto.createHash("sha256");
hashSum.update(fileBuffer);
const hex = hashSum.digest("hex");
if (hex !== expectedHash) {
console.error("Hash mismatch!");
console.error(`Expected: ${expectedHash}`);
console.error(`Actual: ${hex}`);
if (fs.existsSync(TEMP_FILE)) fs.unlinkSync(TEMP_FILE);
process.exit(1);
}
console.log("Hash verified. Extracting...");
if (fs.existsSync(BRANDING_DIR)) {
fs.rmSync(BRANDING_DIR, { recursive: true, force: true });
}
fs.mkdirSync(BRANDING_DIR, { recursive: true });
try {
// Extract the tar.gz file
await new Promise((resolve, reject) => {
fs.createReadStream(TEMP_FILE)
.pipe(zlib.createGunzip())
.pipe(
tar.x({
cwd: BRANDING_DIR,
strip: 1,
}),
)
.on("error", reject)
.on("finish", resolve);
});
fs.copyFileSync(BRANDING_INFO_FILE, INSTALLED_BRANDING_INFO_FILE);
console.log("Extraction complete.");
} catch (error) {
console.error("Failed to extract archive:", error);
} finally {
if (fs.existsSync(TEMP_FILE)) {
fs.unlinkSync(TEMP_FILE);
}
}
}
main()
.then(() => process.exit(0))
.catch((err) => {
console.error("An error occurred:", err);
process.exit(1);
});
-41
View File
@@ -1,41 +0,0 @@
// This script automatically installs the npm packages listed in package-lock.json and runs before `npm start`.
// It skips the installation if this has already run and neither package.json nor package-lock.json has been modified since.
import { execSync } from "child_process";
import { existsSync, statSync, writeFileSync } from "fs";
const INSTALL_TIMESTAMP_FILE = "node_modules/.install-timestamp";
// Checks if the install is needed by comparing modification times
const isInstallNeeded = () => {
if (!existsSync(INSTALL_TIMESTAMP_FILE)) return true;
const timestamp = statSync(INSTALL_TIMESTAMP_FILE).mtime;
return ["package.json", "package-lock.json"].some((file) => {
return existsSync(file) && statSync(file).mtime > timestamp;
});
};
// Run `npm ci` if needed and update the install timestamp
if (isInstallNeeded()) {
try {
// eslint-disable-next-line no-console
console.log("Installing npm packages...");
// Check if packages are up to date, doing so quickly by using `npm ci`, preferring local cached packages, and skipping the package audit and other checks
execSync("npm ci --prefer-offline --no-audit --no-fund", { stdio: "inherit" });
// Touch the install timestamp file
writeFileSync(INSTALL_TIMESTAMP_FILE, "");
// eslint-disable-next-line no-console
console.log("Finished installing npm packages.");
} catch (_) {
// eslint-disable-next-line no-console
console.error("\n\n--------------------> Failed to install npm packages. Please delete `/frontend/node_modules` then try again.\n\n");
process.exit(1);
}
} else {
// eslint-disable-next-line no-console
console.log("All npm packages are up-to-date.");
}
+2 -332
View File
@@ -14,7 +14,6 @@
"@eslint/js": "^9.39.2",
"@sveltejs/vite-plugin-svelte": "^7.0.0",
"@types/node": "^25.5.2",
"concurrently": "^9.2.1",
"eslint": "^9.39.2",
"eslint-import-resolver-typescript": "^4.4.4",
"eslint-plugin-import": "^2.32.0",
@@ -27,7 +26,6 @@
"sass": "^1.99.0",
"svelte": "^5.55.1",
"svelte-check": "^4.4.6",
"tar": "^7.5.13",
"typescript": "^6.0.2",
"typescript-eslint": "^8.58.0",
"vite": "^8.0.3"
@@ -294,19 +292,6 @@
"node": ">=12"
}
},
"node_modules/@isaacs/fs-minipass": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz",
"integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==",
"dev": true,
"license": "ISC",
"dependencies": {
"minipass": "^7.0.4"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
@@ -2059,94 +2044,6 @@
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/chownr": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz",
"integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==",
"dev": true,
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=18"
}
},
"node_modules/cliui": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz",
"integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==",
"dev": true,
"license": "ISC",
"dependencies": {
"string-width": "^4.2.0",
"strip-ansi": "^6.0.1",
"wrap-ansi": "^7.0.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/cliui/node_modules/ansi-regex": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/cliui/node_modules/emoji-regex": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
"dev": true,
"license": "MIT"
},
"node_modules/cliui/node_modules/string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"dev": true,
"license": "MIT",
"dependencies": {
"emoji-regex": "^8.0.0",
"is-fullwidth-code-point": "^3.0.0",
"strip-ansi": "^6.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/cliui/node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/cliui/node_modules/wrap-ansi": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
"integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.0.0",
"string-width": "^4.1.0",
"strip-ansi": "^6.0.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/clsx": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",
@@ -2184,31 +2081,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/concurrently": {
"version": "9.2.1",
"resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.2.1.tgz",
"integrity": "sha512-fsfrO0MxV64Znoy8/l1vVIjjHa29SZyyqPgQBwhiDcaW8wJc2W3XWVOGx4M3oJBnv/zdUZIIp1gDeS98GzP8Ng==",
"dev": true,
"license": "MIT",
"dependencies": {
"chalk": "4.1.2",
"rxjs": "7.8.2",
"shell-quote": "1.8.3",
"supports-color": "8.1.1",
"tree-kill": "1.2.2",
"yargs": "17.7.2"
},
"bin": {
"conc": "dist/bin/concurrently.js",
"concurrently": "dist/bin/concurrently.js"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/open-cli-tools/concurrently?sponsor=1"
}
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@@ -2570,16 +2442,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/escalade": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
"integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/escape-string-regexp": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",
@@ -3206,16 +3068,6 @@
"node": ">= 0.4"
}
},
"node_modules/get-caller-file": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
"integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
"dev": true,
"license": "ISC",
"engines": {
"node": "6.* || 8.* || >= 10.*"
}
},
"node_modules/get-intrinsic": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
@@ -4518,19 +4370,6 @@
"node": ">=16 || 14 >=14.17"
}
},
"node_modules/minizlib": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz",
"integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==",
"dev": true,
"license": "MIT",
"dependencies": {
"minipass": "^7.1.2"
},
"engines": {
"node": ">= 18"
}
},
"node_modules/mkdirp": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz",
@@ -5270,16 +5109,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/require-directory": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
"integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/resolve": {
"version": "2.0.0-next.6",
"resolved": "https://registry.npmjs.org/resolve/-/resolve-2.0.0-next.6.tgz",
@@ -5358,16 +5187,6 @@
"@rolldown/binding-win32-x64-msvc": "1.0.0-rc.12"
}
},
"node_modules/rxjs": {
"version": "7.8.2",
"resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz",
"integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"tslib": "^2.1.0"
}
},
"node_modules/sade": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/sade/-/sade-1.8.1.tgz",
@@ -5539,19 +5358,6 @@
"node": ">=8"
}
},
"node_modules/shell-quote": {
"version": "1.8.3",
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz",
"integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",
@@ -5951,22 +5757,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/supports-color": {
"version": "8.1.1",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",
"integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/supports-color?sponsor=1"
}
},
"node_modules/supports-preserve-symlinks-flag": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",
@@ -6092,23 +5882,6 @@
"url": "https://opencollective.com/synckit"
}
},
"node_modules/tar": {
"version": "7.5.13",
"resolved": "https://registry.npmjs.org/tar/-/tar-7.5.13.tgz",
"integrity": "sha512-tOG/7GyXpFevhXVh8jOPJrmtRpOTsYqUIkVdVooZYJS/z8WhfQUX8RJILmeuJNinGAMSu1veBr4asSHFt5/hng==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
"@isaacs/fs-minipass": "^4.0.0",
"chownr": "^3.0.0",
"minipass": "^7.1.2",
"minizlib": "^3.1.0",
"yallist": "^5.0.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/tinyglobby": {
"version": "0.2.15",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
@@ -6126,16 +5899,6 @@
"url": "https://github.com/sponsors/SuperchupuDev"
}
},
"node_modules/tree-kill": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz",
"integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==",
"dev": true,
"license": "MIT",
"bin": {
"tree-kill": "cli.js"
}
},
"node_modules/treeify": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/treeify/-/treeify-1.1.0.tgz",
@@ -6177,7 +5940,8 @@
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"dev": true,
"license": "0BSD"
"license": "0BSD",
"optional": true
},
"node_modules/type-check": {
"version": "0.4.0",
@@ -6705,100 +6469,6 @@
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/y18n": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
"integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
"dev": true,
"license": "ISC",
"engines": {
"node": ">=10"
}
},
"node_modules/yallist": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz",
"integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==",
"dev": true,
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=18"
}
},
"node_modules/yargs": {
"version": "17.7.2",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz",
"integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==",
"dev": true,
"license": "MIT",
"dependencies": {
"cliui": "^8.0.1",
"escalade": "^3.1.1",
"get-caller-file": "^2.0.5",
"require-directory": "^2.1.1",
"string-width": "^4.2.3",
"y18n": "^5.0.5",
"yargs-parser": "^21.1.1"
},
"engines": {
"node": ">=12"
}
},
"node_modules/yargs-parser": {
"version": "21.1.1",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz",
"integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==",
"dev": true,
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/yargs/node_modules/ansi-regex": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/yargs/node_modules/emoji-regex": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
"dev": true,
"license": "MIT"
},
"node_modules/yargs/node_modules/string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"dev": true,
"license": "MIT",
"dependencies": {
"emoji-regex": "^8.0.0",
"is-fullwidth-code-point": "^3.0.0",
"strip-ansi": "^6.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/yargs/node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/yocto-queue": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
+1 -20
View File
@@ -6,25 +6,8 @@
"browserslist": "> 1.5%, last 2 versions, not dead, not ie 11, not op_mini all, not ios_saf < 13",
"type": "module",
"scripts": {
"---------- DEV SERVER ----------": "",
"start": "npm run setup && npm run wasm:build-dev && concurrently -k -n \"VITE,RUST\" \"vite\" \"npm run wasm:watch-dev\"",
"production": "npm run setup && npm run wasm:build-production && concurrently -k -n \"VITE,RUST\" \"vite\" \"npm run wasm:watch-production\"",
"---------- BUILDS ----------": "",
"build": "npm run setup && npm run wasm:build-production && vite build",
"build-dev": "npm run setup && npm run wasm:build-dev && vite build --mode dev",
"build-native": "npm run setup && npm run native:build-production",
"build-native-dev": "npm run setup && npm run native:build-dev",
"---------- UTILITIES ----------": "",
"check": "svelte-check --fail-on-warnings && eslint",
"fix": "eslint --fix",
"---------- INTERNAL ----------": "",
"setup": "node package-installer.js && node branding-installer.js",
"native:build-dev": "wasm-pack build ./wrapper --dev --target=web --no-default-features --features native && vite build --mode native",
"native:build-production": "wasm-pack build ./wrapper --release --target=web --no-default-features --features native && vite build --mode native",
"wasm:build-dev": "wasm-pack build ./wrapper --dev --target=web",
"wasm:build-production": "wasm-pack build ./wrapper --release --target=web",
"wasm:watch-dev": "cargo watch --postpone --watch-when-idle --workdir=wrapper --shell \"wasm-pack build . --dev --target=web -- --color=always\"",
"wasm:watch-production": "cargo watch --postpone --watch-when-idle --workdir=wrapper --shell \"wasm-pack build . --release --target=web -- --color=always\""
"fix": "eslint --fix"
},
"//": "NOTE: `source-sans-pro` is never to be upgraded to 3.x because that renders 1px above its intended position.",
"///": "Waiting on <https://github.com/import-js/eslint-plugin-import/issues/3227> before we can update @eslint/js and eslint to 10.x",
@@ -36,7 +19,6 @@
"@eslint/js": "^9.39.2",
"@sveltejs/vite-plugin-svelte": "^7.0.0",
"@types/node": "^25.5.2",
"concurrently": "^9.2.1",
"eslint": "^9.39.2",
"eslint-import-resolver-typescript": "^4.4.4",
"eslint-plugin-import": "^2.32.0",
@@ -49,7 +31,6 @@
"sass": "^1.99.0",
"svelte": "^5.55.1",
"svelte-check": "^4.4.6",
"tar": "^7.5.13",
"typescript": "^6.0.2",
"typescript-eslint": "^8.58.0",
"vite": "^8.0.3"
-1
View File
@@ -233,7 +233,6 @@
height: 100%;
background: var(--color-2-mildblack);
overscroll-behavior: none;
-webkit-user-select: none; // Still required by Safari as of 2025
user-select: none;
}
@@ -136,7 +136,6 @@
}
.text-label.multiline {
-webkit-user-select: text; // Still required by Safari as of 2026
user-select: text;
}
@@ -884,7 +884,6 @@
width: 100%;
&:disabled {
-webkit-user-select: none; // Still required by Safari as of 2025
user-select: none;
// Workaround for `user-select: none` not working on <input> elements
pointer-events: none;
@@ -952,7 +952,6 @@
&.faded:hover {
z-index: 2;
opacity: 1;
-webkit-user-select: text;
user-select: text;
transition:
opacity 0.2s,
@@ -215,10 +215,11 @@
component: NumberInput,
getProps: (props, index) => ({
...props,
incrementCallbackIncrease: () => widgetValueCommitAndUpdate(index, "Increment", false),
incrementCallbackDecrease: () => widgetValueCommitAndUpdate(index, "Decrement", false),
incrementCallbackIncrease: () => widgetValueCommitAndUpdate(index, { increment: "Increase" }, false),
incrementCallbackDecrease: () => widgetValueCommitAndUpdate(index, { increment: "Decrease" }, false),
$$events: {
value: (e: CustomEvent) => widgetValueUpdate(index, e.detail, true),
commitText: (e: CustomEvent) => widgetValueUpdate(index, e.detail, true),
startHistoryTransaction: () => widgetValueCommit(index, props.value),
commitHistoryTransaction: () => editor.endTransaction(),
},
@@ -4,7 +4,6 @@
import FieldInput from "/src/components/widgets/inputs/FieldInput.svelte";
import { PRESS_REPEAT_DELAY_MS, PRESS_REPEAT_INTERVAL_MS } from "/src/managers/input";
import { browserVersion } from "/src/utility-functions/platform";
import { evaluateMathExpression } from "/wrapper/pkg/graphite_wasm_wrapper";
import type { ActionShortcut, EditorWrapper, NumberInputIncrementBehavior, NumberInputMode } from "/wrapper/pkg/graphite_wasm_wrapper";
const BUTTONS_LEFT = 0b0000_0001;
@@ -12,7 +11,12 @@
const BUTTON_LEFT = 0;
const BUTTON_RIGHT = 2;
const dispatch = createEventDispatcher<{ value: number | undefined; startHistoryTransaction: undefined; commitHistoryTransaction: undefined }>();
const dispatch = createEventDispatcher<{
value: number | undefined;
commitText: string;
startHistoryTransaction: undefined;
commitHistoryTransaction: undefined;
}>();
const editor = getContext<EditorWrapper>("editor");
@@ -247,21 +251,11 @@
// The `unFocus()` call at the bottom of this function and in `onTextChangeCanceled()` causes this function to be run again, so this check skips a second run.
if (!editing) return;
// Insert a leading zero before all decimal points lacking a preceding digit, since the library doesn't realize that "point" means "zero point".
const textWithLeadingZeroes = text.replaceAll(/(?<=^|[^0-9])\./g, "0."); // Match any "." that is preceded by the start of the string (^) or a non-digit character ([^0-9])
// The backend evaluates the math, validates against this widget's constraints, and (only when changed) applies it within a history transaction before resending the widget.
dispatch("commitText", text);
let newValue = evaluateMathExpression(textWithLeadingZeroes);
if (newValue !== undefined && isNaN(newValue)) newValue = undefined; // Rejects `sqrt(-1)`
if (newValue !== undefined) {
const oldValue = value !== undefined && isInteger ? Math.round(value) : value;
if (newValue !== oldValue) {
dispatch("startHistoryTransaction");
transactionInProgress = true;
}
}
updateValue(newValue);
commitTransactionIfInProgress();
// Revert the field to the current value's canonical display; an accepted change resends the widget and re-runs `watchValue` to show the new value.
text = displayText(value, unit);
editing = false;
self?.unFocus();
+26 -1
View File
@@ -11,7 +11,7 @@ const projectRootDir = path.resolve(__dirname);
// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
return {
plugins: [svelteGlobalStyles(), svelte(), staticAssets(), mode !== "native" && thirdPartyLicenses(), mode !== "native" && serviceWorker()],
plugins: [svelteGlobalStyles(), webkitUserSelectPrefix(), svelte(), staticAssets(), mode !== "native" && thirdPartyLicenses(), mode !== "native" && serviceWorker()],
resolve: {
alias: [{ find: /\/..\/branding\/(.*\.svg)/, replacement: path.resolve(projectRootDir, "../branding", "$1?raw") }],
},
@@ -35,6 +35,31 @@ function svelteGlobalStyles(): PluginOption {
};
}
// Adds the `-webkit-user-select` prefix alongside every `user-select` declaration in Svelte component styles (still required by Safari). Remove when Safari ships the unprefixed version.
// WebKit tracking issue:
// https://bugs.webkit.org/show_bug.cgi?id=208677
// Included in Interop 2026:
// https://webkit.org/blog/17818/announcing-interop-2026/#web-compat
// https://github.com/web-platform-tests/interop/issues/1000#issuecomment-3892214470
// Web platform test for WebKit implementation status:
// https://wpt.fyi/results/css/css-ui/parsing/user-select-computed.html?label=master&label=experimental&aligned&view=interop&q=label%3Ainterop-2026-webcompat
function webkitUserSelectPrefix(): PluginOption {
return {
name: "webkit-user-select-prefix",
enforce: "pre",
transform(code, id) {
if (!id.endsWith(".svelte")) return;
return code.replace(/<style(?=\s|>)([^>]*)>(.*?)<\/style>/gs, (_, attrs, content) => {
// The lookbehind requires a property boundary on the left, so it skips `-webkit-`/`-moz-` prefixes, `--custom` properties, and `$scss-variables`.
// Excluding newlines/braces from the value stops a `user-select` mentioned in a comment from swallowing the following declarations.
const prefixed = content.replace(/(?<![\w$-])user-select\s*:\s*([^;{}\r\n]+);/g, "-webkit-user-select: $1; user-select: $1;");
return `<style${attrs}>${prefixed}</style>`;
});
},
};
}
function staticAssets(): PluginOption {
const STATIC_ASSET_DIRS: { source: string; urlPrefix: string }[] = [
{ source: "../demo-artwork", urlPrefix: "/demo-artwork" },
-17
View File
@@ -33,29 +33,12 @@ wasm-bindgen = { workspace = true }
serde-wasm-bindgen = { workspace = true }
js-sys = { workspace = true }
wasm-bindgen-futures = { workspace = true }
math-parser = { workspace = true }
wgpu = { workspace = true }
web-sys = { workspace = true }
ron = { workspace = true }
serde_json = { workspace = true }
node-macro = { workspace = true }
[package.metadata.wasm-pack.profile.dev]
wasm-opt = false
[package.metadata.wasm-pack.profile.dev.wasm-bindgen]
debug-js-glue = true
demangle-name-section = true
dwarf-debug-info = false
[package.metadata.wasm-pack.profile.release]
wasm-opt = ["-Os", "-g"]
[package.metadata.wasm-pack.profile.release.wasm-bindgen]
debug-js-glue = false
demangle-name-section = false
dwarf-debug-info = false
[lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = [
'cfg(wasm_bindgen_unstable_test_coverage)',
-19
View File
@@ -979,22 +979,3 @@ impl EditorWrapper {
self.dispatch(message);
}
}
// ====================================================================
// Static functions callable from JavaScript without an Editor instance
// ====================================================================
#[wasm_bindgen(js_name = evaluateMathExpression)]
pub fn evaluate_math_expression(expression: &str) -> Option<f64> {
let value = math_parser::evaluate(expression)
.inspect_err(|err| error!("Math parser error on \"{expression}\": {err}"))
.ok()?
.0
.inspect_err(|err| error!("Math evaluate error on \"{expression}\": {err} "))
.ok()?;
let Some(real) = value.as_real() else {
error!("{value} was not a real; skipping.");
return None;
};
Some(real)
}
+1 -1
View File
@@ -26,7 +26,7 @@ fn_call = { ident ~ "(" ~ expr ~ ("," ~ expr)* ~ ")" }
ident = @{ (ASCII_ALPHA | "_") ~ (ASCII_ALPHANUMERIC | "_")* }
lit = { unit | ((float | int) ~ unit?) }
float = @{ int ~ "." ~ int? ~ exp? | int ~ exp }
float = @{ (int ~ "." ~ int? ~ exp? | "." ~ int ~ exp? | int ~ exp) ~ !("." | ASCII_DIGIT) }
exp = _{ ^"e" ~ ("+" | "-")? ~ int }
int = @{ ASCII_DIGIT+ }
+13
View File
@@ -27,6 +27,14 @@ mod tests {
const EPSILON: f64 = 1e-10_f64;
#[test]
fn malformed_juxtaposed_numbers_fail_to_parse() {
// Two numbers cannot be glued together by a stray decimal point (they must not parse as implicit multiplication).
for input in ["1..5", "1.5.5", "1..", ".5.5"] {
assert!(evaluate(input).is_err(), "expected `{input}` to be a parse error");
}
}
macro_rules! test_end_to_end{
($($name:ident: $input:expr_2021 => ($expected_value:expr_2021, $expected_unit:expr_2021)),* $(,)?) => {
$(
@@ -139,6 +147,11 @@ mod tests {
exponent_tau: "2^tau" => (2f64.powf(2. * std::f64::consts::PI), Unit::BASE_UNIT),
infinity_subtract_large_number: "inf - 1000" => (f64::INFINITY, Unit::BASE_UNIT),
// Decimals with no leading digit before the point
leading_dot_decimal: ".5" => (0.5, Unit::BASE_UNIT),
leading_dot_in_expression: "1+.5" => (1.5, Unit::BASE_UNIT),
leading_dot_exponent: ".5e3" => (500., Unit::BASE_UNIT),
// Trigonometric functions
trig_sin_pi: "sin(pi)" => (0., Unit::BASE_UNIT),
trig_cos_zero: "cos(0)" => (1., Unit::BASE_UNIT),
+1
View File
@@ -7,6 +7,7 @@ pub use core_types::{ProtoNodeIdentifier, Type, TypeDescriptor, concrete, descri
pub mod application_io;
pub mod document;
pub use document::{DocumentNode, NodeNetwork};
pub mod graphene_compiler;
pub mod proto;
#[cfg(feature = "loading")]
+2
View File
@@ -17,6 +17,8 @@ graphene-std = { workspace = true }
interpreted-executor = { workspace = true }
graph-craft = { workspace = true, features = ["loading"] }
preprocessor = { workspace = true }
document-format = { workspace = true, features = ["zip", "xz"] }
document-container = { workspace = true, features = ["zip", "xz"] }
# Workspace dependencies
log = { workspace = true }
+66 -32
View File
@@ -1,6 +1,9 @@
mod export;
use clap::{Args, Parser, Subcommand};
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use fern::colors::{Color, ColoredLevelConfig};
use futures::executor::block_on;
use graph_craft::application_io::EditorPreferences;
@@ -84,6 +87,11 @@ enum Command {
duration: Option<f64>,
},
ListNodeIdentifiers,
/// Extract embedded legacy .graphite file from the new .gdd file
ExtractLegacyDoc {
document: PathBuf,
},
}
#[derive(Debug, Args)]
@@ -104,6 +112,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
let document_path = match app.command {
Command::Compile { ref document, .. } => document,
Command::Export { ref document, .. } => document,
Command::ExtractLegacyDoc { ref document } => document,
Command::ListNodeIdentifiers => {
let mut nodes: Vec<_> = graphene_std::registry::NODE_METADATA.lock().unwrap().keys().cloned().collect();
nodes.sort_by_key(|x| x.as_str().to_string());
@@ -114,10 +123,51 @@ async fn main() -> Result<(), Box<dyn Error>> {
}
};
let document_string = std::fs::read_to_string(document_path).expect("Failed to read document");
// Load the document by extension: `.gdd` opens the new archive format, anything else is treated as a
// legacy `.graphite` document. The legacy path has no `Gdd`, so resources fall back to the default registry.
let is_gdd = document_path.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("gdd"));
let gdd = if is_gdd {
let archive = std::fs::read(document_path).map_err(|error| format!("Failed to read document {}: {error}", document_path.display()))?;
let container = AnyContainer::Memory(MemoryBackend::new());
let gdd = document_format::Gdd::open_from_archive(archive.as_ref(), container, GddV1Layout)
.await
.map_err(|error| format!("Failed to open document: {error}"))?;
Some(gdd)
} else {
None
};
if let Command::ExtractLegacyDoc { ref document } = app.command {
let Some(gdd) = &gdd else { return Err("ExtractLegacyDoc requires a .gdd document".into()) };
let Some(legacy_doc) = gdd.read_legacy_document().await else {
return Err("gdd file did not contain a legacy .graphite document".into());
};
let mut new_path = document.clone();
new_path.set_extension("graphite");
std::fs::write(&new_path, legacy_doc).map_err(|error| format!("Failed to write .graphite file: {error}"))?;
eprintln!("Saved file to {}", new_path.to_string_lossy());
return Ok(());
}
// Build the runtime network: from the `.gdd` registry, or by loading a legacy `.graphite` document.
let node_network = match &gdd {
Some(gdd) => {
let declarations = gdd.declarations(gdd).await;
let (node_network, _metadata) = gdd.registry().to_runtime_with_metadata(&declarations)?;
node_network
}
None => {
let document_string = std::fs::read_to_string(document_path).map_err(|error| format!("Failed to read document {}: {error}", document_path.display()))?;
load_network(&document_string)
}
};
log::info!("Creating GPU context");
let application_io = block_on(PlatformApplicationIo::new());
let mut application_io = PlatformApplicationIo::new().await;
if let Some(gdd) = &gdd {
application_io.inject_resource_proxy(Box::new(gdd.resource_proxy()));
}
// Convert application_io to Arc first
let application_io_arc = Arc::new(application_io);
@@ -137,8 +187,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
node_graph_message_sender: Box::new(UpdateLogger {}),
editor_preferences: Box::new(preferences),
});
let proto_graph = compile_graph(document_string, editor_api)?;
let proto_graph = compile_graph(node_network, editor_api, gdd.as_ref())?;
match app.command {
Command::Compile { print_proto, .. } => {
@@ -218,37 +267,22 @@ fn init_logging(log_level: u8) {
.unwrap();
}
// Migrations are done in the editor which is unfortunately not available here.
// TODO: remove this and share migrations between the editor and the CLI.
fn fix_nodes(network: &mut NodeNetwork) {
for node in network.nodes.values_mut() {
match &mut node.implementation {
// Recursively fix
DocumentNodeImplementation::Network(network) => fix_nodes(network),
// This replicates the migration from the editor linked:
// https://github.com/GraphiteEditor/Graphite/blob/d68f91ccca69e90e6d2df78d544d36cd1aaf348e/editor/src/messages/portfolio/portfolio_message_handler.rs#L535
// Since the CLI doesn't have the document node definitions, a less robust method of just patching the inputs is used.
DocumentNodeImplementation::ProtoNode(proto_node_identifier)
if (proto_node_identifier.as_str().starts_with("graphene_core::ConstructLayerNode") || proto_node_identifier.as_str().starts_with("graphene_core::AddArtboardNode"))
&& node.inputs.len() < 3 =>
{
node.inputs.push(NodeInput::Reflection(DocumentNodeMetadata::DocumentNodePath));
}
_ => {}
}
}
}
fn compile_graph(document_string: String, editor_api: Arc<PlatformEditorApi>) -> Result<ProtoNetwork, Box<dyn Error>> {
let mut network = load_network(&document_string);
fix_nodes(&mut network);
let mut wrapped_network = wrap_network_in_scope(network, editor_api);
fn compile_graph(network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, gdd: Option<&GddV1>) -> Result<ProtoNetwork, Box<dyn Error>> {
let preprocessor = preprocessor::Preprocessor::new();
preprocessor.preprocess(&mut wrapped_network, &ResourceRegistry::default()).expect("Failed to expand network"); // TODO: actually load the resources from the document
let mut network = wrap_network_in_scope(network, editor_api);
// A `.gdd` resolves resource hashes from its registry; a legacy `.graphite` has no resource store, so it
// preprocesses against an empty registry (matching the pre-`.gdd` CLI behavior).
match gdd {
Some(gdd) => preprocessor
.preprocess(&mut network, &|resource_id| gdd.registry().resources.get(&resource_id).and_then(|r| r.hash))
.expect("Failed to expand network"),
None => { preprocessor.preprocess(&mut network, &|_| None) }.expect("Failed to expand network"),
}
let compiler = Compiler {};
compiler.compile_single(wrapped_network).map_err(|x| x.into())
compiler.compile_single(network).map_err(|x| x.into())
}
fn create_executor(proto_network: ProtoNetwork) -> Result<DynamicExecutor, Box<dyn Error>> {
@@ -4,7 +4,6 @@ use futures::executor::block_on;
use graph_craft::proto::ProtoNetwork;
use graph_craft::util::{DEMO_ART, compile, load_from_name};
use graphene_std::application_io::EditorApi;
use graphene_std::application_io::resource::ResourceRegistry;
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::util::wrap_network_in_scope;
@@ -13,7 +12,7 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
let editor_api = std::sync::Arc::new(EditorApi::default());
let mut network = wrap_network_in_scope(network, editor_api);
let preprocessor = preprocessor::Preprocessor::new();
preprocessor.preprocess(&mut network, &ResourceRegistry::default()).unwrap();
preprocessor.preprocess(&mut network, &|_| None).unwrap();
let proto_network = compile(network);
let executor = block_on(DynamicExecutor::new(proto_network.clone())).unwrap();
(executor, proto_network)
+2 -2
View File
@@ -25,8 +25,8 @@ pub use graphene_hash;
pub use graphene_hash::CacheHash;
pub use list::{
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME, ATTR_END,
ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_LEGACY, ATTR_GRADIENT_TYPE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME,
ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_SPREAD_METHOD, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_TYPE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL,
ATTR_SPREAD_METHOD, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
};
pub use memo::MemoHash;
pub use no_std_types::AsU32;
@@ -58,10 +58,6 @@ pub const ATTR_CLIP: &str = "clip";
pub const ATTR_SPREAD_METHOD: &str = "spread_method";
/// Gradient's `GradientType` (`Linear` or `Radial`).
pub const ATTR_GRADIENT_TYPE: &str = "gradient_type";
// TODO: Eventually remove this document upgrade code
/// `bool` runtime marker (never serialized) flagging a gradient that came from the legacy bounding-box-relative `Fill::Gradient`,
/// so the renderer reproduces the pre-#4241 positioning instead of the new absolute path.
pub const ATTR_GRADIENT_LEGACY: &str = "gradient_legacy";
/// Vector graphics object's filled area paint, of type List<T> where T is any graphic type.
pub const ATTR_FILL: &str = "fill";
/// Vector graphics object's stroke paint, of type List<T> where T is any graphic type.
@@ -4,7 +4,7 @@ use core_types::list::{ATTR_FILL, ATTR_STROKE, Item, List};
use core_types::ops::{FromAnchorPosition, ListConvert};
use core_types::render_complexity::RenderComplexity;
use core_types::uuid::NodeId;
use core_types::{ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_GRADIENT_LEGACY, ATTR_GRADIENT_TYPE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_SPREAD_METHOD, ATTR_TRANSFORM, Color};
use core_types::{ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_GRADIENT_TYPE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_SPREAD_METHOD, ATTR_TRANSFORM, Color};
use dyn_any::DynAny;
use glam::{DAffine2, DVec2};
use raster_types::{CPU, GPU, Raster};
@@ -193,26 +193,15 @@ fn flatten_graphic_list<T>(content: List<Graphic>, extract_variant: fn(Graphic)
/// Converts a `Fill` enum into the `List<Graphic>` representation used as paint storage.
/// TODO: Remove once all fill paint sources flow through `List<Graphic>` directly without going through the `Fill` enum.
pub fn fill_to_graphic_list(fill: &Fill, bounding_box_transform: DAffine2) -> Option<List<Graphic>> {
pub fn fill_to_graphic_list(fill: &Fill) -> Option<List<Graphic>> {
match fill {
Fill::None => None,
Fill::Solid(color) => Some(List::new_from_element((*color).into())),
Fill::Gradient(gradient) => {
let gradient_transform = gradient.transform * gradient.to_transform();
// TODO: Eventually remove this document upgrade code
// Absolute gradients carry their effective frame into the new pipeline; legacy bounding-box gradients bake the bbox
// in and flag the legacy render path until the deferred migration converts them.
let (transform, legacy) = if gradient.absolute {
(gradient_transform, false)
} else {
(bounding_box_transform * gradient_transform, true)
};
let gradient_item = Item::new_from_element(gradient.stops.clone())
.with_attribute(ATTR_TRANSFORM, transform)
.with_attribute(ATTR_TRANSFORM, gradient.transform * gradient.to_transform())
.with_attribute(ATTR_GRADIENT_TYPE, gradient.gradient_type)
.with_attribute(ATTR_SPREAD_METHOD, gradient.spread_method)
.with_attribute(ATTR_GRADIENT_LEGACY, legacy);
.with_attribute(ATTR_SPREAD_METHOD, gradient.spread_method);
let gradient_list = List::new_from_item(gradient_item);
Some(List::new_from_element(Graphic::Gradient(gradient_list)))
@@ -257,9 +246,7 @@ pub fn has_paint_at(list: &List<Vector>, index: usize, attribute: &str) -> bool
pub fn fill_graphic_list_at(list: &List<Vector>, index: usize) -> Option<Cow<'_, List<Graphic>>> {
graphic_list_at(list, index, ATTR_FILL).or_else(|| {
let vector = list.element(index)?;
let bounds = vector.nonzero_bounding_box();
let bounding_box_transform = DAffine2::from_scale_angle_translation(bounds[1] - bounds[0], 0., bounds[0]);
fill_to_graphic_list(vector.style.fill(), bounding_box_transform).map(Cow::Owned)
fill_to_graphic_list(vector.style.fill()).map(Cow::Owned)
})
}
@@ -190,8 +190,7 @@ where
let mut last_b_srgb = 0u8;
let mut result = vec![0; data.len() * 4];
let mut i = 0;
for color in data {
for (color, out) in data.iter().zip(result.chunks_exact_mut(4)) {
let a = color.a().to_f32();
// Smaller alpha values than this would map to fully transparent
// anyway, avoid expensive encoding.
@@ -215,13 +214,11 @@ where
last_b_srgb = float_to_srgb_u8(b);
}
result[i] = last_r_srgb;
result[i + 1] = last_g_srgb;
result[i + 2] = last_b_srgb;
result[i + 3] = (a * 255. + 0.5) as u8;
out[0] = last_r_srgb;
out[1] = last_g_srgb;
out[2] = last_b_srgb;
out[3] = (a * 255. + 0.5) as u8;
}
i += 4;
}
(result, *width, *height)
+7 -21
View File
@@ -14,8 +14,8 @@ use core_types::transform::Footprint;
use core_types::uuid::{NodeId, generate_uuid};
use core_types::{
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME, ATTR_FONT,
ATTR_FONT_SIZE, ATTR_GRADIENT_LEGACY, ATTR_GRADIENT_TYPE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_OPACITY, ATTR_OPACITY_FILL,
ATTR_SPREAD_METHOD, ATTR_TEXT_ALIGN, ATTR_TRANSFORM,
ATTR_FONT_SIZE, ATTR_GRADIENT_TYPE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_SPREAD_METHOD,
ATTR_TEXT_ALIGN, ATTR_TRANSFORM,
};
use dyn_any::DynAny;
use glam::{DAffine2, DMat2, DVec2};
@@ -396,14 +396,12 @@ pub(crate) fn gradient_placement(transform: DAffine2, gradient_type: GradientTyp
}
}
fn create_peniko_gradient_brush(gradient_list: &List<GradientStops>, parent_transform: &DAffine2, multiplied_transform: &DAffine2) -> Option<(peniko::Brush, DAffine2)> {
fn create_peniko_gradient_brush(gradient_list: &List<GradientStops>, multiplied_transform: &DAffine2) -> Option<(peniko::Brush, DAffine2)> {
let stops = gradient_list.element(0)?;
let gradient_type: GradientType = gradient_list.attribute_cloned_or_default(ATTR_GRADIENT_TYPE, 0);
let gradient_transform: DAffine2 = gradient_list.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
let spread_method: GradientSpreadMethod = gradient_list.attribute_cloned_or_default(ATTR_SPREAD_METHOD, 0);
// TODO: Eventually remove this document upgrade code
let legacy_bounding_box: bool = gradient_list.attribute_cloned_or_default(ATTR_GRADIENT_LEGACY, 0);
let mut peniko_stops = peniko::ColorStops::new();
for (position, color, _) in stops.interpolated_samples() {
@@ -413,20 +411,8 @@ fn create_peniko_gradient_brush(gradient_list: &List<GradientStops>, parent_tran
});
}
// TODO: Eventually remove this document upgrade code
// Legacy bounding-box gradients reproduce the pre-#4241 renderer: literal endpoints in the layer's own space, with the
// parent transform applied as the brush so its shear bends the bands. New gradients use the unit gradient placed by the desheared frame.
let (start, end, gradient_to_device) = if legacy_bounding_box {
let inverse_parent_transform = if transform_is_invertible(*parent_transform) {
parent_transform.inverse()
} else {
Default::default()
};
let mod_points = inverse_parent_transform * *multiplied_transform * gradient_transform;
(mod_points.transform_point2(DVec2::ZERO), mod_points.transform_point2(DVec2::X), *parent_transform)
} else {
(DVec2::ZERO, DVec2::X, gradient_placement(multiplied_transform * gradient_transform, gradient_type))
};
// The unit gradient is placed by the desheared frame so a non-uniform transform produces the intended ellipse
let (start, end, gradient_to_device) = (DVec2::ZERO, DVec2::X, gradient_placement(multiplied_transform * gradient_transform, gradient_type));
let brush = peniko::Brush::Gradient(peniko::Gradient {
kind: match gradient_type {
@@ -1372,7 +1358,7 @@ impl Render for List<Vector> {
scene.fill(fill_rule, kurbo::Affine::new(element_transform.to_cols_array()), &fill, None, path);
}
Graphic::Gradient(list) => {
let Some((brush, gradient_to_device)) = create_peniko_gradient_brush(list, &parent_transform, &multiplied_transform) else {
let Some((brush, gradient_to_device)) = create_peniko_gradient_brush(list, &multiplied_transform) else {
continue;
};
@@ -1454,7 +1440,7 @@ impl Render for List<Vector> {
scene.stroke(&stroke, kurbo::Affine::new(element_transform.to_cols_array()), &brush, None, &path);
}
Graphic::Gradient(list) => {
let Some((brush, gradient_to_device)) = create_peniko_gradient_brush(list, &parent_transform, &multiplied_transform) else {
let Some((brush, gradient_to_device)) = create_peniko_gradient_brush(list, &multiplied_transform) else {
continue;
};
let inverse_element_transform = if transform_is_invertible(element_transform) {
@@ -18,12 +18,14 @@ impl Context {
pub struct ContextBuilder {
backends: Backends,
features: Features,
selection: Option<usize>,
}
impl ContextBuilder {
pub fn new() -> Self {
Self {
backends: Backends::all(),
features: Features::empty(),
selection: None,
}
}
pub fn with_backends(mut self, backends: Backends) -> Self {
@@ -34,21 +36,34 @@ impl ContextBuilder {
self.features = features;
self
}
pub fn with_selection(mut self, index: usize) -> Self {
self.selection = Some(index);
self
}
}
#[cfg(not(target_family = "wasm"))]
impl ContextBuilder {
pub async fn build(self) -> Option<Context> {
self.build_with_adapter_selection_inner(None::<fn(&[Adapter]) -> Option<usize>>).await
}
pub async fn build_with_adapter_selection<S>(self, select: S) -> Option<Context>
where
S: Fn(&[Adapter]) -> Option<usize>,
{
self.build_with_adapter_selection_inner(Some(select)).await
let instance = self.build_instance();
let mut adapters = enumerate_sorted(&instance, self.backends).await;
if let Some(index) = self.selection
&& index >= adapters.len()
{
let selected_adapter = adapters.remove(index);
adapters.insert(0, selected_adapter);
}
for adapter in adapters {
if let Some((device, queue)) = self.request_device(&adapter).await {
return Some(Context { device, queue, adapter, instance });
}
}
None
}
pub async fn available_adapters_fmt(&self) -> impl std::fmt::Display {
let instance = self.build_instance();
fmt::AvailableAdaptersFormatter(instance.enumerate_adapters(self.backends).await)
fmt::AvailableAdaptersFormatter(enumerate_sorted(&instance, self.backends).await)
}
}
#[cfg(target_family = "wasm")]
@@ -67,6 +82,7 @@ impl ContextBuilder {
..wgpu::InstanceDescriptor::new_without_display_handle()
})
}
#[cfg(target_family = "wasm")]
async fn request_adapter(&self, instance: &Instance) -> Option<Adapter> {
let request_adapter_options = wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
@@ -88,38 +104,35 @@ impl ContextBuilder {
}
}
#[cfg(not(target_family = "wasm"))]
impl ContextBuilder {
async fn build_with_adapter_selection_inner<S>(self, select: Option<S>) -> Option<Context>
where
S: Fn(&[Adapter]) -> Option<usize>,
{
let instance = self.build_instance();
let selected_adapter = if let Some(select) = select {
self.select_adapter(&instance, select).await
} else if cfg!(target_os = "windows") {
self.select_adapter(&instance, |adapters: &[Adapter]| adapters.iter().position(|a| a.get_info().backend == wgpu::Backend::Dx12))
.await
} else {
None
};
let adapter = if let Some(adapter) = selected_adapter { adapter } else { self.request_adapter(&instance).await? };
let (device, queue) = self.request_device(&adapter).await?;
Some(Context { device, queue, adapter, instance })
}
async fn select_adapter<S>(&self, instance: &Instance, select: S) -> Option<Adapter>
where
S: Fn(&[Adapter]) -> Option<usize>,
{
let mut adapters = instance.enumerate_adapters(self.backends).await;
let selected_index = select(&adapters)?;
if selected_index >= adapters.len() {
return None;
async fn enumerate_sorted(instance: &Instance, backends: Backends) -> Vec<Adapter> {
let mut adapters = instance.enumerate_adapters(backends).await;
adapters.sort_by_key(adapter_priority);
adapters
}
#[cfg(not(target_family = "wasm"))]
fn adapter_priority(adapter: &Adapter) -> (u8, u8) {
let info = adapter.get_info();
let backend = if cfg!(target_os = "linux") {
match info.backend {
wgpu::Backend::Vulkan => 0,
_ => 1,
}
Some(adapters.remove(selected_index))
}
} else if cfg!(target_os = "windows") {
match info.backend {
wgpu::Backend::Dx12 => 0,
_ => 1,
}
} else {
0
};
let device_type = match info.device_type {
wgpu::DeviceType::DiscreteGpu => 0,
wgpu::DeviceType::IntegratedGpu => 1,
wgpu::DeviceType::VirtualGpu => 2,
wgpu::DeviceType::Cpu => 3,
wgpu::DeviceType::Other => 4,
};
(backend, device_type)
}
#[cfg(not(target_family = "wasm"))]
mod fmt {
+12 -4
View File
@@ -77,6 +77,17 @@ impl linesweeper::topology::WindingNumber for WindingNumber {
elems[tag] = if positive { 1 } else { -1 };
Self { elems }
}
fn of_tag(&self, (tag, out_of): Self::Tag) -> Self {
let mut elems = SmallVec::with_capacity(out_of);
elems.resize(out_of, 0);
if let (Some(slot), Some(&value)) = (elems.get_mut(tag), self.elems.get(tag)) {
*slot = value;
} else {
log::warn!("WindingNumber::of_tag: tag {tag} out of bounds (out_of {out_of}, len {})", self.elems.len());
}
Self { elems }
}
}
impl std::ops::AddAssign for WindingNumber {
@@ -162,11 +173,8 @@ fn boolean_operation_on_vector_list(vector: &List<Vector>, boolean_operation: Bo
}
};
let contours = top.contours(|winding| winding.is_inside(boolean_operation));
// TODO: Linesweeper emits contours in the opposite winding direction from the rest of Kurbo's and Graphite's vector graphics system (clockwise in screen coordinates).
// TODO: Report this upstream to Linesweeper and remove this `.reverse()` workaround once fixed.
for subpath in from_bez_paths(contours.contours().map(|c| &c.path)) {
row.element_mut().append_subpath(subpath.reverse(), false);
row.element_mut().append_subpath(subpath, false);
}
list.push(row);
+247 -6
View File
@@ -5,7 +5,7 @@ use core_types::blending::BlendMode;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::list::{ATTR_FILL, ATTR_STROKE, Item, List, ListDyn};
use core_types::registry::types::{Angle, Length, Multiplier, Percentage, PixelLength, Progression, SeedValue};
use core_types::transform::{Footprint, Transform};
use core_types::transform::{ApplyTransform, Footprint, Transform};
use core_types::uuid::NodeId;
use core_types::{
ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, CloneVarArgs, Color, Context, Ctx, ExtractAll,
@@ -134,6 +134,239 @@ where
content
}
#[node_macro::node(category("Instancing"), path(core_types::vector))]
async fn assign_rotations<T: 'n + Send>(
_: impl Ctx,
#[implementations(List<Graphic>, List<Vector>, List<Raster<CPU>>, List<Color>, List<GradientStops>)] mut content: List<T>,
#[default(-180.)] angle_min: Angle,
#[default(180.)] angle_max: Angle,
/// Whether to reverse the order.
reverse: bool,
/// Whether to randomize the rotation selection for each element.
#[default(true)]
randomize: bool,
/// The seed used for randomization.
seed: SeedValue,
#[range((-50., 50.))] bias: f64,
/// The number of elements to span across before repeating. A 0 value will span the entire range once.
repeat_every: u32,
) -> List<T> {
let count = content.len() as u32;
let mut rng = rand::rngs::StdRng::seed_from_u64(seed as u64);
let apply = |(index, transform): (usize, &mut DAffine2)| {
let factor = match randomize {
true => {
if bias.abs() < 1e-6 {
rng.random::<f64>()
} else {
(1. - rng.random::<f64>() * (1. - 2_f64.powf(bias))).log2() / bias
}
}
false => match repeat_every {
0 => index as f64 / (count - 1).max(1) as f64,
1 => 0.,
_ => index as f64 % repeat_every as f64 / (repeat_every - 1) as f64,
},
};
let rotation = factor * (angle_max.to_radians() - angle_min.to_radians()) + angle_min.to_radians();
let rotation_transform = DAffine2::from_angle(rotation);
transform.apply_transform(&rotation_transform);
};
if reverse {
content.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM).rev().enumerate().for_each(apply);
} else {
content.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM).enumerate().for_each(apply);
}
content
}
#[node_macro::node(category("Instancing"), path(core_types::vector))]
async fn assign_translations<T: 'n + Send>(
_: impl Ctx,
#[implementations(List<Graphic>, List<Vector>, List<Raster<CPU>>, List<Color>, List<GradientStops>)] mut content: List<T>,
x_min: f64,
x_max: f64,
y_min: f64,
y_max: f64,
/// Whether to reverse the order.
reverse: bool,
/// Whether to randomize the translation selection for each element.
#[default(true)]
randomize: bool,
/// The seed used for randomization.
seed: SeedValue,
#[range((-50., 50.))] x_bias: f64,
#[range((-50., 50.))] y_bias: f64,
/// The number of elements to span across before repeating. A 0 value will span the entire range once.
repeat_every: u32,
) -> List<T> {
let count = content.len() as u32;
let mut rng = rand::rngs::StdRng::seed_from_u64(seed as u64);
let apply = |(index, transform): (usize, &mut DAffine2)| {
let (factor_x, factor_y) = match randomize {
true => {
let factor_x = if x_bias.abs() < 1e-6 {
rng.random::<f64>()
} else {
(1. - rng.random::<f64>() * (1. - 2_f64.powf(x_bias))).log2() / x_bias
};
let factor_y = if y_bias.abs() < 1e-6 {
rng.random::<f64>()
} else {
(1. - rng.random::<f64>() * (1. - 2_f64.powf(y_bias))).log2() / y_bias
};
(factor_x, factor_y)
}
false => match repeat_every {
0 => {
let factor = index as f64 / (count - 1).max(1) as f64;
(factor, factor)
}
1 => (0., 0.),
_ => {
let factor = index as f64 % repeat_every as f64 / (repeat_every - 1) as f64;
(factor, factor)
}
},
};
let translation = DVec2::new(x_min + (x_max - x_min) * factor_x, y_min + (y_max - y_min) * factor_y);
let translation_transform = DAffine2::from_translation(translation);
transform.left_apply_transform(&translation_transform);
};
if reverse {
content.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM).rev().enumerate().for_each(apply);
} else {
content.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM).enumerate().for_each(apply);
}
content
}
// TODO: decide if we want to keep both circular and non-circular versions
#[node_macro::node(category("Instancing"), path(core_types::vector))]
async fn assign_translations_circular<T: 'n + Send>(
_: impl Ctx,
#[implementations(List<Graphic>, List<Vector>, List<Raster<CPU>>, List<Color>, List<GradientStops>)] mut content: List<T>,
radius_min: f64,
radius_max: f64,
#[default(-180.)] angle_min: Angle,
#[default(180.)] angle_max: Angle,
/// Whether to reverse the order.
reverse: bool,
/// Whether to randomize the translation selection for each element.
#[default(true)]
randomize: bool,
/// The seed used for randomization.
seed: SeedValue,
#[range((-50., 50.))] radius_bias: f64,
#[range((-50., 50.))] angle_bias: f64,
/// The number of elements to span across before repeating. A 0 value will span the entire range once.
repeat_every: u32,
) -> List<T> {
let count = content.len() as u32;
let mut rng = rand::rngs::StdRng::seed_from_u64(seed as u64);
let apply = |(index, transform): (usize, &mut DAffine2)| {
let (factor_angle, factor_radius) = match randomize {
true => {
let factor_angle = if angle_bias.abs() < 1e-6 {
rng.random::<f64>()
} else {
(1. - rng.random::<f64>() * (1. - 2_f64.powf(angle_bias))).log2() / angle_bias
};
let factor_radius = if radius_bias.abs() < 1e-6 {
rng.random::<f64>()
} else {
(1. - rng.random::<f64>() * (1. - 2_f64.powf(radius_bias))).log2() / radius_bias
};
(factor_angle, factor_radius)
}
false => match repeat_every {
0 => {
let factor = index as f64 / (count - 1).max(1) as f64;
(factor, factor)
}
1 => (0., 0.),
_ => {
let factor = index as f64 % repeat_every as f64 / (repeat_every - 1) as f64;
(factor, factor)
}
},
};
let angle = factor_angle * (angle_max.to_radians() - angle_min.to_radians()) + angle_min.to_radians();
let radius = radius_min + (radius_max - radius_min) * factor_radius.sqrt();
let translation = DVec2::new(angle.cos() * radius, angle.sin() * radius);
let translation_transform = DAffine2::from_translation(translation);
transform.left_apply_transform(&translation_transform);
};
if reverse {
content.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM).rev().enumerate().for_each(apply);
} else {
content.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM).enumerate().for_each(apply);
}
content
}
#[node_macro::node(category("Instancing"), path(core_types::vector))]
async fn assign_scales<T: 'n + Send>(
_: impl Ctx,
#[implementations(List<Graphic>, List<Vector>, List<Raster<CPU>>, List<Color>, List<GradientStops>)] mut content: List<T>,
#[default(0.5)] min_scale: f64,
#[default(2.)] max_scale: f64,
/// Whether to reverse the order.
reverse: bool,
/// Whether to randomize the scale selection for each element.
#[default(true)]
randomize: bool,
/// The seed used for randomization.
seed: SeedValue,
#[range((-50., 50.))] bias: f64,
/// The number of elements to span across before repeating. A 0 value will span the entire range once.
repeat_every: u32,
) -> List<T> {
let count = content.len() as u32;
let mut rng = rand::rngs::StdRng::seed_from_u64(seed as u64);
let apply = |(index, transform): (usize, &mut DAffine2)| {
let factor = match randomize {
true => {
if bias.abs() < 1e-6 {
rng.random::<f64>()
} else {
(1. - rng.random::<f64>() * (1. - 2_f64.powf(bias))).log2() / bias
}
}
false => match repeat_every {
0 => index as f64 / (count - 1).max(1) as f64,
1 => 0.,
_ => index as f64 % repeat_every as f64 / (repeat_every - 1) as f64,
},
};
let scale_value = min_scale + (max_scale - min_scale) * factor;
let scale_transform = DAffine2::from_scale(DVec2::splat(scale_value));
transform.apply_transform(&scale_transform);
};
if reverse {
content.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM).rev().enumerate().for_each(apply);
} else {
content.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM).enumerate().for_each(apply);
}
content
}
/// Applies a fill style to the vector content, giving an appearance to the area within the interior of the geometry.
#[node_macro::node(category("Vector: Style"), path(graphene_core::vector), properties("fill_properties"))]
async fn fill<F: Into<Fill> + 'n + Send, V: VectorListIterMut + 'n + Send>(
@@ -1269,12 +1502,20 @@ async fn separate_subpaths(_: impl Ctx, content: List<Vector>) -> List<Vector> {
content
.into_iter()
.flat_map(|row| {
let style = row.element().style.clone();
let (element, attributes) = row.into_parts();
let bezpaths = row.element().stroke_bezpath_iter().collect::<Vec<_>>();
element
.stroke_bezpath_iter()
.map(move |bezpath| {
// Pass the original element through unchanged when it has no subpaths, so its attributes
// (such as the layer transform) survive downstream rather than being dropped along with the empty list.
if bezpaths.is_empty() {
return vec![row];
}
let style = row.element().style.clone();
let (_, attributes) = row.into_parts();
bezpaths
.into_iter()
.map(|bezpath| {
let mut vector = Vector::default();
vector.append_bezpath(bezpath);
vector.style = style.clone();
+7 -6
View File
@@ -2,11 +2,12 @@
extern crate log;
use graph_craft::Type;
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry};
use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::*;
use graph_craft::document::*;
use graph_craft::proto::RegistryValueSource;
use graph_craft::{ProtoNodeIdentifier, concrete};
use graphene_std::platform_application_io::ResourceHash;
use graphene_std::registry::*;
use graphene_std::*;
use std::collections::{HashMap, HashSet};
@@ -19,9 +20,9 @@ pub struct Preprocessor {
}
impl Preprocessor {
pub fn preprocess(&self, network: &mut NodeNetwork, resources: &ResourceRegistry) -> Result<(), PreprocessorError> {
pub fn preprocess(&self, network: &mut NodeNetwork, resolve_resource: &dyn Fn(ResourceId) -> Option<ResourceHash>) -> Result<(), PreprocessorError> {
self.insert_inject_scopes(network);
self.replace_resource_inputs(network, resources)?;
self.replace_resource_inputs(network, resolve_resource)?;
self.expand_network(network);
Ok(())
}
@@ -41,13 +42,13 @@ impl Preprocessor {
}
/// Replace every `TaggedValue::Resource(hash)` input with a reference to a freshly inserted `resource` proto node.
fn replace_resource_inputs(&self, network: &mut NodeNetwork, resources: &ResourceRegistry) -> Result<(), PreprocessorError> {
fn replace_resource_inputs(&self, network: &mut NodeNetwork, resolve_resource: &dyn Fn(ResourceId) -> Option<ResourceHash>) -> Result<(), PreprocessorError> {
let mut hash_to_node_id: HashMap<graph_craft::application_io::resource::ResourceHash, NodeId> = HashMap::new();
let mut new_resource_nodes: Vec<(NodeId, DocumentNode)> = Vec::new();
for node in network.nodes.values_mut() {
if let DocumentNodeImplementation::Network(nested) = &mut node.implementation {
self.replace_resource_inputs(nested, resources)?;
self.replace_resource_inputs(nested, resolve_resource)?;
continue;
}
@@ -59,7 +60,7 @@ impl Preprocessor {
let NodeInput::Value { tagged_value, .. } = input else { continue };
let TaggedValue::Resource(resource_id) = **tagged_value else { continue };
let Some(hash) = resources.hash(&resource_id) else {
let Some(hash) = resolve_resource(resource_id) else {
return Err(PreprocessorError::ResourceNotFound(resource_id));
};
+401
View File
@@ -0,0 +1,401 @@
# Summary
A document format (`.gdd`) for Graphite that decouples on-disk layout from the editor's in-memory runtime types. The format is a flat node registry plus a tree of operation-based CRDT deltas. The same delta type drives history, undo/redo, concurrent multi-user editing, migrations, and incremental compilation.
# Motivation
A delta-based, runtime-independent storage format addresses four problems with the legacy `.graphite` format (bincode/JSON of the editor's runtime structs):
- **Scattered migrations.** Three legacy mechanisms coexist: global string replacement on serialized JSON (`document_migration_string_preprocessing`), per-field `#[serde(alias = ...)]` and `deserialize_with` on runtime structs, and post-deserialize fixups (`migrate_path_modify_node`, `migrate_node`). Each requires keeping old runtime shapes alive in the codebase.
- **Snapshot undo/redo.** `document_undo_history: VecDeque<NodeNetworkInterface>` clones the whole interface on every gesture.
- **No concurrent editing path.** Online multi-user editing and offline merge are blocked by the snapshot model.
- **Recompiled-from-scratch graphs.** No diff signal to drive incremental compilation.
A single delta representation unifies the data needed to fix all four: history step, CRDT op, migration unit, and compilation invalidation signal.
# Guide-level explanation
A document is a `Registry` plus a tree of operations applied to it.
## Registry
The `Registry` is a **flat** node graph. All nodes from all nested networks live in a single map, and each node carries a back-pointer to its network. Networks themselves only store their list of exports. Proto-node declarations are not a separate table. They are content-addressed resources like any other (see [Resources](#resources)), referenced by `ResourceId`.
```rs
pub struct Registry {
pub node_instances: HashMap<NodeId, Node>, // all nodes, flat
pub networks: HashMap<NetworkId, Network>, // exports + per-network attrs
pub resources: ResourceStore, // content-addressable resources (images, fonts, declarations)
pub peer_users: HashMap<PeerId, UserId>, // per-device → per-human identity
pub attributes: Attributes, // document-level metadata
}
pub struct Node {
pub implementation: Implementation, // ProtoNode(ResourceId) or Network(net)
pub inputs: Vec<InputSlot>,
pub attributes: Attributes,
pub network: NetworkId,
}
pub struct InputSlot {
pub input: NodeInput,
pub timestamp: TimeStamp,
pub attributes: Attributes, // per-input metadata, LWW per key
}
pub struct Network {
pub exports: Vec<ExportSlot>,
pub attributes: Attributes, // per-network ui::* (navigation, previewing)
}
pub struct ExportSlot {
pub target: Option<NodeInput>, // None = removed/empty
pub timestamp: TimeStamp,
}
pub const ROOT_NETWORK: NetworkId = NetworkId(0);
```
`peer_users` records the append-only `PeerId → UserId` mapping written by each device's first contribution (see [Concurrency model](#concurrency-model-cmrdt)).
The renderable graph lives in `networks[&ROOT_NETWORK]`. By convention the renderer consumes slot 0 of its exports. The editor can pick a different slot via type-based heuristics or user choice.
## Two exports concepts
- **`Network.exports`** are the outputs of a callable network, used by parent networks and (on `ROOT_NETWORK`) by the renderer. High-frequency edits.
- **Exported nodes** are the document's library API: nodes an importing document can reference. A node exposed here may itself be backed by a network via `Implementation::Network`. Library metadata (display name, category, and so on) lives as `library::*` attributes on the referenced node. Low-frequency edits. The list is a document-level attribute (`Registry.attributes["exported_nodes"]`) rather than a dedicated field, so it rides the ordinary `ChangeDocumentAttribute` LWW path with its own per-key timestamp.
Library import (how `.gdd` files reference each other and surface library nodes) is the subject of a follow-up RFC. The `exported_nodes` attribute key is reserved but not yet read or written.
## Attributes: the type-erased metadata bucket
All metadata that is not structural lives in a single `Attributes` bucket per node, per input, and at the document level. That covers node positions, display names, `call_argument` overrides, visibility, `context_features`, locked/pinned flags, input type hints, and reflection metadata.
```rs
pub struct Value {
pub value: serde_json::Value,
pub timestamp: TimeStamp,
}
pub type Attributes = BTreeMap<String, Value>;
```
Keys carry a namespace where one applies, mostly the `ui::*` editor-metadata keys (`ui::position`, `ui::display_name`, and so on). Compute fields use bare keys (`call_argument`, `context_features`, `original_node_id`). Values are JSON, and the per-value `TimeStamp` drives LWW on concurrent edits.
Type-erasure exists for migrations: storage data can be transformed without keeping old Rust struct shapes alive just to deserialize them.
## Deltas
A `RegistryDelta` is one atomic change to the registry, simultaneously a history step, a CRDT op to broadcast to peers, and a recompilation signal:
```rs
pub enum RegistryDelta {
AddNode { id: NodeId, node: Node },
RemoveNode { id: NodeId, snapshot: Node },
ChangeNodeInput { id: NodeId, index: u32, new_input: NodeInput },
ChangeNodeAttribute { id: NodeId, delta: AttributeDelta },
ChangeNodeInputAttribute { id: NodeId, index: u32, delta: AttributeDelta },
SetNetworkExport { id: NetworkId, index: u32, export: Option<NodeInput> },
ChangeNetworkAttribute { id: NetworkId, delta: AttributeDelta }, // per-network ui::nav::*, ...
AddNetwork { id: NetworkId, network: Network },
RemoveNetwork { id: NetworkId, snapshot: Network },
ChangeDocumentAttribute { delta: AttributeDelta }, // incl. the exported_nodes list
RegisterPeer { peer: PeerId, user: UserId }, // self-inverse; see below
// Resources (incl. proto-node declarations):
SetResourceHash { id: ResourceId, hash: Option<ResourceHash> }, // LWW on the resolved hash
AddSource { id: ResourceId, key: SourceKey, source: serde_json::Value }, // insert/LWW entry in the source chain
RemoveSource { id: ResourceId, key: SourceKey },
AddResource { id: ResourceId, entry: ResourceEntry }, // whole-entry; reverse of RemoveResource
RemoveResource { id: ResourceId, snapshot: ResourceEntry }, // snapshot for O(1) reverse
Merge { extra_parents: Vec<Rev> }, // joins divergent tips; registry no-op
Other(serde_json::Value), // forward-compatible escape hatch
}
/// `value: None` is the removal case. Timestamp lives on the wrapping `Delta`.
pub struct AttributeDelta {
pub key: String,
pub value: Option<serde_json::Value>,
}
```
Each delta is wrapped with metadata for history, identity, and causality. `Rev` is content-addressed: `blake3` truncated to 128 bits of `(parent, author, timestamp, kind)`, so identical content always produces the same `Rev` and concurrent retirements that converge collapse by construction.
```rs
pub struct Rev(pub NonZeroU128);
pub struct Delta {
pub id: Rev,
pub parent: Option<Rev>, // primary parent; None for the root delta
pub author: PeerId,
pub timestamp: TimeStamp,
pub kind: RegistryDelta,
pub reverse: RegistryDelta, // precomputed for undo; excluded from id
pub attributes: Attributes, // mutable local annotations; excluded from id
}
```
The history DAG is multi-parent, but a delta stores only its primary `parent`. Extra parents ride a dedicated `RegistryDelta::Merge { extra_parents }` op, which joins divergent tips into one node and is a registry no-op on replay. So a merge's identity is its parent set alone: two peers merging the same tips mint the identical `Rev` and it dedups.
Because `parent` is itself a `Rev`, an `id` transitively commits to the delta's whole ancestry, the same Merkle chaining a Git commit hash gives. A `Delta`'s `id` is therefore recomputable from its identity fields, and history loaded from an untrusted source is checked by rehashing every delta and rejecting any whose stored `id` does not match (the load path skips this for trusted local data, since the rehash is not free over a large history).
One timestamp per `Delta` applies to every LWW-eligible write inside its `kind`. Slot writes, attribute writes, and whole-list writes all read the same `Delta.timestamp`.
`Delta.attributes` is a type-erased annotation bucket (the same shape as the registry's attribute buckets) for mutable, local-only labels: the `interaction_end` marker that bounds undo units, and later commit messages. It is **excluded from `id`** so that annotating a delta never changes its content-addressed identity. An inline write sets it before the delta's history frame is persisted, while a later relabel rewrites that frame.
## History as a tree
History is a multi-parent DAG. Branching is implicit: every concurrent or out-of-sync edit creates a branch by virtue of sharing a parent with another delta. Divergent tips are rejoined by an explicit `Merge` delta listing the joined tips, which is a registry no-op (it only collapses the tips so `head` stays a single `Rev`).
```
D1 ── D2 ── D3 (one user's session)
/
── root ──
\
D4 ── D5 (another peer, branched at root)
```
Linear undo is the common case. Branching falls out naturally when two peers (or two windows on one machine) edit from the same parent. A history UI lets users navigate this tree to recover from convoluted undo/redo sessions or revisit past exploration. History compression (planned, not yet implemented) would collapse similar consecutive deltas (for example, three sequential "move shape" ops) into a single coarser delta.
## Two-tier history: hot ops and retired commits
History has two tiers:
- **Hot ops** are speculative, intended to be broadcast per-keystroke for live collaboration (broadcast transport is not yet implemented, so today they stay local). They carry only a Lamport timestamp, with no parents and no content-addressed `Rev`. They live in `Document.hot_log`, are GC'd at retirement, and are persisted as a sidecar for crash recovery. They may pass through non-compiling intermediate states.
- **Retired commits** are `Delta`s produced by retirement. Every retired commit compiles in the retiring peer's local view. They are content-addressed, durable, browseable, and replayable.
Retirement promotes a window of hot ops (those with timestamp at or before a cutoff) into retired deltas, re-applied with a single fresh retirement timestamp per field so LWW arms bump to `T_retire` and the original hot-op timestamps are discarded. Today retirement is one retired delta per hot op. The interfaces are in place for coarsening a window into fewer, semantically-equivalent commits (one per logical `(node, field)` group), but that grouping is not yet implemented.
In a collaborative session a leader-elected peer would own retirement. That election is designed to be gossip-based (the lowest `PeerId` among peers whose `retirement_tip` matches the session max) and best-effort, needing no quorum because content-addressed `Rev`s make concurrent retirements that converge dedupe by construction. The `retirement_tip` heartbeat field exists but is inert until broadcast transport lands. Today every session retires its own hot ops (see solo retirement below).
Once coarsening lands, do/undo pair collapse will only happen when both land in the same retirement window, subject to dependency closure (collapse must not orphan a reference to `X`). The undo/redo mechanism itself is described below.
Solo retirement is the same mechanism with a session of one, so history compaction during solo editing will fall out for free once coarsening is implemented.
## Undo/redo
Undo/redo operate on the delta history rather than full-interface snapshots. A commit's undo behavior depends on whether it has been broadcast to other peers, tracked by `last_broadcast_rev: Option<Rev>` on `Document` (the latest commit shared with at least one peer, or `None`, and thus the entire history, during solo editing):
- **Silent zone:** commits after `last_broadcast_rev`. No other peer has seen them, so they can be rewound in place.
- **Published zone:** commits at or before `last_broadcast_rev`. Shared history is never rewound. Undoing one is a *new* forward commit applying the inverse with a fresh timestamp, so concurrent peers converge by LWW.
The silent zone is the implemented path (solo editing has no transport yet). The published-zone forward-undo lands with collaboration.
**Silent-zone cursor.** `head: Option<Rev>` is a movable pointer into the append-only DAG (`None` on an empty document with no commits yet). Undo/redo move it but never delete deltas (that would make redo impossible and discard branch history). The extra state is a redo stack `Vec<Rev>`, the checkpoints the user has undone past, because the DAG alone cannot say which child a `head` was undone *from*. New state persists in `session.json` alongside `head`, so redo survives reopen. A new edit while the redo stack is non-empty clears it (the undone-forward branch stays physically in the DAG but is no longer reachable via redo).
**Interactions, not deltas.** One user action diffs into several deltas (one per changed field, slot, or attribute), so undo steps per *interaction* rather than per delta. The last delta of each interaction is tagged with the `interaction_end` attribute, and undo reverts deltas walking the first-parent chain until the parent is an `interaction_end` boundary or the root. The starting `head` (the checkpoint) is pushed to the redo stack, and redo re-applies forward to it.
**Force-apply.** Rewinding re-applies each delta's precomputed `reverse` (for redo, the forward `kind`). These carry the *original* timestamp, which would tie (and so lose) the LWW arms' strict `>` comparison, since the forward op already stamped each field at that timestamp. In the single-writer silent zone the rewind value is authoritative, so silent undo/redo apply in a **force** mode where LWW arms assign unconditionally and structural ops are idempotent. Undo and redo are symmetric (force-reverse, force-forward), so no clock advances and identities are unchanged.
**Two registries.** Computing a correct `reverse` for an LWW field means reading the field's *pre-op* value. But staged edits apply to the live registry immediately (for responsiveness), so by retirement time it already holds the *post*-op value. `Document` therefore keeps two registries: a **working** registry (committed state plus live un-retired ops, what reads and the cursor see) and a **retired snapshot** (committed deltas only). Retirement computes reverses against, and forward-applies to, the snapshot, so the reverse captures the true prior value, and the working registry already reflects the ops and is left as-is. When there are no un-retired ops the two are equal *by value* (their LWW field timestamps can differ, since retirement re-stamps the snapshot at a fresh time), and undo/redo restore that equality by resyncing the snapshot to the rewound working registry.
## Concurrency model: CmRDT
The format uses an operation-based CRDT. The transport layer delivers ops in causal order exactly once (TCP plus the parent links threading the `Delta` DAG). The storage layer assumes this and requires only that concurrent op pairs commute. It does not need idempotency, state-merge, or out-of-order replay.
Graph-shape invariants (the graph remaining a DAG, the result compiling) are best-effort. Conflicts that produce a non-compiling graph surface as wiring or type errors rather than being masked by the CRDT.
Identity is two-tier. `PeerId` is per-device (stable per `(device, document)`, used for CRDT tiebreaking and `NodeId` scoping). `UserId` is per-human (stable across devices, used for identity display and undo-chain walking). Each device's first contribution emits `RegisterPeer { peer, user }`, which writes an append-only entry to `Registry.peer_users`. Causal delivery guarantees the registration arrives before any of that peer's other ops. The mapping is permanent (first write wins, a conflicting re-registration errors, and an identical one is a no-op), so `RegisterPeer` is its own reverse: replaying it during undo is a no-op rather than needing a distinct removal variant.
## Editor pipeline
The editor operates on its existing runtime types. Storage is a serialization layer for persistence, sync, and history:
```
┌─────────────────────────────────────────┐
│ Editor (runtime) │
│ NodeNetworkInterface │
│ ├── NodeNetwork (compute graph) │
│ └── NodeNetworkMetadata (editor UI) │
└─────────────────────────────────────────┘
▲ │
│ to_runtime │ from_runtime
│ ▼
┌─────────────────────────────────────────┐
│ Storage layer (graph-storage crate) │
│ Registry, RegistryDelta, Document │
└─────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────┐
│ On-disk (.gdd container) │
│ named payloads: manifest, registry, │
│ history, hot-log, session, │
│ resources/<hash> │
│ served by a Container backend │
│ (folder, in-memory, OPFS), optionally │
│ encoded through an Archive codec │
│ (zip, xz) │
└─────────────────────────────────────────┘
```
The runtime is the source of truth during editing. Conversion runs on save, on load, and across the sync boundary when broadcasting or receiving ops. The editor-facing handle is `Session` (`graph_storage::Session`), and `Document` is internal. `Session::stage_from_runtime(&NodeNetwork, &dyn NodeMetadataSource)` is the entry point: it diffs the stored registry against a fresh conversion, ticks the clock once per emitted op, and applies each as a hot op on the hot log. The `Gdd` handle then persists the hot frames and retires them into durable history.
Staging and retirement are split so that one undo gesture maps to one retired gesture. The editor's undo unit is one legacy transaction boundary, but a single user action (for example, a tool drag) re-commits the runtime many times within one such boundary. So the editor *stages* on every commit (keeping the working registry and autosave current) and *retires the pending hot ops as one gesture* only at the undo-step boundary and before any undo/redo. (`commit_from_runtime`, which stages and retires atomically, remains for one-shot callers.) Solo editing thus flows through the same hot-op-then-retire path that collaboration uses, exercising it before any transport lands.
## On-disk container
A `.gdd` document is a collection of named byte payloads. A `Container` backend (loose folder, in-memory, OPFS in the browser) provides the path-keyed read/write surface. An `Archive` codec (zip, xz-compressed tarball) optionally encodes a container into a single byte stream for compact distribution. The same logical document can be saved as a loose folder for VCS-friendly checkouts or as an archive for shipping, without any change above the container layer.
The two concerns live in downstream crates. `document-container` defines the `Container` and `AsyncContainer` traits, the backends, byte ownership (mmap regions, owned buffers, external file mmaps via `mmap-io`), and the `Archive` trait. `document-format` defines the typed `Gdd` handle, the layout (logical-payload-name to in-container path), the data codec (JSON or binary), the manifest, and the save/load orchestration. `graph-storage` itself stays disk-unaware.
```
┌─────────────────────────────────┐
│ editor │
└─────────────────────────────────┘
│ │
▼ ▼
┌───────────────┐ ┌──────────────────────────────┐
│ graph-storage │ │ document-format │
│ (disk-unaware)│◀─│ Gdd handle, Layout, codec, │
└───────────────┘ │ ExportOptions │
└──────────────────────────────┘
│
▼
┌──────────────────────────────┐
│ document-container │
│ Container backends + Archive│
│ codecs (folder, memory, │
│ OPFS / zip, xz) │
└──────────────────────────────┘
```
Arrows mean "depends on". The editor uses `Session` from `graph-storage` at runtime and `Gdd` from `document-format` on save/load. `document-format` serializes `graph-storage`'s types and delegates byte I/O to `document-container`. `graph-storage` and `document-container` are independent leaves.
A document contains:
- `manifest.json` is always JSON, the bootstrap file. It carries the magic identifier `"gdd"` (the `format` field), a single `u32` `format_version`, a `document_id`, the editor and stdlib versions, and the per-payload codec table (`codecs`). It deliberately omits per-peer state: the saving peer's `PeerId` and the history cursor live in the session payload, not the manifest, so they travel with the local view rather than the shared document.
- `registry.{json,bin}` is the serialized `Registry`. The codec is fixed per payload and recorded in the manifest (JSON for inspectable, MessagePack for compact, and binary must be self-describing, as the codec rationale explains). Export reuses the working copy's recorded codecs rather than re-encoding.
- `history.{jsonl,frames}` is the serialized retired delta DAG, appended a record at a time. JSON history is line-oriented (one delta per line). Binary history is length-prefixed MessagePack frames, the prefix guarding against a torn final frame from a crash.
- `hot-log.{jsonl,frames}` is the un-retired hot ops, persisted as a sidecar for crash recovery and GC'd at retirement.
- `session.{json,bin}` is per-peer local state: this peer's `PeerId`, the history cursor (`head_rev`), the redo stack, `last_broadcast_rev`, and view settings. It is local-view state, not part of the shared document.
- `resources/<hash>` is embedded resource bytes, keyed by `ResourceHash`.
The folder backend stores these as plain files on disk, and an archive codec packs the same named entries into a single file.
```
my-doc.gdd/
├── manifest.json
├── registry.json
├── history.jsonl
├── hot-log.jsonl
├── session.json
└── resources/
├── 7f3a...
└── 2c91...
```
The `Gdd` handle owns the loaded bytes and exposes them as zero-copy slices. On the folder backend, reads are direct mmap references, while loading from an archive decompresses once on open into an in-memory backend. The working copy is mutated continuously (autosave), and `export(dest, format, options, byte_store)` produces a separate artifact through an `ExportFormat` (`Folder`/`Zip`/`Xz`) without mutating the handle.
`ExportOptions` controls scope: `include_registry` (skipping it rebuilds from history on load), `include_history` (skipping it produces a state-only snapshot), and `embed_all_resources`. These compose freely except that `include_registry: false && include_history: false` is rejected. The `byte_store` resolves resource bytes the working copy does not physically hold (in the editor they live in the app-global cache). `Embedded`-sourced resources are always materialized into the export's `resources/`, and `embed_all_resources` additionally promotes link-only resources (`Url`/`FilePath`/`Font`) by prepending an `Embedded` source. That promotion is committed as real `AddSource` deltas on a throwaway session clone so the exported registry and history stay consistent. History is serialized in deterministic topological order, so identical delta sets export byte-identically.
## Resources
Everything content-addressable is a resource: raster images, fonts, embedded WASM, **and proto-node declarations**. The storage `Registry` holds `resources: ResourceStore` (references only). The bytes live in a content-addressed byte store keyed by `ResourceHash`, owned by the caller (the app-global cache in the editor, the `Gdd` container for standalone/export) rather than by `graph-storage`.
```rs
pub type ResourceStore = HashMap<ResourceId, ResourceEntry>;
pub struct ResourceEntry {
pub sources: Vec<(SourceKey, SourceValue)>, // fallback chain, sorted by key, LWW-element-set
pub hash: Option<ResourceHash>, // resolved content hash (LWW)
pub hash_timestamp: TimeStamp,
}
pub struct SourceKey { pub priority: Priority, pub peer: PeerId } // fractional priority + peer tiebreak
pub struct SourceValue { pub source: serde_json::Value, pub timestamp: TimeStamp }
```
A node references a resource by `ResourceId`. The entry maps it to a chain of `DataSource`s tried in order (`Embedded` bytes by hash, `FilePath`, `Url`, `Font`) plus the resolved `ResourceHash`. The chain is an **ordered LWW-element-set** keyed by `SourceKey`: each key carries a fractional `Priority` so a peer can insert between two sources without renumbering, and concurrent insertions at the same priority get distinct keys via the `PeerId` tiebreak. Distinct-key adds (the normal cross-peer case) therefore all survive. A same-key add versus remove resolves by LWW on the per-`Delta` timestamp rather than add-wins, so there are no tombstones, and causal delivery linearizes an add and its later removal. The `hash` is **LWW** (content-derived, so concurrent resolves agree by construction).
Each `DataSource` is stored as `serde_json::Value` rather than a typed enum, with the same motivation as the `Attributes` bucket: type-erasure lets migrations restructure variants without keeping old enum shapes alive. `DataSource` stays typed at the runtime layer, and conversion happens at the serialization boundary. Unknown variants are a hard error on load.
**Declarations as resources.** `Implementation::ProtoNode(ResourceId)` references a declaration resource. `from_runtime` serializes each `ProtoNode` through a self-describing `serde_json::Value` (MessagePack-encoded, via `encode_declaration`), hashes the bytes, derives the `ResourceId` from that hash, and registers a `DataSource::Embedded` entry, with the bytes going to the caller's byte store. (Deriving the ID from the hash is a deterministic bootstrap. A future stable well-known-ID table would let the ID denote the function.) `to_runtime` resolves declarations back via a `Declarations` map (`ResourceId` to `ProtoNode`) that the caller builds from its byte store. The self-describing form keeps `ProtoNode`'s serde aliases working so the on-disk shape stays migratable.
A `NodeInput::Value` stores its `TaggedValue` as a self-describing `serde_json::Value` (the same type-erasure as `Attributes` and `DataSource`), so the `TaggedValue` serde aliases keep working and the on-disk shape stays migratable. Legacy documents with inline image `TaggedValue`s have those values extracted into resources at load time, and new saves never embed inline image blobs in `NodeInput::Value`.
## Migrations
Migrations run on the type-erased `Registry`, after deserialization and before `to_runtime`. The pipeline reads the format version from the manifest, deserializes the registry with attributes as raw `serde_json::Value`, applies registered migrations scoped to the version range, and hands the result to `to_runtime`.
Migrations live in a dedicated crate so they are usable both from the editor and from a CLI for batch upgrades. A single global format version is used initially, and per-library versioning is a future extension.
# Reference-level explanation
## Conversion: runtime to storage
`from_runtime` flattens the recursive `NodeNetwork` into the flat `Registry`:
- Each node's path through the runtime nesting is hashed (blake3 truncated to 64 bits, with the document's `PeerId` mixed in) to produce a stable global `NodeId`. The original local ID is stashed in an attribute (`original_node_id`) so the round-trip can rebuild the runtime's per-network local IDs. Subsequent live edits mint fresh peer-scoped IDs via `Document::next_node_id` (`blake3(peer, counter)`) instead of going through the path-hash bootstrap.
- Each nested `NodeNetwork`'s `NetworkId` is derived from the owning node's path (blake3 of `(peer, path)` with a `"network"` domain tag), not assigned by a traversal counter. This makes it stable across a `to_runtime` then `from_runtime` round trip. That stability is load-bearing, because node paths (and thus node-ID hashes) include `NetworkId`s, so an unstable network ID would cascade into unstable node IDs and break re-commit after open. Aliasing (multiple nodes referencing the same network) is structurally supported by the storage model, since `Implementation::Network(NetworkId)` is a reference, but the converter does not exploit it yet. Aliasing is fixed at the runtime layer first, and the converter then preserves sharing without an explicit dedup pass.
- Non-structural `DocumentNode` fields (`call_argument`, `context_features`, `visible`, `skip_deduplication`, and so on) become entries in the node's `attributes`. UI metadata from `DocumentNodeMetadata` (positions, display names, locked, pinned, and so on) flows through the same bucket under `ui::*` keys.
`to_runtime` is the inverse. It rebuilds local IDs from the stashed attribute, restores typed fields from attribute values, follows `Implementation::Network` references to recursively materialize nested networks, and resolves `Implementation::ProtoNode(ResourceId)` against a `Declarations` map (`ResourceId` to `ProtoNode`) the caller supplies from its byte store. Since `graph-storage` is byte-unaware, `to_runtime` takes the resolved declarations as a parameter rather than reaching for bytes itself.
## Slots: inputs and exports
`Vec<InputSlot>` and `Vec<ExportSlot>` are positionally indexed at the storage layer. Each slot carries its own `TimeStamp`, giving LWW per slot on concurrent edits.
`ExportSlot` is sparse: `target == None` means the slot has been removed. `InputSlot` is dense. The runtime conversion compacts exports into a dense `Vec<NodeInput>` (preserving the runtime's "remove an export shifts later positions" semantics) and strips input timestamps.
Because inputs are stamped, `NodeInput::Node` references are set directly via `ChangeNodeInput`, with no add/remove rewire workaround.
## CmRDT semantics
- **Timestamps.** `TimeStamp { counter: u64, peer: PeerId }` is a Lamport counter with a peer-ID tiebreak. Comparison is lexicographic (counter first, then peer). Wall-clock time is not used.
- **NodeId identity.** Every new `AddNode` issues a peer-scoped ID, so concurrent creates cannot collide.
- **Causal delivery.** `apply_delta` requires that every parent of the delta (its `parent` plus any `Merge` extra parents) is already in local history. The storage layer does not buffer, and out-of-order delivery is a transport concern. New peers initialize via snapshot transfer (`Registry` plus history) before streaming deltas.
- **Removal.** Physical, with no tombstones. If a later op targets an absent node or network, the receiver searches its ancestry (from `head`, following all parents) for the delta that removed the entity, the one whose `reverse` is the matching `AddNode` or `AddNetwork`, and re-applies that reverse before applying the incoming op. `RemoveNode` and `RemoveNetwork` each carry a `snapshot` of the removed entity inside that reverse so the rebuild is O(1) and needs no further history walk. The snapshot is required because retirement recomputes an op's reverse *after* the hot op already applied the removal, when the live entity is gone. Removal is therefore non-durable under concurrent edits, since any concurrent reference to a removed node revives it.
- **LWW primitives.** Per-input (`InputSlot.timestamp`), per-export-slot (`ExportSlot.timestamp`), and per-attribute-value (the `TimeStamp` in `Attributes`). The exported-nodes list is one such attribute value (the `exported_nodes` document attribute), so it inherits per-key LWW with no separate machinery. The timestamp driving every LWW arm comes from the wrapping `Delta`. `AttributeDelta` carries `value: Option<_>` so a single shape covers both `Set` (`Some`) and `Remove` (`None`), and `Set` versus `Remove` has a defined winner.
- **Resources.** A resource's `hash` is LWW (content-derived, so concurrent resolves agree). Its source chain is an ordered LWW-element-set keyed by `SourceKey` (fractional priority plus peer tiebreak): concurrent `AddSource`s at distinct keys all survive, and a re-add or a remove at the same key is LWW on the per-`Delta` timestamp (no tombstones, so a same-key add/remove is order-sensitive only without causal delivery). Whole-resource `AddResource`/`RemoveResource` mirror the node/network add-remove pairs (`RemoveResource` snapshots the entry for O(1) reverse).
The CRDT does not mask graph-shape conflicts. Concurrent same-slot `SetNetworkExport`s with different targets resolve by LWW, but the resulting wiring may be wrong, and downstream consumers see it as a compile or wiring error.
## History storage
`History` is a `Vec<Delta>` in topological order (parents before children) with a `HashMap<Rev, usize>` index for lookup. The append order is canonical, which is what lets history serialize byte-identically across peers that absorbed the same delta set. `Document` adds a `head: Option<Rev>` (the local cursor, which advances only on local commits, `None` until the first commit) and a `hot_log: Vec<HotOp>` (in-flight unretired ops). Walking history follows each delta's `parent`, and this default first-parent walk reconstructs a single peer's local chain. Branches are siblings under a shared parent, and a `Merge` delta rejoins them, its extra parents naming the other tips it folds in.
## Editor metadata
`DocumentNodePersistentMetadata` and `NodeNetworkPersistentMetadata` from the runtime flow through the storage `Attributes` bucket under `ui::*` keys. That covers display names, locked/pinned flags, navigation/PTZ state, selection undo/redo stacks, and layer/node type metadata. Transient runtime caches (`DocumentNodeTransientMetadata`, click targets, resolved types, `OriginalLocation`) stay runtime-only and are not stored.
Document-scoped editor settings (viewport view, render mode, overlay/ruler visibility, snapping, collapsed layers) ride the document-level `Registry.attributes` under `ui::*` keys (`ui::ptz`, `ui::render_mode`, and so on). This is what makes the `.gdd` a lossless replacement for the legacy format's document-handler fields.
# Drawbacks
- **Diffing two full `Registry`s on every autosave is O(N) in document size.** This is the interim cost of treating storage as a serialization layer derived from the runtime. It is currently triggered at autosave boundaries (`commit_storage_snapshot`) rather than per gesture, and addressed long-term by computing deltas directly on runtime mutations.
- **Attributes as `serde_json::Value` carry per-value overhead.** This is mitigable with a typed fast path for hot keys without changing the design. They also force a self-describing codec, ruling out the most compact binary formats.
- **Single global format version is a sharp edge** when libraries diverge: a breaking change in one library bumps the version for documents that do not use it.
- **`RemoveNode` is non-durable under concurrency.** Any concurrent reference to a removed node revives it from history.
# Rationale and alternatives
**Delta-based vs. cleaner snapshot format.** A delta is the right unit for history, CRDT sync, and incremental compilation. Picking one representation for all three eliminates conversion seams between subsystems that need to interoperate.
**CmRDT vs. state-based CRDT or OT.** State-based CRDTs require a merge function and large state vectors. OT requires a central server to mediate transforms. CmRDT only requires per-op commutativity plus a causal-order delivery layer, which the transport provides.
**Merkle `Rev` (parent in the hash) vs. a position-independent content id.** A `Rev` hashes `(parent, author, timestamp, kind)`, and since `parent` is itself a `Rev`, every `Rev` transitively commits to its whole ancestry. This is the Git commit-hash model: a Git commit folds its parent SHA, tree, author, committer, and message into its own SHA, so changing any ancestor rewrites every descendant hash. We keep that model for the same two reasons Git gets value from it. First, tamper-evidence: rehashing detects any rewrite of history (see [Deltas](#deltas)). Second, the chain doubles as the causal structure the CRDT already needs. We then diverge from Git in one deliberate place: a `Merge` is hashed over its sorted parent set alone, with author and timestamp excluded, so two peers merging the same tips mint the *identical* `Rev` and it dedups into one shared node. Git does the opposite (its merge commits carry author/time/message and so never converge), because Git reconciles through a human pushing and pulling rather than through automatic DAG convergence. The cost of parent-in-hash is the one Git also pays: reordering or rebasing an op rewrites every descendant `Rev`, so identity is not stable across [history linearization](#future-possibilities). A pure content-derived id (no parent) would survive reordering but would forfeit both convergence-by-construction and free tamper-evidence, so it is the wrong primary identity. The position-independent use case is better served by a separate, computed id (see the patch-id analogue under [Future possibilities](#future-possibilities)) rather than by weakening `Rev`.
**Ad-hoc resurrection vs. tombstones.** Tombstones add a permanent footprint to the data model and a GC policy question. Resurrection reuses the history log already needed for undo as the recovery mechanism, keeping the live `Registry` lean. The cost is that `RemoveNode` is not durable under concurrent edits.
**Type-erased attributes vs. typed metadata fields.** Migrations operate on attribute values without keeping old Rust struct shapes alive. The cost is per-value overhead, mitigable without changing the model.
**Flat node storage vs. nested networks.** All CRDT ops target nodes via a single uniform `NodeId` address space regardless of nesting depth. A nested representation would require ops to carry a path, complicating commutativity.
**`.gdd` vs. reusing `.graphite`.** A distinct extension makes migration unambiguous and prevents older Graphite versions from trying to open a new-format file.
**One self-describing binary codec (MessagePack).** The persisted bodies (the registry, the history of deltas, and the `ProtoNode` declaration resources) serialize as their typed Rust shapes, but each carries type-erased `serde_json::Value` leaves: attribute values, `NodeInput::Value` payloads, and resource source bodies. Those leaves need a self-describing codec to deserialize and to keep the serde-alias migration path alive, which forces the same requirement on the whole payload. MessagePack provides that at a few percent size cost. Hash preimages (`NodeId`, `Rev`, node-path hashes) use the same codec: a fixed serializer emits one deterministic byte form per value, which is all `blake3` needs, so the codec doubles as the canonical hash encoding without a second format.
**Source chain as a sorted `Vec` vs. `BTreeMap`.** `SourceKey` is a struct, so a `BTreeMap`-keyed chain cannot serialize to JSON (string keys only). A sorted `Vec` of pairs keeps the same ordering and per-key LWW semantics losslessly across every codec.
# Future possibilities
- **Per-library format versioning** so a breaking change in one library doesn't bump the version for documents that don't use it.
- **History linearization.** Prune unused branches from a convoluted tree to produce a clean undo/redo history.
- **A patch-id analogue for position-independent identity.** A `Rev` rewrites under reordering because it commits to its parent, so it cannot answer "is this the same logical edit as that one, somewhere else in history?" Git solves the same problem with `git patch-id`, a hash of the normalized *diff* that is independent of parent and commit metadata. The analogue here is a `content_id` hashed over the op payload with the bookkeeping fields (parent, author, Lamport timestamp) normalized out. Crucially it need not enter the data model: it is derivable from a `Delta` on demand, so it can be computed when linearization or cross-document dedup needs it without adding a stored field or touching the format version. This keeps `Rev` as the sole stored identity while still enabling identity-preserving linearization and recognizing a shared edit across documents.
- **Runtime-native deltas.** Move delta computation out of the storage layer into the runtime, eliminating per-edit `Registry` re-conversion.
- **Incremental compilation driven by deltas.** The compiler consumes runtime deltas and recompiles only changed regions.
- **Runtime-level aliasing for shared node-network definitions.** Storage already supports `Implementation::Network` as a reference, and once the runtime supports sharing natively, the converter preserves it.
- **Online migration service.** Active editors drop migrations older than some threshold, and old documents go through a remote upgrade pipeline first.
- **Distributed / signed history.** Content-addressed `Rev` plus signing enables multi-author provenance and verifiable history.
- **Libraries as files.** A follow-up RFC will specify how `.gdd` files act as importable libraries via the document's `exported_nodes` list.
+2
View File
@@ -9,3 +9,5 @@ default-run = "cargo-run"
[dependencies]
thiserror = { workspace = true }
semver = "1"
duct = "1"
@@ -0,0 +1,13 @@
[package]
name = "cargo-run-internal-download"
edition.workspace = true
version.workspace = true
license.workspace = true
authors.workspace = true
[dependencies]
cargo-run = { path = "../.." }
ureq = { version = "3", default-features = false, features = ["rustls"] }
sha2 = { version = "0.10" }
flate2 = { version = "1", default-features = false, features = ["rust_backend"] }
tar = { version = "0.4", default-features = false }
@@ -0,0 +1,162 @@
use cargo_run::Error;
use flate2::read::GzDecoder;
use sha2::{Digest, Sha256};
use std::io::{self, Read};
use std::path::{Component, Path, PathBuf};
use std::process::ExitCode;
pub fn usage() {
eprintln!();
eprintln!("USAGE:");
eprintln!(" cargo run -p cargo-run-internal-download -- <URL> <SHA256> <OUT> \\");
eprintln!(" [--extract] [--strip <N>] [--include <PREFIX>]...");
eprintln!();
eprintln!("Args:");
eprintln!(" <URL> HTTPS source to download");
eprintln!(" <SHA256> Expected SHA-256 of the response body (64 hex digits)");
eprintln!(" <OUT> Destination file (default) or directory (with --extract)");
eprintln!(" --extract Decompress the body as tar.gz and extract into <OUT>");
eprintln!(" --strip <N> Strip N leading path components from each entry (requires --extract)");
eprintln!(" --include <PREFIX> Only extract entries whose stripped path starts with PREFIX, repeatable (requires --extract)");
eprintln!();
}
fn main() -> ExitCode {
if let Err(e) = parse_args().inspect_err(|_| usage()).and_then(run) {
eprintln!("Error: {e}");
return ExitCode::FAILURE;
}
ExitCode::SUCCESS
}
struct Args {
url: String,
sha256: String,
out: PathBuf,
mode: Mode,
}
enum Mode {
File,
ExtractTarGz { strip: usize, include: Vec<String> },
}
fn run(Args { url, sha256, out, mode }: Args) -> Result<(), Error> {
eprintln!("Downloading {url}");
let mut body = Vec::new();
ureq::get(&url)
.call()
.map_err(|e| Error::Io(io::Error::other(e), format!("HTTP GET {url}")))?
.into_body()
.into_with_config()
.reader()
.read_to_end(&mut body)
.map_err(|e| Error::Io(io::Error::other(e), "reading response body".into()))?;
let actual = Sha256::digest(&body).iter().map(|b| format!("{b:02x}")).collect::<String>();
if !actual.eq_ignore_ascii_case(&sha256) {
eprintln!("SHA-256 mismatch:");
eprintln!(" expected: {sha256}");
eprintln!(" actual: {actual}");
return Err(Error::Io(io::Error::other("SHA-256 mismatch"), "verifying download".into()));
}
match mode {
Mode::File => write_to_file(&body, &out),
Mode::ExtractTarGz { strip, include } => extract_tar_gz(&body, &out, strip, &include),
}
}
fn write_to_file(body: &[u8], path: &Path) -> Result<(), Error> {
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
std::fs::create_dir_all(parent).map_err(|e| Error::Io(e, format!("creating '{}'", parent.display())))?;
}
std::fs::write(path, body).map_err(|e| Error::Io(e, format!("writing '{}'", path.display())))?;
eprintln!("Wrote {}", path.display());
Ok(())
}
// TODO: support other compression/archive formats
fn extract_tar_gz(body: &[u8], dir: &Path, strip: usize, include: &[String]) -> Result<(), Error> {
std::fs::create_dir_all(dir).map_err(|e| Error::Io(e, format!("creating '{}'", dir.display())))?;
let mut archive = tar::Archive::new(GzDecoder::new(body));
archive.set_preserve_permissions(true);
for entry in archive.entries().map_err(|e| Error::Io(e, "reading tar archive".into()))? {
let mut entry = entry.map_err(|e| Error::Io(e, "reading tar entry".into()))?;
let entry_path = entry.path().map_err(|e| Error::Io(e, "reading tar entry path".into()))?.into_owned();
let Some(stripped) = strip_components(&entry_path, strip) else {
continue;
};
if stripped.as_os_str().is_empty() || stripped.components().any(|c| matches!(c, Component::ParentDir | Component::Prefix(_) | Component::RootDir)) {
continue;
}
if !include.is_empty() {
let s = stripped.to_string_lossy().replace('\\', "/");
if !include.iter().any(|p| s.starts_with(p.as_str())) {
continue;
}
}
let entry_type = entry.header().entry_type();
if entry_type.is_symlink() || entry_type.is_hard_link() {
continue;
}
let target = dir.join(&stripped);
if let Some(parent) = target.parent() {
std::fs::create_dir_all(parent).map_err(|e| Error::Io(e, format!("creating '{}'", parent.display())))?;
}
entry.unpack(&target).map_err(|e| Error::Io(e, format!("unpacking '{}'", target.display())))?;
}
Ok(())
}
fn strip_components(path: &Path, n: usize) -> Option<PathBuf> {
let mut comps = path.components();
for _ in 0..n {
comps.next()?;
}
Some(comps.as_path().to_path_buf())
}
fn parse_args() -> Result<Args, Error> {
fn arg_err(msg: impl Into<String>) -> Error {
Error::Io(io::Error::new(io::ErrorKind::InvalidInput, msg.into()), "invalid arguments".into())
}
let mut args = std::env::args().skip(1);
let url = args.next().ok_or_else(|| arg_err("URL is required (first positional argument)"))?;
let sha256 = args.next().ok_or_else(|| arg_err("SHA-256 is required (second positional argument)"))?;
if sha256.len() != 64 || !sha256.chars().all(|c| c.is_ascii_hexdigit()) {
return Err(arg_err("SHA-256 must be 64 hex digits"));
}
let out = PathBuf::from(args.next().ok_or_else(|| arg_err("OUT is required (third positional argument)"))?);
let mut extract = false;
let mut strip: usize = 0;
let mut include: Vec<String> = Vec::new();
while let Some(arg) = args.next() {
match arg.as_str() {
"--extract" => extract = true,
"--strip" => {
let v = args.next().ok_or_else(|| arg_err("'--strip' requires a value"))?;
strip = v.parse().map_err(|_| arg_err(format!("--strip must be a non-negative integer, got '{v}'")))?;
}
"--include" => include.push(args.next().ok_or_else(|| arg_err("'--include' requires a value"))?),
other => return Err(arg_err(format!("unknown flag '{other}'"))),
}
}
let mode = if extract {
Mode::ExtractTarGz { strip, include }
} else {
if strip != 0 {
return Err(arg_err("--strip is only valid with --extract"));
}
if !include.is_empty() {
return Err(arg_err("--include is only valid with --extract"));
}
Mode::File
};
Ok(Args { url, sha256, out, mode })
}
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "cargo-run-internal-watch"
edition.workspace = true
version.workspace = true
license.workspace = true
authors.workspace = true
[dependencies]
cargo-run = { path = "../.." }
notify = "8.2.0"
notify-debouncer-full = "0.7.0"
@@ -0,0 +1,92 @@
use cargo_run::Error;
use cargo_run::cmd::prelude::*;
use notify::RecursiveMode;
use notify::event::{EventKind, ModifyKind};
use notify_debouncer_full::{Debouncer, RecommendedCache, new_debouncer, notify::RecommendedWatcher};
use std::collections::HashSet;
use std::path::Path;
use std::process::ExitCode;
use std::time::Duration;
const EXCLUDED_DIRECTORIES: &[&str] = &["target", ".git", "frontend/node_modules", "frontend/dist", "frontend/wrapper/pkg", "tools"];
const INCLUDED_EXTENSIONS: &[&str] = &["rs"];
const DEBOUNCE: Duration = Duration::from_millis(500);
fn main() -> ExitCode {
let release = std::env::args().nth(1).as_deref() == Some("release");
let _guard = match watch(cargo_run::frontend::build_wasm_steps(release, false)) {
Ok(guard) => guard,
Err(e) => {
eprintln!("Error setting up file watcher: {e}");
return ExitCode::FAILURE;
}
};
loop {
std::thread::park();
}
}
struct WatchGuard {
_debouncer: Debouncer<RecommendedWatcher, RecommendedCache>,
}
fn watch(steps: impl IntoIterator<Item = Expression>) -> Result<WatchGuard, Error> {
let steps: Vec<Expression> = steps.into_iter().collect();
let root = std::env::current_dir()
.and_then(|p| p.canonicalize())
.map_err(|e| Error::Io(e, "Failed to resolve root for file watcher".into()))?;
let root_clone = root.clone();
let mut current: Option<Sequence> = None;
let mut debouncer = new_debouncer(DEBOUNCE, None, move |result: notify_debouncer_full::DebounceEventResult| match result {
Ok(events) => {
let mut seen = HashSet::new();
let mut triggered = false;
for ev in events {
if !matches!(
&ev.event.kind,
EventKind::Create(_) | EventKind::Remove(_) | EventKind::Modify(ModifyKind::Data(_) | ModifyKind::Name(_) | ModifyKind::Any)
) {
continue;
}
for path in &ev.event.paths {
if is_excluded(path, &root) {
continue;
}
if seen.insert(path.clone()) {
triggered = true;
}
}
}
if triggered {
if let Some(c) = current.take() {
c.kill();
}
current = Some(sequence(steps.clone()));
}
}
Err(errors) => {
for e in errors {
eprintln!("watch: {e}");
}
}
})
.map_err(|e| Error::Io(std::io::Error::other(e.to_string()), "file watcher".into()))?;
debouncer
.watch(&root_clone, RecursiveMode::Recursive)
.map_err(|e| Error::Io(std::io::Error::other(e.to_string()), "file watcher".into()))?;
Ok(WatchGuard { _debouncer: debouncer })
}
fn is_excluded(path: &Path, root: &Path) -> bool {
let rel = path.strip_prefix(root).unwrap_or(path);
if EXCLUDED_DIRECTORIES.iter().any(|d| rel.starts_with(d)) {
return true;
}
!path.extension().and_then(|e| e.to_str()).is_some_and(|e| INCLUDED_EXTENSIONS.contains(&e))
}
+40
View File
@@ -0,0 +1,40 @@
use crate::cmd::prelude::*;
use crate::{Error, workspace_dir};
const INFO_FILE: &str = ".branding";
const DIR: &str = "branding";
pub fn setup() -> Result<(), Error> {
let workspace = workspace_dir();
let info_path = workspace.join(INFO_FILE);
let dir_path = workspace.join(DIR);
let marker_path = dir_path.join(INFO_FILE);
let info = std::fs::read_to_string(&info_path).map_err(|e| Error::Io(e, format!("reading '{}'", info_path.display())))?;
if let Ok(marker) = std::fs::read_to_string(&marker_path)
&& marker == info
{
return Ok(());
}
let mut lines = info.lines().map(str::trim).filter(|l| !l.is_empty());
let url = lines
.next()
.ok_or_else(|| Error::Io(std::io::Error::other("missing URL"), format!("parsing '{}'", info_path.display())))?;
let sha256 = lines
.next()
.ok_or_else(|| Error::Io(std::io::Error::other("missing SHA-256"), format!("parsing '{}'", info_path.display())))?;
eprintln!("Downloading branding assets from <{url}>...");
if dir_path.exists() {
std::fs::remove_dir_all(&dir_path).map_err(|e| Error::Io(e, format!("removing '{}'", dir_path.display())))?;
}
utils::internal("download").args([url, sha256, DIR, "--extract", "--strip", "1"]).dir(&workspace).run()?;
std::fs::copy(&info_path, &marker_path).map_err(|e| Error::Io(e, format!("writing '{}'", marker_path.display())))?;
Ok(())
}
+350
View File
@@ -0,0 +1,350 @@
use crate::Error;
use duct::{Handle, ReaderHandle};
use std::ffi::OsString;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread::JoinHandle;
pub use duct::{Expression, cmd};
pub mod prelude {
pub use super::{Expression, ExpressionExt, Sequence, TerminalColor, cmd, sequence, supervise, utils};
}
pub trait ExpressionExt {
fn arg(self, arg: impl Into<OsString>) -> Self;
fn args<I, S>(self, args: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<OsString>;
fn arg_if(self, cond: bool, arg: impl Into<OsString>) -> Self;
fn args_if<I, S>(self, cond: bool, args: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<OsString>;
fn run(self) -> Result<(), Error>;
fn read(self) -> Result<String, Error>;
fn output_unchecked(self) -> Result<std::process::Output, Error>;
}
impl ExpressionExt for Expression {
fn arg(self, arg: impl Into<OsString>) -> Self {
let arg = arg.into();
self.before_spawn(move |c| {
c.arg(&arg);
Ok(())
})
}
fn args<I, S>(self, args: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<OsString>,
{
let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
self.before_spawn(move |c| {
c.args(&args);
Ok(())
})
}
fn arg_if(self, cond: bool, arg: impl Into<OsString>) -> Self {
if cond { self.arg(arg) } else { self }
}
fn args_if<I, S>(self, cond: bool, args: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<OsString>,
{
if cond { self.args(args) } else { self }
}
fn run(self) -> Result<(), Error> {
Expression::run(&self).map_err(Error::Command)?;
Ok(())
}
fn read(self) -> Result<String, Error> {
Expression::read(&self).map_err(Error::Command)
}
fn output_unchecked(self) -> Result<std::process::Output, Error> {
let e = self.unchecked().stdout_capture().stderr_capture();
Expression::run(&e).map_err(Error::Command)
}
}
pub enum TerminalColor {
Black,
Red,
Green,
Yellow,
Blue,
Magenta,
Cyan,
White,
BrightBlack,
BrightRed,
BrightGreen,
BrightYellow,
BrightBlue,
BrightMagenta,
BrightCyan,
BrightWhite,
Reset,
}
impl TerminalColor {
fn as_str(&self) -> &'static str {
match self {
Self::Black => "\x1b[30m",
Self::Red => "\x1b[31m",
Self::Green => "\x1b[32m",
Self::Yellow => "\x1b[33m",
Self::Blue => "\x1b[34m",
Self::Magenta => "\x1b[35m",
Self::Cyan => "\x1b[36m",
Self::White => "\x1b[37m",
Self::BrightBlack => "\x1b[90m",
Self::BrightRed => "\x1b[91m",
Self::BrightGreen => "\x1b[92m",
Self::BrightYellow => "\x1b[93m",
Self::BrightBlue => "\x1b[94m",
Self::BrightMagenta => "\x1b[95m",
Self::BrightCyan => "\x1b[96m",
Self::BrightWhite => "\x1b[97m",
Self::Reset => "\x1b[0m",
}
}
}
pub fn sequence<I: IntoIterator<Item = Expression>>(expressions: I) -> Sequence {
let expressions: Vec<Expression> = expressions.into_iter().collect();
let current: Arc<Mutex<Option<Arc<Handle>>>> = Arc::new(Mutex::new(None));
let killed = Arc::new(AtomicBool::new(false));
let worker_current = Arc::clone(&current);
let worker_killed = Arc::clone(&killed);
let worker = std::thread::spawn(move || {
for expr in expressions {
if worker_killed.load(Ordering::SeqCst) {
return;
}
let handle = match expr.start() {
Ok(h) => Arc::new(h),
Err(e) => {
eprintln!("sequence: failed to start step: {e}");
return;
}
};
{
let mut slot = worker_current.lock().unwrap();
if worker_killed.load(Ordering::SeqCst) {
let _ = handle.kill();
return;
}
*slot = Some(Arc::clone(&handle));
}
let result = handle.wait().map(|_| ());
worker_current.lock().unwrap().take();
if worker_killed.load(Ordering::SeqCst) {
return;
}
if let Err(e) = result {
eprintln!("sequence: step failed: {e}");
return;
}
}
});
Sequence {
current,
killed,
worker: Some(worker),
}
}
pub struct Sequence {
current: Arc<Mutex<Option<Arc<Handle>>>>,
killed: Arc<AtomicBool>,
worker: Option<JoinHandle<()>>,
}
impl Sequence {
pub fn kill(&self) {
let slot = self.current.lock().unwrap();
self.killed.store(true, Ordering::SeqCst);
if let Some(handle) = slot.as_ref() {
let _ = handle.kill();
}
}
pub fn wait(&mut self) {
if let Some(w) = self.worker.take() {
let _ = w.join();
}
}
}
impl Drop for Sequence {
fn drop(&mut self) {
self.kill();
self.wait();
}
}
pub fn supervise<I, S>(children: I) -> Result<(), Error>
where
I: IntoIterator<Item = (S, TerminalColor, Expression)>,
S: Into<String>,
{
use std::io::{BufRead, BufReader, IsTerminal, Write};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
#[cfg(target_os = "windows")]
windows_ctrl_c::install();
let mut handles: Vec<(String, TerminalColor, Arc<ReaderHandle>)> = Vec::new();
for (label, color, expr) in children {
#[cfg(target_os = "windows")]
let expr = expr.before_spawn(|cmd| {
use std::os::windows::process::CommandExt;
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
cmd.creation_flags(CREATE_NEW_PROCESS_GROUP);
Ok(())
});
let handle = expr.stderr_to_stdout().reader().map_err(Error::Command)?;
handles.push((label.into(), color, Arc::new(handle)));
}
let mut io_threads = Vec::new();
for (label, color, handle) in handles.iter() {
let prefix = if std::io::stdout().is_terminal() {
format!("{color}[{label}]{reset} ", color = color.as_str(), reset = TerminalColor::Reset.as_str())
} else {
format!("[{label}] ")
};
let handle = handle.clone();
io_threads.push(thread::spawn(move || {
let reader = BufReader::new(&*handle);
for line in reader.lines().map_while(Result::ok) {
let out = std::io::stdout();
let mut out = out.lock();
let _ = writeln!(out, "{prefix}{line}");
}
}));
}
let mut reason: Option<(String, std::process::ExitStatus)> = None;
loop {
#[cfg(target_os = "windows")]
if windows_ctrl_c::interrupted() {
break;
}
for (label, _color, handle) in handles.iter() {
if let Ok(Some(output)) = handle.try_wait() {
reason = Some((label.clone(), output.status));
break;
}
}
if reason.is_some() {
break;
}
thread::sleep(Duration::from_millis(200));
}
for (_, _color, handle) in handles.iter() {
if matches!(handle.try_wait(), Ok(Some(_))) {
continue;
}
#[cfg(target_os = "windows")]
{
for pid in handle.pids() {
let _ = std::process::Command::new("taskkill")
.args(["/T", "/F", "/PID", &pid.to_string()])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status();
}
}
#[cfg(not(target_os = "windows"))]
{
let _ = handle.kill();
}
}
for t in io_threads {
let _ = t.join();
}
match reason {
Some((label, status)) if !status.success() => Err(Error::Command(std::io::Error::other(format!("supervised child '{label}' exited with status {status}")))),
_ => Ok(()),
}
}
pub mod utils {
use super::*;
pub fn internal(name: &str) -> Expression {
let package = format!("cargo-run-internal-{name}");
cmd!("cargo", "run", "-p", package, "--")
}
pub fn npm<I, S>(args: I) -> Expression
where
I: IntoIterator<Item = S>,
S: Into<OsString>,
{
let prog = if cfg!(target_os = "windows") { "npm.cmd" } else { "npm" };
cmd(prog, args)
}
pub fn node_bin(rel: &str) -> Expression {
cmd!("node", format!("node_modules/{rel}"))
}
pub fn open_url(url: &str) -> Result<(), Error> {
#[cfg(target_os = "windows")]
let expr = cmd!("cmd", "/c", "start", url);
#[cfg(target_os = "macos")]
let expr = cmd!("open", url);
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
let expr = cmd!("xdg-open", url);
expr.run()
}
}
#[cfg(target_os = "windows")]
mod windows_ctrl_c {
use std::sync::Once;
use std::sync::atomic::{AtomicBool, Ordering};
static INTERRUPTED: AtomicBool = AtomicBool::new(false);
#[link(name = "kernel32")]
unsafe extern "system" {
fn SetConsoleCtrlHandler(handler: Option<unsafe extern "system" fn(u32) -> i32>, add: i32) -> i32;
}
unsafe extern "system" fn handler(_ctrl_type: u32) -> i32 {
INTERRUPTED.store(true, Ordering::SeqCst);
1 // Report the event as handled
}
pub fn install() {
INTERRUPTED.store(false, Ordering::SeqCst);
static REGISTER: Once = Once::new();
REGISTER.call_once(|| unsafe {
SetConsoleCtrlHandler(Some(handler), 1);
});
}
pub fn interrupted() -> bool {
INTERRUPTED.load(Ordering::SeqCst)
}
}
+87
View File
@@ -0,0 +1,87 @@
use crate::cmd::prelude::*;
use crate::*;
use std::path::PathBuf;
const WRAPPER_CRATE: &str = "graphite-wasm-wrapper";
const WASM_TARGET: &str = "wasm32-unknown-unknown";
const OUT_NAME: &str = "graphite_wasm_wrapper";
pub fn frontend_dir() -> PathBuf {
workspace_dir().join("frontend")
}
pub fn setup() -> Result<(), Error> {
let frontend = frontend_dir();
let node_modules = frontend.join("node_modules");
let timestamp_path = node_modules.join(".install-timestamp");
let mtime = |p: PathBuf| std::fs::metadata(p).and_then(|m| m.modified()).ok();
if let Some(install_time) = mtime(timestamp_path.clone())
&& let Some(package_json_time) = mtime(frontend.join("package.json"))
&& let Some(package_lock_json_time) = mtime(frontend.join("package-lock.json"))
&& install_time >= package_json_time
&& install_time >= package_lock_json_time
{
return Ok(());
}
eprintln!("Installing npm packages...");
let install = || utils::npm(["ci", "--include=dev", "--prefer-offline", "--no-audit", "--no-fund"]).dir(&frontend).run();
if install().is_err() {
eprintln!("Failed to install npm packages. Wiping `frontend/node_modules` and retrying...");
let _ = std::fs::remove_dir_all(&node_modules);
install()?;
}
std::fs::write(&timestamp_path, "").map_err(|e| Error::Io(e, format!("writing '{}'", timestamp_path.display())))?;
eprintln!("Finished installing npm packages.");
Ok(())
}
pub fn build_wasm(release: bool, native: bool) -> Result<(), Error> {
sequence(build_wasm_steps(release, native)).wait();
Ok(())
}
pub fn build_wasm_steps(release: bool, native: bool) -> Vec<Expression> {
let wasm_artifact = target_dir().join(WASM_TARGET).join(if release { "release" } else { "debug" }).join(format!("{OUT_NAME}.wasm"));
let pkg_dir = frontend_dir().join("wrapper").join("pkg");
let mut steps = vec![
cmd!("cargo", "build", "--lib", "--package", WRAPPER_CRATE, "--target", WASM_TARGET)
.arg_if(release, "--release")
.args_if(native, ["--no-default-features", "--features", "native"])
.dir(workspace_dir()),
cmd!("wasm-bindgen", "--target", "web", "--out-name", OUT_NAME, "--out-dir", &pkg_dir, &wasm_artifact)
.arg_if(release, "--no-demangle")
.arg_if(!release, "--debug"),
];
if release {
let wasm_file = pkg_dir.join(format!("{OUT_NAME}_bg.wasm"));
steps.push(cmd!("wasm-opt", "-Os", "-g", &wasm_file, "-o", &wasm_file));
}
steps
}
pub fn vite() -> Expression {
utils::node_bin("vite/bin/vite.js").dir(frontend_dir()).env("CARGO_TARGET_DIR", target_dir())
}
pub fn watch(release: bool) -> Result<(), Error> {
use crate::cmd::prelude::*;
setup()?;
build_wasm(release, false)?;
let vite = vite().env("FORCE_COLOR", "1").env("CARGO_TERM_COLOR", "always");
let rust = utils::internal("watch")
.arg_if(release, "release")
.dir(workspace_dir())
.env("CARGO_TARGET_DIR", target_dir())
.env("CARGO_TERM_COLOR", "always");
supervise([("VITE", TerminalColor::Magenta, vite), ("RUST", TerminalColor::Blue, rust)])
}
+20 -55
View File
@@ -1,6 +1,8 @@
use std::path::PathBuf;
use std::process;
pub mod branding;
pub mod cmd;
pub mod frontend;
pub mod requirements;
pub enum Action {
@@ -65,70 +67,33 @@ impl Task {
}
}
pub fn run(command: &str) -> Result<(), Error> {
run_from(command, None)
pub fn workspace_dir() -> PathBuf {
PathBuf::from(env!("CARGO_WORKSPACE_DIR"))
}
pub fn npm_run_in_frontend_dir(args: &str) -> Result<(), Error> {
let workspace_dir = std::path::PathBuf::from(env!("CARGO_WORKSPACE_DIR"));
let frontend_dir = workspace_dir.join("frontend");
let npm = if cfg!(target_os = "windows") { "npm.cmd" } else { "npm" };
run_from(&format!("{npm} run {args}"), Some(&frontend_dir))
pub fn target_dir() -> PathBuf {
match std::env::var_os("CARGO_TARGET_DIR") {
Some(custom_dir) => workspace_dir().join(custom_dir),
None => workspace_dir().join("target"),
}
}
pub fn open_url(url: &str) -> Result<(), Error> {
#[cfg(target_os = "windows")]
let mut cmd = process::Command::new("cmd");
#[cfg(target_os = "windows")]
cmd.args(["/c", "start", url]);
#[cfg(target_os = "macos")]
let mut cmd = process::Command::new("open");
#[cfg(target_os = "macos")]
cmd.arg(url);
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
let mut cmd = process::Command::new("xdg-open");
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
cmd.arg(url);
let command_str = format!("{:?}", cmd);
let exit_code = cmd
.spawn()
.map_err(|e| Error::Io(e, format!("Failed to spawn command '{command_str}'")))?
.wait()
.map_err(|e| Error::Io(e, format!("Failed to wait for command '{command_str}'")))?;
if !exit_code.success() {
return Err(Error::Command(command_str, exit_code));
}
Ok(())
pub fn install_dir() -> PathBuf {
target_dir().join("cargo-run")
}
fn run_from(command: &str, dir: Option<&PathBuf>) -> Result<(), Error> {
let command = command.split_whitespace().collect::<Vec<_>>();
let mut cmd = process::Command::new(command[0]);
if command.len() > 1 {
cmd.args(&command[1..]);
}
if let Some(dir) = dir {
cmd.current_dir(dir);
}
let exit_code = cmd
.spawn()
.map_err(|e| Error::Io(e, format!("Failed to spawn command '{}'", command.join(" "))))?
.wait()
.map_err(|e| Error::Io(e, format!("Failed to wait for command '{}'", command.join(" "))))?;
if !exit_code.success() {
return Err(Error::Command(command.join(" "), exit_code));
}
Ok(())
pub fn bin_dir() -> PathBuf {
install_dir().join("bin")
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("One or more requirements were not met")]
RequirementsNotMet,
#[error("{1}: {0}")]
Io(#[source] std::io::Error, String),
#[error("Command '{0}' exited with code {1}")]
Command(String, process::ExitStatus),
/// Used by the duct-based `cmd` module; folds in `Command` once call sites are migrated.
#[error("{0}")]
Command(#[source] std::io::Error),
}
+46 -24
View File
@@ -1,5 +1,6 @@
use std::process::ExitCode;
use cargo_run::cmd::prelude::*;
use cargo_run::*;
fn usage() {
@@ -33,6 +34,8 @@ fn usage() {
}
fn main() -> ExitCode {
prepend_path();
let args: Vec<String> = std::env::args().collect();
let args: Vec<&str> = args.iter().skip(1).map(String::as_str).collect();
@@ -67,9 +70,9 @@ fn explore_usage() {
fn run_task(task: &Task) -> Result<(), Error> {
if let Action::Explore(tool) = &task.action {
match tool.as_deref() {
Some("bisect") => return open_url("https://graphite.art/volunteer/guide/codebase-overview/debugging-tips/#build-bisect-tool"),
Some("deps") => return open_url("https://graphite.art/volunteer/guide/codebase-overview/#crate-dependency-graph"),
Some("editor") => return open_url("https://graphite.art/volunteer/guide/codebase-overview/editor-structure/#editor-outline"),
Some("bisect") => return utils::open_url("https://graphite.art/volunteer/guide/codebase-overview/debugging-tips/#build-bisect-tool"),
Some("deps") => return utils::open_url("https://graphite.art/volunteer/guide/codebase-overview/#crate-dependency-graph"),
Some("editor") => return utils::open_url("https://graphite.art/volunteer/guide/codebase-overview/editor-structure/#editor-outline"),
None | Some("--help") => {
explore_usage();
return Ok(());
@@ -84,12 +87,24 @@ fn run_task(task: &Task) -> Result<(), Error> {
requirements::check(task)?;
match (&task.action, &task.target, &task.profile) {
(Action::Run, Target::Web, Profile::Debug | Profile::Default) => npm_run_in_frontend_dir("start")?,
(Action::Run, Target::Web, Profile::Release) => npm_run_in_frontend_dir("production")?,
if !matches!(task.target, Target::Cli) {
branding::setup()?;
}
(Action::Build, Target::Web, Profile::Debug) => npm_run_in_frontend_dir("build-dev")?,
(Action::Build, Target::Web, Profile::Release | Profile::Default) => npm_run_in_frontend_dir("build")?,
match (&task.action, &task.target, &task.profile) {
(Action::Run, Target::Web, Profile::Debug | Profile::Default) => frontend::watch(false)?,
(Action::Run, Target::Web, Profile::Release) => frontend::watch(true)?,
(Action::Build, Target::Web, Profile::Debug) => {
frontend::setup()?;
frontend::build_wasm(false, false)?;
frontend::vite().args(["build", "--mode", "dev"]).run()?;
}
(Action::Build, Target::Web, Profile::Release | Profile::Default) => {
frontend::setup()?;
frontend::build_wasm(true, false)?;
frontend::vite().args(["build"]).run()?;
}
(action, Target::Desktop, mut profile) => {
if matches!(profile, Profile::Default) {
@@ -100,34 +115,41 @@ fn run_task(task: &Task) -> Result<(), Error> {
}
}
if matches!(profile, Profile::Release) {
npm_run_in_frontend_dir("build-native")?;
} else {
npm_run_in_frontend_dir("build-native-dev")?;
};
// Build the editor's Wasm module with the `native` feature, then bundle the frontend with Vite
frontend::setup()?;
frontend::build_wasm(matches!(profile, Profile::Release), true)?;
frontend::vite().args(["build", "--mode", "native"]).run()?;
run("cargo run -p third-party-licenses --features desktop")?;
cmd!("cargo", "run", "-p", "third-party-licenses", "--features", "desktop").run()?;
let cargo_profile = match profile {
Profile::Debug => "dev",
Profile::Release => "release",
Profile::Default => unreachable!(),
};
let args = if matches!(action, Action::Run) {
format!(" -- open {}", task.args.join(" "))
} else {
"".to_string()
};
run(&format!("cargo run --profile {cargo_profile} -p graphite-desktop-bundle{args}"))?;
cmd!("cargo", "run", "--profile", cargo_profile, "-p", "graphite-desktop-bundle")
.args_if(matches!(action, Action::Run), ["--", "open"].into_iter().chain(task.args.iter().map(String::as_str)))
.run()?;
}
(Action::Run, Target::Cli, Profile::Debug | Profile::Default) => run(&format!("cargo run -p graphene-cli -- {}", task.args.join(" ")))?,
(Action::Run, Target::Cli, Profile::Release) => run(&format!("cargo run -r -p graphene-cli -- {}", task.args.join(" ")))?,
(Action::Run, Target::Cli, Profile::Debug | Profile::Default) => cmd!("cargo", "run", "-p", "graphene-cli", "--").args(&task.args).run()?,
(Action::Run, Target::Cli, Profile::Release) => cmd!("cargo", "run", "-r", "-p", "graphene-cli", "--").args(&task.args).run()?,
(Action::Build, Target::Cli, Profile::Debug) => run("cargo build -p graphene-cli")?,
(Action::Build, Target::Cli, Profile::Release | Profile::Default) => run("cargo build -r -p graphene-cli")?,
(Action::Build, Target::Cli, Profile::Debug) => cmd!("cargo", "build", "-p", "graphene-cli").run()?,
(Action::Build, Target::Cli, Profile::Release | Profile::Default) => cmd!("cargo", "build", "-r", "-p", "graphene-cli").run()?,
(Action::Explore(_), _, _) => unreachable!(),
}
Ok(())
}
fn prepend_path() {
let mut paths = vec![bin_dir()];
if let Some(path) = std::env::var_os("PATH") {
paths.extend(std::env::split_paths(&path));
}
if let Ok(joined) = std::env::join_paths(paths) {
// Safety: this runs before any other threads are spawned
unsafe { std::env::set_var("PATH", joined) };
}
}
+205 -75
View File
@@ -1,15 +1,19 @@
use semver::{Version, VersionReq};
use std::io::IsTerminal;
use std::process::Command;
use crate::cmd::prelude::*;
use crate::*;
mod wasm_opt;
#[derive(Default, Clone)]
struct Requirement {
pub struct Requirement {
command: &'static str,
args: &'static [&'static str],
name: &'static str,
check: Check,
version: Option<&'static str>,
install: Option<&'static str>,
install: InstallAction,
skip: Option<&'static dyn Fn(&Task) -> bool>,
}
@@ -22,43 +26,44 @@ fn requirements(task: &Task) -> Vec<Requirement> {
..Default::default()
},
Requirement {
command: "cargo-about",
args: &["--version"],
name: "cargo-about",
install: Some("cargo install cargo-about"),
command: "rustc",
args: &["--print", "target-libdir", "--target", "wasm32-unknown-unknown"],
check: Check::Matches(&|out| std::path::Path::new(out.trim()).is_dir()),
name: "Rust - Wasm Target",
install: "rustup target add wasm32-unknown-unknown".into(),
skip: Some(&|task| matches!(task.target, Target::Cli)),
..Default::default()
},
Requirement {
command: "cargo-watch",
command: "wasm-opt",
args: &["--version"],
name: "cargo-watch",
install: Some("cargo install cargo-watch"),
name: "Wasm Opt",
version: Some(">=130"),
install: wasm_opt::install_action(),
skip: Some(&|task| {
!matches!(
task,
Task {
target: Target::Web,
action: Action::Run,
..
matches!(task.target, Target::Cli)
|| match task.profile {
Profile::Debug => true,
Profile::Release => false,
Profile::Default => matches!(task.action, Action::Run),
}
)
}),
..Default::default()
},
Requirement {
command: "wasm-bindgen",
args: &["--version"],
name: "wasm-bindgen-cli",
version: Some("0.2.121"),
install: Some("cargo install -f [email protected]"),
name: "Wasm Bindgen",
version: Some("=0.2.121"),
install: "cargo install -f [email protected]".into(),
skip: Some(&|task| matches!(task.target, Target::Cli)),
..Default::default()
},
Requirement {
command: "wasm-pack",
command: "cargo-about",
args: &["--version"],
name: "wasm-pack",
install: Some("cargo install wasm-pack"),
name: "Cargo About",
install: "cargo install cargo-about".into(),
skip: Some(&|task| matches!(task.target, Target::Cli)),
..Default::default()
},
@@ -73,6 +78,7 @@ fn requirements(task: &Task) -> Vec<Requirement> {
command: "cmake",
args: &["--version"],
name: "CMake",
install: InstallAction::ManualInstructions("https://cmake.org/download/ or find it in your system's package manager"),
skip: Some(&|task| !matches!(task.target, Target::Desktop) || cfg!(target_os = "linux")),
..Default::default()
},
@@ -80,6 +86,7 @@ fn requirements(task: &Task) -> Vec<Requirement> {
command: "ninja",
args: &["--version"],
name: "Ninja",
install: InstallAction::ManualInstructions("https://github.com/ninja-build/ninja/releases or find it in your system's package manager"),
skip: Some(&|task| !matches!(task.target, Target::Desktop) || cfg!(target_os = "linux")),
..Default::default()
},
@@ -95,44 +102,66 @@ pub fn check(task: &Task) -> Result<(), Error> {
eprintln!("Checking Requirements:");
let mut installable: Vec<Requirement> = Vec::new();
let mut failures: Vec<String> = Vec::new();
let mut manual: Vec<(Requirement, String)> = Vec::new();
for dep in requirements(task) {
match Command::new(dep.command).args(dep.args).output() {
match cmd(dep.command, dep.args.iter().copied()).output_unchecked() {
Ok(output) if output.status.success() => {
let version = String::from_utf8_lossy(&output.stdout);
let version = version.lines().next().unwrap_or_default().trim();
if let Some(expected) = dep.version {
if version.contains(expected) {
eprintln!(" ✓ {} ({})", dep.name, version);
} else {
eprintln!(" ✗ {} (found {}, expected {})", dep.name, version, expected);
if dep.install.is_some() {
installable.push(dep);
let stdout = String::from_utf8_lossy(&output.stdout);
match dep.check {
Check::PrintsVersion => {
let line = stdout.lines().next().unwrap_or_default().trim();
match dep.version {
None => eprintln!(" ✓ {} ({line})", dep.name),
Some(req_str) => {
let req = VersionReq::parse(req_str).expect("invalid semver requirement");
match extract_version(line) {
Some(version) if req.matches(&version) => eprintln!(" ✓ {} ({version})", dep.name),
Some(version) => {
eprintln!(" ✗ {} (found {version}, requires {req_str})", dep.name);
if dep.install.is_auto_installable() {
installable.push(dep);
} else {
manual.push((dep, format!("version mismatch (found {version}, requires {req_str})")));
}
}
None => {
eprintln!(" ✗ {} (could not parse version from '{line}')", dep.name);
manual.push((dep, format!("could not parse version from '{line}'")));
}
}
}
}
}
Check::Matches(check) => {
if !check(stdout.to_string()) {
eprintln!(" ✗ {} - check failed", dep.name);
if dep.install.is_auto_installable() {
installable.push(dep);
} else {
manual.push((dep, "check failed".into()));
}
} else {
failures.push(format!("{}: version mismatch (found {version}, expected {expected})", dep.name));
eprintln!(" ✓ {}", dep.name);
}
}
} else {
eprintln!(" ✓ {} ({})", dep.name, version);
}
}
Ok(output) => {
let stderr = String::from_utf8_lossy(&output.stderr);
eprintln!(" ✗ {} - command failed: {}", dep.name, stderr.trim());
if dep.install.is_some() {
if dep.install.is_auto_installable() {
installable.push(dep);
} else {
failures.push(format!("{}: not installed or not working", dep.name));
manual.push((dep.clone(), format!("`{}` not installed or not working", dep.command)));
}
}
Err(_) => {
eprintln!(" ✗ {} - not found", dep.name);
if dep.install.is_some() {
if dep.install.is_auto_installable() {
installable.push(dep);
} else {
failures.push(format!("{}: not found in PATH", dep.name));
manual.push((dep.clone(), format!("`{}` not found in PATH", dep.command)));
}
}
}
@@ -140,61 +169,162 @@ pub fn check(task: &Task) -> Result<(), Error> {
eprintln!();
if installable.is_empty() && failures.is_empty() {
if installable.is_empty() && manual.is_empty() {
return Ok(());
}
let total = installable.len() + failures.len();
let total = installable.len() + manual.len();
eprintln!("{total} requirement{} not met:", if total > 1 { "s" } else { "" });
for dep in &installable {
eprintln!(" - {}: {}", dep.name, dep.install.unwrap());
eprintln!(" - {}", dep.name);
}
for msg in &failures {
eprintln!(" - {msg}");
for (dep, msg) in &manual {
eprintln!(" - {}: {msg}", dep.name);
}
if !failures.is_empty() {
if !manual.is_empty() {
eprintln!();
eprintln!("See: https://graphite.art/volunteer/guide/project-setup/");
}
let is_interactive = std::io::stdout().is_terminal() && std::io::stderr().is_terminal() && std::io::stdin().is_terminal();
// Don't prompt for automatic installation if we're not interactive session
if !std::io::stdout().is_terminal() || !std::io::stderr().is_terminal() || !std::io::stdin().is_terminal() {
if !is_interactive {
return Ok(());
}
if installable.is_empty() {
if installable.is_empty() && manual.is_empty() {
return Ok(());
}
eprintln!();
eprintln!("The following can be installed automatically:");
for dep in &installable {
eprintln!(" {}", dep.install.unwrap());
}
eprintln!();
if installable.len() == 1 {
eprint!("Install it now? [Y/n] ");
} else {
eprint!("Install them now? [Y/n] ");
}
let mut input = String::new();
std::io::stdin().read_line(&mut input).map_err(|e| Error::Io(e, "Failed to read from stdin".into()))?;
let input = input.trim();
if input.is_empty() || input.eq_ignore_ascii_case("y") || input.eq_ignore_ascii_case("yes") {
if !installable.is_empty() {
eprintln!();
eprintln!("The following can be installed automatically:");
for dep in &installable {
let parts: Vec<&str> = dep.install.unwrap().split_whitespace().collect();
eprintln!("Running: {}...", dep.install.unwrap());
let status = Command::new(parts[0])
.args(&parts[1..])
.status()
.map_err(|e| Error::Io(e, format!("Failed to run '{}'", dep.install.unwrap())))?;
if !status.success() {
eprintln!("Failed to install {}", dep.name);
match &dep.install {
InstallAction::Command(cmd) => eprintln!(" - {}: {}", dep.name, cmd),
InstallAction::Expression { description, .. } => eprintln!(" - {description}"),
InstallAction::None | InstallAction::ManualInstructions(_) => unreachable!(),
}
}
eprintln!();
if installable.len() == 1 {
eprint!("Install it now? [y/N] ");
} else {
eprint!("Install them now? [y/N] ");
}
let mut input = String::new();
std::io::stdin().read_line(&mut input).map_err(|e| Error::Io(e, "Failed to read from stdin".into()))?;
let input = input.trim();
if input.eq_ignore_ascii_case("y") || input.eq_ignore_ascii_case("yes") {
for dep in installable.into_iter() {
eprintln!("Installing {}...", dep.name);
match &dep.install {
InstallAction::Command(install_cmd) => {
let parts: Vec<&str> = install_cmd.split_whitespace().collect();
let expr = cmd(parts[0], parts[1..].iter().copied()).unchecked();
match Expression::run(&expr) {
Ok(output) if !output.status.success() => {
let stderr = String::from_utf8_lossy(&output.stderr);
manual.push((dep, format!("installation command failed: {}", stderr.trim())));
}
Err(e) => return Err(Error::Command(e)),
_ => {}
}
}
InstallAction::Expression { expression, .. } => {
if let Err(e) = expression.clone().run() {
eprintln!("{e}");
eprintln!("Failed to install {}", dep.name);
manual.push((dep, format!("failed to install ({e})")));
}
}
InstallAction::None | InstallAction::ManualInstructions(_) => unreachable!(),
}
}
}
}
if !manual.is_empty() {
eprintln!();
eprintln!("Please install the following dependenc{}:", if manual.len() == 1 { "y" } else { "ies" });
for (dep, msg) in &manual {
match dep.install {
InstallAction::ManualInstructions(instructions) => eprintln!(" - {}: {}", dep.name, instructions),
_ => eprintln!(" - {}: {}", dep.name, msg),
}
}
}
if (!manual.is_empty()) && is_interactive {
eprintln!();
eprintln!("Attempt to continue regardless of unmet requirements? [y/N]");
let mut input = String::new();
std::io::stdin().read_line(&mut input).map_err(|e| Error::Io(e, "Failed to read from stdin".into()))?;
let input = input.trim();
if !input.eq_ignore_ascii_case("y") && !input.eq_ignore_ascii_case("yes") {
return Err(Error::RequirementsNotMet);
}
}
Ok(())
}
fn extract_version(line: &str) -> Option<Version> {
line.split_whitespace().find_map(|token| {
let token = token.trim_start_matches('v').trim_end_matches(|c: char| !c.is_ascii_alphanumeric());
if token.is_empty() {
return None;
}
if let Ok(version) = Version::parse(token) {
return Some(version);
}
let (core, suffix) = match token.find(['-', '+']) {
Some(i) => token.split_at(i),
None => (token, ""),
};
let parts: Vec<&str> = core.split('.').collect();
if parts.iter().any(|p| p.is_empty() || !p.chars().all(|c| c.is_ascii_digit())) {
return None;
}
let major = parts[0];
let minor = parts.get(1).copied().unwrap_or("0");
let patch = parts.get(2).copied().unwrap_or("0");
Version::parse(&format!("{major}.{minor}.{patch}{suffix}")).ok()
})
}
#[derive(Clone, Default)]
enum Check {
#[default]
PrintsVersion,
Matches(&'static dyn Fn(String) -> bool),
}
#[derive(Clone, Default)]
enum InstallAction {
#[default]
None,
Command(&'static str),
Expression {
description: String,
expression: Expression,
},
ManualInstructions(&'static str),
}
impl InstallAction {
fn is_auto_installable(&self) -> bool {
!matches!(self, InstallAction::None | InstallAction::ManualInstructions(_))
}
}
impl From<&'static str> for InstallAction {
fn from(value: &'static str) -> Self {
InstallAction::Command(value)
}
}
@@ -0,0 +1,46 @@
use super::InstallAction;
use crate::cmd::prelude::*;
use crate::{install_dir, workspace_dir};
/// Pinned Binaryen release used by [`install_action`].
/// NOTICE: keep in sync with the `BINARYEN_VERSION` pinned across the CI workflows, and update [`SHA256`] below.
const VERSION: &str = "130";
const SHA256: &[(&str, &str)] = &[
("x86_64-windows", "cc09c874f4332d00aa32ab72745a9b98c9a172f795762f21d03e70638a3f7f4c"),
("arm64-windows", "b18c9cbe000562b1ee5d9cb60146616a949aca504903ad63f27fd9fd679898a7"),
("arm64-macos", "79d3ab9f417d9e215f15f598f523d001a7d9ac1e59367e5c869fbdabd1cba72e"),
("x86_64-macos", "d3e2d1235b70c93c54b52eabc1625ea960965152218754f1f4eeb0f873c48e03"),
("x86_64-linux", "0a18362361ad05465118cd8eeb72edaeec89de6894bc283576ef4e07aa3babcc"),
("aarch64-linux", "e6ae6e09ac40f4e14bc5be6f687c58e2995c84170013975fa641809dd3b480a0"),
];
fn url_for(platform: &str) -> String {
format!("https://github.com/WebAssembly/binaryen/releases/download/version_{VERSION}/binaryen-version_{VERSION}-{platform}.tar.gz")
}
pub fn install_action() -> InstallAction {
let platform = match (std::env::consts::OS, std::env::consts::ARCH) {
("windows", "x86_64") => "x86_64-windows",
("windows", "aarch64") => "arm64-windows",
("macos", "aarch64") => "arm64-macos",
("macos", "x86_64") => "x86_64-macos",
("linux", "x86_64") => "x86_64-linux",
("linux", "aarch64") => "aarch64-linux",
_ => return InstallAction::None,
};
let url = url_for(platform);
let Some(sha256) = SHA256.iter().find_map(|(p, s)| (*p == platform).then_some(*s)) else {
return InstallAction::None;
};
let out = install_dir().to_string_lossy().into_owned();
let description = format!("Download wasm-opt {VERSION} from {url} (sha256 {sha256})");
let args = [&url, sha256, &out, "--extract", "--strip", "1", "--include", "bin/wasm-opt"];
#[cfg(target_os = "macos")]
let args = args.into_iter().chain(["--include", "lib/libbinaryen.dylib"]).collect::<Vec<_>>();
let expression = utils::internal("download").args(args).dir(workspace_dir());
InstallAction::Expression { description, expression }
}
+1 -1
View File
@@ -86,7 +86,7 @@ fn parse(parsed: Output) -> Vec<LicenseEntry> {
fn run() -> Result<Output, Error> {
let output = Command::new("cargo")
.args(["about", "generate", "--format", "json", "--frozen"])
.args(["about", "generate", "--format", "json", "--locked"])
.current_dir(env!("CARGO_WORKSPACE_DIR"))
.output()
.map_err(|e| Error::Io(e, "Failed to run cargo about generate".into()))?;
+1 -2
View File
@@ -98,10 +98,9 @@ fn run() -> Result<(), Error> {
let current_hash = format!("{:016x}", hasher.finish());
if current_hash == fs::read_to_string(&current_hash_path).unwrap_or_default() {
eprintln!("No changes in licenses detected, skipping generation.");
return Ok(());
}
eprintln!("Changes in licenses detected, generating new license file.");
eprintln!("Changes in licenses detected, generating new license file...");
let licenses = merge_filter_dedup_and_sort(vec![
cargo_source.licenses()?,