Compare commits

..
Author SHA1 Message Date
Timon 0cfe3cd053 Fix 2026-07-05 18:24:58 +00:00
YohYamasakiandKeavon Chambers 6a54dcb5da Remove the legacy Fill, Gradient, and PathStyle types now that paints live in attributes (#4297)
* Remove `Stroke.color`

* Remove legacy Gradient struct usage

* Fix gradient tool tests

* Remove `Fill` enum

* Fix direction of `gradient_orientation_rightward`

* Remove `Gradient` struct

* Remove `PathStyle` struct

* Fix old `VectorData` migration

* Refactor

- Remove unnecessary wrapper functions
- Use `as_ref` instead of `clone` for stroke if possible
- Comment cleanup

* Clean up stale style comments and bindings left by the paint attribute migration

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-07-04 23:08:06 -07:00
YohYamasakiandKeavon Chambers 9f9899cfd0 Refactor the 'Fill' and 'Stroke' nodes to set "fill" and "stroke" attributes for paints (#4257)
* Allow using any graphics type for fill

* Adapt gradient/fill property panels and tools to handle List<T>

* Make the initial gradient transform covers the target's bounding box

* Introduce AnyGraphicListDyn to avoid combinatorial explosion

* Allow using any graphics type for stroke paint

* Add FIll node migration

* Add `for_each_vector_list_mut` instead of `set_paint_attribute`

* Adapt paint flow to read and write attributes instead of legacy Fill/Stroke.color

* Fix responsibilities of paint related node input setters

* Fix Morph by storing List<Graphic> for attributes rather than the concrete types

Store fill/stroke paints as List<Graphic> so Color/Gradient transitions
do not hit set_attribute_value_dyn's type-mismatch fallback to default paint.

* Preserve paint attributes in vector editing ops

* Enhance the clarity between direct and chained fill gradients

* Update demo arts

* Consolidate Fill node gradient appearance inputs

* Fix after the cubic review

* Revert "Consolidate Fill node gradient appearance inputs"

This reverts commit 9622feb20196e2c4da99e98ca95dcc2e34c2c98e.

* Replace AnyGraphicListDyn with generic paint connectors on the Fill and Stroke nodes

* Canonicalize paint attribute storage to List<Graphic> with a single write helper

* Fix Solidify Stroke missing fills stored in the legacy style

* Fix Solidify Stroke producing invisible strokes for legacy-only stroke colors

* Fix the initial gradient transform ignoring the bounding box's vertical extent

* Step paint at the morph midpoint instead of dropping it for unmixable pairings

* Remove migration-stage comments

* Clarify the initial gradient transform helper's doc and name

* Correct the bake_paint_transforms doc and prune dead tolerance arms

* Delete the unused Gradient::lerp

* Fix a comment typo

* Thread network paths through the legacy gradient bake so nested fills migrate

* Restore the legacy fill fallback in Expand Fill and Stroke

* Read gradient stops from the node's own input in the Fill properties panel

* Use the transform input constant instead of a hardcoded index

* Remove the unreachable wired color fallback in the Fill properties solid branch

* Narrow the fill overlay redraw check to actual fill inputs

* Coalesce the fill setter's graph runs into a single dispatch

* Position the Gradient Value node inserted for gradient stops

* Bake backup gradient placement during migration

* Persist pending gradient bakes so unfinished migrations retry on reopen

* Migrate the backup gradient's type and spread method

* Harden the gradient-migration pass against document switches and stale bakes

* Keep the Fill properties UI for layerless and nested Fill nodes

* Leave a wired gradient transform input connected instead of overwriting it

* Refuse to start a gradient chain ahead of existing layer content

* Decode a Fill node's gradient through one shared reader

* Nudge a degenerate bounding box so the Fill gradient transform stays invertible

* Broadcast Fill and Stroke paint with a single attribute-column pass

* Fix Morph stepping the target's stroke in near the source instead of the target

* Tidy conventions: clippy get_first, comment periods, sentence-case test messages

* Reattach the gradient orientation doc to its function

* Re-save demo artwork

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-07-04 23:08:21 +00:00
Keavon Chambers f82b0a8fca Switch production builds from -Os to -Oz to avoid 25 MB deployment limit (#4309) 2026-07-04 14:25:38 -07:00
Dennis KobertandTimon 540a4ff273 Integrate document-format storage into the editor (#4265)
* Integrate document-format storage into the editor

* Address review feedback: drop redundant clones and dedupe metadata traversal

* Extract DocumentHistory and move storage-metadata tests to their own file

* Extract storage diffing/IO, gate validation and .gdd save behind preferences, restructure tests

* Address PR review: save-format/path consistency, autosave persistence, and view-settings/diff fixes

* Skip storage remount on .gdd open and split value/timestamp drift in attribute diff

* Rename storage tests module and surface .gdd open failures with per-resource diff detail

* Add debug-menu toggle to hide the storage preferences section

* Hopefully fix async tests

* Shorten comments

* Fix tests

* Review

* Review

* Review

* Block on future mesages in tests

* Review

* Shorten comments

---------

Co-authored-by: Timon <[email protected]>
2026-07-04 19:27:00 +00:00
Timon 294952e152 Desktop: Use dirty rects for UI texture uploads (#4305) 2026-07-04 16:25:16 +00:00
Keavon Chambers f05a644bd9 Revamp the syntax to #[hard(a..b)] and #[soft(a..b)] bounds on node definitions (#4307)
* Revamp the syntax to #[hard(a..b)] and #[soft(a..b)] bounds on node definitions

* Address review feedback: error on empty bounds ranges and remove redundant count clamps

* Fix NaN transform from Repeat Array with a count of 1

* Remove redundant manual clamps already enforced by #[hard(...)] bounds
2026-07-03 18:48:58 -07:00
Keavon Chambers 95c1ab81f3 Prep for the RC6 release of the desktop app 2026-07-01 04:55:57 -07:00
Keavon Chambers 7ae7bda3d3 Add persistence to the collapsed state of Properties panel node sections (#4300)
* Add persistence to the collapsed state of Properties panel node sections

* Improve comments

* Fix generator node handling with #4299
2026-07-01 04:54:39 -07:00
Keavon Chambers 1648e33c1f Implement dragging to reorder Properties panel node sections (#4299)
* Implement dragging to reorder Properties panel node sections

* Code review
2026-07-01 03:39:52 -07:00
TimonandKeavon Chambers 8a38af5be7 Rework clipboard handling to carry embedded resources across documents (#4296)
* Move clipboard code to its dedicated handler

* Adapt clipboard format to work with resources

* Restore visibility, lock, and collapse state when pasting layers

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-07-01 09:31:55 +00:00
Keavon Chambers 7c870d9426 Fix skewed linear gradient layers ignoring the horizontal shear axis in Vello 2026-06-30 21:48:51 -07:00
TimonandKeavon Chambers 0882637801 Auto-recover from corrupt Wasm builds that emit undefined env imports (#4287)
Co-authored-by: Keavon Chambers <[email protected]>
2026-06-30 22:07:17 +00:00
Timon 9626c047a4 Fix CI builds by pinning cargo-about for Windows and Mac 2026-06-30 21:40:18 +00:00
Keavon Chambers 3e674c939b Revamp the stand-in for embedded YouTube videos on the website 2026-06-30 01:42:40 -07:00
Keavon Chambers 2a3f1a12a8 Fix nondeterministic Vector point IDs from the 'As Vector' node 2026-06-29 23:52:51 -07:00
Timon 6ee0239b96 Desktop: Update CEF to 149 (#4286) 2026-06-29 15:25:30 +00:00
Keavon Chambers 244b25708d Add color picker gradient color stop duplication by holding Alt (#4291)
* Add color picker gradient color stop duplication by holding Alt

* Fix bugs

* Bug fix
2026-06-28 17:34:27 -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
188 changed files with 8017 additions and 5638 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`
+32 -14
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,8 @@ jobs:
env:
WASM_BINDGEN_CLI_VERSION: "0.2.121"
BINARYEN_VERSION: "130"
CARGO_ABOUT_VERSION: "0.9.0"
steps:
- name: 📥 Clone repository
@@ -341,14 +350,16 @@ 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
cargo binstall --no-confirm --force cargo-about
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@$env:CARGO_ABOUT_VERSION"
cargo binstall --no-confirm --force "wasm-bindgen-cli@$env:WASM_BINDGEN_CLI_VERSION"
- name: 🏗 Build Windows bundle
@@ -485,6 +496,8 @@ jobs:
env:
WASM_BINDGEN_CLI_VERSION: "0.2.121"
BINARYEN_VERSION: "130"
CARGO_ABOUT_VERSION: "0.9.0"
steps:
- name: 📥 Clone repository
@@ -529,7 +542,6 @@ jobs:
brew install \
pkg-config \
openssl@3 \
binaryen \
llvm \
cargo-binstall
@@ -537,8 +549,14 @@ 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
cargo binstall --no-confirm --force cargo-about
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_ABOUT_VERSION}"
cargo binstall --no-confirm --force "wasm-bindgen-cli@${WASM_BINDGEN_CLI_VERSION}"
- name: 🏗 Build Mac bundle
-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
+8 -21
View File
@@ -1,26 +1,11 @@
{ pkgs, ... }:
let
version = "147.0.14+g76d2442+chromium-147.0.7727.138";
hashes = {
aarch64-linux = "sha256-Gy2Xs1NHwmIr+buzoqDso1QJVkKlA/UMXytHjNGqpNk=";
x86_64-linux = "sha256-os7wAFJ+mVK65HCikvEjhMeQUj2ty7y+6Ad0OlOcbeA=";
};
version = "149.0.5+g6770623+chromium-149.0.7827.197";
selectSystem =
attrs:
attrs.${pkgs.stdenv.hostPlatform.system}
or (throw "Unsupported system ${pkgs.stdenv.hostPlatform.system}");
src = pkgs.fetchurl {
url = "https://cef-builds.spotifycdn.com/cef_binary_${version}_${
selectSystem {
aarch64-linux = "linuxarm64";
x86_64-linux = "linux64";
}
}_minimal.tar.bz2";
hash = selectSystem hashes;
};
# Local custom CEF build (tarball) instead of the Spotify CDN download.
# Absolute path outside the flake source tree, so this needs `nix develop --impure`.
src = /home/timon/tmp/cef-build/dist/cef_149_7827_x86-64_linux_fixed_buffer_usage.tar.xz;
in
pkgs.cef-binary.overrideAttrs (finalAttrs: {
version = builtins.head (builtins.split "\\+" version);
@@ -33,12 +18,14 @@ pkgs.cef-binary.overrideAttrs (finalAttrs: {
mv ./Resources/* $out/
mv ./include $out/
cat ./CREDITS.html | ${pkgs.xz}/bin/xz -9 -e -c > $out/CREDITS.html.xz
if [ -f ./CREDITS.html ]; then
cat ./CREDITS.html | ${pkgs.xz}/bin/xz -9 -e -c > $out/CREDITS.html.xz
fi
echo '${
builtins.toJSON {
type = "minimal";
name = builtins.baseNameOf finalAttrs.src.url;
name = "cef_binary_${version}_linux64_minimal.tar.xz";
sha1 = "";
}
}' > $out/archive.json
+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
+257 -128
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"
@@ -572,8 +594,8 @@ dependencies = [
[[package]]
name = "cef"
version = "148.1.0+147.0.14"
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite#b36fbe355fdb0cb101295da4554dbb285f2d91f2"
version = "149.2.0+149.0.5"
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite-149#877c9cd8f7776e6c52e365d501ad44c73e17117a"
dependencies = [
"anyhow",
"ash",
@@ -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",
@@ -593,14 +615,14 @@ dependencies = [
"thiserror 2.0.18",
"tracing",
"wgpu",
"windows 0.62.2",
"windows",
"windows-sys 0.61.2",
]
[[package]]
name = "cef-dll-sys"
version = "148.1.0+147.0.14"
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite#b36fbe355fdb0cb101295da4554dbb285f2d91f2"
version = "149.2.0+149.0.5"
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite-149#877c9cd8f7776e6c52e365d501ad44c73e17117a"
dependencies = [
"anyhow",
"cmake",
@@ -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",
]
@@ -1201,7 +1223,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -1213,7 +1235,7 @@ dependencies = [
"bitflags 2.11.0",
"block2 0.6.2",
"libc",
"objc2 0.6.4",
"objc2 0.6.3",
]
[[package]]
@@ -1296,7 +1318,7 @@ checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
[[package]]
name = "download-cef"
version = "2.3.2"
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite#b36fbe355fdb0cb101295da4554dbb285f2d91f2"
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite-149#877c9cd8f7776e6c52e365d501ad44c73e17117a"
dependencies = [
"bzip2",
"clap",
@@ -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"
@@ -1440,7 +1474,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "778e2ac28f6c47af28e4907f13ffd1e1ddbd400980a9abd7c8df189bf578a5ad"
dependencies = [
"libc",
"windows-sys 0.60.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -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"
@@ -1879,7 +1931,7 @@ dependencies = [
"log",
"presser",
"thiserror 2.0.18",
"windows 0.62.2",
"windows",
]
[[package]]
@@ -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",
@@ -2157,7 +2211,7 @@ dependencies = [
"vello",
"wgpu",
"window_clipboard",
"windows 0.58.0",
"windows",
"winit",
]
@@ -2244,6 +2298,7 @@ dependencies = [
"js-sys",
"kurbo",
"log",
"math-parser",
"num_enum",
"once_cell",
"preprocessor",
@@ -2286,7 +2341,6 @@ dependencies = [
"graphite-editor",
"js-sys",
"log",
"math-parser",
"node-macro",
"ron",
"serde",
@@ -2798,6 +2852,26 @@ dependencies = [
"rustversion",
]
[[package]]
name = "inotify"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "533e68a5842e734946fe159fb03fc9bbbb254f590dd0d8ad321ae5ff7beca2c1"
dependencies = [
"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]]
name = "interpreted-executor"
version = "0.1.0"
@@ -2993,6 +3067,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"
@@ -3078,9 +3172,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",
@@ -3258,6 +3352,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",
]
@@ -3285,7 +3380,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",
@@ -3434,6 +3529,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"
@@ -3454,9 +3589,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"
@@ -3528,9 +3663,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",
]
@@ -3559,7 +3694,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",
]
@@ -3585,7 +3720,7 @@ dependencies = [
"bitflags 2.11.0",
"block2 0.6.2",
"dispatch2",
"objc2 0.6.4",
"objc2 0.6.3",
]
[[package]]
@@ -3649,7 +3784,7 @@ dependencies = [
"bitflags 2.11.0",
"block2 0.6.2",
"libc",
"objc2 0.6.4",
"objc2 0.6.3",
"objc2-core-foundation",
]
@@ -3661,7 +3796,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",
]
@@ -3687,7 +3822,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",
@@ -3713,7 +3848,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",
@@ -3726,7 +3861,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",
]
@@ -3808,6 +3943,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.45.0",
]
[[package]]
name = "owned_ttf_parser"
version = "0.25.1"
@@ -4365,7 +4510,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.60.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -4503,7 +4648,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",
@@ -4702,7 +4847,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",
@@ -4841,14 +4986,14 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.60.2",
"windows-sys 0.59.0",
]
[[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",
@@ -4909,7 +5054,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -4920,9 +5065,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",
@@ -5208,12 +5353,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"
@@ -5594,7 +5787,7 @@ dependencies = [
"getrandom 0.3.3",
"once_cell",
"rustix",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -5705,30 +5898,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",
@@ -6787,7 +6980,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",
@@ -6809,7 +7002,7 @@ dependencies = [
"web-sys",
"wgpu-naga-bridge",
"wgpu-types",
"windows 0.62.2",
"windows",
"windows-core 0.62.2",
"windows-result 0.4.1",
]
@@ -6866,7 +7059,7 @@ version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0978bf7171b3d90bac376700cb56d606feb40f251a475a5d6634613564460b22"
dependencies = [
"windows-sys 0.60.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -6889,16 +7082,6 @@ dependencies = [
"thiserror 1.0.69",
]
[[package]]
name = "windows"
version = "0.58.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6"
dependencies = [
"windows-core 0.58.0",
"windows-targets 0.52.6",
]
[[package]]
name = "windows"
version = "0.62.2"
@@ -6920,27 +7103,14 @@ dependencies = [
"windows-core 0.62.2",
]
[[package]]
name = "windows-core"
version = "0.58.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99"
dependencies = [
"windows-implement 0.58.0",
"windows-interface 0.58.0",
"windows-result 0.2.0",
"windows-strings 0.1.0",
"windows-targets 0.52.6",
]
[[package]]
name = "windows-core"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3"
dependencies = [
"windows-implement 0.60.2",
"windows-interface 0.59.3",
"windows-implement",
"windows-interface",
"windows-link 0.1.3",
"windows-result 0.3.4",
"windows-strings 0.4.2",
@@ -6952,8 +7122,8 @@ version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement 0.60.2",
"windows-interface 0.59.3",
"windows-implement",
"windows-interface",
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
@@ -6970,17 +7140,6 @@ dependencies = [
"windows-threading",
]
[[package]]
name = "windows-implement"
version = "0.58.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.106",
]
[[package]]
name = "windows-implement"
version = "0.60.2"
@@ -6992,17 +7151,6 @@ dependencies = [
"syn 2.0.106",
]
[[package]]
name = "windows-interface"
version = "0.58.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.106",
]
[[package]]
name = "windows-interface"
version = "0.59.3"
@@ -7047,15 +7195,6 @@ dependencies = [
"windows-strings 0.4.2",
]
[[package]]
name = "windows-result"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e"
dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-result"
version = "0.3.4"
@@ -7074,16 +7213,6 @@ dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-strings"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10"
dependencies = [
"windows-result 0.2.0",
"windows-targets 0.52.6",
]
[[package]]
name = "windows-strings"
version = "0.4.2"
@@ -7393,7 +7522,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",
@@ -7412,7 +7541,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",
@@ -7460,7 +7589,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",
+8 -7
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",
@@ -213,8 +214,8 @@ gungraun = { version = "0.18" }
ndarray = "0.16"
strum = { version = "0.27", features = ["derive"] }
dirs = "6.0"
cef = "148"
cef-dll-sys = "148"
cef = "149"
cef-dll-sys = "149"
include_dir = "0.7"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tracing = "0.1"
@@ -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 }
@@ -256,5 +257,5 @@ debug = true
# Force cargo to use only one version of the dpi crate (vendoring breaks without this)
dpi = { git = "https://github.com/rust-windowing/winit.git" }
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
cef = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite" }
cef-dll-sys = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite" }
cef = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-149" }
cef-dll-sys = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-149" }
+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":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::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,"contextLine 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":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5],"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_valLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5],"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_valLine 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":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::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::graphiLine 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":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":null},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::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":Line 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":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[31.556350940025634,-2.7755575615628914e-17,2.7755575615628914e-17,31.556350940025634,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::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.0Line 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":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::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":{"StrinLine 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
+1 -1
View File
@@ -55,7 +55,7 @@ window_clipboard = "0.5"
# Windows-specific dependencies
[target.'cfg(target_os = "windows")'.dependencies]
windows = { version = "0.58.0", features = [
windows = { version = "0.62.2", features = [
"Win32_Foundation",
"Win32_Graphics_Dwm",
"Win32_Graphics_Gdi",
+8 -60
View File
@@ -21,9 +21,8 @@ use std::sync::{Arc, Mutex};
use std::time::Instant;
use crate::event::{AppEvent, AppEventScheduler};
use crate::render::FrameBufferRef;
use crate::window::Cursor;
use crate::wrapper::{WgpuContext, deserialize_editor_message};
use crate::wrapper::deserialize_editor_message;
mod consts;
mod context;
@@ -32,17 +31,14 @@ mod internal;
mod ipc;
mod platform;
mod utility;
#[cfg(feature = "accelerated_paint")]
use cef::osr_texture_import::SharedTextureHandle;
mod view;
pub(crate) use context::{CefContext, CefContextBuilder, InitError};
pub(crate) use view::View;
pub(crate) trait CefEventHandler: Send + Sync + 'static {
fn view_info(&self) -> ViewInfo;
fn draw<'a>(&self, frame_buffer: FrameBufferRef<'a>);
#[cfg(feature = "accelerated_paint")]
fn draw_gpu(&self, shared_texture: SharedTextureHandle);
fn draw(&self, view: &View);
fn load_resource(&self, path: PathBuf) -> Option<Resource>;
fn cursor_change(&self, cursor: Cursor);
/// Schedule the main event loop to run the CEF event loop after the timeout.
@@ -120,15 +116,13 @@ impl Read for ResourceReader {
}
pub(crate) struct CefHandler {
wgpu_context: WgpuContext,
app_event_scheduler: AppEventScheduler,
view_info_receiver: Arc<Mutex<ViewInfoReceiver>>,
}
impl CefHandler {
pub(crate) fn new(wgpu_context: WgpuContext, app_event_scheduler: AppEventScheduler, view_info_receiver: Receiver<ViewInfoUpdate>) -> Self {
pub(crate) fn new(app_event_scheduler: AppEventScheduler, view_info_receiver: Receiver<ViewInfoUpdate>) -> Self {
Self {
wgpu_context,
app_event_scheduler,
view_info_receiver: Arc::new(Mutex::new(ViewInfoReceiver::new(view_info_receiver))),
}
@@ -147,55 +141,10 @@ impl CefEventHandler for CefHandler {
}
*view_info
}
fn draw<'a>(&self, frame_buffer: FrameBufferRef<'a>) {
let width = frame_buffer.width() as u32;
let height = frame_buffer.height() as u32;
let texture = self.wgpu_context.device.create_texture(&wgpu::TextureDescriptor {
label: Some("CEF Texture"),
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Bgra8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
self.wgpu_context.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
frame_buffer.buffer(),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(4 * width),
rows_per_image: Some(height),
},
wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
);
self.app_event_scheduler.schedule(AppEvent::UiUpdate(texture));
}
#[cfg(feature = "accelerated_paint")]
fn draw_gpu(&self, shared_texture: SharedTextureHandle) {
match shared_texture.import_texture(&self.wgpu_context.device) {
Ok(texture) => {
self.app_event_scheduler.schedule(AppEvent::UiUpdate(texture));
}
Err(e) => {
tracing::error!("Failed to import shared texture: {}", e);
}
fn draw(&self, view: &View) {
if let Some(texture) = view.texture() {
self.app_event_scheduler.schedule(AppEvent::UiUpdate(texture));
}
}
@@ -279,7 +228,6 @@ impl CefEventHandler for CefHandler {
Self: Sized,
{
Self {
wgpu_context: self.wgpu_context.clone(),
app_event_scheduler: self.app_event_scheduler.clone(),
view_info_receiver: self.view_info_receiver.clone(),
}
+7 -6
View File
@@ -13,6 +13,7 @@ use crate::cef::consts::{RESOURCE_DOMAIN, RESOURCE_SCHEME};
use crate::cef::input::InputState;
use crate::cef::internal::{BrowserProcessAppImpl, BrowserProcessClientImpl, RenderProcessAppImpl, SchemeHandlerFactoryImpl};
use crate::dirs::TempDir;
use crate::wrapper::WgpuContext;
pub(crate) struct CefContextBuilder<H: CefEventHandler> {
pub(crate) args: Args,
@@ -67,19 +68,19 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
}
#[cfg(target_os = "macos")]
pub(crate) fn create(self, event_handler: H, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
pub(crate) fn create(self, event_handler: H, wgpu_context: WgpuContext, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
let instance_dir = TempDir::new().expect("Failed to create temporary directory for CEF instance");
let accelerated_paint = accelerated_paint(disable_gpu_acceleration);
self.build_inner(&event_handler, instance_dir.as_ref(), accelerated_paint)?;
create_browser(event_handler, instance_dir, accelerated_paint)
create_browser(event_handler, wgpu_context, instance_dir, accelerated_paint)
}
#[cfg(not(target_os = "macos"))]
pub(crate) fn create(self, event_handler: H, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
pub(crate) fn create(self, event_handler: H, wgpu_context: WgpuContext, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
let instance_dir = TempDir::new().expect("Failed to create temporary directory for CEF instance");
let accelerated_paint = accelerated_paint(disable_gpu_acceleration);
self.build_inner(&event_handler, instance_dir.as_ref(), accelerated_paint)?;
super::multithreaded::run_on_ui_thread(move || match create_browser(event_handler, instance_dir, accelerated_paint) {
super::multithreaded::run_on_ui_thread(move || match create_browser(event_handler, wgpu_context, instance_dir, accelerated_paint) {
Ok(context) => super::multithreaded::CONTEXT.with(|b| *b.borrow_mut() = Some(context)),
Err(e) => panic!("Failed to initialize CEF context: {:?}", e),
});
@@ -149,8 +150,8 @@ fn platform_settings(instance_dir: &Path) -> Settings {
}
}
fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: TempDir, accelerated_paint: bool) -> Result<SingleThreadedCefContext, InitError> {
let mut client = Client::new(BrowserProcessClientImpl::new(&event_handler));
fn create_browser<H: CefEventHandler>(event_handler: H, wgpu_context: WgpuContext, instance_dir: TempDir, accelerated_paint: bool) -> Result<SingleThreadedCefContext, InitError> {
let mut client = Client::new(BrowserProcessClientImpl::new(&event_handler, wgpu_context));
let window_info = WindowInfo {
windowless_rendering_enabled: 1,
@@ -4,6 +4,7 @@ use cef::{ContextMenuHandler, DisplayHandler, ImplClient, LifeSpanHandler, LoadH
use crate::cef::CefEventHandler;
use crate::cef::ipc::{MessageType, UnpackMessage, UnpackedMessage};
use crate::wrapper::WgpuContext;
use super::context_menu_handler::ContextMenuHandlerImpl;
use super::display_handler::DisplayHandlerImpl;
@@ -21,12 +22,12 @@ pub(crate) struct BrowserProcessClientImpl<H: CefEventHandler> {
request_handler: RequestHandler,
}
impl<H: CefEventHandler> BrowserProcessClientImpl<H> {
pub(crate) fn new(event_handler: &H) -> Self {
pub(crate) fn new(event_handler: &H, wgpu_context: WgpuContext) -> Self {
Self {
object: std::ptr::null_mut(),
event_handler: event_handler.duplicate(),
load_handler: LoadHandler::new(LoadHandlerImpl::new(event_handler.duplicate())),
render_handler: RenderHandler::new(RenderHandlerImpl::new(event_handler.duplicate())),
render_handler: RenderHandler::new(RenderHandlerImpl::new(event_handler.duplicate(), wgpu_context)),
display_handler: DisplayHandler::new(DisplayHandlerImpl::new(event_handler.duplicate())),
request_handler: RequestHandler::new(RequestHandlerImpl::new()),
}
+19 -19
View File
@@ -2,18 +2,20 @@ use cef::rc::{Rc, RcImpl};
use cef::sys::{_cef_render_handler_t, cef_base_ref_counted_t};
use cef::{Browser, ImplRenderHandler, PaintElementType, Rect, WrapRenderHandler};
use crate::cef::CefEventHandler;
use crate::render::FrameBufferRef;
use crate::cef::{CefEventHandler, View};
use crate::wrapper::WgpuContext;
pub(crate) struct RenderHandlerImpl<H: CefEventHandler> {
object: *mut RcImpl<_cef_render_handler_t, Self>,
event_handler: H,
view: View,
}
impl<H: CefEventHandler> RenderHandlerImpl<H> {
pub(crate) fn new(event_handler: H) -> Self {
pub(crate) fn new(event_handler: H, wgpu_context: WgpuContext) -> Self {
Self {
object: std::ptr::null_mut(),
event_handler,
view: View::new(wgpu_context),
}
}
}
@@ -31,29 +33,26 @@ impl<H: CefEventHandler> ImplRenderHandler for RenderHandlerImpl<H> {
}
}
fn on_paint(&self, _browser: Option<&mut Browser>, _type_: PaintElementType, _dirty_rects: Option<&[Rect]>, buffer: *const u8, width: std::ffi::c_int, height: std::ffi::c_int) {
let buffer_size = (width * height * 4) as usize;
let buffer_slice = unsafe { std::slice::from_raw_parts(buffer, buffer_size) };
let frame_buffer = FrameBufferRef::new(buffer_slice, width as usize, height as usize).expect("Failed to create frame buffer");
self.event_handler.draw(frame_buffer)
}
#[cfg(feature = "accelerated_paint")]
fn on_accelerated_paint(&self, _browser: Option<&mut Browser>, type_: PaintElementType, _dirty_rects: Option<&[Rect]>, info: Option<&cef::AcceleratedPaintInfo>) {
use cef::osr_texture_import::SharedTextureHandle;
fn on_paint(&self, _browser: Option<&mut Browser>, type_: PaintElementType, dirty_rects: Option<&[Rect]>, buffer: *const u8, width: std::ffi::c_int, height: std::ffi::c_int) {
if type_ != PaintElementType::default() {
return;
}
let shared_handle = SharedTextureHandle::new(info.unwrap());
if let SharedTextureHandle::Unsupported = shared_handle {
tracing::error!("Platform does not support accelerated painting");
let buffer_size = (width * height * 4) as usize;
let buffer_slice = unsafe { std::slice::from_raw_parts(buffer, buffer_size) };
self.view.upload_frame_buffer(buffer_slice, width as u32, height as u32, dirty_rects.unwrap_or(&[]));
self.event_handler.draw(&self.view)
}
#[cfg(feature = "accelerated_paint")]
fn on_accelerated_paint(&self, _browser: Option<&mut Browser>, type_: PaintElementType, _dirty_rects: Option<&[Rect]>, info: Option<&cef::AcceleratedPaintInfo>) {
if type_ != PaintElementType::default() {
return;
}
self.event_handler.draw_gpu(shared_handle);
self.view.import_shared_texture(info.unwrap());
self.event_handler.draw(&self.view)
}
fn get_raw(&self) -> *mut _cef_render_handler_t {
@@ -70,6 +69,7 @@ impl<H: CefEventHandler> Clone for RenderHandlerImpl<H> {
Self {
object: self.object,
event_handler: self.event_handler.duplicate(),
view: self.view.clone(),
}
}
}
+8 -1
View File
@@ -1,6 +1,6 @@
use cef::rc::{Rc, RcImpl};
use cef::sys::{_cef_request_handler_t, cef_base_ref_counted_t};
use cef::{AuthCallback, Browser, CefString, Frame, ImplRequest, ImplRequestHandler, Request, ResourceRequestHandler, WrapRequestHandler};
use cef::{AuthCallback, Browser, CefString, Frame, ImplRequest, ImplRequestHandler, Request, ResourceRequestHandler, TerminationStatus, WrapRequestHandler};
use std::ffi::c_int;
use super::resource_request_handler::ResourceRequestHandlerImpl;
@@ -55,6 +55,13 @@ impl ImplRequestHandler for RequestHandlerImpl {
0
}
fn on_render_process_terminated(&self, _browser: Option<&mut Browser>, status: TerminationStatus, error_code: c_int, error_string: Option<&CefString>) {
tracing::error!(
"CEF render process terminated: status={status:?}, error_code={error_code}, error={}",
error_string.map(|error| error.to_string()).unwrap_or_default()
);
}
fn get_raw(&self) -> *mut _cef_request_handler_t {
self.object.cast()
}
+108
View File
@@ -0,0 +1,108 @@
use cef::Rect;
use std::sync::{Arc, Mutex};
use crate::wrapper::WgpuContext;
#[derive(Clone)]
pub(crate) struct View {
context: WgpuContext,
texture: Arc<Mutex<Option<wgpu::Texture>>>,
}
impl View {
pub(crate) fn new(context: WgpuContext) -> Self {
Self {
context,
texture: Arc::new(Mutex::new(None)),
}
}
pub(crate) fn texture(&self) -> Option<wgpu::Texture> {
let Ok(texture) = self.texture.lock() else {
tracing::error!("Failed to lock view texture");
return None;
};
texture.clone()
}
pub(super) fn upload_frame_buffer(&self, buffer: &[u8], width: u32, height: u32, dirty_rects: &[Rect]) {
debug_assert_eq!(buffer.len(), width as usize * height as usize * 4);
let Ok(mut slot) = self.texture.lock() else {
tracing::error!("Failed to lock view texture");
return;
};
let needs_new_texture = slot.as_ref().is_none_or(|texture| texture.width() != width || texture.height() != height);
if needs_new_texture {
*slot = Some(self.context.device.create_texture(&wgpu::TextureDescriptor {
label: Some("CEF Texture"),
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Bgra8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
}));
}
let texture = slot.as_ref().expect("Texture was just created");
let full_frame = [Rect {
x: 0,
y: 0,
width: width as i32,
height: height as i32,
}];
let rects = if needs_new_texture || dirty_rects.is_empty() { &full_frame } else { dirty_rects };
for rect in rects {
let x = (rect.x.max(0) as u32).min(width);
let y = (rect.y.max(0) as u32).min(height);
let rect_width = (rect.width.max(0) as u32).min(width - x);
let rect_height = (rect.height.max(0) as u32).min(height - y);
if rect_width == 0 || rect_height == 0 {
continue;
}
self.context.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture,
mip_level: 0,
origin: wgpu::Origin3d { x, y, z: 0 },
aspect: wgpu::TextureAspect::All,
},
buffer,
wgpu::TexelCopyBufferLayout {
offset: 4 * (y as u64 * width as u64 + x as u64),
bytes_per_row: Some(4 * width),
rows_per_image: None,
},
wgpu::Extent3d {
width: rect_width,
height: rect_height,
depth_or_array_layers: 1,
},
);
}
}
#[cfg(feature = "accelerated_paint")]
pub(super) fn import_shared_texture(&self, info: &cef::AcceleratedPaintInfo) {
let texture = match cef::osr_texture_import::SharedTextureHandle::new(info).import_texture(&self.context.device) {
Ok(texture) => texture,
Err(e) => {
tracing::error!("Failed to import shared texture: {e}");
return;
}
};
let Ok(mut slot) = self.texture.lock() else {
tracing::error!("Failed to lock view texture");
return;
};
*slot = Some(texture);
}
}
+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());
+2 -2
View File
@@ -96,8 +96,8 @@ pub fn start() {
println!("UI acceleration is disabled");
}
let cef_handler = cef::CefHandler::new(wgpu_context.clone(), app_event_scheduler.clone(), cef_view_info_receiver);
let cef_context = match cef_context_builder.create(cef_handler, prefs.disable_ui_acceleration) {
let cef_handler = cef::CefHandler::new(app_event_scheduler.clone(), cef_view_info_receiver);
let cef_context = match cef_context_builder.create(cef_handler, wgpu_context.clone(), prefs.disable_ui_acceleration) {
Ok(context) => {
tracing::info!("CEF initialized successfully");
context
-3
View File
@@ -1,5 +1,2 @@
mod frame_buffer_ref;
pub(crate) use frame_buffer_ref::FrameBufferRef;
mod state;
pub(crate) use state::{RenderError, RenderState};
-53
View File
@@ -1,53 +0,0 @@
use thiserror::Error;
pub(crate) struct FrameBufferRef<'a> {
buffer: &'a [u8],
width: usize,
height: usize,
}
impl<'a> FrameBufferRef<'a> {
pub(crate) fn new(buffer: &'a [u8], width: usize, height: usize) -> Result<Self, FrameBufferError> {
let fb = Self { buffer, width, height };
fb.validate_size()?;
Ok(fb)
}
pub(crate) fn buffer(&self) -> &[u8] {
self.buffer
}
pub(crate) fn width(&self) -> usize {
self.width
}
pub(crate) fn height(&self) -> usize {
self.height
}
fn validate_size(&self) -> Result<(), FrameBufferError> {
if self.buffer.len() != self.width * self.height * 4 {
Err(FrameBufferError::InvalidSize {
buffer_size: self.buffer.len(),
expected_size: self.width * self.height * 4,
width: self.width,
height: self.height,
})
} else {
Ok(())
}
}
}
impl<'a> std::fmt::Debug for FrameBufferRef<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FrameBuffer")
.field("width", &self.width)
.field("height", &self.height)
.field("len", &self.buffer.len())
.finish()
}
}
#[derive(Error, Debug)]
pub(crate) enum FrameBufferError {
#[error("Invalid buffer size {buffer_size}, expected {expected_size} for width {width} multiplied with height {height} multiplied by 4 channels")]
InvalidSize { buffer_size: usize, expected_size: usize, width: usize, height: usize },
}
+6 -2
View File
@@ -206,8 +206,12 @@ impl RenderState {
self.update_bindgroup();
}
pub(crate) fn bind_ui_texture(&mut self, bind_ui_texture: wgpu::Texture) {
self.ui_texture = Some(bind_ui_texture);
pub(crate) fn bind_ui_texture(&mut self, ui_texture: wgpu::Texture) {
if self.ui_texture.as_ref() == Some(&ui_texture) {
self.surface_outdated = true;
return;
}
self.ui_texture = Some(ui_texture);
self.update_bindgroup();
}
+29 -11
View File
@@ -61,9 +61,9 @@ impl NativeWindowHandle {
0,
0,
0,
main,
Some(main),
None,
None,
HINSTANCE(std::ptr::null_mut()),
// Pass the main window's HWND to WM_NCCREATE so the helper can store it.
Some(&main as *const _ as _),
)
@@ -103,18 +103,36 @@ impl NativeWindowHandle {
};
let _ = unsafe { DwmExtendFrameIntoClientArea(main, &margins) };
let hinst = unsafe { GetModuleHandleW(None) }.unwrap();
let hinst: HINSTANCE = unsafe { GetModuleHandleW(None) }.unwrap().into();
// Set taskbar icon
if let Ok(big) = unsafe { LoadImageW(hinst, PCWSTR(1usize as *const u16), IMAGE_ICON, GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON), LR_SHARED) } {
if let Ok(big) = unsafe {
LoadImageW(
Some(hinst),
PCWSTR(1usize as *const u16),
IMAGE_ICON,
GetSystemMetrics(SM_CXICON),
GetSystemMetrics(SM_CYICON),
LR_SHARED,
)
} {
unsafe { SetClassLongPtrW(main, GCLP_HICON, big.0 as isize) };
unsafe { SendMessageW(main, WM_SETICON, WPARAM(ICON_BIG as usize), LPARAM(big.0 as isize)) };
unsafe { SendMessageW(main, WM_SETICON, Some(WPARAM(ICON_BIG as usize)), Some(LPARAM(big.0 as isize))) };
}
// Set window icon
if let Ok(small) = unsafe { LoadImageW(hinst, PCWSTR(1usize as *const u16), IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_SHARED) } {
if let Ok(small) = unsafe {
LoadImageW(
Some(hinst),
PCWSTR(1usize as *const u16),
IMAGE_ICON,
GetSystemMetrics(SM_CXSMICON),
GetSystemMetrics(SM_CYSMICON),
LR_SHARED,
)
} {
unsafe { SetClassLongPtrW(main, GCLP_HICONSM, small.0 as isize) };
unsafe { SendMessageW(main, WM_SETICON, WPARAM(ICON_SMALL as usize), LPARAM(small.0 as isize)) };
unsafe { SendMessageW(main, WM_SETICON, Some(WPARAM(ICON_SMALL as usize)), Some(LPARAM(small.0 as isize))) };
}
// Force window update
@@ -197,7 +215,7 @@ unsafe fn ensure_helper_class() {
lpfnWndProc: Some(helper_window_handle_message),
hInstance: unsafe { GetModuleHandleW(None).unwrap().into() },
hIcon: HICON::default(),
hCursor: unsafe { LoadCursorW(HINSTANCE(std::ptr::null_mut()), IDC_ARROW).unwrap() },
hCursor: unsafe { LoadCursorW(None, IDC_ARROW).unwrap() },
// No painting; the ring is invisible.
hbrBackground: HBRUSH::default(),
lpszClassName: PCWSTR(class_name.as_ptr()),
@@ -292,7 +310,7 @@ unsafe extern "system" fn helper_window_handle_message(hwnd: HWND, msg: u32, wpa
// Extract the main window's HWND from GWLP_USERDATA that we saved earlier.
let main_ptr = unsafe { GetWindowLongPtrW(hwnd, GWLP_USERDATA) } as *mut std::ffi::c_void;
let main = HWND(main_ptr);
if unsafe { IsWindow(main).as_bool() } {
if unsafe { IsWindow(Some(main)).as_bool() } {
let Some(wmsz) = (unsafe { calculate_resize_direction(hwnd, lparam) }) else {
return LRESULT(0);
};
@@ -301,7 +319,7 @@ unsafe extern "system" fn helper_window_handle_message(hwnd: HWND, msg: u32, wpa
let _ = unsafe { SetForegroundWindow(main) };
// Start sizing on the main window in the calculated direction. (SC_SIZE + WMSZ_*)
let _ = unsafe { PostMessageW(main, WM_SYSCOMMAND, WPARAM((SC_SIZE + wmsz) as usize), lparam) };
let _ = unsafe { PostMessageW(Some(main), WM_SYSCOMMAND, WPARAM((SC_SIZE + wmsz) as usize), lparam) };
}
return LRESULT(0);
}
@@ -325,7 +343,7 @@ unsafe fn position_helper(main: HWND, helper: HWND) {
let w = (r.right - r.left) + RESIZE_BAND_THICKNESS * 2;
let h = (r.bottom - r.top) + RESIZE_BAND_THICKNESS * 2;
let _ = unsafe { SetWindowPos(helper, main, x, y, w, h, SWP_NOACTIVATE | SWP_NOSENDCHANGING) };
let _ = unsafe { SetWindowPos(helper, Some(main), x, y, w, h, SWP_NOACTIVATE | SWP_NOSENDCHANGING) };
}
unsafe fn calculate_hit(helper: HWND, lparam: LPARAM) -> u32 {
@@ -37,13 +37,14 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
if let Some(path) = path {
dispatcher.respond(DesktopFrontendMessage::WriteFile { path, content });
} else {
let extension = std::path::Path::new(&name).extension().and_then(|extension| extension.to_str()).unwrap_or("*").to_string();
dispatcher.respond(DesktopFrontendMessage::SaveFileDialog {
title: "Save Document".to_string(),
default_filename: name,
default_folder: folder,
filters: vec![FileFilter {
name: "Graphite Document".to_string(),
extensions: vec!["gdd".to_string()],
extensions: vec![extension],
}],
context: SaveFileDialogContext::Document { document_id, content },
});
+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
@@ -26,6 +26,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 }
+2 -2
View File
@@ -176,8 +176,8 @@ pub const COLOR_OVERLAY_BLACK_75: &str = "#000000bf";
// DOCUMENT
pub const FILE_EXTENSION: &str = "graphite";
/// New document container format. Save now writes a `.gdd` (with the legacy `.graphite` embedded as a
/// fallback during the dual-write soak); `.graphite` stays a supported open/import input.
/// New document container format. Save writes a `.gdd` with the legacy `.graphite` embedded as a fallback
/// during the dual-write soak; `.graphite` stays a supported open/import input.
pub const GDD_FILE_EXTENSION: &str = "gdd";
pub const DEFAULT_DOCUMENT_NAME: &str = "Untitled Document";
pub const MAX_UNDO_HISTORY_LEN: usize = 100; // TODO: Add this to user preferences
+9 -136
View File
@@ -187,7 +187,14 @@ impl Dispatcher {
self.message_handlers.future_message_handler.process_message(message, &mut queue, FutureMessageContext {});
}
Message::Broadcast(message) => self.message_handlers.broadcast_message_handler.process_message(message, &mut queue, ()),
Message::Clipboard(message) => self.message_handlers.clipboard_message_handler.process_message(message, &mut queue, ()),
Message::Clipboard(message) => {
let context = ClipboardMessageContext {
portfolio: &mut self.message_handlers.portfolio_message_handler,
current_tool: &self.message_handlers.tool_message_handler.tool_state.tool_data.active_tool_type,
resource_storage: &self.message_handlers.resource_storage_message_handler,
};
self.message_handlers.clipboard_message_handler.process_message(message, &mut queue, context);
}
Message::ColorPicker(message) => self.message_handlers.color_picker_message_handler.process_message(message, &mut queue, ()),
Message::Debug(message) => {
self.message_handlers.debug_message_handler.process_message(message, &mut queue, ());
@@ -265,6 +272,7 @@ impl Dispatcher {
menu_bar_message_handler.properties_panel_open = layout.is_panel_present(PanelType::Properties);
menu_bar_message_handler.message_logging_verbosity = self.message_handlers.debug_message_handler.message_logging_verbosity;
menu_bar_message_handler.reset_node_definitions_on_open = self.message_handlers.portfolio_message_handler.reset_node_definitions_on_open;
menu_bar_message_handler.show_storage_preferences = self.message_handlers.preferences_message_handler.show_storage_preferences;
if let Some(document) = self
.message_handlers
@@ -420,141 +428,6 @@ impl Dispatcher {
mod test {
pub use crate::test_utils::test_prelude::*;
/// Create an editor with three layers
/// 1. A red rectangle
/// 2. A blue shape
/// 3. A green ellipse
async fn create_editor_with_three_layers() -> EditorTestUtils {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.select_primary_color(Color::RED).await;
editor.draw_rect(100., 200., 300., 400.).await;
editor.select_primary_color(Color::BLUE).await;
editor.draw_polygon(10., 1200., 1300., 400.).await;
editor.select_primary_color(Color::GREEN).await;
editor.draw_ellipse(104., 1200., 1300., 400.).await;
editor
}
/// - create rect, shape and ellipse
/// - copy
/// - paste
/// - assert that ellipse was copied
#[tokio::test]
async fn copy_paste_single_layer() {
let mut editor = create_editor_with_three_layers().await;
let layers_before_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
editor.handle_message(PortfolioMessage::Copy { clipboard: Clipboard::Internal }).await;
editor
.handle_message(PortfolioMessage::PasteIntoFolder {
clipboard: Clipboard::Internal,
parent: LayerNodeIdentifier::ROOT_PARENT,
insert_index: 0,
})
.await;
let layers_after_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
assert_eq!(layers_before_copy.len(), 3);
assert_eq!(layers_after_copy.len(), 4);
// Existing layers are unaffected
for i in 0..=2 {
assert_eq!(layers_before_copy[i], layers_after_copy[i + 1]);
}
}
#[cfg_attr(miri, ignore)]
/// - create rect, shape and ellipse
/// - select shape
/// - copy
/// - paste
/// - assert that shape was copied
#[tokio::test]
async fn copy_paste_single_layer_from_middle() {
let mut editor = create_editor_with_three_layers().await;
let layers_before_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
let shape_id = editor.active_document().metadata().all_layers().nth(1).unwrap();
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![shape_id.to_node()] }).await;
editor.handle_message(PortfolioMessage::Copy { clipboard: Clipboard::Internal }).await;
editor
.handle_message(PortfolioMessage::PasteIntoFolder {
clipboard: Clipboard::Internal,
parent: LayerNodeIdentifier::ROOT_PARENT,
insert_index: 0,
})
.await;
let layers_after_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
assert_eq!(layers_before_copy.len(), 3);
assert_eq!(layers_after_copy.len(), 4);
// Existing layers are unaffected
for i in 0..=2 {
assert_eq!(layers_before_copy[i], layers_after_copy[i + 1]);
}
}
#[cfg_attr(miri, ignore)]
/// - create rect, shape and ellipse
/// - select ellipse and rect
/// - copy
/// - delete
/// - create another rect
/// - paste
/// - paste
#[tokio::test]
async fn copy_paste_deleted_layers() {
let mut editor = create_editor_with_three_layers().await;
assert_eq!(editor.active_document().metadata().all_layers().count(), 3);
let layers_before_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
let rect_id = layers_before_copy[0];
let shape_id = layers_before_copy[1];
let ellipse_id = layers_before_copy[2];
editor
.handle_message(NodeGraphMessage::SelectedNodesSet {
nodes: vec![rect_id.to_node(), ellipse_id.to_node()],
})
.await;
editor.handle_message(PortfolioMessage::Copy { clipboard: Clipboard::Internal }).await;
editor.handle_message(NodeGraphMessage::DeleteSelectedNodes { delete_children: true }).await;
editor.draw_rect(0., 800., 12., 200.).await;
editor
.handle_message(PortfolioMessage::PasteIntoFolder {
clipboard: Clipboard::Internal,
parent: LayerNodeIdentifier::ROOT_PARENT,
insert_index: 0,
})
.await;
editor
.handle_message(PortfolioMessage::PasteIntoFolder {
clipboard: Clipboard::Internal,
parent: LayerNodeIdentifier::ROOT_PARENT,
insert_index: 0,
})
.await;
let layers_after_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
assert_eq!(layers_before_copy.len(), 3);
assert_eq!(layers_after_copy.len(), 6);
println!("{layers_after_copy:?} {layers_before_copy:?}");
assert_eq!(layers_after_copy[5], shape_id);
}
#[tokio::test]
/// This test will fail when you make changes to the underlying serialization format for a document.
async fn check_if_demo_art_opens() {
@@ -1,4 +1,4 @@
use crate::messages::clipboard::utility_types::{ClipboardContent, ClipboardContentRaw};
use crate::messages::clipboard::utility_types::{ClipboardContent, ClipboardContentRaw, ClipboardItem, ClipboardLayer, ClipboardVectorEntry};
use crate::messages::prelude::*;
#[impl_message(Message, Clipboard)]
@@ -10,4 +10,11 @@ pub enum ClipboardMessage {
ReadClipboard { content: ClipboardContentRaw },
ReadSelection { content: Option<String>, cut: bool },
Write { content: ClipboardContent },
CopyLayers,
CutLayers,
WriteItems { items: Vec<ClipboardItem> },
PasteItems { data: String },
PasteLayers { entries: Vec<ClipboardLayer> },
PasteVectors { paths: Vec<ClipboardVectorEntry> },
}
@@ -1,36 +1,58 @@
use crate::messages::clipboard::utility_types::{ClipboardContent, ClipboardContentRaw};
use crate::consts::DEFAULT_STROKE_WIDTH;
use crate::messages::clipboard::utility_types::{ClipboardContent, ClipboardContentRaw, ClipboardItem, ClipboardLayer, ClipboardResource, ResourceData};
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface;
use crate::messages::portfolio::document::utility_types::nodes::SelectedNodes;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::utility_types::ToolType;
use graph_craft::application_io::resource::{DataSource, ResourceHash};
use graph_craft::document::NodeId;
use graphene_std::Color;
use graphene_std::raster::Image;
use graphene_std::subpath::BezierHandles;
use graphene_std::vector::misc::HandleId;
use graphene_std::vector::{PointId, SegmentId, VectorModificationType};
use graphite_proc_macros::{ExtractField, message_handler_data};
use std::sync::Arc;
const CLIPBOARD_PREFIX_LAYER: &str = "graphite/layer: ";
const CLIPBOARD_PREFIX_NODES: &str = "graphite/nodes: ";
const CLIPBOARD_PREFIX_VECTOR: &str = "graphite/vector: ";
const CLIPBOARD_PREFIX: &str = "graphite: ";
#[derive(ExtractField)]
pub struct ClipboardMessageContext<'a> {
pub portfolio: &'a mut PortfolioMessageHandler,
pub current_tool: &'a ToolType,
pub resource_storage: &'a ResourceStorageMessageHandler,
}
#[derive(Debug, Clone, Default, ExtractField)]
pub struct ClipboardMessageHandler {}
#[message_handler_data]
impl MessageHandler<ClipboardMessage, ()> for ClipboardMessageHandler {
fn process_message(&mut self, message: ClipboardMessage, responses: &mut std::collections::VecDeque<Message>, _: ()) {
impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for ClipboardMessageHandler {
fn process_message(&mut self, message: ClipboardMessage, responses: &mut std::collections::VecDeque<Message>, context: ClipboardMessageContext) {
let ClipboardMessageContext {
portfolio,
current_tool,
resource_storage,
} = context;
match message {
ClipboardMessage::Cut => responses.add(FrontendMessage::TriggerSelectionRead { cut: true }),
ClipboardMessage::Copy => responses.add(FrontendMessage::TriggerSelectionRead { cut: false }),
ClipboardMessage::Paste => responses.add(FrontendMessage::TriggerClipboardRead),
ClipboardMessage::ReadClipboard { content } => match content {
ClipboardContentRaw::Text(text) => {
if let Some(layer) = text.strip_prefix(CLIPBOARD_PREFIX_LAYER) {
responses.add(PortfolioMessage::PasteSerializedData { data: layer.to_string() });
} else if let Some(nodes) = text.strip_prefix(CLIPBOARD_PREFIX_NODES) {
responses.add(NodeGraphMessage::PasteNodes { serialized_nodes: nodes.to_string() });
} else if let Some(vector) = text.strip_prefix(CLIPBOARD_PREFIX_VECTOR) {
responses.add(PortfolioMessage::PasteSerializedVector { data: vector.to_string() });
if let Some(graphite) = text.strip_prefix(CLIPBOARD_PREFIX) {
responses.add(ClipboardMessage::PasteItems { data: graphite.to_string() });
} else {
responses.add(FrontendMessage::TriggerSelectionWrite { content: text });
}
}
ClipboardContentRaw::Svg(svg) => {
responses.add(PortfolioMessage::PasteSvg {
responses.add(PortfolioMessage::InsertSvg {
svg,
name: None,
mouse: None,
@@ -38,7 +60,7 @@ impl MessageHandler<ClipboardMessage, ()> for ClipboardMessageHandler {
});
}
ClipboardContentRaw::Image { data, width, height } => {
responses.add(PortfolioMessage::PasteImage {
responses.add(PortfolioMessage::InsertImage {
image: Image::from_image_data(&data, width, height),
name: None,
mouse: None,
@@ -47,15 +69,14 @@ impl MessageHandler<ClipboardMessage, ()> for ClipboardMessageHandler {
}
},
ClipboardMessage::ReadSelection { content, cut } => {
use crate::messages::portfolio::document::utility_types::clipboards::Clipboard;
if let Some(text) = content {
responses.add(ClipboardMessage::Write {
content: ClipboardContent::Text(text),
});
} else if cut {
responses.add(PortfolioMessage::Cut { clipboard: Clipboard::Device });
responses.add(ClipboardMessage::CutLayers);
} else {
responses.add(PortfolioMessage::Copy { clipboard: Clipboard::Device });
responses.add(ClipboardMessage::CopyLayers);
}
}
ClipboardMessage::Write { content } => {
@@ -68,13 +89,381 @@ impl MessageHandler<ClipboardMessage, ()> for ClipboardMessageHandler {
log::error!("Image copying is not yet supported");
return;
}
ClipboardContent::Layer(layer) => format!("{CLIPBOARD_PREFIX_LAYER}{layer}"),
ClipboardContent::Nodes(nodes) => format!("{CLIPBOARD_PREFIX_NODES}{nodes}"),
ClipboardContent::Vector(vector) => format!("{CLIPBOARD_PREFIX_VECTOR}{vector}"),
ClipboardContent::Graphite(graphite) => format!("{CLIPBOARD_PREFIX}{graphite}"),
ClipboardContent::Text(text) => text,
};
responses.add(FrontendMessage::TriggerClipboardWrite { content: text });
}
ClipboardMessage::CopyLayers => {
if current_tool == &ToolType::Path {
responses.add(PathToolMessage::Copy);
return;
}
let Some(active_document) = portfolio.active_document_id.and_then(|id| portfolio.documents.get_mut(&id)) else {
return;
};
if active_document.graph_view_overlay_open() {
responses.add(NodeGraphMessage::Copy);
return;
}
let mut buffer = Vec::new();
let mut ordered_last_elements = active_document.network_interface.shallowest_unique_layers(&[]).collect::<Vec<_>>();
ordered_last_elements.sort_by_key(|layer| {
let Some(parent) = layer.parent(active_document.metadata()) else { return usize::MAX };
DocumentMessageHandler::get_calculated_insert_index(active_document.metadata(), &SelectedNodes(vec![layer.to_node()]), parent)
});
for layer in ordered_last_elements.into_iter() {
let layer_node_id = layer.to_node();
let mut copy_ids = HashMap::new();
copy_ids.insert(layer_node_id, NodeId(0));
active_document
.network_interface
.upstream_flow_back_from_nodes(vec![layer_node_id], &[], network_interface::FlowType::LayerChildrenUpstreamFlow)
.enumerate()
.for_each(|(index, node_id)| {
copy_ids.insert(node_id, NodeId((index + 1) as u64));
});
// The layer panel keys collapse state on the top-down path of node IDs down to the layer
let mut tree_path = layer
.ancestors(active_document.metadata())
.filter(|ancestor| *ancestor != LayerNodeIdentifier::ROOT_PARENT)
.map(|ancestor| ancestor.to_node())
.collect::<Vec<_>>();
tree_path.reverse();
buffer.push(ClipboardLayer {
nodes: active_document.network_interface.copy_nodes(&copy_ids, &[]).collect(),
visible: active_document.network_interface.selected_nodes().layer_visible(layer, &active_document.network_interface),
locked: active_document.network_interface.selected_nodes().layer_locked(layer, &active_document.network_interface),
collapsed: active_document.collapsed.0.contains(&tree_path),
});
}
responses.add(ClipboardMessage::WriteItems {
items: buffer.into_iter().map(ClipboardItem::Layer).collect(),
});
}
ClipboardMessage::CutLayers => {
if current_tool == &ToolType::Path {
responses.add(PathToolMessage::Cut);
return;
}
if let Some(active_document) = portfolio.active_document()
&& active_document.graph_view_overlay_open()
{
responses.add(NodeGraphMessage::Cut);
return;
}
responses.add(ClipboardMessage::CopyLayers);
responses.add(DocumentMessage::DeleteSelectedLayers);
}
ClipboardMessage::WriteItems { items } => {
let has_content = items.iter().any(|item| match item {
ClipboardItem::Layer(entry) => !entry.nodes.is_empty(),
ClipboardItem::Nodes(nodes) => !nodes.is_empty(),
ClipboardItem::Vector(vector) => !vector.is_empty(),
ClipboardItem::Resource(_) => true,
});
if !has_content {
return;
}
let mut resource_ids = HashSet::new();
for item in &items {
match item {
ClipboardItem::Layer(entry) => entry
.nodes
.iter()
.for_each(|(_, template)| network_interface::collect_node_resources(&template.document_node, &mut resource_ids)),
ClipboardItem::Nodes(nodes) => nodes
.iter()
.for_each(|(_, template)| network_interface::collect_node_resources(&template.document_node, &mut resource_ids)),
ClipboardItem::Vector(_) | ClipboardItem::Resource(_) => {}
}
}
// Snapshot each resource's registry entry; embedded ones also need their bytes
let mut resources = Vec::new();
let mut bytes_to_load = Vec::new();
if let Some(document) = portfolio.active_document() {
for id in resource_ids {
let Some(info) = document.resources.registry.info(&id) else { continue };
if let Some(hash) = info.hash
&& info.sources.contains(&DataSource::Embedded)
{
bytes_to_load.push((resources.len(), *hash));
}
resources.push(ClipboardResource {
id,
hash: info.hash.copied(),
sources: info.sources.to_vec(),
data: None,
});
}
}
if bytes_to_load.is_empty() {
let mut items = items;
items.extend(resources.into_iter().map(ClipboardItem::Resource));
if let Some(content) = serialize_clipboard(&items) {
responses.add(ClipboardMessage::Write { content });
}
} else {
// Load the embedded bytes from the resource storage, then write
let load_handle = resource_storage.resources();
responses.add(async move {
let mut resources = resources;
for (index, hash) in bytes_to_load {
if let Some(resource) = load_handle.load(hash).await {
resources[index].data = Some(ResourceData(resource.as_ref().to_vec()));
}
}
let mut items = items;
items.extend(resources.into_iter().map(ClipboardItem::Resource));
match serialize_clipboard(&items) {
Some(content) => ClipboardMessage::Write { content }.into(),
None => Message::NoOp,
}
});
}
}
ClipboardMessage::PasteItems { data } => {
let items = match serde_json::from_str::<Vec<ClipboardItem>>(&data) {
Ok(items) => items,
Err(error) => {
log::error!("Failed to deserialize clipboard payload: {error}");
return;
}
};
let mut layers = Vec::new();
let mut node_groups = Vec::new();
let mut vectors = Vec::new();
let mut resources = Vec::new();
for item in items {
match item {
ClipboardItem::Layer(entry) => layers.push(entry),
ClipboardItem::Nodes(nodes) => node_groups.push(nodes),
ClipboardItem::Vector(vector) => vectors.push(vector),
ClipboardItem::Resource(resource) => resources.push(resource),
}
}
// Re-register the carried resources and store their bytes
let mut needs_resolve = false;
if !resources.is_empty()
&& let Some(document) = portfolio.active_document_mut()
{
for resource in resources {
if document.resources.registry.contains(&resource.id) {
continue;
}
for source in resource.sources {
document.resources.registry.push_source_back(&resource.id, source);
}
match resource.data {
Some(data) => match resource.hash {
Some(hash) if ResourceHash::from(data.0.as_slice()) == hash => {
document.resources.registry.resolve(&resource.id, hash);
responses.add(ResourceStorageMessage::Store { data: Arc::from(data.0) });
}
_ => warn!("Discarding pasted resource {:?}: embedded bytes do not match its advertised hash", resource.id),
},
None => needs_resolve = true,
}
}
}
// Paste the content through the existing per-type handlers
if !layers.is_empty() {
responses.add(ClipboardMessage::PasteLayers { entries: layers });
}
for nodes in node_groups {
responses.add(NodeGraphMessage::InsertNodes { nodes });
}
for paths in vectors {
responses.add(ClipboardMessage::PasteVectors { paths });
}
// Re-resolve resources that carried no bytes (URL- or font-backed)
if needs_resolve && let Some(document_id) = portfolio.active_document_id {
responses.add(PortfolioMessage::ResolveDocumentResources { document_id });
}
}
ClipboardMessage::PasteLayers { entries } => {
if let Some(document) = portfolio.active_document() {
let parent = document.new_layer_parent(false);
// Top-down node ID path of the destination parent, used to derive each pasted layer's collapse path
let mut parent_tree_path = parent
.ancestors(document.metadata())
.filter(|ancestor| *ancestor != LayerNodeIdentifier::ROOT_PARENT)
.map(|ancestor| ancestor.to_node())
.collect::<Vec<_>>();
parent_tree_path.reverse();
let mut all_new_ids = Vec::new();
let mut layers = Vec::new();
let mut added_nodes = false;
for entry in entries.into_iter().rev() {
let new_ids: HashMap<_, _> = entry.nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect();
let Some(&root_id) = new_ids.get(&NodeId(0)) else {
warn!("Skipping pasted layer missing its root node");
continue;
};
let layer = LayerNodeIdentifier::new_unchecked(root_id);
if !added_nodes {
responses.add(DocumentMessage::DeselectAllLayers);
responses.add(DocumentMessage::AddTransaction);
added_nodes = true;
}
all_new_ids.extend(new_ids.values().copied());
responses.add(NodeGraphMessage::AddNodes { nodes: entry.nodes, new_ids });
responses.add(NodeGraphMessage::MoveLayerToStack { layer, parent, insert_index: 0 });
// Restore the copied layer's visibility, lock, and collapse state
if !entry.visible {
responses.add(NodeGraphMessage::SetVisibility {
node_id: root_id,
network_path: Vec::new(),
visible: false,
});
}
if entry.locked {
responses.add(NodeGraphMessage::SetLocked {
node_id: root_id,
network_path: Vec::new(),
locked: true,
});
}
if entry.collapsed {
let mut tree_path = parent_tree_path.clone();
tree_path.push(root_id);
responses.add(DocumentMessage::ToggleLayerExpansion { tree_path, recursive: false });
}
layers.push(layer);
}
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: all_new_ids });
responses.add(DeferMessage::AfterGraphRun {
messages: vec![PortfolioMessage::CenterLayers { layers }.into()],
});
}
}
ClipboardMessage::PasteVectors { paths } => {
// If using Path tool then send the operation to Path tool
// TODO: Consider if this is actually the correct place to put this logic
// TODO: Consider making paste in general go through the current tool, so that the tool can decide what to do
if *current_tool == ToolType::Path {
responses.add(PathToolMessage::Paste { paths });
return;
}
// If not using Path tool, create new layers and add paths into those
if let Some(document) = portfolio.active_document() {
let mut layers = Vec::new();
for (_, new_vector, transform) in paths {
let Some(node_type) = resolve_network_node_type("Path") else {
error!("Path node does not exist");
continue;
};
let nodes = vec![(NodeId(0), node_type.default_node_template())];
let parent = document.new_layer_parent(false);
let layer = graph_modification_utils::new_custom(NodeId::new(), nodes, parent, responses);
layers.push(layer);
// Adding the transform back into the layer
responses.add(GraphOperationMessage::TransformSet {
layer,
transform,
transform_in: TransformIn::Local,
skip_rerender: false,
});
// Add default fill and stroke to the layer
responses.add(GraphOperationMessage::FillColorSet { layer, color: Some(Color::WHITE) });
let color = Some(Color::BLACK);
let stroke = graphene_std::vector::style::Stroke::new(DEFAULT_STROKE_WIDTH);
responses.add(GraphOperationMessage::StrokeSet { layer, color, stroke });
// Create new point ids and add those into the existing Vector path
let mut points_map = HashMap::new();
for (point, position) in new_vector.point_domain.iter() {
let new_point_id = PointId::generate();
points_map.insert(point, new_point_id);
let modification_type = VectorModificationType::InsertPoint { id: new_point_id, position };
responses.add(GraphOperationMessage::Vector { layer, modification_type });
}
// Create new segment ids and add the segments into the existing Vector path
let mut segments_map = HashMap::new();
for (segment_id, bezier, start, end) in new_vector.segment_bezier_iter() {
let (Some(&start_point), Some(&end_point)) = (points_map.get(&start), points_map.get(&end)) else {
warn!("Skipping pasted vector segment with an unknown endpoint");
continue;
};
let new_segment_id = SegmentId::generate();
segments_map.insert(segment_id, new_segment_id);
let handles = match bezier.handles {
BezierHandles::Linear => [None, None],
BezierHandles::Quadratic { handle } => [Some(handle - bezier.start), None],
BezierHandles::Cubic { handle_start, handle_end } => [Some(handle_start - bezier.start), Some(handle_end - bezier.end)],
};
let points = [start_point, end_point];
let modification_type = VectorModificationType::InsertSegment { id: new_segment_id, points, handles };
responses.add(GraphOperationMessage::Vector { layer, modification_type });
}
// Set G1 continuity
for handles in new_vector.colinear_manipulators {
let to_new_handle = |handle: HandleId| -> Option<HandleId> {
Some(HandleId {
ty: handle.ty,
segment: *segments_map.get(&handle.segment)?,
})
};
let (Some(first), Some(second)) = (to_new_handle(handles[0]), to_new_handle(handles[1])) else {
continue;
};
let modification_type = VectorModificationType::SetG1Continuous {
handles: [first, second],
enabled: true,
};
responses.add(GraphOperationMessage::Vector { layer, modification_type });
}
}
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(Message::Defer(DeferMessage::AfterGraphRun {
messages: vec![PortfolioMessage::CenterLayers { layers }.into()],
}));
}
}
}
}
advertise_actions!(ClipboardMessageDiscriminant;
@@ -83,3 +472,183 @@ impl MessageHandler<ClipboardMessage, ()> for ClipboardMessageHandler {
Paste,
);
}
/// Serialize the clipboard items, logging on failure.
fn serialize_clipboard(items: &[ClipboardItem]) -> Option<ClipboardContent> {
match serde_json::to_string(items) {
Ok(data) => Some(ClipboardContent::Graphite(data)),
Err(error) => {
log::error!("Failed to serialize clipboard payload: {error}");
None
}
}
}
#[cfg(test)]
mod test {
use crate::messages::clipboard::utility_types::{ClipboardItem, ClipboardResource, ResourceData};
use crate::test_utils::test_prelude::*;
use graph_craft::application_io::resource::{DataSource, ResourceHash, ResourceId};
/// Create an editor with three layers
/// 1. A red rectangle
/// 2. A blue shape
/// 3. A green ellipse
async fn create_editor_with_three_layers() -> EditorTestUtils {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.select_primary_color(Color::RED).await;
editor.draw_rect(100., 200., 300., 400.).await;
editor.select_primary_color(Color::BLUE).await;
editor.draw_polygon(10., 1200., 1300., 400.).await;
editor.select_primary_color(Color::GREEN).await;
editor.draw_ellipse(104., 1200., 1300., 400.).await;
editor
}
/// Copies the layer selection and returns the written clipboard payload.
async fn copy_layers_to_clipboard(editor: &mut EditorTestUtils) -> String {
editor
.handle_message(ClipboardMessage::CopyLayers)
.await
.into_iter()
.find_map(|message| match message {
FrontendMessage::TriggerClipboardWrite { content } => Some(content),
_ => None,
})
.expect("copying layers should write a payload to the clipboard")
}
/// Pastes a clipboard string as if read from the system clipboard.
async fn paste_from_clipboard(editor: &mut EditorTestUtils, clipboard: &str) {
editor
.handle_message(ClipboardMessage::ReadClipboard {
content: ClipboardContentRaw::Text(clipboard.to_string()),
})
.await;
}
/// - create rect, shape and ellipse
/// - copy
/// - paste
/// - assert that ellipse was copied
#[tokio::test]
async fn copy_paste_single_layer() {
let mut editor = create_editor_with_three_layers().await;
let layers_before_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
let clipboard = copy_layers_to_clipboard(&mut editor).await;
paste_from_clipboard(&mut editor, &clipboard).await;
let layers_after_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
assert_eq!(layers_before_copy.len(), 3);
assert_eq!(layers_after_copy.len(), 4);
// Existing layers are unaffected
for i in 0..=2 {
assert_eq!(layers_before_copy[i], layers_after_copy[i + 1]);
}
}
#[cfg_attr(miri, ignore)]
/// - create rect, shape and ellipse
/// - select shape
/// - copy
/// - paste
/// - assert that shape was copied
#[tokio::test]
async fn copy_paste_single_layer_from_middle() {
let mut editor = create_editor_with_three_layers().await;
let layers_before_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
let shape_id = editor.active_document().metadata().all_layers().nth(1).unwrap();
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![shape_id.to_node()] }).await;
let clipboard = copy_layers_to_clipboard(&mut editor).await;
paste_from_clipboard(&mut editor, &clipboard).await;
let layers_after_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
assert_eq!(layers_before_copy.len(), 3);
assert_eq!(layers_after_copy.len(), 4);
// Existing layers are unaffected
for i in 0..=2 {
assert_eq!(layers_before_copy[i], layers_after_copy[i + 1]);
}
}
#[cfg_attr(miri, ignore)]
/// - create rect, shape and ellipse
/// - select ellipse and rect
/// - copy
/// - delete
/// - create another rect
/// - paste
/// - paste
#[tokio::test]
async fn copy_paste_deleted_layers() {
let mut editor = create_editor_with_three_layers().await;
assert_eq!(editor.active_document().metadata().all_layers().count(), 3);
let layers_before_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
let rect_id = layers_before_copy[0];
let shape_id = layers_before_copy[1];
let ellipse_id = layers_before_copy[2];
editor
.handle_message(NodeGraphMessage::SelectedNodesSet {
nodes: vec![rect_id.to_node(), ellipse_id.to_node()],
})
.await;
let clipboard = copy_layers_to_clipboard(&mut editor).await;
editor.handle_message(NodeGraphMessage::DeleteSelectedNodes { delete_children: true }).await;
editor.draw_rect(0., 800., 12., 200.).await;
paste_from_clipboard(&mut editor, &clipboard).await;
paste_from_clipboard(&mut editor, &clipboard).await;
let layers_after_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
assert_eq!(layers_before_copy.len(), 3);
assert_eq!(layers_after_copy.len(), 6);
assert_eq!(layers_after_copy[5], shape_id);
}
/// A pasted `graphite:` payload re-registers the resources it carries into the active document.
#[tokio::test]
async fn paste_carries_embedded_resource() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let id = ResourceId::new();
assert!(!editor.active_document().resources.registry.contains(&id));
// Carry the resource and its bytes through the clipboard
let bytes = b"a pretend png".to_vec();
let hash = ResourceHash::from(bytes.as_slice());
let items = vec![ClipboardItem::Resource(ClipboardResource {
id,
hash: Some(hash),
sources: vec![DataSource::Embedded],
data: Some(ResourceData(bytes)),
})];
let payload = format!("graphite: {}", serde_json::to_string(&items).unwrap());
editor
.handle_message(ClipboardMessage::ReadClipboard {
content: ClipboardContentRaw::Text(payload),
})
.await;
let registry = &editor.active_document().resources.registry;
assert!(registry.contains(&id), "the carried resource should be registered after paste");
assert_eq!(registry.hash(&id), Some(hash), "the carried resource should resolve to the carried bytes' hash");
}
}
+1 -1
View File
@@ -5,4 +5,4 @@ pub mod utility_types;
#[doc(inline)]
pub use clipboard_message::{ClipboardMessage, ClipboardMessageDiscriminant};
#[doc(inline)]
pub use clipboard_message_handler::ClipboardMessageHandler;
pub use clipboard_message_handler::{ClipboardMessageContext, ClipboardMessageHandler};
+57 -3
View File
@@ -1,3 +1,12 @@
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use glam::DAffine2;
use graph_craft::application_io::resource::{DataSource, ResourceHash, ResourceId};
use graph_craft::document::NodeId;
use graphene_std::vector::Vector;
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum ClipboardContentRaw {
Text(String),
@@ -7,10 +16,55 @@ pub enum ClipboardContentRaw {
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum ClipboardContent {
Layer(String),
Nodes(String),
Vector(String),
Graphite(String),
Text(String),
Svg(String),
Image { data: Vec<u8>, width: u32, height: u32 },
}
pub type ClipboardVectorEntry = (LayerNodeIdentifier, Vector, DAffine2);
/// An entry in the `graphite:` clipboard payload.
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum ClipboardItem {
Layer(ClipboardLayer),
Nodes(Vec<(NodeId, NodeTemplate)>),
Vector(Vec<ClipboardVectorEntry>),
Resource(ClipboardResource),
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ClipboardLayer {
pub nodes: Vec<(NodeId, NodeTemplate)>,
pub visible: bool,
pub locked: bool,
pub collapsed: bool,
}
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ClipboardResource {
pub id: ResourceId,
pub hash: Option<ResourceHash>,
pub sources: Vec<DataSource>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub data: Option<ResourceData>,
}
#[derive(PartialEq, Clone)]
pub struct ResourceData(pub Vec<u8>);
impl std::fmt::Debug for ResourceData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ResourceData").field("len", &self.0.len()).finish()
}
}
impl serde::Serialize for ResourceData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&BASE64.encode(&self.0))
}
}
impl<'de> serde::Deserialize<'de> for ResourceData {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let encoded = String::deserialize(deserializer)?;
Ok(Self(BASE64.decode(&encoded).map_err(serde::de::Error::custom)?))
}
}
@@ -339,6 +339,31 @@ impl ColorPickerMessageHandler {
self.snapshot_old();
}
}
SpectrumInputUpdate::InsertDuplicate { index, position } => {
let source = index as usize;
let Some(insert_index) = gradient.duplicate_stop(source, position) else { return };
// The dragged stop (the duplication source) stays active. Its index shifts up if the frozen copy landed at or before it.
let dragged_index = if insert_index <= source { source + 1 } else { source };
self.active_marker_index = Some(dragged_index as u32);
self.active_marker_is_midpoint = false;
}
SpectrumInputUpdate::RemoveDuplicate { index } => {
let anchor = index as usize;
if anchor >= gradient.position.len() || gradient.position.len() <= 2 {
return;
}
// Never remove the active (dragged) stop itself, this should only ever target the frozen copy.
if self.active_marker_index == Some(anchor as u32) {
return;
}
gradient.remove(anchor);
// Keep the dragged stop active. Its index shifts down if the removed copy came before it.
if let Some(active) = self.active_marker_index
&& (anchor as u32) < active
{
self.active_marker_index = Some(active - 1);
}
}
SpectrumInputUpdate::DeleteMarker { index } => {
// Enforce minimum stop count. The gradient editor needs at least 2 stops to remain meaningful.
if gradient.position.len() <= 2 || (index as usize) >= gradient.position.len() {
@@ -303,6 +303,62 @@ impl PreferencesDialogMessageHandler {
rows.extend_from_slice(&[header, node_graph_wires_label, graph_wire_style, brush_tool]);
}
// =========
// DOCUMENTS
// =========
// Soak-only `.gdd` storage options, hidden unless enabled from the developer debug menu.
if preferences.show_storage_preferences {
let header = vec![TextLabel::new("Documents").italic(true).widget_instance()];
let save_as_gdd_description = "
Save documents in the new .gdd container format (with the legacy .graphite file embedded as a recovery fallback) instead of a plain .graphite file. The .gdd format is still being validated, so this is opt-in for now.\n\
\n\
*Default: Off.*
"
.trim();
let save_as_gdd_checkbox_id = CheckboxId::new();
let save_as_gdd = vec![
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(preferences.save_as_gdd)
.tooltip_label("Save as .gdd")
.tooltip_description(save_as_gdd_description)
.on_update(|checkbox_input: &CheckboxInput| PreferencesMessage::SaveAsGdd { enabled: checkbox_input.checked }.into())
.for_label(save_as_gdd_checkbox_id)
.widget_instance(),
TextLabel::new("Save as .gdd")
.tooltip_label("Save as .gdd")
.tooltip_description(save_as_gdd_description)
.for_checkbox(save_as_gdd_checkbox_id)
.widget_instance(),
];
let validate_description = "
Validate every document save, open, and undo by round-tripping it through the .gdd storage format and comparing against the legacy path, logging any mismatch. Useful for debugging the .gdd format during its soak, but the per-edit round-trip has a performance cost.\n\
\n\
*Default: Off.*
"
.trim();
let validate_checkbox_id = CheckboxId::new();
let validate_storage_round_trip = vec![
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(preferences.validate_storage_round_trip)
.tooltip_label("Validate Storage Round-Trip")
.tooltip_description(validate_description)
.on_update(|checkbox_input: &CheckboxInput| PreferencesMessage::ValidateStorageRoundTrip { enabled: checkbox_input.checked }.into())
.for_label(validate_checkbox_id)
.widget_instance(),
TextLabel::new("Validate Storage Round-Trip")
.tooltip_label("Validate Storage Round-Trip")
.tooltip_description(validate_description)
.for_checkbox(validate_checkbox_id)
.widget_instance(),
];
rows.extend_from_slice(&[header, save_as_gdd, validate_storage_round_trip]);
}
// =============
// COMPATIBILITY
// =============
@@ -7,11 +7,6 @@ use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender, unbounded};
use crate::messages::prelude::*;
// Native spawns onto a multi-thread tokio runtime, so the boxed future must be `Send`. Wasm uses
// `spawn_local` on the single JS thread, where `Send` is unavailable (OPFS/`JsFuture` are `!Send`)
// and unnecessary. `WasmNotSend` (`Send` on native, no-op on wasm) expresses the input bound on
// `MessageFuture::new`; the stored trait-object alias still needs a `cfg` split because `Send` is
// an auto trait usable in a `dyn` bound while `WasmNotSend` is not.
#[cfg(not(target_family = "wasm"))]
type InnerMessageFuture = Pin<Box<dyn Future<Output = Message> + Send + 'static>>;
#[cfg(target_family = "wasm")]
@@ -78,8 +73,10 @@ pub struct FutureMessageContext {}
#[derive(ExtractField)]
pub struct FutureMessageHandler {
#[cfg_attr(test, expect(dead_code))]
spawner: Arc<dyn MessageSpawner>,
wake: Wake,
#[cfg_attr(test, expect(dead_code))]
results_sender: UnboundedSender<Message>,
results_receiver: UnboundedReceiver<Message>,
}
@@ -124,7 +121,15 @@ impl MessageHandler<FutureMessage, FutureMessageContext> for FutureMessageHandle
fn process_message(&mut self, message: FutureMessage, _responses: &mut VecDeque<Message>, _context: FutureMessageContext) {
match message {
FutureMessage::Await { future } => {
#[cfg(not(test))]
self.spawner.spawn(future.into_future(), self.results_sender.clone(), self.wake.clone());
// For tests, block on the future to ensure the result is available when validating editor state afterwards.
#[cfg(test)]
{
let message = futures::executor::block_on(future.into_future());
_responses.push_back(message);
}
}
FutureMessage::Wake => {
// Tick-only message: the dispatcher's top-of-tick drain handles the real work.
@@ -137,7 +142,7 @@ impl MessageHandler<FutureMessage, FutureMessageContext> for FutureMessageHandle
#[cfg(not(target_family = "wasm"))]
fn default_spawner() -> Arc<dyn MessageSpawner> {
Arc::new(TokioSpawner)
Arc::new(TokioSpawner::default())
}
#[cfg(target_family = "wasm")]
@@ -145,27 +150,37 @@ fn default_spawner() -> Arc<dyn MessageSpawner> {
Arc::new(WasmSpawner)
}
/// Process-global runtime for editor async work. Held in a `LazyLock` so it lives for the lifetime
/// of the process and is never dropped: dropping a `tokio::runtime::Runtime` blocks to join its
/// worker threads, which panics if it happens inside an async context (e.g. a `#[tokio::test]` body
/// or the desktop event loop). A leaked-for-process runtime sidesteps that entirely.
#[cfg(not(target_family = "wasm"))]
static EDITOR_ASYNC_RUNTIME: std::sync::LazyLock<tokio::runtime::Runtime> = std::sync::LazyLock::new(|| {
tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.thread_name("graphite-async")
.enable_all()
.build()
.expect("failed to construct async-message tokio runtime")
});
struct TokioSpawner {
/// Built lazily on first spawn. `multi_thread(1)` lets Tokio manage its own driver.
runtime: std::sync::OnceLock<tokio::runtime::Runtime>,
}
#[cfg(not(target_family = "wasm"))]
struct TokioSpawner;
impl Default for TokioSpawner {
fn default() -> Self {
Self { runtime: std::sync::OnceLock::new() }
}
}
#[cfg(not(target_family = "wasm"))]
impl TokioSpawner {
fn runtime(&self) -> &tokio::runtime::Runtime {
self.runtime.get_or_init(|| {
tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.thread_name("graphite-async")
.enable_all()
.build()
.expect("failed to construct async-message tokio runtime")
})
}
}
#[cfg(not(target_family = "wasm"))]
impl MessageSpawner for TokioSpawner {
fn spawn(&self, future: InnerMessageFuture, results: UnboundedSender<Message>, wake: Wake) {
EDITOR_ASYNC_RUNTIME.spawn(async move {
self.runtime().spawn(async move {
let message = future.await;
let _ = results.unbounded_send(message);
wake();
@@ -7,7 +7,6 @@ use crate::messages::input_mapper::utility_types::macros::*;
use crate::messages::input_mapper::utility_types::misc::MappingEntry;
use crate::messages::input_mapper::utility_types::misc::{KeyMappingEntries, Mapping};
use crate::messages::portfolio::document::node_graph::utility_types::Direction;
use crate::messages::portfolio::document::utility_types::clipboards::Clipboard;
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::messages::prelude::*;
use crate::messages::tool::tool_messages::brush_tool::BrushToolMessageOptionsUpdate;
@@ -224,8 +223,8 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
entry!(KeyDown(Backspace); modifiers=[Accel], action_dispatch=PathToolMessage::DeleteAndBreakPath),
entry!(KeyDown(Delete); modifiers=[Shift], action_dispatch=PathToolMessage::BreakPath),
entry!(KeyDown(Backspace); modifiers=[Shift], action_dispatch=PathToolMessage::BreakPath),
entry!(KeyDown(KeyX); modifiers=[Accel], action_dispatch=PathToolMessage::Cut { clipboard: Clipboard::Device }),
entry!(KeyDown(KeyC); modifiers=[Accel], action_dispatch=PathToolMessage::Copy { clipboard: Clipboard::Device }),
entry!(KeyDown(KeyX); modifiers=[Accel], action_dispatch=PathToolMessage::Cut),
entry!(KeyDown(KeyC); modifiers=[Accel], action_dispatch=PathToolMessage::Copy),
entry!(KeyDown(KeyD); modifiers=[Accel], action_dispatch=PathToolMessage::Duplicate),
entry!(KeyDownNoRepeat(Tab); action_dispatch=PathToolMessage::SwapSelectedHandles),
entry!(KeyDown(MouseLeft); action_dispatch=PathToolMessage::MouseDown { extend_selection: Shift, lasso_select: Control, handle_drag_from_anchor: Alt, drag_restore_handle: Control, segment_editing_modifier: Control }),
@@ -447,8 +446,6 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
entry!(KeyDown(KeyW); modifiers=[Accel, Alt], action_dispatch=PortfolioMessage::CloseAllDocumentsWithConfirmation),
entry!(KeyDown(KeyO); modifiers=[Accel], action_dispatch=PortfolioMessage::Open),
entry!(KeyDown(KeyI); modifiers=[Accel], action_dispatch=PortfolioMessage::Import),
entry!(KeyDown(KeyX); modifiers=[Accel], action_dispatch=PortfolioMessage::Cut { clipboard: Clipboard::Device }),
entry!(KeyDown(KeyC); modifiers=[Accel], action_dispatch=PortfolioMessage::Copy { clipboard: Clipboard::Device }),
entry!(KeyDown(KeyR); modifiers=[Alt], action_dispatch=PortfolioMessage::ToggleRulers),
entry!(KeyDown(KeyD); modifiers=[Alt], action_dispatch=PortfolioMessage::ToggleDataPanelOpen),
entry!(KeyDown(Enter); modifiers=[Alt], action_dispatch=PortfolioMessage::ToggleFocusDocument),
@@ -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)
}
@@ -370,14 +370,25 @@ pub struct WidgetTable {
pub unstyled: bool,
}
/// A collapsible Properties panel section for a single node: a header with its name and pin, delete, and visibility controls, above its input parameter widgets.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct WidgetSection {
/// The node's name shown in the section header: its given alias with the implementation name in parentheses, or just the implementation name.
pub name: String,
/// The node definition's description, shown as the header's tooltip (empty when it has none).
pub description: String,
/// Whether the node is visible rather than hidden (shown as the eye icon).
pub visible: bool,
/// Whether the node is pinned, keeping its section shown in the Properties panel when nothing is selected (shown as the pin icon).
pub pinned: bool,
/// Whether this section can be dragged to reorder it within its layer's chain of nodes (true for a layer chain's nodes, but not its terminal layer node).
pub draggable: bool,
/// Whether this section is expanded to show its contents, as opposed to being collapsed down to just its header.
pub expanded: bool,
/// The ID of the node whose properties this section displays.
pub id: u64,
/// The node's properties content, rendered as the section's body when expanded.
pub layout: Layout,
}
@@ -405,12 +416,14 @@ impl LayoutGroup {
Self::Table(WidgetTable { rows, unstyled })
}
pub fn section(name: impl Into<String>, description: impl Into<String>, visible: bool, pinned: bool, id: u64, layout: Layout) -> Self {
pub fn section(name: impl Into<String>, description: impl Into<String>, visible: bool, pinned: bool, expanded: bool, id: u64, layout: Layout) -> Self {
Self::Section(WidgetSection {
name: name.into(),
description: description.into(),
visible,
pinned,
draggable: false,
expanded,
id,
layout,
})
@@ -507,6 +520,8 @@ impl Diffable for LayoutGroup {
description: current_description,
visible: current_visible,
pinned: current_pinned,
draggable: current_draggable,
expanded: current_expanded,
id: current_id,
layout: current_layout,
}),
@@ -515,6 +530,8 @@ impl Diffable for LayoutGroup {
description: new_description,
visible: new_visible,
pinned: new_pinned,
draggable: new_draggable,
expanded: new_expanded,
id: new_id,
layout: new_layout,
}),
@@ -526,6 +543,8 @@ impl Diffable for LayoutGroup {
|| *current_description != new_description
|| *current_visible != new_visible
|| *current_pinned != new_pinned
|| *current_draggable != new_draggable
|| *current_expanded != new_expanded
|| *current_id != new_id
{
// Update self to reflect new changes
@@ -533,6 +552,8 @@ impl Diffable for LayoutGroup {
current_description.clone_from(&new_description);
*current_visible = new_visible;
*current_pinned = new_pinned;
*current_draggable = new_draggable;
*current_expanded = new_expanded;
*current_id = new_id;
current_layout.clone_from(&new_layout);
@@ -542,6 +563,8 @@ impl Diffable for LayoutGroup {
description: new_description,
visible: new_visible,
pinned: new_pinned,
draggable: new_draggable,
expanded: new_expanded,
id: new_id,
layout: new_layout,
})
@@ -612,6 +612,16 @@ pub enum SpectrumInputUpdate {
DeleteMarker {
index: u32,
},
/// Insert a copy (same color and midpoint) of the marker at `index` at `position`, keeping the marker at `index` active.
InsertDuplicate {
index: u32,
position: f64,
},
/// Remove the marker at `index` while keeping the currently active marker active (renumbered to account for the removal).
/// Used to un-duplicate when Alt is released mid-drag, deleting the frozen copy left by [`InsertDuplicate`](Self::InsertDuplicate).
RemoveDuplicate {
index: u32,
},
/// Emitted when the user double-clicks a marker. The consumer decides what (if anything) to reset the marker to.
ResetMarker {
index: u32,
@@ -17,6 +17,7 @@ pub struct MenuBarMessageHandler {
pub has_selection_history: (bool, bool),
pub message_logging_verbosity: MessageLoggingVerbosity,
pub reset_node_definitions_on_open: bool,
pub show_storage_preferences: bool,
pub make_path_editable_is_allowed: bool,
pub data_panel_open: bool,
pub layers_panel_open: bool,
@@ -50,6 +51,7 @@ impl LayoutHolder for MenuBarMessageHandler {
let message_logging_verbosity_names = self.message_logging_verbosity == MessageLoggingVerbosity::Names;
let message_logging_verbosity_contents = self.message_logging_verbosity == MessageLoggingVerbosity::Contents;
let reset_node_definitions_on_open = self.reset_node_definitions_on_open;
let show_storage_preferences = self.show_storage_preferences;
let make_path_editable_is_allowed = self.make_path_editable_is_allowed;
let about = MenuListEntry::new("About Graphite…")
@@ -718,6 +720,10 @@ impl LayoutHolder for MenuBarMessageHandler {
.label("Reset Nodes to Definitions on Open")
.icon(if reset_node_definitions_on_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
.on_commit(|_| PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen.into()),
MenuListEntry::new("Show Storage Preferences")
.label("Show Storage Preferences")
.icon(if show_storage_preferences { "CheckboxChecked" } else { "CheckboxUnchecked" })
.on_commit(|_| PreferencesMessage::ToggleShowStoragePreferences.into()),
],
vec![
MenuListEntry::new("Print Trace Logs")
@@ -13,7 +13,7 @@ use graphene_std::list::List;
use graphene_std::memo::IORecord;
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::vector::Vector;
use graphene_std::vector::style::{Fill, FillChoice, FillChoiceUI, GradientSpreadMethod, GradientType};
use graphene_std::vector::style::{FillChoice, FillChoiceUI, GradientSpreadMethod, GradientType};
use graphene_std::{Artboard, Color, Context, Graphic};
use std::any::Any;
use std::sync::Arc;
@@ -385,61 +385,7 @@ impl TableItemLayout for Vector {
VectorTableTab::Properties => {
table_rows.push(column_headings(&["property", "value"]));
match self.style.fill.clone() {
Fill::None => table_rows.push(vec![
TextLabel::new("Fill").narrow(true).widget_instance(),
ColorInput::new(FillChoiceUI::None)
.disabled(true)
.menu_direction(Some(MenuDirection::Top))
.narrow(true)
.widget_instance(),
]),
Fill::Solid(color) => table_rows.push(vec![
TextLabel::new("Fill").narrow(true).widget_instance(),
ColorInput::new(FillChoiceUI::from(&FillChoice::Solid(color)))
.disabled(true)
.menu_direction(Some(MenuDirection::Top))
.narrow(true)
.widget_instance(),
]),
Fill::Gradient(gradient) => {
table_rows.push(vec![
TextLabel::new("Fill").narrow(true).widget_instance(),
ColorInput::new(FillChoiceUI::from(&FillChoice::Gradient(gradient.stops)))
.disabled(true)
.menu_direction(Some(MenuDirection::Top))
.narrow(true)
.widget_instance(),
]);
table_rows.push(vec![
TextLabel::new("Fill Gradient Type").narrow(true).widget_instance(),
TextLabel::new(gradient.gradient_type.to_string()).narrow(true).widget_instance(),
]);
table_rows.push(vec![
TextLabel::new("Fill Gradient Start").narrow(true).widget_instance(),
TextLabel::new(format_dvec2(gradient.start)).narrow(true).widget_instance(),
]);
table_rows.push(vec![
TextLabel::new("Fill Gradient End").narrow(true).widget_instance(),
TextLabel::new(format_dvec2(gradient.end)).narrow(true).widget_instance(),
]);
table_rows.push(vec![
TextLabel::new("Fill Gradient Transform").narrow(true).widget_instance(),
TextLabel::new(format_transform_matrix(gradient.transform)).narrow(true).widget_instance(),
]);
}
}
if let Some(stroke) = self.style.stroke.clone() {
let color = if let Some(color) = stroke.color { FillChoice::Solid(color) } else { FillChoice::None };
table_rows.push(vec![
TextLabel::new("Stroke").narrow(true).widget_instance(),
ColorInput::new(FillChoiceUI::from(&color))
.disabled(true)
.menu_direction(Some(MenuDirection::Top))
.narrow(true)
.widget_instance(),
]);
if let Some(stroke) = self.stroke.as_ref() {
table_rows.push(vec![
TextLabel::new("Stroke Weight").narrow(true).widget_instance(),
TextLabel::new(format!("{} px", stroke.weight)).narrow(true).widget_instance(),
@@ -0,0 +1,276 @@
//! Human-readable pretty-printers for the dual-write soak's validation checks: registry-vs-registry and
//! runtime-network-vs-runtime-network diffs. The callers are gated behind the `validate_storage_round_trip`
//! preference, so these ship in release but only run when the soak is turned on.
use std::fmt::Write;
pub(crate) fn diff_registries(stored: &graph_storage::Registry, target: &graph_storage::Registry) -> String {
let mut out = String::new();
let stored_node_ids: std::collections::BTreeSet<_> = stored.node_instances.keys().copied().collect();
let target_node_ids: std::collections::BTreeSet<_> = target.node_instances.keys().copied().collect();
let missing_nodes: Vec<_> = target_node_ids.difference(&stored_node_ids).collect();
let extra_nodes: Vec<_> = stored_node_ids.difference(&target_node_ids).collect();
let shared_node_diffs: Vec<_> = stored_node_ids
.intersection(&target_node_ids)
.filter(|id| !stored.node_instances[id].value_equal(&target.node_instances[id]))
.collect();
let stored_network_ids: std::collections::BTreeSet<_> = stored.networks.keys().copied().collect();
let target_network_ids: std::collections::BTreeSet<_> = target.networks.keys().copied().collect();
let missing_networks: Vec<_> = target_network_ids.difference(&stored_network_ids).collect();
let extra_networks: Vec<_> = stored_network_ids.difference(&target_network_ids).collect();
let shared_network_diffs: Vec<_> = stored_network_ids
.intersection(&target_network_ids)
.filter(|id| !stored.networks[id].value_equal(&target.networks[id]))
.collect();
let _ = writeln!(out, " nodes: stored={} target={}", stored_node_ids.len(), target_node_ids.len());
if !missing_nodes.is_empty() {
let _ = writeln!(out, " missing from stored: {missing_nodes:?}");
}
if !extra_nodes.is_empty() {
let _ = writeln!(out, " extra in stored: {extra_nodes:?}");
}
if !shared_node_diffs.is_empty() {
let _ = writeln!(out, " differing payloads: {shared_node_diffs:?}");
for id in &shared_node_diffs {
let stored_node = &stored.node_instances[id];
let target_node = &target.node_instances[id];
let _ = writeln!(out, " node {id}:");
diff_node(&mut out, stored_node, target_node);
}
}
let _ = writeln!(out, " networks: stored={} target={}", stored_network_ids.len(), target_network_ids.len());
if !missing_networks.is_empty() {
let _ = writeln!(out, " missing from stored: {missing_networks:?}");
}
if !extra_networks.is_empty() {
let _ = writeln!(out, " extra in stored: {extra_networks:?}");
}
if !shared_network_diffs.is_empty() {
let _ = writeln!(out, " differing payloads: {shared_network_diffs:?}");
for id in &shared_network_diffs {
let stored_network = &stored.networks[id];
let target_network = &target.networks[id];
let _ = writeln!(out, " network {id}:");
diff_network(&mut out, stored_network, target_network);
}
}
let stored_resources: std::collections::BTreeSet<_> = stored.resources.keys().copied().collect();
let target_resources: std::collections::BTreeSet<_> = target.resources.keys().copied().collect();
let missing_resources: Vec<_> = target_resources.difference(&stored_resources).collect();
let extra_resources: Vec<_> = stored_resources.difference(&target_resources).collect();
let shared_resource_diffs: Vec<_> = stored_resources
.intersection(&target_resources)
.filter(|id| !resource_value_equal(&stored.resources[id], &target.resources[id]))
.collect();
if !missing_resources.is_empty() || !extra_resources.is_empty() || !shared_resource_diffs.is_empty() {
let _ = writeln!(out, " resources: stored={} target={}", stored_resources.len(), target_resources.len());
if !missing_resources.is_empty() {
let _ = writeln!(out, " missing from stored: {missing_resources:?}");
}
if !extra_resources.is_empty() {
let _ = writeln!(out, " extra in stored: {extra_resources:?}");
}
if !shared_resource_diffs.is_empty() {
let _ = writeln!(out, " differing payloads: {shared_resource_diffs:?}");
for id in &shared_resource_diffs {
let _ = writeln!(out, " resource {id}:");
diff_resource(&mut out, &stored.resources[id], &target.resources[id]);
}
}
}
if stored.attributes != target.attributes {
diff_attributes(&mut out, " document attributes", &stored.attributes, &target.attributes);
}
out
}
fn diff_node(out: &mut String, stored: &graph_storage::Node, target: &graph_storage::Node) {
if stored.implementation() != target.implementation() {
let _ = writeln!(out, " implementation: stored={:?} target={:?}", stored.implementation(), target.implementation());
}
if stored.network() != target.network() {
let _ = writeln!(out, " network back-pointer: stored={} target={}", stored.network(), target.network());
}
let stored_inputs = stored.inputs();
let target_inputs = target.inputs();
if stored_inputs.len() != target_inputs.len() {
let _ = writeln!(out, " inputs.len: stored={} target={}", stored_inputs.len(), target_inputs.len());
}
for (i, (s, t)) in stored_inputs.iter().zip(target_inputs.iter()).enumerate() {
if s != t {
let value_differs = s.input != t.input;
let timestamp_differs = s.timestamp != t.timestamp;
let _ = writeln!(out, " input[{i}]: value_differs={value_differs} timestamp_differs={timestamp_differs}");
if value_differs {
let _ = writeln!(out, " stored.value={:?}\n target.value={:?}", s.input, t.input);
}
if s.attributes != t.attributes {
diff_attributes(out, &format!(" input[{i}].attributes"), &s.attributes, &t.attributes);
}
}
}
if stored.attributes() != target.attributes() {
diff_attributes(out, " attributes", stored.attributes(), target.attributes());
}
}
fn diff_network(out: &mut String, stored: &graph_storage::Network, target: &graph_storage::Network) {
if stored.exports.len() != target.exports.len() {
let _ = writeln!(out, " exports.len: stored={} target={}", stored.exports.len(), target.exports.len());
}
for (i, (s, t)) in stored.exports.iter().zip(target.exports.iter()).enumerate() {
if s != t {
let target_differs = s.target != t.target;
let timestamp_differs = s.timestamp != t.timestamp;
let _ = writeln!(out, " export[{i}]: target_differs={target_differs} timestamp_differs={timestamp_differs}");
if target_differs {
let _ = writeln!(out, " stored.target={:?}\n target.target={:?}", s.target, t.target);
}
}
}
if stored.attributes != target.attributes {
diff_attributes(out, " attributes", &stored.attributes, &target.attributes);
}
}
/// Value-level resource comparison (same resolved hash, same source bodies keyed by `SourceKey`),
/// ignoring LWW timestamps. Mirrors `graph_storage`'s internal `resources_value_equal` for a single
/// entry, since that helper is crate-private and only operates over a whole store.
fn resource_value_equal(stored: &graph_storage::ResourceEntry, target: &graph_storage::ResourceEntry) -> bool {
stored.hash == target.hash && stored.sources.len() == target.sources.len() && stored.sources.iter().all(|(key, value)| target.source(key).is_some_and(|other| value.source == other.source))
}
fn diff_resource(out: &mut String, stored: &graph_storage::ResourceEntry, target: &graph_storage::ResourceEntry) {
if stored.hash != target.hash {
let _ = writeln!(out, " hash: stored={:?} target={:?}", stored.hash, target.hash);
}
if stored.sources.len() != target.sources.len() {
let _ = writeln!(out, " sources.len: stored={} target={}", stored.sources.len(), target.sources.len());
}
// Report source bodies that drift for a shared key, plus keys present on only one side.
for (key, value) in &stored.sources {
match target.source(key) {
Some(other) if other.source != value.source => {
let _ = writeln!(out, " source[{key:?}]: stored={:?} target={:?}", value.source, other.source);
}
None => {
let _ = writeln!(out, " source[{key:?}]: only in stored");
}
Some(_) => {}
}
}
for (key, _) in &target.sources {
if stored.source(key).is_none() {
let _ = writeln!(out, " source[{key:?}]: only in target");
}
}
}
fn diff_attributes(out: &mut String, label: &str, stored: &graph_storage::Attributes, target: &graph_storage::Attributes) {
let stored_keys: std::collections::BTreeSet<_> = stored.keys().collect();
let target_keys: std::collections::BTreeSet<_> = target.keys().collect();
let missing: Vec<_> = target_keys.difference(&stored_keys).collect();
let extra: Vec<_> = stored_keys.difference(&target_keys).collect();
// Split value drift from timestamp-only drift: each attribute carries an LWW timestamp, so comparing
// whole records would flag equal-value entries that merely differ in when they were last set.
let (differing_values, differing_timestamps): (Vec<_>, Vec<_>) = stored_keys
.intersection(&target_keys)
.copied()
.filter(|k| stored.get(*k) != target.get(*k))
.partition(|k| stored.get(*k).map(|v| &v.value) != target.get(*k).map(|v| &v.value));
let _ = writeln!(
out,
"{label}: missing_from_stored={missing:?} extra_in_stored={extra:?} differing_values={differing_values:?} differing_timestamps={differing_timestamps:?}"
);
}
/// Human-readable summary of how two networks differ (exports, node set, per-node payloads, scope injections).
pub(crate) fn diff_networks(expected: &graph_craft::document::NodeNetwork, actual: &graph_craft::document::NodeNetwork) -> String {
let mut out = String::new();
if expected.exports != actual.exports {
let _ = writeln!(out, " exports differ: expected={} actual={}", expected.exports.len(), actual.exports.len());
for (i, (exp, act)) in expected.exports.iter().zip(actual.exports.iter()).enumerate() {
if exp != act {
let _ = writeln!(out, " [{i}] expected={exp:?}\n actual= {act:?}");
}
}
}
let expected_ids: std::collections::BTreeSet<_> = expected.nodes.keys().copied().collect();
let actual_ids: std::collections::BTreeSet<_> = actual.nodes.keys().copied().collect();
let missing: Vec<_> = expected_ids.difference(&actual_ids).collect();
let extra: Vec<_> = actual_ids.difference(&expected_ids).collect();
let differing: Vec<_> = expected_ids.intersection(&actual_ids).filter(|id| expected.nodes.get(id) != actual.nodes.get(id)).collect();
if !missing.is_empty() || !extra.is_empty() || !differing.is_empty() {
let _ = writeln!(out, " nodes: expected={} actual={}", expected_ids.len(), actual_ids.len());
if !missing.is_empty() {
let _ = writeln!(out, " missing from actual: {missing:?}");
}
if !extra.is_empty() {
let _ = writeln!(out, " extra in actual: {extra:?}");
}
if !differing.is_empty() {
let _ = writeln!(out, " differing payloads: {differing:?}");
for id in &differing {
if let (Some(exp), Some(act)) = (expected.nodes.get(id), actual.nodes.get(id)) {
let _ = writeln!(out, " node {id}:");
diff_document_node(&mut out, exp, act);
}
}
}
}
if expected.scope_injections != actual.scope_injections {
let _ = writeln!(out, " scope_injections differ");
}
out
}
/// Field-level diff between two runtime `DocumentNode`s with the same ID, so the compare-on-open log
/// names *which* field diverged rather than just the node ID. `original_location` is `#[serde(skip)]`
/// and recomputed at load, so it's a likely culprit for a payload mismatch that doesn't affect behavior.
fn diff_document_node(out: &mut String, expected: &graph_craft::document::DocumentNode, actual: &graph_craft::document::DocumentNode) {
if expected.inputs != actual.inputs {
let _ = writeln!(out, " inputs differ (len expected={} actual={})", expected.inputs.len(), actual.inputs.len());
for (i, (e, a)) in expected.inputs.iter().zip(actual.inputs.iter()).enumerate() {
if e != a {
let _ = writeln!(out, " input[{i}]: expected={e:?}\n actual= {a:?}");
}
}
}
if expected.call_argument != actual.call_argument {
let _ = writeln!(out, " call_argument: expected={:?} actual={:?}", expected.call_argument, actual.call_argument);
}
if expected.implementation != actual.implementation {
let _ = writeln!(out, " implementation: expected={:?} actual={:?}", expected.implementation, actual.implementation);
}
if expected.visible != actual.visible {
let _ = writeln!(out, " visible: expected={} actual={}", expected.visible, actual.visible);
}
if expected.skip_deduplication != actual.skip_deduplication {
let _ = writeln!(out, " skip_deduplication: expected={} actual={}", expected.skip_deduplication, actual.skip_deduplication);
}
if expected.context_features != actual.context_features {
let _ = writeln!(out, " context_features: expected={:?} actual={:?}", expected.context_features, actual.context_features);
}
if expected.original_location != actual.original_location {
let _ = writeln!(out, " original_location differs (recomputed at load, not stored):");
let _ = writeln!(out, " expected={:?}\n actual= {:?}", expected.original_location, actual.original_location);
}
}
@@ -0,0 +1,267 @@
use std::collections::VecDeque;
use std::collections::{BTreeMap, HashSet};
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry, ResourceStorage};
use graph_storage::Registry;
use super::utility_types::network_interface::NodeNetworkInterface;
use super::utility_types::network_interface::storage_metadata::{StorageMetadataView, collect_network_view_settings};
/// Per-document undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor that is
/// becoming the authoritative history. Owns the dual-stack bookkeeping push/pop/clear and the cursor's stage/retire/move/verify
/// lifecycle, so the handler drives history through one surface rather than three loose fields.
///
/// Not serialized: the legacy stacks are runtime-only, and a clone shares the working-copy container by
/// `Arc`, so it keeps reading the live working copy.
#[derive(derivative::Derivative)]
#[derivative(Clone, Debug, Default)]
pub struct DocumentHistory {
/// Stack of document network snapshots for previous history states.
lagacy_undo_stack: VecDeque<NodeNetworkInterface>,
/// Stack of document network snapshots for future history states.
lagacy_redo_stack: VecDeque<NodeNetworkInterface>,
/// The `Gdd` working copy: owns the CRDT `Session` and mirrors edits to disk. `None` until the mount
/// future built by `load_document` resolves.
#[derivative(Debug = "ignore")]
storage: Option<document_format::GddV1>,
}
impl DocumentHistory {
// ===== Legacy snapshot stacks =====
/// Push a snapshot onto the undo stack, evicting the oldest entry past the history cap.
pub fn push_undo(&mut self, snapshot: NodeNetworkInterface) {
Self::push_capped(&mut self.lagacy_undo_stack, snapshot);
}
/// Push a snapshot onto the redo stack, evicting the oldest entry past the history cap.
pub fn push_redo(&mut self, snapshot: NodeNetworkInterface) {
Self::push_capped(&mut self.lagacy_redo_stack, snapshot);
}
/// Pop the most recent undo snapshot, or `None` when the stack is empty.
pub fn pop_undo(&mut self) -> Option<NodeNetworkInterface> {
self.lagacy_undo_stack.pop_back()
}
/// Pop the most recent redo snapshot, or `None` when the stack is empty.
pub fn pop_redo(&mut self) -> Option<NodeNetworkInterface> {
self.lagacy_redo_stack.pop_back()
}
/// Drop the most recently pushed undo snapshot (used to cancel a transaction that ended up unmodified).
pub fn discard_last_undo(&mut self) {
self.lagacy_undo_stack.pop_back();
}
/// Clear the redo stack, called when a fresh edit invalidates the redo future.
pub fn clear_redo(&mut self) {
self.lagacy_redo_stack.clear();
}
/// Add the resources referenced by every snapshot in both history stacks into `resources`, so
/// history-only resources stay alive for legacy undo/redo.
pub fn collect_used_resources(&self, resources: &mut HashSet<ResourceId>) {
for interface in self.lagacy_undo_stack.iter().chain(&self.lagacy_redo_stack) {
interface.collect_used_resources(resources);
}
}
// ===== Gdd working-copy cursor =====
/// The `Gdd` working copy, `None` until the mount future resolves.
pub fn storage(&self) -> Option<&document_format::GddV1> {
self.storage.as_ref()
}
/// Mutable access to the `Gdd` working copy.
pub fn storage_mut(&mut self) -> Option<&mut document_format::GddV1> {
self.storage.as_mut()
}
/// Attach (or clear) the `Gdd` working copy once the mount future resolves.
pub fn set_storage(&mut self, storage: Option<document_format::GddV1>) {
self.storage = storage;
}
/// Retire the pending staged hot ops into durable Gdd history as one undo unit. Called at each undo-step
/// boundary (a new `StartTransaction`) and before undo/redo, so the per-`CommitTransaction` staging
/// coalesces into one interaction aligned with the legacy step. No-op while unmounted.
pub fn retire_storage_interaction(&mut self) {
let Some(storage) = self.storage.as_mut() else { return };
if let Err(error) = storage.retire_pending_interaction() {
log::error!("Storage interaction retirement failed: {error}");
}
}
/// Stage the runtime snapshot into the `Gdd` working copy at each `CommitTransaction`. No-op while
/// unmounted. Proto-node declaration bytes go into `byte_store` (the app-global resource cache). The
/// staged hot ops are retired by [`retire_storage_interaction`](Self::retire_storage_interaction) at
/// undo-step boundaries. `validate` (the `validate_storage_round_trip` preference) gates the per-commit
/// round-trip check, off by default for its perf cost.
pub fn stage_snapshot(
&mut self,
interface: &NodeNetworkInterface,
registry: &ResourceRegistry,
view_settings: BTreeMap<String, serde_json::Value>,
legacy_document: &str,
byte_store: &dyn ResourceStorage,
) {
let Some(storage) = self.storage.as_mut() else { return };
let network = interface.document_network();
let metadata_view = StorageMetadataView::new(interface);
let network_view_settings = storage
.network_ids(network, &metadata_view)
.ok()
.map(|network_ids| collect_network_view_settings(interface, &network_ids));
// Stage without retiring: a tool drag fires several `CommitTransaction`s but is one legacy undo
// step, so the deltas accumulate as hot ops and coalesce at the next undo-step boundary.
if let Err(error) = storage.stage_runtime_snapshot(network, &metadata_view, registry, byte_store) {
log::error!("Storage snapshot staging failed: {error}");
return;
}
if let Err(error) = storage.set_view_settings(view_settings) {
log::error!("Persisting view settings failed: {error}");
}
if let Some(network_view_settings) = network_view_settings
&& let Err(error) = storage.set_network_view_settings(network_view_settings)
{
log::error!("Persisting per-network view settings failed: {error}");
}
// Dual-write soak: embed the legacy `.graphite` bytes so the new format
// can be validated against (and recovered from) the old one on open.
if let Err(error) = storage.store_legacy_document(legacy_document.as_bytes()) {
log::error!("Embedding legacy document into working copy failed: {error}");
}
}
/// Move the `Gdd` undo/redo cursor along the retired interaction chain, flushing any open interaction
/// first. Returns a clone of the post-move `Gdd` (`Arc`-shared) so a `'static` rebuild future can read
/// the rewound state while the live document keeps its cursor. `None` when there is nothing to move to,
/// unmounted, or the move failed.
pub fn move_cursor(&mut self, undo: bool) -> Option<document_format::GddV1> {
self.retire_storage_interaction();
let storage = self.storage.as_mut()?;
let moved = if undo {
if !storage.can_undo() {
return None;
}
storage.undo().map(|_| ())
} else {
if !storage.can_redo() {
return None;
}
storage.redo().map(|_| ())
};
if let Err(error) = moved {
log::error!("Storage undo/redo cursor move failed: {error}");
return None;
}
Some(storage.clone())
}
// Soak round-trip verification (runtime-gated by `validate_storage_round_trip`)
// These log drift rather than panicking, since the soak can run in release where a crash is
// unacceptable; tests still fail loud via the `#[cfg(test)]` panics.
/// Soak check: the stored registry should equal a fresh `from_runtime`, and a `to_runtime` of it should
/// equal the original network.
pub fn verify_round_trip(&self, interface: &NodeNetworkInterface, registry: &ResourceRegistry) {
use super::diff_networks;
use super::document_diff::diff_registries;
let Some(storage) = &self.storage else { return };
let peer = storage.session().peer();
let network = interface.document_network();
let metadata_view = StorageMetadataView::new(interface);
let conversion = match Registry::convert_from_runtime(network, &metadata_view, registry, peer) {
Ok(conversion) => conversion,
Err(error) => {
log::error!("storage round-trip: from_runtime failed: {error}");
return;
}
};
let target = &conversion.registry;
let declarations = match conversion.declarations() {
Ok(declarations) => declarations,
Err(error) => {
log::error!("storage round-trip: declaration rebuild failed: {error}");
return;
}
};
let stored = storage.registry();
if !stored.value_equal(target) {
log::error!("storage round-trip: registry value drift after commit\n{}", diff_registries(stored, target));
#[cfg(test)]
panic!("storage round-trip: registry value drift after commit");
}
if !stored.order_consistent(target) {
log::error!("storage round-trip: timestamp order inconsistent between stored and target");
#[cfg(test)]
panic!("storage round-trip: timestamp order inconsistent between stored and target");
}
let (round_tripped, _entries) = match stored.to_runtime_with_metadata(&declarations) {
Ok(result) => result,
Err(error) => {
log::error!("storage round-trip: to_runtime failed: {error}");
return;
}
};
if &round_tripped != network {
log::error!("storage round-trip: network drift after to_runtime\n{}", diff_networks(network, &round_tripped));
#[cfg(test)]
panic!("storage round-trip: network drift after to_runtime");
}
}
/// Soak check: after a cursor move, the cursor's registry should equal a fresh `from_runtime` of the
/// current (legacy-restored) interface. `current_resources` are the resources the live network
/// references; history-only resources the cursor dropped are expected, not drift.
pub fn verify_cursor_matches_runtime(&self, interface: &NodeNetworkInterface, registry: &ResourceRegistry, current_resources: &HashSet<ResourceId>) {
use super::document_diff::diff_registries;
let Some(storage) = &self.storage else { return };
let peer = storage.session().peer();
let network = interface.document_network();
let metadata_view = StorageMetadataView::new(interface);
let Ok(mut conversion) = Registry::convert_from_runtime(network, &metadata_view, registry, peer) else {
log::error!("undo/redo shadow: from_runtime failed");
return;
};
let stored = storage.registry();
// The cursor reverts the interaction's `AddResource` while the runtime keeps the resource alive for
// legacy redo, so a history-only resource the cursor dropped is expected. Drop those before comparing.
conversion.registry.resources.retain(|id, _| stored.resources.contains_key(id) || current_resources.contains(id));
if !stored.value_equal(&conversion.registry) {
log::error!(
"undo/redo shadow: cursor registry diverged from the restored interface\n{}",
diff_registries(stored, &conversion.registry)
);
}
}
fn push_capped(stack: &mut VecDeque<NodeNetworkInterface>, snapshot: NodeNetworkInterface) {
stack.push_back(snapshot);
if stack.len() > crate::consts::MAX_UNDO_HISTORY_LEN {
stack.pop_front();
}
}
}
@@ -103,6 +103,10 @@ pub enum DocumentMessage {
parent: LayerNodeIdentifier,
insert_index: usize,
},
ReorderPropertiesSection {
node_id: NodeId,
insert_index: usize,
},
MoveSelectedLayersToGroup {
parent: LayerNodeIdentifier,
},
@@ -112,7 +116,7 @@ pub enum DocumentMessage {
resize: Key,
resize_opposite: Key,
},
PasteImage {
InsertImage {
name: Option<String>,
image: Image<Color>,
mouse: Option<(f64, f64)>,
@@ -121,7 +125,7 @@ pub enum DocumentMessage {
/// can wrap it without a content Transform node. When false, place at the cursor or viewport center.
place_at_origin: bool,
},
PasteSvg {
InsertSvg {
name: Option<String>,
svg: String,
mouse: Option<(f64, f64)>,
@@ -212,6 +216,9 @@ pub enum DocumentMessage {
tree_path: Vec<NodeId>,
recursive: bool,
},
ToggleNodePropertiesSectionExpanded {
node_id: NodeId,
},
ToggleSelectedVisibility,
ToggleSelectedLocked,
ToggleGridVisibility,
@@ -225,8 +232,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>>>,
},
File diff suppressed because it is too large. Load diff
@@ -10,15 +10,22 @@ use graphene_std::raster::BlendMode;
use graphene_std::raster_types::Image;
use graphene_std::subpath::Subpath;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::style::{Fill, GradientSpreadMethod, GradientType, Stroke};
use graphene_std::vector::style::{GradientSpreadMethod, GradientType, Stroke};
use graphene_std::vector::{GradientStops, PointId, VectorModificationType};
#[impl_message(Message, DocumentMessage, GraphOperation)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum GraphOperationMessage {
FillSet {
FillColorSet {
layer: LayerNodeIdentifier,
fill: Fill,
color: Option<Color>,
},
FillGradientSet {
layer: LayerNodeIdentifier,
gradient: GradientStops,
gradient_type: GradientType,
spread_method: GradientSpreadMethod,
transform: DAffine2,
},
BlendingFillSet {
layer: LayerNodeIdentifier,
@@ -28,10 +35,9 @@ pub enum GraphOperationMessage {
layer: LayerNodeIdentifier,
stops: GradientStops,
},
GradientLineSet {
GradientTransformSet {
layer: LayerNodeIdentifier,
start: DVec2,
end: DVec2,
transform: DAffine2,
},
GradientTypeSet {
layer: LayerNodeIdentifier,
@@ -54,6 +60,7 @@ pub enum GraphOperationMessage {
},
StrokeSet {
layer: LayerNodeIdentifier,
color: Option<Color>,
stroke: Stroke,
},
TransformChange {
@@ -13,7 +13,7 @@ use graph_craft::document::{NodeId, NodeInput};
use graphene_std::list::List;
use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::style::{Fill, Gradient, GradientSpreadMethod, GradientStop, GradientStops, GradientType, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::style::{GradientSpreadMethod, GradientStop, GradientStops, GradientType, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::{Artboard, Color};
#[derive(ExtractField)]
@@ -34,9 +34,20 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
let GraphOperationMessageContext { network_interface, .. } = context;
match message {
GraphOperationMessage::FillSet { layer, fill } => {
GraphOperationMessage::FillColorSet { layer, color } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.fill_set(fill);
modify_inputs.fill_color_set(color);
}
}
GraphOperationMessage::FillGradientSet {
layer,
gradient,
gradient_type,
spread_method,
transform,
} => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.fill_gradient_set(gradient, gradient_type, spread_method, transform);
}
}
GraphOperationMessage::BlendingFillSet { layer, fill } => {
@@ -49,9 +60,9 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
modify_inputs.gradient_stops_set(stops);
}
}
GraphOperationMessage::GradientLineSet { layer, start, end } => {
GraphOperationMessage::GradientTransformSet { layer, transform } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.gradient_line_set(start, end);
modify_inputs.gradient_transform_set(transform);
}
}
GraphOperationMessage::GradientTypeSet { layer, gradient_type } => {
@@ -80,9 +91,9 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
modify_inputs.clip_mode_toggle(clip_mode);
}
}
GraphOperationMessage::StrokeSet { layer, stroke } => {
GraphOperationMessage::StrokeSet { layer, color, stroke } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.stroke_set(stroke);
modify_inputs.stroke_set(color, stroke);
}
}
GraphOperationMessage::TransformChange {
@@ -622,7 +633,7 @@ fn import_usvg_node(
usvg::Node::Text(text) => {
let font = Font::new(graphene_std::consts::DEFAULT_FONT_FAMILY.to_string(), graphene_std::consts::DEFAULT_FONT_STYLE.to_string());
modify_inputs.insert_text(text.chunks().iter().map(|chunk| chunk.text()).collect(), font, TypesettingConfig::default(), layer);
modify_inputs.fill_set(Fill::Solid(Color::BLACK));
modify_inputs.fill_color_set(Some(Color::BLACK));
}
}
}
@@ -674,7 +685,7 @@ fn import_usvg_node_inner(
usvg::Node::Text(text) => {
let font = Font::new(graphene_std::consts::DEFAULT_FONT_FAMILY.to_string(), graphene_std::consts::DEFAULT_FONT_STYLE.to_string());
modify_inputs.insert_text(text.chunks().iter().map(|chunk| chunk.text()).collect(), font, TypesettingConfig::default(), layer);
modify_inputs.fill_set(Fill::Solid(Color::BLACK));
modify_inputs.fill_color_set(Some(Color::BLACK));
0
}
}
@@ -762,27 +773,29 @@ fn set_import_child_positions(
fn apply_usvg_stroke(stroke: &usvg::Stroke, modify_inputs: &mut ModifyInputsContext, transform: DAffine2) {
if let usvg::Paint::Color(color) = &stroke.paint() {
modify_inputs.stroke_set(Stroke {
color: Some(usvg_color(*color, stroke.opacity().get())),
weight: stroke.width().get() as f64,
dash_lengths: stroke.dasharray().as_ref().map(|lengths| lengths.iter().map(|&length| length as f64).collect()).unwrap_or_default(),
dash_offset: stroke.dashoffset() as f64,
cap: match stroke.linecap() {
usvg::LineCap::Butt => StrokeCap::Butt,
usvg::LineCap::Round => StrokeCap::Round,
usvg::LineCap::Square => StrokeCap::Square,
modify_inputs.stroke_set(
Some(usvg_color(*color, stroke.opacity().get())),
Stroke {
weight: stroke.width().get() as f64,
dash_lengths: stroke.dasharray().as_ref().map(|lengths| lengths.iter().map(|&length| length as f64).collect()).unwrap_or_default(),
dash_offset: stroke.dashoffset() as f64,
cap: match stroke.linecap() {
usvg::LineCap::Butt => StrokeCap::Butt,
usvg::LineCap::Round => StrokeCap::Round,
usvg::LineCap::Square => StrokeCap::Square,
},
join: match stroke.linejoin() {
usvg::LineJoin::Miter => StrokeJoin::Miter,
usvg::LineJoin::MiterClip => StrokeJoin::Miter,
usvg::LineJoin::Round => StrokeJoin::Round,
usvg::LineJoin::Bevel => StrokeJoin::Bevel,
},
join_miter_limit: stroke.miterlimit().get() as f64,
align: StrokeAlign::Center,
paint_order: PaintOrder::StrokeAbove,
transform,
},
join: match stroke.linejoin() {
usvg::LineJoin::Miter => StrokeJoin::Miter,
usvg::LineJoin::MiterClip => StrokeJoin::Miter,
usvg::LineJoin::Round => StrokeJoin::Round,
usvg::LineJoin::Bevel => StrokeJoin::Bevel,
},
join_miter_limit: stroke.miterlimit().get() as f64,
align: StrokeAlign::Center,
paint_order: PaintOrder::StrokeAbove,
transform,
})
)
}
}
@@ -795,16 +808,18 @@ fn convert_spread_method(spread_method: usvg::SpreadMethod) -> GradientSpreadMet
}
fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, graphite_gradient_stops: &HashMap<String, GradientStops>) {
modify_inputs.fill_set(match &fill.paint() {
usvg::Paint::Color(color) => Fill::solid(usvg_color(*color, fill.opacity().get())),
match &fill.paint() {
usvg::Paint::Color(color) => modify_inputs.fill_color_set(Some(usvg_color(*color, fill.opacity().get()))),
usvg::Paint::LinearGradient(linear) => {
let gradient_transform = usvg_transform(linear.transform());
let (start, end) = (DVec2::new(linear.x1() as f64, linear.y1() as f64), DVec2::new(linear.x2() as f64, linear.y2() as f64));
let (start, end) = (gradient_transform.transform_point2(start), gradient_transform.transform_point2(end));
let direction = end - start;
let transform = DAffine2::from_cols(direction, direction.perp(), start);
let gradient_type = GradientType::Linear;
let stops = match graphite_gradient_stops.get(linear.id()) {
let gradient = match graphite_gradient_stops.get(linear.id()) {
Some(graphite_stops) => graphite_stops.clone(),
None => {
let stops = linear.stops().iter().map(|stop| GradientStop {
@@ -816,27 +831,19 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
}
};
let spread_method = convert_spread_method(linear.spread_method());
Fill::Gradient(Gradient {
start,
end,
gradient_type,
stops,
spread_method,
// TODO: Eventually remove this document upgrade code
absolute: true,
transform: DAffine2::IDENTITY,
})
modify_inputs.fill_gradient_set(gradient, gradient_type, spread_method, transform);
}
usvg::Paint::RadialGradient(radial) => {
let gradient_transform = usvg_transform(radial.transform());
let center = DVec2::new(radial.cx() as f64, radial.cy() as f64);
let edge = center + DVec2::X * radial.r().get() as f64;
let (start, end) = (gradient_transform.transform_point2(center), gradient_transform.transform_point2(edge));
let direction = end - start;
let transform = DAffine2::from_cols(direction, direction.perp(), start);
let gradient_type = GradientType::Radial;
let stops = match graphite_gradient_stops.get(radial.id()) {
let gradient = match graphite_gradient_stops.get(radial.id()) {
Some(graphite_stops) => graphite_stops.clone(),
None => {
let stops = radial.stops().iter().map(|stop| GradientStop {
@@ -849,20 +856,8 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
};
let spread_method = convert_spread_method(radial.spread_method());
Fill::Gradient(Gradient {
start,
end,
gradient_type,
stops,
spread_method,
// TODO: Eventually remove this document upgrade code
absolute: true,
transform: DAffine2::IDENTITY,
})
modify_inputs.fill_gradient_set(gradient, gradient_type, spread_method, transform);
}
usvg::Paint::Pattern(_) => {
warn!("SVG patterns are not currently supported");
return;
}
});
usvg::Paint::Pattern(_) => warn!("SVG patterns are not currently supported"),
};
}
@@ -4,7 +4,7 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, OutputConnector};
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::{get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input};
use glam::{DAffine2, DVec2};
use glam::{DAffine2, DVec2, IVec2};
use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
@@ -15,7 +15,7 @@ use graphene_std::raster::BlendMode;
use graphene_std::raster_types::Image;
use graphene_std::subpath::Subpath;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::style::{Fill, GradientSpreadMethod, GradientType, Stroke};
use graphene_std::vector::style::{GradientSpreadMethod, GradientType, Stroke};
use graphene_std::vector::{GradientStops, PointId, Vector, VectorModification, VectorModificationType};
use graphene_std::{Artboard, Color, Graphic, NodeInputDecleration};
@@ -453,30 +453,59 @@ impl<'a> ModifyInputsContext<'a> {
Some(node_id)
}
pub fn fill_set(&mut self, fill: Fill) {
let fill_index = 1;
let backup_color_index = 2;
let backup_gradient_index = 3;
pub fn fill_color_set(&mut self, color: Option<Color>) {
let Some(fill_node_id) = self.existing_proto_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true) else {
return;
};
match &fill {
Fill::None => {
let input_connector = InputConnector::node(fill_node_id, backup_color_index);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(None), false), true);
}
Fill::Solid(color) => {
let input_connector = InputConnector::node(fill_node_id, backup_color_index);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(Some(*color)), false), true);
}
Fill::Gradient(gradient) => {
let input_connector = InputConnector::node(fill_node_id, backup_gradient_index);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::FillGradient(gradient.clone()), false), true);
}
let input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX);
let backup_input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::BackupColorInput::INDEX);
self.set_input_with_refresh(backup_input_connector, NodeInput::value(TaggedValue::Color(color), false), true);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(color), false), false);
}
pub fn fill_gradient_set(&mut self, gradient: GradientStops, gradient_type: GradientType, spread_method: GradientSpreadMethod, transform: DAffine2) {
let Some(fill_node_id) = self.existing_proto_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true) else {
return;
};
let backup_input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::BackupGradientInput::INDEX);
self.set_input_with_refresh(backup_input_connector, NodeInput::value(TaggedValue::Gradient(gradient.clone()), false), true);
// Skip the rerender on all but the last input so the whole update triggers a single graph run
self.set_input_with_refresh(
InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX),
NodeInput::value(TaggedValue::Gradient(gradient), false),
true,
);
// Reposition the gradient only when the transform is a plain value, leaving a wired transform source connected
let transform_is_value = self
.network_interface
.document_network()
.nodes
.get(&fill_node_id)
.and_then(|node| node.inputs.get(graphene_std::vector::fill::TransformInput::INDEX))
.is_some_and(|input| input.as_value().is_some());
if transform_is_value {
self.set_input_with_refresh(
InputConnector::node(fill_node_id, graphene_std::vector::fill::TransformInput::INDEX),
NodeInput::value(TaggedValue::OptionalDAffine2(Some(transform)), false),
true,
);
}
let input_connector = InputConnector::node(fill_node_id, fill_index);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Fill(fill), false), false);
self.set_input_with_refresh(
InputConnector::node(fill_node_id, graphene_std::vector::fill::GradientTypeInput::INDEX),
NodeInput::value(TaggedValue::GradientType(gradient_type), false),
true,
);
self.set_input_with_refresh(
InputConnector::node(fill_node_id, graphene_std::vector::fill::SpreadMethodInput::INDEX),
NodeInput::value(TaggedValue::GradientSpreadMethod(spread_method), false),
false,
);
}
pub fn blend_mode_set(&mut self, blend_mode: BlendMode) {
@@ -536,18 +565,52 @@ impl<'a> ModifyInputsContext<'a> {
/// Write the gradient stops to the 'Gradient Value' node feeding the layer.
pub fn gradient_stops_set(&mut self, stops: GradientStops) {
let Some(output_layer) = self.get_output_layer() else { return };
let Some(gradient_value_id) = get_upstream_gradient_value_node_id(output_layer, self.network_interface) else {
return;
let gradient_value_id = match get_upstream_gradient_value_node_id(output_layer, self.network_interface) {
Some(id) => id,
None => {
let target = gradient_chain_target_input(output_layer, self.network_interface);
let starts_layer_chain = target == InputConnector::node(output_layer.to_node(), 1);
// The Gradient Value node discards its primary input, so starting a chain ahead of existing layer content would drop that content; refuse instead
if starts_layer_chain && self.network_interface.upstream_output_connector(&target, &[]).is_some() {
log::error!("Refusing to start a gradient chain ahead of existing layer content");
return;
}
let Some(node_definition) = resolve_proto_node_type(graphene_std::math_nodes::gradient_value::IDENTIFIER) else {
return;
};
let node_id = NodeId::new();
self.network_interface.insert_node(node_id, node_definition.default_node_template(), &[]);
if starts_layer_chain {
// No Fill node: the new node starts the layer's chain
self.network_interface.move_node_to_chain_start(&node_id, output_layer, &[], self.import);
} else {
// Feeding a Fill node's paint input: wire it up and place it one chain-width left and a step below the Fill
self.network_interface.set_input(&target, NodeInput::node(node_id, 0), &[]);
if let Some(target_node_id) = target.node_id()
&& let Some(target_position) = self.network_interface.position(&target_node_id, &[])
{
let node_position = self.network_interface.position(&node_id, &[]).unwrap_or_default();
let desired_position = target_position + IVec2::new(-crate::consts::NODE_CHAIN_WIDTH, 2);
self.network_interface.shift_absolute_node_position(&node_id, desired_position - node_position, &[]);
}
}
node_id
}
};
let input_connector = InputConnector::node(gradient_value_id, graphene_std::math_nodes::gradient_value::GradientInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Gradient(stops), false), false);
}
/// Update the gradient line so its endpoints are at `new_start` and `new_end`.
/// Update the transform to map the unit gradient ((0,0), (1, 0)) to the geometry's local space.
/// With multiple `Transform` nodes the last one (closest to the layer) is modified so the chain still composes to the target.
/// With none, one is inserted unless the target is the identity.
pub fn gradient_line_set(&mut self, new_start: DVec2, new_end: DVec2) {
pub fn gradient_transform_set(&mut self, transform: DAffine2) {
let Some(output_layer) = self.get_output_layer() else { return };
let walk_from = if let Some(fill_input_node_id) = get_fill_input_node_id(output_layer, self.network_interface) {
@@ -583,14 +646,9 @@ impl<'a> ModifyInputsContext<'a> {
.map_or(acc, |document_node| acc * transform_utils::get_current_transform(&document_node.inputs))
})
};
let composed_old = compose(&upstream_transforms);
let prior_combined = compose(prior_transforms);
// Rebuild the y-axis from the new x-axis using the old (parallel, perpendicular) decomposition and length ratio,
// so the gradient's aspect ratio and skew survive an endpoint drag (so an ellipse stays the same ellipse) instead of
// the old y-axis vector remaining fixed while x changes
let new_composed = build_transform_with_y_preservation(composed_old, new_start, new_end);
let last_transform_value = new_composed * prior_combined.inverse();
let last_transform_value = transform * prior_combined.inverse();
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let transform_node_id = if let Some(id) = last_transform_node_id {
@@ -615,6 +673,7 @@ impl<'a> ModifyInputsContext<'a> {
/// from the default (`Linear`).
pub fn gradient_type_set(&mut self, gradient_type: GradientType) {
let Some(output_layer) = self.get_output_layer() else { return };
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let identifier = graphene_std::math_nodes::gradient_type::IDENTIFIER;
let create_if_nonexistent = gradient_type != GradientType::default();
@@ -630,6 +689,7 @@ impl<'a> ModifyInputsContext<'a> {
/// from the default (`Pad`).
pub fn gradient_spread_method_set(&mut self, spread_method: GradientSpreadMethod) {
let Some(output_layer) = self.get_output_layer() else { return };
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let identifier = graphene_std::math_nodes::spread_method::IDENTIFIER;
let create_if_nonexistent = spread_method != GradientSpreadMethod::default();
@@ -650,13 +710,13 @@ impl<'a> ModifyInputsContext<'a> {
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Bool(clip), false), false);
}
pub fn stroke_set(&mut self, stroke: Stroke) {
pub fn stroke_set(&mut self, color: Option<Color>, stroke: Stroke) {
let Some(stroke_node_id) = self.existing_proto_node_id(graphene_std::vector::stroke::IDENTIFIER, true) else {
return;
};
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::ColorInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(stroke.color), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintInput::<List<Graphic>>::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(color), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::WeightInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.weight), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::AlignInput::INDEX);
@@ -804,40 +864,3 @@ impl<'a> ModifyInputsContext<'a> {
}
}
}
/// Rebuild the y-axis so its (parallel, perpendicular) components in the x-axis-aligned frame stay constant, both
/// rescaled by `|new_x| / |old_x|`. This holds the (x, y) parallelogram's aspect ratio and skew fixed across an endpoint
/// drag, so a radial ellipse stays the same shape (just rotated and resized) instead of distorting as x grows or shrinks.
/// Falls back to a +90° rotation of `new_x` when `old_x` is degenerate.
fn scale_y_axis_to_match_new_x(old_x: DVec2, old_y: DVec2, new_x: DVec2) -> DVec2 {
let old_x_length = old_x.length();
if old_x_length < 1e-9 {
return DVec2::new(-new_x.y, new_x.x);
}
let ex_old = old_x / old_x_length;
let ey_old = DVec2::new(-ex_old.y, ex_old.x);
let new_x_length = new_x.length();
if new_x_length < 1e-9 {
return DVec2::ZERO;
}
let ex_new = new_x / new_x_length;
let ey_new = DVec2::new(-ex_new.y, ex_new.x);
let parallel = old_y.dot(ex_old);
let perpendicular = old_y.dot(ey_old);
let scale = new_x_length / old_x_length;
scale * (parallel * ex_new + perpendicular * ey_new)
}
/// Build a new affine that maps canonical (0,0) -> (1,0) to (new_start, new_end), preserving the y-axis
/// shape of `old` proportionally to the x-axis length change.
fn build_transform_with_y_preservation(old: DAffine2, new_start: DVec2, new_end: DVec2) -> DAffine2 {
let new_x_axis = new_end - new_start;
let preserved_y_axis = scale_y_axis_to_match_new_x(old.matrix2.x_axis, old.matrix2.y_axis, new_x_axis);
DAffine2 {
matrix2: glam::DMat2::from_cols(new_x_axis, preserved_y_axis),
translation: new_start,
}
}
@@ -1,7 +1,9 @@
pub(crate) mod document_diff;
mod document_history;
mod document_message;
mod document_message_handler;
#[cfg(test)]
mod storage_round_trip_tests;
mod storage_tests;
pub mod data_panel;
pub mod graph_operation;
@@ -12,8 +14,9 @@ pub mod properties_panel;
pub mod resource;
pub mod utility_types;
pub(crate) use document_diff::diff_networks;
pub(crate) use document_history::DocumentHistory;
#[doc(inline)]
pub use document_message::{DocumentMessage, DocumentMessageDiscriminant};
pub(crate) use document_message_handler::diff_networks;
#[doc(inline)]
pub use document_message_handler::{DocumentMessageContext, DocumentMessageHandler};
@@ -34,6 +34,8 @@ pub struct NodePropertiesContext<'a> {
pub fonts: &'a FontsMessageHandler,
pub selection_network_path: &'a [NodeId],
pub document_name: &'a str,
/// The node IDs whose Properties panel sections the user has collapsed.
pub properties_panel_collapsed_sections: &'a [NodeId],
}
impl NodePropertiesContext<'_> {
@@ -1662,15 +1664,18 @@ fn static_input_properties() -> InputProperties {
if let Some(unit) = field.unit {
number_input = number_input.unit(unit);
}
if let Some(number_min) = field.number_min {
number_input = number_input.min(number_min);
// Typing is clamped only by the hard bounds; the slider extent prefers the soft bounds (see `property_from_type`)
if let Some(hard_min) = field.number_hard_min {
number_input = number_input.min(hard_min);
}
if let Some(number_max) = field.number_max {
number_input = number_input.max(number_max);
if let Some(hard_max) = field.number_hard_max {
number_input = number_input.max(hard_max);
}
if let Some((range_min, range_max)) = field.number_mode_range {
number_input = number_input.range_min(Some(range_min));
number_input = number_input.range_max(Some(range_max));
if field.number_mode_range {
number_input = number_input
.mode_range()
.range_min(field.number_soft_min.or(field.number_hard_min))
.range_max(field.number_soft_max.or(field.number_hard_max));
}
number_input = number_input.is_integer(false);
if let Some(number_step) = field.number_step {
@@ -94,11 +94,19 @@ pub enum NodeGraphMessage {
node_id: NodeId,
parent: LayerNodeIdentifier,
},
ReorderChainNode {
node_id: NodeId,
insert_index: usize,
},
ReorderPinnedNode {
node_id: NodeId,
insert_index: usize,
},
SetChainPosition {
node_id: NodeId,
},
PasteNodes {
serialized_nodes: String,
InsertNodes {
nodes: Vec<(NodeId, NodeTemplate)>,
},
PointerDown {
shift_click: bool,
@@ -1,7 +1,7 @@
use super::node_properties;
use super::utility_types::{BoxSelection, ContextMenuInformation, DragStart, FrontendNode};
use crate::consts::GRID_SIZE;
use crate::messages::clipboard::utility_types::ClipboardContent;
use crate::messages::clipboard::utility_types::ClipboardItem;
use crate::messages::input_mapper::utility_types::macros::{action_shortcut, action_shortcut_manual};
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::document_message_handler::navigation_controls;
@@ -12,9 +12,7 @@ use crate::messages::portfolio::document::node_graph::document_node_definitions:
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction, FrontendGraphDataType, NodeGraphErrorDiagnostic};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::messages::portfolio::document::utility_types::network_interface::{
self, FlowType, InputConnector, NodeNetworkInterface, NodeTemplate, NodeTypePersistentMetadata, OutputConnector, Previewing,
};
use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, NodeTypePersistentMetadata, OutputConnector, Previewing};
use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelEntry};
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
use crate::messages::prelude::*;
@@ -41,6 +39,7 @@ pub struct NodeGraphMessageContext<'a> {
pub breadcrumb_network_path: &'a [NodeId],
pub document_id: DocumentId,
pub collapsed: &'a mut CollapsedLayers,
pub properties_panel_collapsed_sections: &'a mut Vec<NodeId>,
pub ipp: &'a InputPreprocessorMessageHandler,
pub graph_view_overlay_open: bool,
pub graph_fade_artwork_percentage: f64,
@@ -112,6 +111,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
breadcrumb_network_path,
document_id,
collapsed,
properties_panel_collapsed_sections,
ipp,
graph_view_overlay_open,
graph_fade_artwork_percentage,
@@ -188,8 +188,15 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
on: EventMessage::SelectionChanged,
send: Box::new(NodeGraphMessage::SelectedNodesUpdated.into()),
});
network_interface.load_structure();
// Prune the Layers panel collapsed state for any layer tree paths whose nodes no longer exist, so it doesn't accumulate across loads
collapsed.0.retain(|path| path.iter().all(|&node_id| network_interface.document_network().nodes.contains_key(&node_id)));
// Prune the Properties panel node section collapsed state for any nodes (in any nested network) that no longer exist, so it doesn't accumulate across loads
let existing_nodes = network_interface.document_network().recursive_nodes().map(|(node_id, ..)| *node_id).collect::<HashSet<_>>();
properties_panel_collapsed_sections.retain(|node_id| existing_nodes.contains(node_id));
}
NodeGraphMessage::SelectedNodesUpdated => {
let selected_layers = network_interface.selected_nodes().selected_layers(network_interface.document_metadata()).collect::<Vec<_>>();
@@ -248,12 +255,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
let new_ids = &all_selected_nodes.iter().enumerate().map(|(new, old)| (*old, NodeId(new as u64))).collect();
let copied_nodes = network_interface.copy_nodes(new_ids, selection_network_path).collect::<Vec<_>>();
let Ok(data) = serde_json::to_string(&copied_nodes) else {
log::error!("Failed to serialize nodes for clipboard");
return;
};
responses.add(ClipboardMessage::Write {
content: ClipboardContent::Nodes(data),
responses.add(ClipboardMessage::WriteItems {
items: vec![ClipboardItem::Nodes(copied_nodes)],
});
}
NodeGraphMessage::CreateNodeInLayerNoTransaction { node_type, layer } => {
@@ -759,29 +762,27 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
NodeGraphMessage::MoveNodeToChainStart { node_id, parent } => {
network_interface.move_node_to_chain_start(&node_id, parent, selection_network_path, false);
}
NodeGraphMessage::ReorderChainNode { node_id, insert_index } => {
network_interface.reorder_chain_node(node_id, insert_index, selection_network_path);
}
NodeGraphMessage::ReorderPinnedNode { node_id, insert_index } => {
network_interface.reorder_pinned_node(node_id, insert_index, selection_network_path);
}
NodeGraphMessage::SetChainPosition { node_id } => {
network_interface.set_chain_position(&node_id, selection_network_path);
}
NodeGraphMessage::PasteNodes { serialized_nodes } => {
let data = match serde_json::from_str::<Vec<(NodeId, NodeTemplate)>>(&serialized_nodes) {
Ok(d) => d,
Err(e) => {
warn!("Invalid node data {e:?}");
return;
}
};
if data.is_empty() {
NodeGraphMessage::InsertNodes { nodes } => {
if nodes.is_empty() {
return;
}
responses.add(DocumentMessage::AddTransaction);
let new_ids: HashMap<_, _> = data.iter().map(|(id, _)| (*id, NodeId::new())).collect();
let new_ids: HashMap<_, _> = nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect();
responses.add(NodeGraphMessage::AddNodes { nodes, new_ids: new_ids.clone() });
let nodes: Vec<_> = new_ids.values().copied().collect();
responses.add(NodeGraphMessage::AddNodes {
nodes: data,
new_ids: new_ids.clone(),
});
responses.add(NodeGraphMessage::SelectedNodesSet { nodes })
}
NodeGraphMessage::PointerDown {
@@ -1764,11 +1765,11 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
NodeGraphMessage::SetInputValue { node_id, input_index, value } => {
use graphene_std::vector::generator_nodes::*;
let is_fill = matches!(value, TaggedValue::Fill(_));
let reference = network_interface.reference(&node_id, selection_network_path);
let is_text_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER));
let is_stroke_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER));
let is_fill_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER));
let is_fill_input = is_fill_node && input_index == graphene_std::vector::fill::FillInput::<graphene_std::list::List<Graphic>>::INDEX;
let is_shape_generator_node = reference.as_ref().is_some_and(|r| {
[regular_polygon::IDENTIFIER, star::IDENTIFIER, arc::IDENTIFIER, spiral::IDENTIFIER, grid::IDENTIFIER, arrow::IDENTIFIER]
.into_iter()
@@ -1781,10 +1782,11 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
input,
});
responses.add(PropertiesPanelMessage::Refresh);
if is_fill {
if is_fill_input {
responses.add(OverlaysMessage::Draw);
}
if is_stroke_node || is_fill_node || is_shape_generator_node || is_text_node {
responses.add(SelectToolMessage::SelectionChanged);
responses.add(PenToolMessage::SelectionChanged);
responses.add(FreehandToolMessage::SelectionChanged);
responses.add(SplineToolMessage::SelectionChanged);
@@ -2538,25 +2540,18 @@ impl NodeGraphMessageHandler {
Separator::new(SeparatorStyle::Related).widget_instance(),
])];
let Some(network) = context.network_interface.nested_network(context.selection_network_path) else {
warn!("No network in collate_properties");
return Vec::new();
};
// And if no nodes are selected, show properties for all pinned nodes
let pinned_node_properties = network
.nodes
.keys()
.cloned()
.collect::<Vec<_>>()
.iter()
.filter_map(|node_id| {
if context.network_interface.is_pinned(node_id, context.selection_network_path) {
Some(node_properties::generate_node_properties(*node_id, context))
} else {
None
}
})
// And if no nodes are selected, show properties for all pinned nodes (in the user's saved order, each draggable to reorder)
let mut pinned_node_properties = context
.network_interface
.ordered_pinned_nodes(context.selection_network_path)
.into_iter()
.map(|node_id| node_properties::generate_node_properties(node_id, context))
.collect::<Vec<_>>();
for pinned_section in pinned_node_properties.iter_mut() {
if let LayoutGroup::Section(section) = pinned_section {
section.draggable = true;
}
}
properties.extend(pinned_node_properties);
properties
@@ -2618,7 +2613,7 @@ impl NodeGraphMessageHandler {
])];
// Iterate through all the upstream nodes, but stop when we reach another layer (since that's a point where we switch from horizontal to vertical flow)
let node_properties = context
let mut node_properties = context
.network_interface
.upstream_flow_back_from_nodes(vec![layer], context.selection_network_path, network_interface::FlowType::HorizontalFlow)
.enumerate()
@@ -2635,6 +2630,14 @@ impl NodeGraphMessageHandler {
.map(|node_id| node_properties::generate_node_properties(node_id, context))
.collect::<Vec<_>>();
// Mark each chain node (but not the layer node itself, which is first) draggable so its section can be reordered.
// A node without a primary input (e.g. a generator) is left non-draggable.
for chain_node_section in node_properties.iter_mut().skip(1) {
if let LayoutGroup::Section(section) = chain_node_section {
section.draggable = context.network_interface.has_primary_input(&NodeId(section.id), context.selection_network_path);
}
}
layer_properties.extend(node_properties);
layer_properties
}
@@ -16,9 +16,11 @@ use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
use graph_craft::{Type, concrete};
use graphene_std::Graphic;
use graphene_std::NodeInputDecleration;
use graphene_std::animation::RealTimeMode;
use graphene_std::brush::brush_stroke::BrushStroke;
use graphene_std::color::SRGBA8;
use graphene_std::extract_xy::XY;
use graphene_std::list::List;
use graphene_std::raster::{
@@ -31,7 +33,9 @@ use graphene_std::text_nodes::StringCapitalization;
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
use graphene_std::vector::misc::BooleanOperation;
use graphene_std::vector::misc::{ArcType, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType};
use graphene_std::vector::style::{Fill, FillChoice, FillChoiceUI, GradientSpreadMethod, GradientStops, GradientStopsUI, GradientType, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::style::{
FillChoice, FillChoiceUI, GradientSpreadMethod, GradientStops, GradientStopsUI, GradientType, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, build_transform_with_y_preservation,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
pub(crate) fn string_properties(text: &str) -> Vec<LayoutGroup> {
@@ -149,22 +153,36 @@ pub fn start_widgets(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<Widget
widgets
}
/// The numeric bounds and widget mode of a number parameter, sourced from the node's field metadata.
#[derive(Clone, Copy, Default)]
pub(crate) struct NumberOptions {
pub soft_min: Option<f64>,
pub soft_max: Option<f64>,
pub hard_min: Option<f64>,
pub hard_max: Option<f64>,
pub slider: bool,
}
pub(crate) fn property_from_type(
node_id: NodeId,
index: usize,
ty: &Type,
number_options: (Option<f64>, Option<f64>, Option<(f64, f64)>),
number_options: NumberOptions,
unit: Option<&str>,
display_decimal_places: Option<u32>,
step: Option<f64>,
context: &mut NodePropertiesContext,
) -> Result<Vec<LayoutGroup>, Vec<LayoutGroup>> {
let (mut number_min, mut number_max, range) = number_options;
let NumberOptions {
soft_min,
soft_max,
hard_min,
hard_max,
slider,
} = number_options;
let mut number_input = NumberInput::default();
if let Some((range_start, range_end)) = range {
number_min = Some(range_start);
number_max = Some(range_end);
number_input = number_input.mode_range().min(range_start).max(range_end);
if slider {
number_input = number_input.mode_range();
}
if let Some(unit) = unit {
number_input = number_input.unit(unit);
@@ -176,8 +194,22 @@ pub(crate) fn property_from_type(
number_input = number_input.step(step);
}
let min = |x: f64| number_min.unwrap_or(x);
let max = |x: f64| number_max.unwrap_or(x);
// Applies the parameter's typing clamp and slider extent to the widget, given the type's own default bounds.
// Per end: the clamp is the hard bound (or unbounded if only a soft bound is given, since soft is a suggested
// extent rather than a limit), and the slider extent is the soft bound, each falling back to the hard bound
// and then to the type default when unspecified. An end with any explicit bound ignores the type default.
let bounded = |number_input: NumberInput, type_min: f64, type_max: f64| {
let clamp_min = hard_min.unwrap_or(if soft_min.is_some() { f64::NEG_INFINITY } else { type_min });
let clamp_max = hard_max.unwrap_or(if soft_max.is_some() { f64::INFINITY } else { type_max });
let extent_min = soft_min.or(hard_min).unwrap_or(type_min);
let extent_max = soft_max.or(hard_max).unwrap_or(type_max);
number_input
.min(clamp_min)
.max(clamp_max)
.range_min(Some(extent_min).filter(|bound| bound.is_finite()))
.range_max(Some(extent_max).filter(|bound| bound.is_finite()))
};
let default_info = ParameterWidgetsInfo::new(node_id, index, true, context);
@@ -186,16 +218,16 @@ pub(crate) fn property_from_type(
Type::Concrete(concrete_type) => {
match concrete_type.alias.as_ref().map(|x| x.as_ref()) {
// Aliased types (ambiguous values)
Some("Percentage") | Some("PercentageF32") => number_widget(default_info, number_input.percentage().min(min(0.)).max(max(100.))).into(),
Some("SignedPercentage") | Some("SignedPercentageF32") => number_widget(default_info, number_input.percentage().min(min(-100.)).max(max(100.))).into(),
Some("Angle") | Some("AngleF32") => number_widget(default_info, number_input.mode_range().min(min(-180.)).max(max(180.)).unit(unit.unwrap_or("°"))).into(),
Some("Multiplier") => number_widget(default_info, number_input.unit(unit.unwrap_or("x"))).into(),
Some("PixelLength") => number_widget(default_info, number_input.min(min(0.)).unit(unit.unwrap_or(" px"))).into(),
Some("Length") => number_widget(default_info, number_input.min(min(0.))).into(),
Some("Fraction") => number_widget(default_info, number_input.mode_range().min(min(0.)).max(max(1.))).into(),
Some("Progression") => progression_widget(default_info, number_input.min(min(0.))).into(),
Some("SignedInteger") => number_widget(default_info, number_input.int()).into(),
Some("SeedValue") => number_widget(default_info, number_input.int().min(min(0.))).into(),
Some("Percentage") | Some("PercentageF32") => number_widget(default_info, bounded(number_input.percentage(), 0., 100.)).into(),
Some("SignedPercentage") | Some("SignedPercentageF32") => number_widget(default_info, bounded(number_input.percentage(), -100., 100.)).into(),
Some("Angle") | Some("AngleF32") => number_widget(default_info, bounded(number_input.mode_range(), -180., 180.).unit(unit.unwrap_or("°"))).into(),
Some("Multiplier") => number_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY).unit(unit.unwrap_or("x"))).into(),
Some("PixelLength") => number_widget(default_info, bounded(number_input, 0., f64::INFINITY).unit(unit.unwrap_or(" px"))).into(),
Some("Length") => number_widget(default_info, bounded(number_input, 0., f64::INFINITY)).into(),
Some("Fraction") => number_widget(default_info, bounded(number_input.mode_range(), 0., 1.)).into(),
Some("Progression") => progression_widget(default_info, bounded(number_input, 0., f64::INFINITY)).into(),
Some("SignedInteger") => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
Some("SeedValue") => number_widget(default_info, bounded(number_input.int(), 0., f64::INFINITY)).into(),
Some("PixelSize") => vec2_widget(default_info, "X", "Y", unit.unwrap_or(" px"), None, false),
Some("TextArea") => text_area_widget(default_info).into(),
@@ -206,9 +238,9 @@ pub(crate) fn property_from_type(
// ===============
// PRIMITIVE TYPES
// ===============
Some(x) if x == TypeId::of::<f64>() || x == TypeId::of::<f32>() => number_widget(default_info, number_input.min(min(f64::NEG_INFINITY)).max(max(f64::INFINITY))).into(),
Some(x) if x == TypeId::of::<u32>() => number_widget(default_info, number_input.int().min(min(0.)).max(max(f64::from(u32::MAX)))).into(),
Some(x) if x == TypeId::of::<u64>() => number_widget(default_info, number_input.int().min(min(0.))).into(),
Some(x) if x == TypeId::of::<f64>() || x == TypeId::of::<f32>() => number_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(),
Some(x) if x == TypeId::of::<u32>() => number_widget(default_info, bounded(number_input.int(), 0., f64::from(u32::MAX))).into(),
Some(x) if x == TypeId::of::<u64>() => number_widget(default_info, bounded(number_input.int(), 0., f64::INFINITY)).into(),
Some(x) if x == TypeId::of::<bool>() => bool_widget(default_info, CheckboxInput::default()).into(),
Some(x) if x == TypeId::of::<String>() => text_widget(default_info).into(),
Some(x) if x == TypeId::of::<DVec2>() => vec2_widget(default_info, "X", "Y", "", None, false),
@@ -2281,13 +2313,21 @@ 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}");
return Vec::new();
};
let mut number_options = (None, None, None);
let mut number_options = NumberOptions::default();
let mut display_decimal_places = None;
let mut step = None;
let mut unit_suffix = None;
@@ -2299,7 +2339,13 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
.get(proto_node_identifier)
.and_then(|metadata| metadata.fields.get(input_index))
{
number_options = (field.number_min, field.number_max, field.number_mode_range);
number_options = NumberOptions {
soft_min: field.number_soft_min,
soft_max: field.number_soft_max,
hard_min: field.number_hard_min,
hard_max: field.number_hard_max,
slider: field.number_mode_range,
};
display_decimal_places = field.number_display_decimal_places;
unit_suffix = field.unit;
step = field.number_step;
@@ -2365,64 +2411,116 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
let visible = context.network_interface.is_visible(&node_id, context.selection_network_path);
let pinned = context.network_interface.is_pinned(&node_id, context.selection_network_path);
let expanded = !context.properties_panel_collapsed_sections.contains(&node_id);
LayoutGroup::section(name, description, visible, pinned, node_id.0, Layout(layout))
LayoutGroup::section(name, description, visible, pinned, expanded, node_id.0, Layout(layout))
}
/// The layer that a chain node ultimately feeds, if any. Returns `None` in a nested network since the layer metadata structure
/// is only loaded for the root document network, so a `LayerNodeIdentifier` can't be constructed there.
fn root_layer_for_chain_node(node_id: NodeId, context: &mut NodePropertiesContext) -> Option<LayerNodeIdentifier> {
if !context.selection_network_path.is_empty() {
return None;
}
let layer_node = context.network_interface.downstream_layer_for_chain_node(&node_id, context.selection_network_path)?;
Some(LayerNodeIdentifier::new(layer_node, context.network_interface))
}
/// Resolve the viewport-space orientation of a Fill node's gradient by walking downstream to its owning layer
/// and reusing the same helper the Gradient tool uses, so canvas tilt and layer transforms behave identically.
fn gradient_orientation_in_fill_node(node_id: NodeId, gradient: &graphene_std::vector::style::Gradient, context: &mut NodePropertiesContext) -> Option<bool> {
let layer_node = context.network_interface.downstream_layer_for_chain_node(&node_id, context.selection_network_path)?;
let layer = LayerNodeIdentifier::new(layer_node, context.network_interface);
fn gradient_orientation_in_fill_node(node_id: NodeId, gradient_transform: DAffine2, context: &mut NodePropertiesContext) -> Option<bool> {
let layer = root_layer_for_chain_node(node_id, context)?;
let transform = graph_modification_utils::gradient_space_transform(layer, context.network_interface);
Some(graph_modification_utils::gradient_orientation_rightward(gradient.start, gradient.end, transform))
Some(graph_modification_utils::gradient_orientation_rightward(transform * gradient_transform))
}
/// Fill Node Widgets LayoutGroup
pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesContext) -> Vec<LayoutGroup> {
use graphene_std::vector::fill::*;
#[derive(Debug, Clone)]
enum ResolvedFill {
Solid(Option<Color>),
Gradient {
gradient: GradientStops,
gradient_type: GradientType,
spread_method: GradientSpreadMethod,
transform: DAffine2,
/// Whether the transform input holds a plain value (so the "Reverse Direction" button may write to it) rather than a wire.
transform_is_value: bool,
},
Other,
}
let connector = InputConnector::node(node_id, FillInput::<List<Graphic>>::INDEX);
let input_type = context.network_interface.input_type(&connector, context.selection_network_path);
// Pass blank_assist=false because the assist slot is filled below ("Reverse Stops" button when in gradient mode)
let mut widgets_first_row = start_widgets(ParameterWidgetsInfo::new(node_id, FillInput::<Color>::INDEX, false, context));
let mut widgets_first_row = start_widgets(ParameterWidgetsInfo::new(node_id, FillInput::<List<Graphic>>::INDEX, false, context));
let document_node = match get_document_node(node_id, context) {
Ok(document_node) => document_node,
Err(err) => {
log::error!("Could not get document node in fill_properties: {err}");
return Vec::new();
}
};
let (fill, backup_color, backup_gradient) = if let (Some(TaggedValue::Fill(fill)), Some(TaggedValue::Color(backup_color)), Some(TaggedValue::FillGradient(backup_gradient))) = (
&document_node.inputs[FillInput::<Color>::INDEX].as_value(),
&document_node.inputs[BackupColorInput::INDEX].as_value(),
&document_node.inputs[BackupGradientInput::INDEX].as_value(),
) {
(fill, backup_color, backup_gradient)
} else {
if get_document_node(node_id, context).is_ok_and(|node| node.inputs.get(FillInput::<List<Graphic>>::INDEX).is_some_and(|input| input.is_exposed())) {
return vec![LayoutGroup::row(widgets_first_row)];
}
// A Fill node not attached to a layer (or living in a nested network) still shows its full fill UI; only the gradient's
// bounding-box default transform needs the layer, and it falls back to a unit box when there isn't one.
let layer = root_layer_for_chain_node(node_id, context);
let fill = match input_type.compiled_nested_type() {
Some(ty) if ty == &concrete!(List<Color>) => {
if let Ok(document_node) = get_document_node(node_id, context) {
let color = match document_node.inputs[FillInput::<List<Graphic>>::INDEX].as_value() {
Some(&TaggedValue::Color(c)) => c,
_ => None,
};
ResolvedFill::Solid(color)
} else {
ResolvedFill::Other
}
}
Some(ty) if ty == &concrete!(List<GradientStops>) => {
// Read this node's own inputs rather than the layer's nearest Fill, which may be a different node when Fills are chained
if let Ok(document_node) = get_document_node(node_id, context)
&& let Some(gradient) = graph_modification_utils::read_fill_node_gradient(document_node, || {
layer.map_or([DVec2::ZERO, DVec2::ONE], |layer| context.network_interface.document_metadata().nonzero_bounding_box(layer))
}) {
ResolvedFill::Gradient {
gradient: gradient.stops,
gradient_type: gradient.gradient_type,
spread_method: gradient.spread_method,
transform: gradient.transform,
transform_is_value: gradient.transform_is_value,
}
} else {
ResolvedFill::Other
}
}
_ => ResolvedFill::Other,
};
let fill2 = fill.clone();
let backup_color_fill: Fill = (*backup_color).into();
let backup_gradient_fill: Fill = backup_gradient.clone().into();
let (backup_color, backup_gradient) = match get_document_node(node_id, context) {
Ok(document_node) => {
let backup_color = match document_node.inputs[BackupColorInput::INDEX].as_value() {
Some(&TaggedValue::Color(color)) => color,
_ => None,
};
let backup_stops = match document_node.inputs[BackupGradientInput::INDEX].as_value() {
Some(TaggedValue::Gradient(stops)) => stops.clone(),
_ => GradientStops::default(),
};
(backup_color, backup_stops)
}
Err(_) => (None, GradientStops::default()),
};
match &fill {
ResolvedFill::Gradient { gradient: stops, .. } => {
let stops = stops.clone();
match fill {
Fill::Gradient(gradient) => {
let reverse_button = IconButton::new("Reverse", 24)
.tooltip_label("Reverse Stops")
.tooltip_description("Reverse the gradient color stops.")
.on_update(update_value(
{
let gradient = gradient.clone();
move |_| {
let mut gradient = gradient.clone();
gradient.stops = gradient.stops.reversed();
TaggedValue::Fill(Fill::Gradient(gradient))
}
},
node_id,
FillInput::<Color>::INDEX,
))
.on_update(update_value(move |_| TaggedValue::Gradient(stops.reversed()), node_id, FillInput::<List<Graphic>>::INDEX))
.widget_instance();
widgets_first_row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
widgets_first_row.push(reverse_button);
@@ -2430,32 +2528,65 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
_ => add_blank_assist(&mut widgets_first_row),
}
let fill_choice_ui = match &fill {
ResolvedFill::Solid(color) => {
if let Some(color) = color {
FillChoiceUI::Solid(SRGBA8::from(*color))
} else {
FillChoiceUI::None
}
}
ResolvedFill::Gradient { gradient: stops, .. } => FillChoiceUI::Gradient(GradientStopsUI::from(stops)),
ResolvedFill::Other => FillChoiceUI::None,
};
let solid_set_messages = move |color: Option<Color>| Message::Batched {
messages: Box::new([
NodeGraphMessage::SetInputValue {
node_id,
input_index: FillInput::<List<Graphic>>::INDEX,
value: TaggedValue::Color(color),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: BackupColorInput::INDEX,
value: TaggedValue::Color(color),
}
.into(),
]),
};
let gradient_set_messages = move |gradient: GradientStops| Message::Batched {
messages: Box::new([
NodeGraphMessage::SetInputValue {
node_id,
input_index: FillInput::<List<Graphic>>::INDEX,
value: TaggedValue::Gradient(gradient.clone()),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: BackupGradientInput::INDEX,
value: TaggedValue::Gradient(gradient),
}
.into(),
]),
};
widgets_first_row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
widgets_first_row.push(
ColorInput::default()
.value(FillChoiceUI::from(&FillChoice::from(fill.clone())))
.on_update(move |x: &ColorInput| {
let new_fill = FillChoice::from(&x.value).to_fill(fill2.as_gradient());
let (backup_index, backup_value) = match &new_fill {
Fill::None => (BackupColorInput::INDEX, TaggedValue::Color(None)),
Fill::Solid(color) => (BackupColorInput::INDEX, TaggedValue::Color(Some(*color))),
Fill::Gradient(gradient) => (BackupGradientInput::INDEX, TaggedValue::FillGradient(gradient.clone())),
};
Message::Batched {
messages: Box::new([
NodeGraphMessage::SetInputValue {
node_id,
input_index: backup_index,
value: backup_value,
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: FillInput::<Color>::INDEX,
value: TaggedValue::Fill(new_fill),
}
.into(),
]),
.value(fill_choice_ui)
.on_update(move |x: &ColorInput| match &x.value {
FillChoiceUI::None => solid_set_messages(None),
FillChoiceUI::Solid(srgba8) => {
let color = Some(Color::from(*srgba8));
solid_set_messages(color)
}
FillChoiceUI::Gradient(gradient_stops_ui) => {
let gradient = GradientStops::from(gradient_stops_ui);
gradient_set_messages(gradient)
}
})
.on_commit(commit_value)
@@ -2471,61 +2602,50 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
let entries = vec![
RadioEntryData::new("solid")
.label("Solid")
.on_update(update_value(move |_| TaggedValue::Fill(backup_color_fill.clone()), node_id, FillInput::<Color>::INDEX))
.on_update(update_value(move |_| TaggedValue::Color(backup_color), node_id, FillInput::<List<Graphic>>::INDEX))
.on_commit(commit_value),
RadioEntryData::new("gradient")
.label("Gradient")
.on_update(update_value(move |_| TaggedValue::Fill(backup_gradient_fill.clone()), node_id, FillInput::<Color>::INDEX))
.on_update(update_value(move |_| TaggedValue::Gradient(backup_gradient.clone()), node_id, FillInput::<List<Graphic>>::INDEX))
.on_commit(commit_value),
];
row.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
RadioInput::new(entries).selected_index(Some(if fill.as_gradient().is_some() { 1 } else { 0 })).widget_instance(),
RadioInput::new(entries)
.selected_index(Some(if matches!(fill, ResolvedFill::Gradient { .. }) { 1 } else { 0 }))
.widget_instance(),
]);
LayoutGroup::row(row)
};
widgets.push(fill_type_switch);
if let Fill::Gradient(gradient) = fill.clone() {
if let ResolvedFill::Gradient {
gradient_type,
spread_method,
transform,
transform_is_value,
..
} = fill.clone()
{
// Linear/Radial radio: blank assist (the "Reverse Direction" button has been moved down to the spread method row)
let mut row = vec![TextLabel::new("").widget_instance()];
add_blank_assist(&mut row);
let gradient_for_closure = gradient.clone();
let entries = [GradientType::Linear, GradientType::Radial]
.iter()
.map(|&grad_type| {
let gradient = gradient_for_closure.clone();
let set_input_value = update_value(
move |_: &()| {
let mut new_gradient = gradient.clone();
new_gradient.gradient_type = grad_type;
TaggedValue::Fill(Fill::Gradient(new_gradient))
},
node_id,
FillInput::<Color>::INDEX,
);
RadioEntryData::new(format!("{:?}", grad_type))
.label(format!("{:?}", grad_type))
.on_update(move |_| Message::Batched {
messages: Box::new([
set_input_value(&()),
GradientToolMessage::UpdateOptions {
options: GradientOptionsUpdate::Type(grad_type),
}
.into(),
]),
})
.on_update(update_value(move |_| TaggedValue::GradientType(grad_type), node_id, GradientTypeInput::INDEX))
.on_commit(commit_value)
})
.collect();
row.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
RadioInput::new(entries).selected_index(Some(gradient.gradient_type as u32)).widget_instance(),
RadioInput::new(entries).selected_index(Some(gradient_type as u32)).widget_instance(),
]);
widgets.push(LayoutGroup::row(row));
@@ -2534,75 +2654,41 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
// space so canvas tilt and layer transforms behave the same as in the Gradient tool's control bar.
let mut spread_methods_row = vec![TextLabel::new("").widget_instance()];
let orientation_rightward = gradient_orientation_in_fill_node(node_id, &gradient, context).unwrap_or(true);
let reverse_direction_button = IconButton::new(if orientation_rightward { "ReverseRadialGradientToRight" } else { "ReverseRadialGradientToLeft" }, 24)
.tooltip_label("Reverse Direction")
.tooltip_description(if gradient.gradient_type == GradientType::Radial {
"Reverse which end the gradient radiates from."
} else {
"Swap the start and end points of the gradient line."
})
.on_update(update_value(
{
let gradient = gradient.clone();
move |_| {
let mut gradient = gradient.clone();
std::mem::swap(&mut gradient.start, &mut gradient.end);
TaggedValue::Fill(Fill::Gradient(gradient))
}
},
node_id,
FillInput::<Color>::INDEX,
))
.widget_instance();
spread_methods_row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
spread_methods_row.push(reverse_direction_button);
// The button writes a value into the transform input, so only offer it when the input isn't wired
if transform_is_value {
let start = transform.transform_point2(DVec2::ZERO);
let end = transform.transform_point2(DVec2::X);
let new_transform = build_transform_with_y_preservation(transform, end, start);
let orientation_rightward = gradient_orientation_in_fill_node(node_id, transform, context).unwrap_or(true);
let reverse_direction_button = IconButton::new(if orientation_rightward { "ReverseRadialGradientToRight" } else { "ReverseRadialGradientToLeft" }, 24)
.tooltip_label("Reverse Direction")
.tooltip_description(if gradient_type == GradientType::Radial {
"Reverse which end the gradient radiates from."
} else {
"Swap the start and end points of the gradient line."
})
.on_update(update_value(move |_| TaggedValue::OptionalDAffine2(Some(new_transform)), node_id, TransformInput::INDEX))
.widget_instance();
spread_methods_row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
spread_methods_row.push(reverse_direction_button);
} else {
add_blank_assist(&mut spread_methods_row);
}
let spread_method_entries = [GradientSpreadMethod::Pad, GradientSpreadMethod::Reflect, GradientSpreadMethod::Repeat]
.iter()
.map(|&spread_method| {
let gradient_for_input = gradient_for_closure.clone();
let gradient_for_backup = gradient_for_closure.clone();
let set_input_value = update_value(
move |_: &()| {
let mut new_gradient = gradient_for_input.clone();
new_gradient.spread_method = spread_method;
TaggedValue::Fill(Fill::Gradient(new_gradient))
},
node_id,
FillInput::<Color>::INDEX,
);
let set_backup_value = update_value(
move |_: &()| {
let mut new_gradient = gradient_for_backup.clone();
new_gradient.spread_method = spread_method;
TaggedValue::FillGradient(new_gradient)
},
node_id,
BackupGradientInput::INDEX,
);
RadioEntryData::new(format!("{:?}", spread_method))
.label(format!("{:?}", spread_method))
.on_update(move |_| Message::Batched {
messages: Box::new([
set_input_value(&()),
set_backup_value(&()),
GradientToolMessage::UpdateOptions {
options: GradientOptionsUpdate::SetSpreadMethod(spread_method),
}
.into(),
]),
})
.on_update(update_value(move |_| TaggedValue::GradientSpreadMethod(spread_method), node_id, SpreadMethodInput::INDEX))
.on_commit(commit_value)
})
.collect();
spread_methods_row.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
RadioInput::new(spread_method_entries).selected_index(Some(gradient.spread_method as u32)).widget_instance(),
RadioInput::new(spread_method_entries).selected_index(Some(spread_method as u32)).widget_instance(),
]);
widgets.push(LayoutGroup::row(spread_methods_row));
@@ -2617,7 +2703,7 @@ pub fn stroke_properties(node_id: NodeId, context: &mut NodePropertiesContext) -
let document_node = match get_document_node(node_id, context) {
Ok(document_node) => document_node,
Err(err) => {
log::error!("Could not get document node in fill_properties: {err}");
log::error!("Could not get document node in stroke_properties: {err}");
return Vec::new();
}
};
@@ -2633,7 +2719,7 @@ pub fn stroke_properties(node_id: NodeId, context: &mut NodePropertiesContext) -
let miter_limit_disabled = join_value != &StrokeJoin::Miter;
let color = color_widget(
ParameterWidgetsInfo::new(node_id, ColorInput::INDEX, true, context),
ParameterWidgetsInfo::new(node_id, PaintInput::<List<Graphic>>::INDEX, true, context),
crate::messages::layout::utility_types::widgets::button_widgets::ColorInput::default(),
);
let weight = number_widget(ParameterWidgetsInfo::new(node_id, WeightInput::INDEX, true, context), NumberInput::default().unit(" px").min(0.));
@@ -27,7 +27,7 @@ impl FrontendGraphDataType {
match TaggedValue::from_type_or_none(input) {
TaggedValue::U32(_) | TaggedValue::U64(_) | TaggedValue::F32(_) | TaggedValue::F64(_) | TaggedValue::DVec2(_) | TaggedValue::F64Array(_) | TaggedValue::DAffine2(_) => Self::Number,
TaggedValue::Color(_) => Self::Color,
TaggedValue::FillGradient(_) | TaggedValue::Gradient(_) => Self::Gradient,
TaggedValue::LegacyGradient(_) | TaggedValue::Gradient(_) => Self::Gradient,
TaggedValue::String(_) => Self::Typography,
// Types whose `TaggedValue` variant has been removed are routed through `TypeDefault` and identified by the descriptor's type name.
TaggedValue::TypeDefault(td) => match td.name.as_ref() {
@@ -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 {
@@ -15,6 +15,7 @@ pub struct PropertiesPanelMessageContext<'a> {
pub document_name: &'a str,
pub fonts: &'a FontsMessageHandler,
pub properties_panel_open: bool,
pub properties_panel_collapsed_sections: &'a [NodeId],
}
#[derive(Debug, Clone, Default, ExtractField)]
@@ -31,6 +32,7 @@ impl MessageHandler<PropertiesPanelMessage, PropertiesPanelMessageContext<'_>> f
document_name,
fonts,
properties_panel_open,
properties_panel_collapsed_sections,
} = context;
match message {
@@ -54,6 +56,7 @@ impl MessageHandler<PropertiesPanelMessage, PropertiesPanelMessageContext<'_>> f
selection_network_path,
document_name,
fonts,
properties_panel_collapsed_sections,
};
let layout = Layout(NodeGraphMessageHandler::collate_properties(&mut node_properties_context));
@@ -0,0 +1,313 @@
//! Conversion-level round-trip tests for the [`storage_metadata`](crate::messages::portfolio::document::utility_types::network_interface::storage_metadata)
//! bridge: drive a demo `.graphite` document through `Registry` (and back through
//! `build_interface_from_storage`) without an actual save/reopen, asserting the editor's `ui::*`
//! metadata survives the conversion. The end-to-end save/reopen pipeline is covered separately in
//! [`round_trip_tests`](super::round_trip_tests).
use std::collections::HashMap;
use graph_storage::{NodeMetadataSource, PeerId, Registry};
use super::test_support::{load_demo, node_paths};
use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler;
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::{DocumentSettings, StorageMetadataView, build_interface_from_storage};
use crate::messages::portfolio::document::utility_types::nodes::CollapsedLayers;
use graph_craft::document::NodeId;
use graphene_std::vector::style::RenderMode;
/// Loads a demo artwork, round-trips its `NodeNetwork + NodeNetworkInterface metadata` through
/// `Registry`, and asserts every node's `ui::*` attributes survive unchanged.
///
/// Uses one demo (rather than the full set) because this is an exhaustive per-node check.
#[test]
fn editor_metadata_round_trip_against_demo() {
let document = load_demo("changing-seasons.graphite");
let interface = &document.network_interface;
let source = StorageMetadataView::new(interface);
let network = interface.document_network().clone();
let conversion = Registry::convert_from_runtime(&network, &source, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations().expect("rebuild declarations");
let registry = conversion.registry;
let (_converted_network, entries) = registry.to_runtime_with_metadata(&declarations).expect("to_runtime_with_metadata failed");
// Index emitted entries by their (network_path, local_id) address.
let entries_by_address: HashMap<(Vec<NodeId>, NodeId), &graph_storage::NodeMetadataEntry> = entries.iter().map(|e| ((e.network_path.clone(), e.local_id), e)).collect();
let mut checked_any_position = false;
let mut checked_any_layer = false;
let mut checked_any_input_metadata = false;
for (network_path, local_id) in node_paths(interface) {
let expected_position = source.position(&network_path, local_id);
let expected_is_layer = source.is_layer(&network_path, local_id);
let expected_display = source.display_name(&network_path, local_id).map(str::to_owned);
let expected_locked = source.locked(&network_path, local_id);
let expected_pinned = source.pinned(&network_path, local_id);
let expected_output_names = source.output_names(&network_path, local_id);
// Use the node's input count as the slot-by-slot iteration bound for the per-input metadata checks.
let input_count = interface.document_node(&local_id, &network_path).map(|node| node.inputs.len()).unwrap_or(0);
let any_input_metadata_present = (0..input_count).any(|i| {
source.input_name(&network_path, local_id, i).is_some_and(|s| !s.is_empty())
|| source.input_description(&network_path, local_id, i).is_some_and(|s| !s.is_empty())
|| source.widget_override(&network_path, local_id, i).is_some()
|| !source.input_data(&network_path, local_id, i).is_empty()
});
let any_metadata = expected_position.is_some()
|| expected_is_layer
|| expected_display.as_deref().is_some_and(|s| !s.is_empty())
|| expected_locked
|| expected_pinned
|| any_input_metadata_present
|| !expected_output_names.is_empty();
if !any_metadata {
assert!(
!entries_by_address.contains_key(&(network_path.clone(), local_id)),
"node {local_id:?} in network {network_path:?} has no editor metadata but produced an entry"
);
continue;
}
let entry = entries_by_address
.get(&(network_path.clone(), local_id))
.unwrap_or_else(|| panic!("missing entry for node {local_id:?} in network {network_path:?}"));
assert_eq!(entry.position, expected_position, "position mismatch for node {local_id:?} in network {network_path:?}");
assert_eq!(entry.is_layer, expected_is_layer, "is_layer mismatch for node {local_id:?} in network {network_path:?}");
// The trait round-trip drops empty display names (treats them as "unset") so the entry's
// `display_name` is `None` when the runtime carries `""`. Normalize before comparing.
let normalized_expected_display = expected_display.as_deref().filter(|s| !s.is_empty()).map(str::to_owned);
assert_eq!(
entry.display_name, normalized_expected_display,
"display_name mismatch for node {local_id:?} in network {network_path:?}"
);
assert_eq!(entry.locked, expected_locked, "locked mismatch for node {local_id:?} in network {network_path:?}");
assert_eq!(entry.pinned, expected_pinned, "pinned mismatch for node {local_id:?} in network {network_path:?}");
assert_eq!(entry.output_names, expected_output_names, "output_names mismatch for node {local_id:?} in network {network_path:?}");
// Per-input metadata: the entry's `input_metadata` has one slot per input, each matching the trait's
// per-field view (same "empty string ↔ None" normalization as `display_name`).
assert_eq!(
entry.input_metadata.len(),
input_count,
"input_metadata length mismatch for node {local_id:?} in network {network_path:?}: entry has {}, node has {input_count}",
entry.input_metadata.len(),
);
for (index, input_entry) in entry.input_metadata.iter().enumerate() {
let expected_name = source.input_name(&network_path, local_id, index).filter(|s| !s.is_empty()).map(str::to_owned);
let expected_description = source.input_description(&network_path, local_id, index).filter(|s| !s.is_empty()).map(str::to_owned);
let expected_widget = source.widget_override(&network_path, local_id, index).map(str::to_owned);
let expected_data = source.input_data(&network_path, local_id, index);
assert_eq!(
input_entry.input_name, expected_name,
"input_name mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
input_entry.input_description, expected_description,
"input_description mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
input_entry.widget_override, expected_widget,
"widget_override mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
input_entry.input_data, expected_data,
"input_data mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
}
if entry.position.is_some() {
checked_any_position = true;
}
if entry.is_layer {
checked_any_layer = true;
}
if any_input_metadata_present {
checked_any_input_metadata = true;
}
}
// Sanity: a real artwork should exercise at least these two shapes; otherwise the test is
// just iterating empty metadata and proving nothing.
assert!(checked_any_position, "demo artwork produced no positioned nodes: fixture is wrong or extraction is broken");
assert!(checked_any_layer, "demo artwork produced no layer nodes: fixture is wrong or extraction is broken");
// Demo artworks always have some custom widget overrides / input names; if not, the
// per-input round-trip isn't actually being exercised here.
assert!(checked_any_input_metadata, "demo artwork produced no per-input metadata: fixture is wrong or extraction is broken");
}
/// Full editor-side round-trip: original interface → Registry → (NodeNetwork, Vec<entry>) →
/// freshly-built interface. Asserts the rebuilt interface presents the same `ui::*` state as
/// the original when read through `StorageMetadataView`.
#[test]
fn editor_interface_rebuild_round_trip() {
let document = load_demo("changing-seasons.graphite");
let original = &document.network_interface;
let original_view = StorageMetadataView::new(original);
let network = original.document_network().clone();
let conversion = Registry::convert_from_runtime(&network, &original_view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations().expect("rebuild declarations");
let registry = conversion.registry;
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime_with_full_metadata failed");
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage failed");
let rebuilt_view = StorageMetadataView::new(&rebuilt);
// Every node the original carried must also resolve identically through the rebuilt view.
// Iterating over the *rebuilt* interface verifies that the rebuild covered every node, not
// just the ones the entries vec mentioned.
for (network_path, local_id) in node_paths(&rebuilt) {
assert_eq!(
rebuilt_view.position(&network_path, local_id),
original_view.position(&network_path, local_id),
"position mismatch for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
rebuilt_view.is_layer(&network_path, local_id),
original_view.is_layer(&network_path, local_id),
"is_layer mismatch for node {local_id:?} in network {network_path:?}"
);
// Original display names are returned by the source as-is (including `""`). After
// round-trip the rebuilt interface also stores `""` for nodes that had no name set,
// so this comparison is exact.
assert_eq!(
rebuilt_view.display_name(&network_path, local_id),
original_view.display_name(&network_path, local_id),
"display_name mismatch for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
rebuilt_view.locked(&network_path, local_id),
original_view.locked(&network_path, local_id),
"locked mismatch for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
rebuilt_view.pinned(&network_path, local_id),
original_view.pinned(&network_path, local_id),
"pinned mismatch for node {local_id:?} in network {network_path:?}"
);
// Per-input metadata: walk both interfaces' input slots in lockstep.
let original_inputs = original.document_node(&local_id, &network_path).map(|n| n.inputs.len()).unwrap_or(0);
let rebuilt_inputs = rebuilt.document_node(&local_id, &network_path).map(|n| n.inputs.len()).unwrap_or(0);
assert_eq!(
rebuilt_inputs, original_inputs,
"input count mismatch for node {local_id:?} in network {network_path:?}: rebuilt={rebuilt_inputs} original={original_inputs}"
);
for index in 0..rebuilt_inputs {
assert_eq!(
rebuilt_view.input_name(&network_path, local_id, index),
original_view.input_name(&network_path, local_id, index),
"input_name mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
rebuilt_view.input_description(&network_path, local_id, index),
original_view.input_description(&network_path, local_id, index),
"input_description mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
rebuilt_view.widget_override(&network_path, local_id, index),
original_view.widget_override(&network_path, local_id, index),
"widget_override mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
rebuilt_view.input_data(&network_path, local_id, index),
original_view.input_data(&network_path, local_id, index),
"input_data mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
}
assert_eq!(
rebuilt_view.output_names(&network_path, local_id),
original_view.output_names(&network_path, local_id),
"output_names mismatch for node {local_id:?} in network {network_path:?}"
);
}
// Symmetric: every node in the original must also exist in the rebuilt interface.
for (network_path, local_id) in node_paths(original) {
assert!(
rebuilt.nested_network(&network_path).and_then(|n| n.nodes.get(&local_id)).is_some(),
"original node {local_id:?} in network {network_path:?} missing after rebuild"
);
}
// Per-network metadata: every nested network path (including the root) must resolve to the same
// `reference` in the rebuilt interface. Node-graph nav + previewing are per-peer view state that
// lives in `session.json`, not the registry, so they're not round-tripped here.
let mut network_paths_to_check: Vec<Vec<NodeId>> = vec![Vec::new()];
for (network_path, local_id) in node_paths(original) {
let mut child = network_path.clone();
child.push(local_id);
if original.nested_network(&child).is_some() {
network_paths_to_check.push(child);
}
}
let mut checked_any_reference = false;
for path in &network_paths_to_check {
assert_eq!(rebuilt_view.reference(path), original_view.reference(path), "reference mismatch for network {path:?}");
if original_view.reference(path).is_some() {
checked_any_reference = true;
}
}
assert!(checked_any_reference, "demo artwork produced no reference metadata: fixture is wrong or extraction is broken");
}
/// Per-peer view settings (`ui::doc::*`) survive the `session.json` round-trip: serialize them into
/// the view map, then apply it onto a fresh handler and confirm each field matches.
#[test]
fn document_settings_round_trip() {
let mut document = load_demo("changing-seasons.graphite");
// Set distinctive, non-default values so the round-trip proves real data moved, not defaults.
document.render_mode = RenderMode::Outline;
document.rulers_visible = false;
document.collapsed = CollapsedLayers(vec![vec![NodeId(7)], vec![NodeId(7), NodeId(42)]]);
let view_settings = DocumentSettings {
document_ptz: &document.document_ptz,
render_mode: &document.render_mode,
overlays_visibility: &document.overlays_visibility_settings,
rulers_visible: document.rulers_visible,
snapping_state: &document.snapping_state,
collapsed: &document.collapsed,
}
.to_view_map();
// Apply the serialized view settings onto a fresh handler and compare each field's serialized
// form (avoids requiring `PartialEq` on every setting type).
let mut restored = DocumentMessageHandler::default();
restored.apply_stored_document_settings(&view_settings);
assert_eq!(serde_json::to_value(restored.render_mode).unwrap(), serde_json::to_value(document.render_mode).unwrap(), "render_mode");
assert_eq!(
serde_json::to_value(restored.rulers_visible).unwrap(),
serde_json::to_value(document.rulers_visible).unwrap(),
"rulers_visible"
);
assert_eq!(
serde_json::to_value(restored.document_ptz).unwrap(),
serde_json::to_value(document.document_ptz).unwrap(),
"document_ptz"
);
assert_eq!(
serde_json::to_value(restored.overlays_visibility_settings).unwrap(),
serde_json::to_value(document.overlays_visibility_settings).unwrap(),
"overlays"
);
assert_eq!(
serde_json::to_value(restored.snapping_state).unwrap(),
serde_json::to_value(document.snapping_state).unwrap(),
"snapping_state"
);
assert_eq!(serde_json::to_value(restored.collapsed).unwrap(), serde_json::to_value(document.collapsed).unwrap(), "collapsed");
}
@@ -0,0 +1,9 @@
//! Integration tests for the `.gdd` document-storage layer, split by altitude:
//! - [`metadata_tests`] drives a demo document through the conversion bridge in-process (no save/reopen).
//! - [`round_trip_tests`] drives real editor edits through a full `Gdd` save/reopen pipeline.
//!
//! Shared fixtures live in [`test_support`].
mod metadata_tests;
mod round_trip_tests;
mod test_support;
@@ -8,62 +8,16 @@ use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::document::{DocumentNodeImplementation, NodeId};
use graph_storage::{NodeMetadataSource, PeerId};
use super::test_support::{RoundTrip, node_paths, round_trip_through_gdd};
use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler;
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::{DocumentSettings, StorageMetadataView, build_interface_from_storage};
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::{StorageMetadataView, build_interface_from_storage};
use crate::test_utils::test_prelude::*;
use graphene_std::vector::style::RenderMode;
/// Result of round-tripping a document through a `Gdd`: the runtime interface rebuilt from the
/// reopened storage, the reopened registry, and the reopened per-peer view settings (`ui::doc::*`).
struct RoundTrip {
rebuilt: NodeNetworkInterface,
registry: graph_storage::Registry,
view_settings: std::collections::BTreeMap<String, serde_json::Value>,
}
/// Push `document`'s current runtime state through a fresh in-memory `Gdd` and reopen it. The commit
/// goes through `commit_from_runtime` (the real autosave path: stage hot ops → retire → persist);
/// the reopen reads the working copy back from the same container bytes, so the whole codec / file
/// / replay pipeline is exercised, not just the in-memory conversion.
async fn round_trip_through_gdd(document: &DocumentMessageHandler) -> RoundTrip {
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
gdd.commit_from_runtime(&network, &view, &document.resources.registry, &byte_store).expect("commit_from_runtime");
// Per-peer view settings persist in session.json, separate from the registry commit.
let view_settings = DocumentSettings {
document_ptz: &document.document_ptz,
render_mode: &document.render_mode,
overlays_visibility: &document.overlays_visibility_settings,
rulers_visible: document.rulers_visible,
snapping_state: &document.snapping_state,
collapsed: &document.collapsed,
}
.to_view_map();
gdd.set_view_settings(view_settings).expect("set_view_settings");
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.expect("open_in");
let declarations = reopened.declarations(&byte_store).await;
let registry = reopened.registry().clone();
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime_with_full_metadata");
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage");
let view_settings = reopened.view_settings().clone();
RoundTrip { rebuilt, registry, view_settings }
}
/// Every node addressable in `original` resolves identically through the round-tripped interface:
/// the compute graph itself, then per-node positions, layer flags, names, locked/pinned.
fn assert_documents_match(original: &NodeNetworkInterface, round_trip: &RoundTrip) {
@@ -90,24 +44,6 @@ fn assert_documents_match(original: &NodeNetworkInterface, round_trip: &RoundTri
}
}
/// Walk every node in every nested network, collecting `(network_path, local_id)` pairs.
fn node_paths(interface: &NodeNetworkInterface) -> Vec<(Vec<NodeId>, NodeId)> {
fn walk(interface: &NodeNetworkInterface, path: Vec<NodeId>, out: &mut Vec<(Vec<NodeId>, NodeId)>) {
let Some(network) = interface.nested_network(&path) else { return };
for (&local_id, node) in &network.nodes {
out.push((path.clone(), local_id));
if matches!(node.implementation, DocumentNodeImplementation::Network(_)) {
let mut child = path.clone();
child.push(local_id);
walk(interface, child, out);
}
}
}
let mut out = Vec::new();
walk(interface, Vec::new(), &mut out);
out
}
#[tokio::test]
async fn round_trip_drawn_shapes() {
let mut editor = EditorTestUtils::create();
@@ -185,9 +121,8 @@ async fn recommit_after_open_is_stable() {
let round_trip = round_trip_through_gdd(document).await;
// Re-convert the rebuilt runtime and assert it reproduces the reopened registry. `round_trip_through_gdd`
// builds the `Gdd` with `PeerId(1)`, which the reopened registry inherits, so the re-conversion must
// use that same peer for deterministic node-ID derivation. (`ui::doc::*` settings live in session.json,
// not the registry, so they don't participate in this comparison.)
// builds the `Gdd` with `PeerId(1)`, which the reopened registry inherits, so the re-conversion must use
// that same peer for deterministic node-ID derivation.
let rebuilt_network = round_trip.rebuilt.document_network().clone();
let view = StorageMetadataView::new(&round_trip.rebuilt);
let reconverted = graph_storage::Registry::convert_from_runtime(&rebuilt_network, &view, &Default::default(), PeerId(1)).expect("re-convert from_runtime");
@@ -195,7 +130,7 @@ async fn recommit_after_open_is_stable() {
assert!(
round_trip.registry.value_equal(&reconverted.registry),
"re-converting the reopened runtime drifted from the reopened registry (network/node IDs not stable across to_runtime -> from_runtime)\n{}",
crate::messages::portfolio::document::document_message_handler::diff_registries(&round_trip.registry, &reconverted.registry)
crate::messages::portfolio::document::document_diff::diff_registries(&round_trip.registry, &reconverted.registry)
);
}
@@ -218,7 +153,7 @@ async fn edit_after_open_commits_cleanly() {
.await;
// Persist the document into a fresh Gdd and reopen it, then build a runtime document from the
// reopened registry — the editor's .gdd-open path.
// reopened registry: the editor's .gdd-open path.
let byte_store = HashMapResourceStorage::new();
let source = editor.active_document();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
@@ -239,16 +174,14 @@ async fn edit_after_open_commits_cleanly() {
{
let document = editor.active_document_mut();
document.network_interface = rebuilt;
document.storage = Some(reopened);
document.set_storage(Some(reopened));
document.finalize_storage_load();
}
// Mirror the live sequence via the real `commit_storage_snapshot` (which uses the full document-
// settings view + the document's own resource registry, and runs `verify_storage_round_trip` in
// debug — panicking on any drift). Initial commit after open, then a deletion, then commit again.
// Deletion (not addition) is the trigger: it emits a `RemoveNode` whose retire/reverse is where
// "Target node does not exist" surfaced live.
editor.active_document_mut().commit_storage_snapshot(&byte_store);
// Mirror the live sequence via the real `commit_storage_snapshot`: initial commit after open, then a
// deletion, then commit again. Deletion (not addition) is the trigger, since it emits a `RemoveNode`
// whose retire/reverse is where "Target node does not exist" surfaced live.
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let layer = editor.active_document().metadata().all_layers().next().expect("at least one layer");
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
@@ -257,11 +190,13 @@ async fn edit_after_open_commits_cleanly() {
// `commit_storage_snapshot` only logs commit failures, so assert on the underlying `commit_from_runtime`
// result directly to make the deletion commit a hard test failure rather than a silent log line.
let document = editor.active_document_mut();
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
// Clone the interface for the metadata view so it doesn't borrow `document` across the mutable
// `storage_mut()` borrow below.
let interface = document.network_interface.clone();
let network = interface.document_network().clone();
let view = StorageMetadataView::new(&interface);
document
.storage
.as_mut()
.storage_mut()
.expect("storage mounted")
.commit_from_runtime(&network, &view, &Default::default(), &byte_store)
.expect("commit after deleting a layer post-open must not fail");
@@ -351,8 +286,8 @@ async fn reopen_after_undo_restores_consistent_registry() {
commit_interaction(&mut gdd, editor.active_document(), &byte_store).await;
let nodes_three: std::collections::BTreeSet<_> = gdd.registry().node_instances.keys().copied().collect();
// Undo the third interaction: in-memory registry is now the two-interaction state and head moved back, but the
// last retirement wrote the three-interaction registry to disk. The undo must re-snapshot it.
// Undo the third interaction: the in-memory registry is back at the two-interaction state, but the last
// retirement wrote the three-interaction registry to disk. The undo must re-snapshot it.
gdd.undo().expect("undo");
assert_eq!(gdd.registry().node_instances.keys().copied().collect::<std::collections::BTreeSet<_>>(), nodes_two);
@@ -399,17 +334,19 @@ async fn live_undo_shadows_storage_cursor() {
let byte_store = mount_in_memory_storage(&mut editor).await;
// Capture the loaded state as the base interaction, then make a real edit (fires CommitTransaction).
editor.active_document_mut().commit_storage_snapshot(&byte_store);
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let before_edit = editor.active_document().network_interface.document_network().clone();
editor.draw_ellipse(50., 50., 150., 150.).await;
assert_ne!(&before_edit, editor.active_document().network_interface.document_network(), "edit should change the network");
let after_edit = editor.active_document().network_interface.document_network().clone();
assert_ne!(&before_edit, &after_edit, "edit should change the network");
// Real undo: the shadow drives gdd.undo() and (debug) asserts the cursor matches the restored interface.
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(editor.active_document().network_interface.document_network(), &before_edit, "undo should restore the pre-edit network");
// Real redo: shadow drives gdd.redo() + checks again.
// Real redo: the shadow drives gdd.redo() and must reproduce the post-edit network.
editor.handle_message(DocumentMessage::Redo).await;
assert_eq!(editor.active_document().network_interface.document_network(), &after_edit, "redo should restore the post-edit network");
}
#[tokio::test]
@@ -456,7 +393,7 @@ async fn gdd_archive_round_trips_view_settings() {
let mut ptz = crate::messages::portfolio::document::utility_types::misc::PTZ::default();
ptz.pan = glam::DVec2::new(-960., -540.);
ptz.set_zoom(0.459);
let view_settings = std::collections::BTreeMap::from([(doc::PTZ.to_string(), serde_json::to_value(&ptz).unwrap())]);
let view_settings = std::collections::BTreeMap::from([(doc::PTZ.to_string(), serde_json::to_value(ptz).unwrap())]);
gdd.set_view_settings(view_settings).expect("set_view_settings");
// Export to an in-memory archive, then reopen it from bytes into a fresh container.
@@ -471,7 +408,7 @@ async fn gdd_archive_round_trips_view_settings() {
assert_eq!(
reopened.view_settings().get(doc::PTZ),
Some(&serde_json::to_value(&ptz).unwrap()),
Some(&serde_json::to_value(ptz).unwrap()),
"the document PTZ must survive a .gdd archive export/open (session.json travels in the archive)"
);
}
@@ -513,7 +450,7 @@ async fn per_network_navigation_round_trips_via_session_not_registry() {
// The registry must NOT carry the node-graph nav (it's per-peer, not document content).
let root_network = gdd.registry().networks.get(&graph_storage::ROOT_NETWORK).expect("root network in registry");
assert!(root_network.attributes.get(network::NAV_PTZ).is_none(), "node-graph nav must not be stored in the registry attributes");
assert!(!root_network.attributes.contains_key(network::NAV_PTZ), "node-graph nav must not be stored in the registry attributes");
// Reopen, rebuild the interface, and apply the persisted per-network view state.
let (working, layout) = gdd.into_storage();
@@ -542,7 +479,7 @@ async fn live_undo_new_document_draw_rect() {
let byte_store = mount_in_memory_storage(&mut editor).await;
// Mount-time snapshot: capture the new-document graph as the base interaction.
editor.active_document_mut().commit_storage_snapshot(&byte_store);
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let before_rect = editor.active_document().network_interface.document_network().clone();
editor.draw_rect(0., 0., 100., 100.).await;
@@ -552,12 +489,10 @@ async fn live_undo_new_document_draw_rect() {
assert_eq!(editor.active_document().network_interface.document_network(), &before_rect, "undo should restore the pre-rect network");
}
/// Pasting an image is one user action and must be one undo step. The paste handler emits a single
/// `AddTransaction` bracketing the layer add, name set, reparent, and transform, so a single undo has
/// to remove the whole layer. When the name set opens its own nested transaction (the historical
/// wart), the first undo only reverts the name and leaves the layer behind, so this asserts the layer
/// count returns to its pre-paste value after exactly one undo. Matches the `Gdd`'s one-interaction
/// coalescing, which is the behavior the undo shadow validates against.
/// Pasting an image is one user action and must be one undo step: the paste handler brackets the layer add,
/// name set, reparent, and transform in a single transaction. Were the name set to open its own nested
/// transaction (a historical wart), the first undo would revert only the name and leave the layer behind, so
/// this asserts the layer count returns to its pre-paste value after exactly one undo.
#[tokio::test]
async fn paste_image_with_name_is_one_undo_step() {
let mut editor = EditorTestUtils::create();
@@ -569,7 +504,7 @@ async fn paste_image_with_name_is_one_undo_step() {
// own transaction. `create_raster_image` passes `name: None` and so wouldn't exercise this path.
let image = Image::new(2, 2, Color::WHITE);
editor
.handle_message(PortfolioMessage::PasteImage {
.handle_message(PortfolioMessage::InsertImage {
name: Some("pasted".into()),
image,
mouse: None,
@@ -590,22 +525,21 @@ async fn paste_image_with_name_is_one_undo_step() {
);
}
/// Pasting an image registers a resource; undoing the paste reverts the interaction's `AddResource` in the
/// `Gdd` cursor while the runtime keeps the resource alive for legacy redo. So the cursor legitimately
/// holds fewer resources than a fresh `from_runtime`, and the shadow must tolerate that. This drives
/// the relaxed comparison: every resource the current network references must be present in the cursor,
/// and any extra the runtime carries must be history-only (not referenced by the restored network).
/// Undoing an image paste reverts the interaction's `AddResource` in the `Gdd` cursor while the runtime keeps
/// the resource alive for legacy redo, so the cursor legitimately holds fewer resources than a fresh
/// `from_runtime`. Drives the relaxed comparison: every resource the current network references must be in
/// the cursor, and any extra the runtime carries must be history-only.
#[tokio::test]
async fn undo_image_paste_resources_subset_of_runtime() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let byte_store = mount_in_memory_storage(&mut editor).await;
editor.active_document_mut().commit_storage_snapshot(&byte_store);
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let image = Image::new(2, 2, Color::WHITE);
editor
.handle_message(PortfolioMessage::PasteImage {
.handle_message(PortfolioMessage::InsertImage {
name: Some("pasted".into()),
image,
mouse: None,
@@ -616,7 +550,7 @@ async fn undo_image_paste_resources_subset_of_runtime() {
editor.handle_message(DocumentMessage::Undo).await;
let document = editor.active_document();
let storage = document.storage.as_ref().expect("storage mounted");
let storage = document.storage().expect("storage mounted");
let stored: std::collections::BTreeSet<_> = storage.registry().resources.keys().copied().collect();
// Every resource the restored network still references must be in the cursor.
@@ -631,20 +565,17 @@ async fn undo_image_paste_resources_subset_of_runtime() {
assert!(stored.is_subset(&runtime), "cursor holds a resource the runtime dropped: stored={stored:?} runtime={runtime:?}");
}
/// Two distinct edits (draw an ellipse, then paste an image) on an *opened* document are two undo
/// steps. Undoing twice must step the `Gdd` cursor back two interactions in lockstep with the legacy
/// snapshot path. The document is opened with existing content (a real demo artwork), so its non-empty
/// base is the loaded state, which is *not* a legacy undo step. The mount-time base must therefore not
/// become an undoable `Gdd` interaction, or the cursor gains one more interaction than the legacy path has undo
/// steps and lags by a interaction once undo reaches back toward the base. Reproduces the live "open, draw,
/// paste image, undo twice" divergence.
/// Two edits (draw, then paste) on an opened document are two undo steps; undoing twice must step the `Gdd`
/// cursor back two interactions in lockstep with the legacy path. The loaded base is not itself an undo
/// step, so the mount-time base must not become an undoable `Gdd` interaction, or the cursor lags the legacy
/// path by one once undo reaches the base. Reproduces the live "open, draw, paste image, undo twice" divergence.
#[tokio::test]
async fn undo_twice_steps_cursor_two_interactions() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let byte_store = mount_in_memory_storage(&mut editor).await;
editor.active_document_mut().commit_storage_snapshot(&byte_store);
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let base = editor.active_document().network_interface.document_network().clone();
editor.draw_rect(0., 0., 100., 100.).await;
@@ -652,7 +583,7 @@ async fn undo_twice_steps_cursor_two_interactions() {
let image = Image::new(2, 2, Color::WHITE);
editor
.handle_message(PortfolioMessage::PasteImage {
.handle_message(PortfolioMessage::InsertImage {
name: Some("pasted".into()),
image,
mouse: None,
@@ -669,15 +600,14 @@ async fn undo_twice_steps_cursor_two_interactions() {
);
assert_cursor_matches_runtime(editor.active_document(), "after first undo");
// Re-stage after the undo, reproducing the live editor's post-undo graph re-evaluation. The pasted
// image's resource is still in the runtime cache (kept alive for redo) though its node is gone, so a
// naive snapshot would re-detect it as a new `AddResource` and retire it as a phantom interaction, which
// would knock the cursor out of lockstep on the next undo. Scoping the snapshot to network-referenced
// resources must keep this a no-op.
editor.active_document_mut().commit_storage_snapshot(&byte_store);
// Re-stage after the undo (the live editor re-evaluates the graph). The pasted image's resource is still
// cached for redo though its node is gone, so a naive snapshot would re-detect it as a new `AddResource`
// and retire a phantom interaction, knocking the cursor out of lockstep. Scoping the snapshot to
// network-referenced resources must keep this a no-op.
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
// Second undo: removes the rectangle, back to the loaded base. The cursor must step a second interaction
// and land on the base, not one interaction short (paste resource resurfaced as a phantom interaction).
// and land on the base, not one short.
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(
editor.active_document().network_interface.document_network(),
@@ -686,20 +616,18 @@ async fn undo_twice_steps_cursor_two_interactions() {
);
assert_cursor_matches_runtime(editor.active_document(), "after second undo");
// Back at the loaded base, neither path should be able to undo further: the load is not an undo step.
// If the `Gdd` retired the mount base as its own interaction, the cursor can still undo here while legacy
// cannot, which is the off-by-one that makes the cursor lag the legacy path by a interaction.
let storage = editor.active_document().storage.as_ref().expect("storage mounted");
// Back at the loaded base, neither path can undo further: the load is not an undo step. Had the `Gdd`
// retired the mount base as its own interaction, the cursor could still undo here, the off-by-one.
let storage = editor.active_document().storage().expect("storage mounted");
assert!(!storage.can_undo(), "cursor must not undo past the loaded base (the load is not an undo step)");
}
/// Assert the `Gdd` cursor's stored registry matches a fresh `from_runtime` of the current interface,
/// mirroring the live shadow check (`verify_storage_cursor_matches_runtime`): node set, network set,
/// and per-network export wiring must agree. The runtime keeps resources alive across undo (for legacy
/// redo) while the cursor reverts the interaction's `AddResource`, so the runtime's resource set is allowed
/// to be a superset of the cursor's, but a resource the current network references must be present.
/// Assert the `Gdd` cursor's stored registry matches a fresh `from_runtime` of the current interface (node
/// set, network set, per-network export wiring), mirroring the live `verify_cursor_matches_runtime` check.
/// The runtime's resource set may be a superset (it keeps undone resources alive for redo), but every
/// resource the current network references must be present.
fn assert_cursor_matches_runtime(document: &DocumentMessageHandler, at: &str) {
let storage = document.storage.as_ref().expect("storage mounted");
let storage = document.storage().expect("storage mounted");
let peer = storage.session().peer();
let network = document.network_interface.document_network().clone();
@@ -731,15 +659,14 @@ async fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> HashMapResourc
let gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0x5EED, "test".into(), "test".into())
.await
.expect("create_in");
editor.active_document_mut().storage = Some(gdd);
editor.active_document_mut().set_storage(Some(gdd));
HashMapResourceStorage::new()
}
/// Open a real demo artwork, mount storage, edit it, and trigger autosave. The autosave runs
/// `verify_storage_round_trip`, which panics (in debug, which tests are) on any conversion or
/// round-trip drift — so a clean run is itself the assertion that the whole pipeline holds on real,
/// non-synthetic document data. Also checks that committing edits grows the retired-delta history
/// and that the editor's undo reverts the modification.
/// `verify_storage_round_trip`, which panics in tests on any conversion or round-trip drift, so a clean run
/// is itself the assertion that the whole pipeline holds on real document data. Also checks that committing
/// edits grows the retired-delta history and that undo reverts the modification.
#[tokio::test]
async fn demo_artwork_edit_autosaves_and_round_trips() {
let mut editor = EditorTestUtils::create();
@@ -756,8 +683,8 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
let byte_store = mount_in_memory_storage(&mut editor).await;
// First autosave: captures the loaded document. `verify_storage_round_trip` panics on drift.
editor.active_document_mut().commit_storage_snapshot(&byte_store);
let history_after_open = editor.active_document().storage.as_ref().unwrap().session().history().count();
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let history_after_open = editor.active_document().storage().unwrap().session().history().count();
// Snapshot the network, then make a real modification.
let before_edit = editor.active_document().network_interface.document_network().clone();
@@ -766,8 +693,8 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
assert_ne!(before_edit, after_edit, "drawing a rectangle should change the document network");
// Second autosave: again verifies the round-trip, and the edit must produce new retired history.
editor.active_document_mut().commit_storage_snapshot(&byte_store);
let history_after_edit = editor.active_document().storage.as_ref().unwrap().session().history().count();
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let history_after_edit = editor.active_document().storage().unwrap().session().history().count();
assert!(
history_after_edit > history_after_open,
"committing an edit should append retired deltas: {history_after_open} -> {history_after_edit}"
@@ -779,5 +706,5 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
assert_eq!(after_undo, before_edit, "undo should restore the pre-edit network");
// Autosaving the undone state still round-trips cleanly (no drift panic).
editor.active_document_mut().commit_storage_snapshot(&byte_store);
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
}
@@ -0,0 +1,88 @@
//! Shared helpers for the storage integration tests ([`metadata_tests`](super::metadata_tests) and
//! [`round_trip_tests`](super::round_trip_tests)): loading demo artwork, walking every addressable
//! node, and pushing a document through a real `Gdd` save/reopen.
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::document::{DocumentNodeImplementation, NodeId};
use graph_storage::PeerId;
use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::{DocumentSettings, StorageMetadataView, build_interface_from_storage};
/// Load a demo `.graphite` straight into a `DocumentMessageHandler` for inspection.
pub fn load_demo(file_name: &str) -> DocumentMessageHandler {
let path = format!("../demo-artwork/{file_name}");
let content = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("Failed to read {path}: {e}"));
DocumentMessageHandler::deserialize_document(&content).unwrap_or_else(|e| panic!("Failed to deserialize {path}: {e:?}"))
}
/// Walk every node in every nested network and collect `(network_path, local_id)` pairs, so a test can
/// iterate every node addressable from the metadata side.
pub fn node_paths(interface: &NodeNetworkInterface) -> Vec<(Vec<NodeId>, NodeId)> {
fn walk(interface: &NodeNetworkInterface, path: Vec<NodeId>, out: &mut Vec<(Vec<NodeId>, NodeId)>) {
let Some(network) = interface.nested_network(&path) else { return };
for (&local_id, node) in &network.nodes {
out.push((path.clone(), local_id));
if matches!(node.implementation, DocumentNodeImplementation::Network(_)) {
let mut child = path.clone();
child.push(local_id);
walk(interface, child, out);
}
}
}
let mut out = Vec::new();
walk(interface, Vec::new(), &mut out);
out
}
/// Result of round-tripping a document through a `Gdd`: the runtime interface rebuilt from the reopened
/// storage, the reopened registry, and the reopened per-peer view settings (`ui::doc::*`).
pub struct RoundTrip {
pub rebuilt: NodeNetworkInterface,
pub registry: graph_storage::Registry,
pub view_settings: std::collections::BTreeMap<String, serde_json::Value>,
}
/// Push `document`'s current runtime state through a fresh in-memory `Gdd` and reopen it. The commit goes
/// through `commit_from_runtime` (the real autosave path: stage hot ops -> retire -> persist); the reopen
/// reads the working copy back from the same container bytes, exercising the whole codec / file / replay
/// pipeline rather than just the in-memory conversion.
pub async fn round_trip_through_gdd(document: &DocumentMessageHandler) -> RoundTrip {
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
gdd.commit_from_runtime(&network, &view, &document.resources.registry, &byte_store).expect("commit_from_runtime");
// Per-peer view settings persist in session.json, separate from the registry commit.
let view_settings = DocumentSettings {
document_ptz: &document.document_ptz,
render_mode: &document.render_mode,
overlays_visibility: &document.overlays_visibility_settings,
rulers_visible: document.rulers_visible,
snapping_state: &document.snapping_state,
collapsed: &document.collapsed,
}
.to_view_map();
gdd.set_view_settings(view_settings).expect("set_view_settings");
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.expect("open_in");
let declarations = reopened.declarations(&byte_store).await;
let registry = reopened.registry().clone();
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime_with_full_metadata");
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage");
let view_settings = reopened.view_settings().clone();
RoundTrip { rebuilt, registry, view_settings }
}
@@ -1,23 +0,0 @@
use super::network_interface::NodeTemplate;
use graph_craft::document::NodeId;
#[repr(u8)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, PartialEq, Eq, Debug)]
pub enum Clipboard {
Internal,
Device,
_InternalClipboardCount, // Keep this as the last entry of **internal** clipboards since it is used for counting the number of enum variants
}
pub const INTERNAL_CLIPBOARD_COUNT: u8 = Clipboard::_InternalClipboardCount as u8;
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct CopyBufferEntry {
pub nodes: Vec<(NodeId, NodeTemplate)>,
pub selected: bool,
pub visible: bool,
pub locked: bool,
pub collapsed: bool,
}
@@ -1,4 +1,3 @@
pub mod clipboards;
pub mod document_metadata;
pub mod error;
pub mod misc;
@@ -353,6 +353,12 @@ impl NodeNetworkInterface {
node.inputs.len()
}
/// Whether the node has an exposed input at index 0 to accept the horizontal flow from upstream.
/// A node without one (e.g. a generator) can only be the most-upstream node in a chain.
pub fn has_primary_input(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
self.input_from_connector(&InputConnector::node(*node_id, 0), network_path).is_some_and(|input| input.is_exposed())
}
pub fn number_of_outputs(&self, node_id: &NodeId, network_path: &[NodeId]) -> usize {
let Some(implementation) = self.implementation(node_id, network_path) else {
log::error!("Could not get node {node_id} in number_of_outputs");
@@ -1055,6 +1061,35 @@ impl NodeNetworkInterface {
node_metadata.persistent_metadata.pinned
}
/// The given network's pinned nodes in display order: pinning appends, dragging rearranges, and any not yet recorded go last.
pub fn ordered_pinned_nodes(&self, network_path: &[NodeId]) -> Vec<NodeId> {
let Some(network) = self.nested_network(network_path) else { return Vec::new() };
let order = self
.network_metadata(network_path)
.map(|network_metadata| network_metadata.persistent_metadata.pinned_node_order.clone())
.unwrap_or_default();
// Follow the saved order, keeping only nodes that still exist and are still pinned
let mut pinned_nodes = order
.iter()
.copied()
.filter(|node_id| network.nodes.contains_key(node_id) && self.is_pinned(node_id, network_path))
.collect::<Vec<_>>();
// Append any pinned nodes missing from the saved order at the end
let mut unordered = network
.nodes
.keys()
.copied()
.filter(|node_id| self.is_pinned(node_id, network_path) && !order.contains(node_id))
.collect::<Vec<_>>();
unordered.sort();
pinned_nodes.extend(unordered);
pinned_nodes
}
pub fn is_visible(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
let Some(node) = self.document_node(node_id, network_path) else {
log::error!("Could not get node in is_visible");
@@ -3418,51 +3453,65 @@ impl NodeNetworkInterface {
// Public mutable methods
impl NodeNetworkInterface {
pub fn copy_all_navigation_metadata(&mut self, other_interface: &NodeNetworkInterface) {
/// Walk every network at every nesting level, invoking `visit` with each network's path and a mutable
/// reference to its metadata. Only nodes that contain a nested network are recursed into.
fn for_each_network_metadata_mut(&mut self, mut visit: impl FnMut(&[NodeId], &mut NodeNetworkMetadata)) {
let mut stack = vec![vec![]];
while let Some(path) = stack.pop() {
let Some(self_network_metadata) = self.network_metadata_mut(&path) else {
continue;
};
if let Some(other_network_metadata) = other_interface.network_metadata(&path) {
self_network_metadata.persistent_metadata.navigation_metadata = other_network_metadata.persistent_metadata.navigation_metadata.clone();
}
stack.extend(self_network_metadata.persistent_metadata.node_metadata.keys().map(|node_id| {
let mut current_path: Vec<NodeId> = path.clone();
current_path.push(*node_id);
current_path
}));
visit(&path, self_network_metadata);
// Only nodes that contain a nested network have metadata to recurse into, so skip leaf nodes.
stack.extend(
self_network_metadata
.persistent_metadata
.node_metadata
.iter()
.filter(|(_, node_metadata)| node_metadata.persistent_metadata.network_metadata.is_some())
.map(|(node_id, _)| {
let mut current_path: Vec<NodeId> = path.clone();
current_path.push(*node_id);
current_path
}),
);
}
}
/// Copy every piece of transient view and selection state from `other_interface` onto `self`, for each
/// network at every nesting level: navigation metadata (pan/zoom), selection undo/redo history, and the
/// document-to-viewport canvas camera. Used when an interface is rebuilt from storage (the `Gdd` undo/redo
/// cursor) and must keep the user's current view and selection rather than reset them, since the registry
/// models document content only. `resolved_types` is a separate runtime cache the caller handles.
pub fn copy_all_transient_view_state(&mut self, other_interface: &NodeNetworkInterface) {
let mut stack = vec![vec![]];
while let Some(path) = stack.pop() {
let Some(self_network_metadata) = self.network_metadata_mut(&path) else {
continue;
};
pub fn copy_all_navigation_metadata(&mut self, other_interface: &NodeNetworkInterface) {
self.for_each_network_metadata_mut(|path, self_network_metadata| {
if let Some(other_network_metadata) = other_interface.network_metadata(path) {
self_network_metadata.persistent_metadata.navigation_metadata = other_network_metadata.persistent_metadata.navigation_metadata.clone();
}
});
}
if let Some(other_network_metadata) = other_interface.network_metadata(&path) {
/// Copy all transient view and selection state from `other_interface` onto `self` at every nesting level:
/// navigation metadata (pan/zoom), selection undo/redo history, and the document-to-viewport camera. Lets
/// an interface rebuilt from storage keep the user's current view rather than reset it. `resolved_types`
/// is a separate runtime cache the caller handles.
pub fn copy_all_transient_view_state(&mut self, other_interface: &NodeNetworkInterface) {
self.for_each_network_metadata_mut(|path, self_network_metadata| {
if let Some(other_network_metadata) = other_interface.network_metadata(path) {
let self_persistent = &mut self_network_metadata.persistent_metadata;
let other_persistent = &other_network_metadata.persistent_metadata;
self_persistent.navigation_metadata = other_persistent.navigation_metadata.clone();
self_persistent.previewing = other_persistent.previewing;
// The live preview root may name a node that the rebuilt-from-storage network no longer contains
// (e.g. after a storage undo), so only carry it over when the root still exists; otherwise drop it.
self_persistent.previewing = match other_persistent.previewing {
Previewing::Yes {
root_node_to_restore: Some(root_node),
} if !self_persistent.node_metadata.contains_key(&root_node.node_id) => Previewing::No,
previewing => previewing,
};
self_persistent.selection_undo_history = other_persistent.selection_undo_history.clone();
self_persistent.selection_redo_history = other_persistent.selection_redo_history.clone();
}
stack.extend(self_network_metadata.persistent_metadata.node_metadata.keys().map(|node_id| {
let mut current_path: Vec<NodeId> = path.clone();
current_path.push(*node_id);
current_path
}));
}
});
self.document_metadata.document_to_viewport = other_interface.document_metadata.document_to_viewport;
}
@@ -4271,6 +4320,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);
@@ -4570,6 +4623,15 @@ impl NodeNetworkInterface {
self.set_chain_position(&previous_chain_node, network_path);
}
}
// Prune this network's pinned display order down to the nodes that still exist, dropping any that were actually removed
let surviving_nodes = self.nested_network(network_path).map(|network| network.nodes.keys().copied().collect::<HashSet<_>>());
if let Some(surviving_nodes) = surviving_nodes
&& let Some(network_metadata) = self.network_metadata_mut(network_path)
{
network_metadata.persistent_metadata.pinned_node_order.retain(|node_id| surviving_nodes.contains(node_id));
}
self.unload_all_nodes_bounding_box(network_path);
// Instead of unloaded all node click targets, just unload the nodes upstream from the deleted nodes. unload_upstream_node_click_targets will not work since the nodes have been deleted.
self.unload_all_nodes_click_targets(network_path);
@@ -4752,6 +4814,43 @@ impl NodeNetworkInterface {
};
node_metadata.persistent_metadata.pinned = pinned;
// Track the node in this network's pinned display order: append when newly pinned, prune when unpinned
if let Some(network_metadata) = self.network_metadata_mut(network_path) {
let order = &mut network_metadata.persistent_metadata.pinned_node_order;
if pinned {
if !order.contains(node_id) {
order.push(*node_id);
}
} else {
order.retain(|id| id != node_id);
}
}
self.transaction_modified();
}
/// Reorders a pinned node within its network's Properties panel display order so it ends up at `insert_index` among the
/// pinned nodes (0 being the topmost). Rebuilds the order from the list as currently shown, which also drops stale entries.
pub fn reorder_pinned_node(&mut self, node_id: NodeId, insert_index: usize, network_path: &[NodeId]) {
let shown = self.ordered_pinned_nodes(network_path);
let Some(from) = shown.iter().position(|id| *id == node_id) else { return };
let to = (if insert_index > from { insert_index - 1 } else { insert_index }).min(shown.len().saturating_sub(1));
if to == from {
return;
}
let mut new_order = shown;
let moved = new_order.remove(from);
new_order.insert(to, moved);
let Some(network_metadata) = self.network_metadata_mut(network_path) else {
log::error!("Could not get network_metadata in reorder_pinned_node");
return;
};
network_metadata.persistent_metadata.pinned_node_order = new_order;
self.transaction_modified();
}
@@ -6030,6 +6129,68 @@ impl NodeNetworkInterface {
self.force_set_upstream_to_chain(node_id, network_path);
}
}
/// Reorders a node within its layer's horizontal chain so it ends up at `insert_index` among the chain's nodes,
/// where index 0 is the node closest to the layer. The connection feeding the top (most-upstream end) of the chain
/// is preserved, as are each node's other (non-primary) inputs.
pub fn reorder_chain_node(&mut self, node_id: NodeId, insert_index: usize, network_path: &[NodeId]) {
let Some(layer) = self.downstream_layer_for_chain_node(&node_id, network_path) else {
log::error!("Could not find downstream layer for chain node {node_id} in reorder_chain_node");
return;
};
// The nodes in the layer's chain, ordered from closest-to-layer outward, stopping at the next layer
let chain = self
.upstream_flow_back_from_nodes(vec![layer], network_path, FlowType::HorizontalFlow)
.skip(1)
.take_while(|upstream_id| !self.is_layer(upstream_id, network_path))
.collect::<Vec<_>>();
// A source node (no primary input) stays pinned at the most-upstream end; only the nodes below it reorder
let pinned_source = chain.last().copied().filter(|last| !self.has_primary_input(last, network_path));
let reorderable = &chain[..chain.len() - pinned_source.is_some() as usize];
let Some(from) = reorderable.iter().position(|id| *id == node_id) else {
log::error!("Node {node_id} is not a reorderable node in its layer's chain in reorder_chain_node");
return;
};
// The drop gap is measured against the reorderable nodes that still include the dragged node, so shift it down by one if the node is being removed from before the gap
let to = (if insert_index > from { insert_index - 1 } else { insert_index }).min(reorderable.len() - 1);
if to == from {
return;
}
let mut new_order = reorderable.to_vec();
new_order.remove(from);
new_order.insert(to, node_id);
// The most-upstream reorderable node connects up to the pinned source, or else whatever fed the top of the chain
let tail_input = if let Some(source) = pinned_source {
NodeInput::node(source, 0)
} else {
let Some(input) = self.input_from_connector(&InputConnector::node(*chain.last().unwrap(), 0), network_path).cloned() else {
log::error!("Could not get the upstream input of the chain in reorder_chain_node");
return;
};
input
};
// Disconnect first so the rewiring can't transiently form a cycle (the pinned source keeps its wiring)
for &chain_node in reorderable {
self.disconnect_input(&InputConnector::node(chain_node, 0), network_path);
}
// Rewire in the new order: layer's secondary input -> new_order[0] -> ... -> new_order[last] -> tail input
self.set_input(&InputConnector::node(layer, 1), NodeInput::node(new_order[0], 0), network_path);
for pair in new_order.windows(2) {
self.set_input(&InputConnector::node(pair[0], 0), NodeInput::node(pair[1], 0), network_path);
}
self.set_input(&InputConnector::node(*new_order.last().unwrap(), 0), tail_input, network_path);
// Re-establish chain positioning for the reordered nodes
self.force_set_upstream_to_chain(&new_order[0], network_path);
}
}
#[derive(PartialEq)]
@@ -6374,6 +6535,9 @@ pub struct NodeNetworkPersistentMetadata {
/// Node metadata must exist for every document node in the network
#[serde(serialize_with = "graphene_std::vector::serialize_hashmap", deserialize_with = "graphene_std::vector::deserialize_hashmap")]
pub node_metadata: HashMap<NodeId, DocumentNodeMetadata>,
/// The display order of pinned nodes in the Properties panel (shown when nothing is selected in this network), keyed by node ID.
#[serde(default)]
pub pinned_node_order: Vec<NodeId>,
/// Cached metadata for each node, which is calculated when adding a node to node_metadata
/// Indicates whether the network is currently rendered with a particular node that is previewed, and if so, which connection should be restored when the preview ends.
pub previewing: Previewing,
@@ -6863,17 +7027,22 @@ pub enum TransactionStatus {
fn collect_network_resources(network: &NodeNetwork, out: &mut HashSet<ResourceId>) {
for node in network.nodes.values() {
for input in &node.inputs {
if let NodeInput::Value { tagged_value, .. } = input
&& let TaggedValue::Resource(id) = &**tagged_value
{
out.insert(*id);
}
}
if let DocumentNodeImplementation::Network(nested) = &node.implementation {
collect_network_resources(nested, out);
collect_node_resources(node, out);
}
}
/// Collects resource IDs referenced by a node and its nested networks.
pub fn collect_node_resources(node: &DocumentNode, out: &mut HashSet<ResourceId>) {
for input in &node.inputs {
if let NodeInput::Value { tagged_value, .. } = input
&& let TaggedValue::Resource(id) = &**tagged_value
{
out.insert(*id);
}
}
if let DocumentNodeImplementation::Network(nested) = &node.implementation {
collect_network_resources(nested, out);
}
}
#[cfg(test)]
@@ -6888,18 +7057,19 @@ mod network_interface_tests {
.await;
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![rectangle] }).await;
let frontend_messages = editor.handle_message(NodeGraphMessage::Copy).await;
let serialized_nodes = frontend_messages
let clipboard = frontend_messages
.into_iter()
.find_map(|msg| match msg {
FrontendMessage::TriggerClipboardWrite { content } => Some(content),
_ => None,
})
.expect("copy message should be dispatched")
.strip_prefix("graphite/nodes: ")
.expect("should start with magic string")
.to_string();
println!("Serialized: {serialized_nodes}");
editor.handle_message(NodeGraphMessage::PasteNodes { serialized_nodes }).await;
.expect("copy message should be dispatched");
println!("Clipboard: {clipboard}");
editor
.handle_message(ClipboardMessage::ReadClipboard {
content: ClipboardContentRaw::Text(clipboard),
})
.await;
let nodes = &mut editor.active_document_mut().network_interface.network_mut(&[]).unwrap().nodes;
let orignal = nodes.remove(&rectangle).expect("original node should exist");
assert!(
@@ -61,7 +61,7 @@ impl TypeSource {
FrontendGraphDataType::Number
}
TaggedValue::Color(_) => FrontendGraphDataType::Color,
TaggedValue::FillGradient(_) | TaggedValue::Gradient(_) => FrontendGraphDataType::Gradient,
TaggedValue::LegacyGradient(_) | TaggedValue::Gradient(_) => FrontendGraphDataType::Gradient,
TaggedValue::String(_) => FrontendGraphDataType::Typography,
// Types whose `TaggedValue` variant has been removed are routed through `TypeDefault` and identified by the descriptor's type name.
TaggedValue::TypeDefault(td) => match td.name.as_ref() {
@@ -1,5 +1,5 @@
//! Bridge between `NodeNetworkInterface` and `graph-storage`'s `NodeMetadataSource` trait, plus
//! an integration round-trip test against a demo `.graphite` document.
//! Bridge between `NodeNetworkInterface` and `graph-storage`'s `NodeMetadataSource` trait.
//! Conversion round-trip tests live in `storage_metadata_tests`.
//!
//! The trait impl lives on the [`StorageMetadataView`] wrapper (not on `NodeNetworkInterface`
//! directly) because several trait method names collide with inherent methods, and Rust silently
@@ -15,8 +15,8 @@ use graphene_std::vector::style::RenderMode;
use super::memo_network::MemoNetwork;
use super::{
DocumentNodePersistentMetadata, DocumentNodeTransientMetadata, InputMetadata, InputPersistentMetadata, LayerPosition, NodeNetworkInterface, NodeNetworkMetadata, NodePersistentMetadata,
NodePosition, NodeTypePersistentMetadata, PTZ, Previewing,
DocumentNodePersistentMetadata, DocumentNodeTransientMetadata, InputMetadata, InputPersistentMetadata, LayerPosition, NavigationMetadata, NodeNetworkInterface, NodeNetworkMetadata,
NodePersistentMetadata, NodePosition, NodeTypePersistentMetadata, PTZ, Previewing,
};
use crate::messages::portfolio::document::overlays::utility_types::OverlaysVisibilitySettings;
use crate::messages::portfolio::document::utility_types::misc::SnappingState;
@@ -173,9 +173,11 @@ pub fn build_interface_from_storage(network: NodeNetwork, node_entries: Vec<Node
apply_entries_into_tree(&network, &mut network_metadata, node_entries)?;
apply_network_entries_into_tree(&mut network_metadata, network_entries);
let mut interface = NodeNetworkInterface::default();
interface.network = MemoNetwork::new(network);
interface.network_metadata = network_metadata;
let interface = NodeNetworkInterface {
network: MemoNetwork::new(network),
network_metadata,
..Default::default()
};
Ok(interface)
}
@@ -186,10 +188,9 @@ pub fn network_ids_from_entries(network_entries: &[NetworkMetadataEntry]) -> Has
}
/// Collect the per-network, per-peer view state (node-graph nav + previewing) from `interface` into a
/// map keyed by the stable storage [`NetworkId`](graph_storage::NetworkId). `network_ids` maps each
/// runtime `network_path` to its id (from the `from_runtime`/`to_runtime` conversion). This is what the
/// editor persists into `session.json` so it stays out of the CRDT/history. Networks at their default
/// nav with no preview produce no entry.
/// `session.json` map keyed by the stable storage [`NetworkId`](graph_storage::NetworkId), which
/// `network_ids` resolves from each runtime `network_path`. Networks at their default nav with no preview
/// produce no entry.
pub fn collect_network_view_settings(
interface: &NodeNetworkInterface,
network_ids: &HashMap<Vec<NodeId>, graph_storage::NetworkId>,
@@ -201,21 +202,30 @@ pub fn collect_network_view_settings(
continue;
};
let navigation = &network_metadata.persistent_metadata.navigation_metadata;
let default_navigation = NavigationMetadata::default();
// Only persist nav fields that diverge from the default, so a network at its default view stays out
// of `session.json` (the `if !settings.is_empty()` guard below skips it entirely).
let mut settings = BTreeMap::new();
if let Ok(value) = serde_json::to_value(navigation.node_graph_ptz) {
if navigation.node_graph_ptz != default_navigation.node_graph_ptz
&& let Ok(value) = serde_json::to_value(navigation.node_graph_ptz)
{
settings.insert(session::network::NAV_PTZ.to_string(), value);
}
if let Ok(value) = serde_json::to_value(navigation.node_graph_to_viewport) {
if navigation.node_graph_to_viewport != default_navigation.node_graph_to_viewport
&& let Ok(value) = serde_json::to_value(navigation.node_graph_to_viewport)
{
settings.insert(session::network::NAV_TRANSFORM.to_string(), value);
}
if let Ok(value) = serde_json::to_value(navigation.node_graph_width) {
if navigation.node_graph_width != default_navigation.node_graph_width
&& let Ok(value) = serde_json::to_value(navigation.node_graph_width)
{
settings.insert(session::network::NAV_WIDTH.to_string(), value);
}
// Skip the inert `Previewing::No` default so a network that has never been previewed stays empty.
if !matches!(network_metadata.persistent_metadata.previewing, Previewing::No)
&& let Ok(value) = serde_json::to_value(&network_metadata.persistent_metadata.previewing)
&& let Ok(value) = serde_json::to_value(network_metadata.persistent_metadata.previewing)
{
settings.insert(session::network::PREVIEWING.to_string(), value);
}
@@ -380,342 +390,3 @@ fn input_metadata_entry_to_runtime(entry: InputMetadataEntry) -> InputMetadata {
..Default::default()
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use graph_storage::{NodeMetadataSource, PeerId, Registry};
use super::*;
use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler;
/// Load a demo `.graphite` straight into a `DocumentMessageHandler` for inspection.
fn load_demo(file_name: &str) -> DocumentMessageHandler {
let path = format!("../demo-artwork/{file_name}");
let content = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("Failed to read {path}: {e}"));
DocumentMessageHandler::deserialize_document(&content).unwrap_or_else(|e| panic!("Failed to deserialize {path}: {e:?}"))
}
/// Walk every node in every nested network and collect `(network_path, local_id)` pairs so the
/// test can iterate every node addressable from the metadata side.
fn collect_all_node_paths(interface: &NodeNetworkInterface) -> Vec<(Vec<NodeId>, NodeId)> {
fn walk(interface: &NodeNetworkInterface, path: Vec<NodeId>, out: &mut Vec<(Vec<NodeId>, NodeId)>) {
let Some(network) = interface.nested_network(&path) else { return };
for (&local_id, node) in &network.nodes {
out.push((path.clone(), local_id));
if matches!(&node.implementation, graph_craft::document::DocumentNodeImplementation::Network(_)) {
let mut child = path.clone();
child.push(local_id);
walk(interface, child, out);
}
}
}
let mut out = Vec::new();
walk(interface, Vec::new(), &mut out);
out
}
/// Loads a demo artwork, round-trips its `NodeNetwork + NodeNetworkInterface metadata` through
/// `Registry`, and asserts every node's `ui::*` attributes survive unchanged.
///
/// Uses one demo (rather than the full set) because this is an exhaustive per-node check.
#[test]
fn editor_metadata_round_trip_against_demo() {
let document = load_demo("changing-seasons.graphite");
let interface = &document.network_interface;
let source = StorageMetadataView::new(interface);
let network = interface.document_network().clone();
let conversion = Registry::convert_from_runtime(&network, &source, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations().expect("rebuild declarations");
let registry = conversion.registry;
let (_converted_network, entries) = registry.to_runtime_with_metadata(&declarations).expect("to_runtime_with_metadata failed");
// Index emitted entries by their (network_path, local_id) address.
let entries_by_address: HashMap<(Vec<NodeId>, NodeId), &graph_storage::NodeMetadataEntry> = entries.iter().map(|e| ((e.network_path.clone(), e.local_id), e)).collect();
let mut checked_any_position = false;
let mut checked_any_layer = false;
let mut checked_any_input_metadata = false;
for (network_path, local_id) in collect_all_node_paths(interface) {
let expected_position = source.position(&network_path, local_id);
let expected_is_layer = source.is_layer(&network_path, local_id);
let expected_display = source.display_name(&network_path, local_id).map(str::to_owned);
let expected_locked = source.locked(&network_path, local_id);
let expected_pinned = source.pinned(&network_path, local_id);
let expected_output_names = source.output_names(&network_path, local_id);
// Pull per-input metadata directly off the runtime side. We use the runtime invariant
// (`input_metadata.len() == inputs.len()`) as the iteration bound rather than calling the
// trait per index, since the trait would return `None` past the end and we want a strict
// slot-by-slot comparison.
let input_count = interface.document_node(&local_id, &network_path).map(|node| node.inputs.len()).unwrap_or(0);
let any_input_metadata_present = (0..input_count).any(|i| {
source.input_name(&network_path, local_id, i).is_some_and(|s| !s.is_empty())
|| source.input_description(&network_path, local_id, i).is_some_and(|s| !s.is_empty())
|| source.widget_override(&network_path, local_id, i).is_some()
|| !source.input_data(&network_path, local_id, i).is_empty()
});
let any_metadata = expected_position.is_some()
|| expected_is_layer
|| expected_display.as_deref().is_some_and(|s| !s.is_empty())
|| expected_locked
|| expected_pinned
|| any_input_metadata_present
|| !expected_output_names.is_empty();
if !any_metadata {
assert!(
entries_by_address.get(&(network_path.clone(), local_id)).is_none(),
"node {local_id:?} in network {network_path:?} has no editor metadata but produced an entry"
);
continue;
}
let entry = entries_by_address
.get(&(network_path.clone(), local_id))
.unwrap_or_else(|| panic!("missing entry for node {local_id:?} in network {network_path:?}"));
assert_eq!(entry.position, expected_position, "position mismatch for node {local_id:?} in network {network_path:?}");
assert_eq!(entry.is_layer, expected_is_layer, "is_layer mismatch for node {local_id:?} in network {network_path:?}");
// The trait round-trip drops empty display names (treats them as "unset") so the entry's
// `display_name` is `None` when the runtime carries `""`. Normalize before comparing.
let normalized_expected_display = expected_display.as_deref().filter(|s| !s.is_empty()).map(str::to_owned);
assert_eq!(
entry.display_name, normalized_expected_display,
"display_name mismatch for node {local_id:?} in network {network_path:?}"
);
assert_eq!(entry.locked, expected_locked, "locked mismatch for node {local_id:?} in network {network_path:?}");
assert_eq!(entry.pinned, expected_pinned, "pinned mismatch for node {local_id:?} in network {network_path:?}");
assert_eq!(entry.output_names, expected_output_names, "output_names mismatch for node {local_id:?} in network {network_path:?}");
// Per-input metadata: the entry's `input_metadata` vec has the same length as the node's
// input slot count, and each slot matches the trait's per-field view (with the same
// "empty string ↔ None" normalization as `display_name`).
assert_eq!(
entry.input_metadata.len(),
input_count,
"input_metadata length mismatch for node {local_id:?} in network {network_path:?}: entry has {}, node has {input_count}",
entry.input_metadata.len(),
);
for (index, input_entry) in entry.input_metadata.iter().enumerate() {
let expected_name = source.input_name(&network_path, local_id, index).filter(|s| !s.is_empty()).map(str::to_owned);
let expected_description = source.input_description(&network_path, local_id, index).filter(|s| !s.is_empty()).map(str::to_owned);
let expected_widget = source.widget_override(&network_path, local_id, index).map(str::to_owned);
let expected_data = source.input_data(&network_path, local_id, index);
assert_eq!(
input_entry.input_name, expected_name,
"input_name mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
input_entry.input_description, expected_description,
"input_description mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
input_entry.widget_override, expected_widget,
"widget_override mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
input_entry.input_data, expected_data,
"input_data mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
}
if entry.position.is_some() {
checked_any_position = true;
}
if entry.is_layer {
checked_any_layer = true;
}
if any_input_metadata_present {
checked_any_input_metadata = true;
}
}
// Sanity: a real artwork should exercise at least these two shapes; otherwise the test is
// just iterating empty metadata and proving nothing.
assert!(checked_any_position, "demo artwork produced no positioned nodes — fixture is wrong or extraction is broken");
assert!(checked_any_layer, "demo artwork produced no layer nodes — fixture is wrong or extraction is broken");
// Demo artworks always have some custom widget overrides / input names; if not, the
// per-input round-trip isn't actually being exercised here.
assert!(checked_any_input_metadata, "demo artwork produced no per-input metadata — fixture is wrong or extraction is broken");
}
/// Full editor-side round-trip: original interface → Registry → (NodeNetwork, Vec<entry>) →
/// freshly-built interface. Asserts the rebuilt interface presents the same `ui::*` state as
/// the original when read through `StorageMetadataView`.
#[test]
fn editor_interface_rebuild_round_trip() {
let document = load_demo("changing-seasons.graphite");
let original = &document.network_interface;
let original_view = StorageMetadataView::new(original);
let network = original.document_network().clone();
let conversion = Registry::convert_from_runtime(&network, &original_view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations().expect("rebuild declarations");
let registry = conversion.registry;
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime_with_full_metadata failed");
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage failed");
let rebuilt_view = StorageMetadataView::new(&rebuilt);
// Every node the original carried must also resolve identically through the rebuilt view.
// Iterating over the *rebuilt* interface verifies that the rebuild covered every node, not
// just the ones the entries vec mentioned.
for (network_path, local_id) in collect_all_node_paths(&rebuilt) {
assert_eq!(
rebuilt_view.position(&network_path, local_id),
original_view.position(&network_path, local_id),
"position mismatch for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
rebuilt_view.is_layer(&network_path, local_id),
original_view.is_layer(&network_path, local_id),
"is_layer mismatch for node {local_id:?} in network {network_path:?}"
);
// Original display names are returned by the source as-is (including `""`). After
// round-trip the rebuilt interface also stores `""` for nodes that had no name set,
// so this comparison is exact.
assert_eq!(
rebuilt_view.display_name(&network_path, local_id),
original_view.display_name(&network_path, local_id),
"display_name mismatch for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
rebuilt_view.locked(&network_path, local_id),
original_view.locked(&network_path, local_id),
"locked mismatch for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
rebuilt_view.pinned(&network_path, local_id),
original_view.pinned(&network_path, local_id),
"pinned mismatch for node {local_id:?} in network {network_path:?}"
);
// Per-input metadata: walk both interfaces' input slots in lockstep.
let original_inputs = original.document_node(&local_id, &network_path).map(|n| n.inputs.len()).unwrap_or(0);
let rebuilt_inputs = rebuilt.document_node(&local_id, &network_path).map(|n| n.inputs.len()).unwrap_or(0);
assert_eq!(
rebuilt_inputs, original_inputs,
"input count mismatch for node {local_id:?} in network {network_path:?}: rebuilt={rebuilt_inputs} original={original_inputs}"
);
for index in 0..rebuilt_inputs {
assert_eq!(
rebuilt_view.input_name(&network_path, local_id, index),
original_view.input_name(&network_path, local_id, index),
"input_name mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
rebuilt_view.input_description(&network_path, local_id, index),
original_view.input_description(&network_path, local_id, index),
"input_description mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
rebuilt_view.widget_override(&network_path, local_id, index),
original_view.widget_override(&network_path, local_id, index),
"widget_override mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
assert_eq!(
rebuilt_view.input_data(&network_path, local_id, index),
original_view.input_data(&network_path, local_id, index),
"input_data mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
);
}
assert_eq!(
rebuilt_view.output_names(&network_path, local_id),
original_view.output_names(&network_path, local_id),
"output_names mismatch for node {local_id:?} in network {network_path:?}"
);
}
// Symmetric: every node in the original must also exist in the rebuilt interface.
for (network_path, local_id) in collect_all_node_paths(original) {
assert!(
rebuilt.nested_network(&network_path).and_then(|n| n.nodes.get(&local_id)).is_some(),
"original node {local_id:?} in network {network_path:?} missing after rebuild"
);
}
// Per-network metadata: every nested network path (including the root) must resolve to the same
// `reference` in the rebuilt interface. Node-graph nav + previewing are per-peer view state that
// lives in `session.json`, not the registry, so they're not round-tripped here.
let mut network_paths_to_check: Vec<Vec<NodeId>> = vec![Vec::new()];
for (network_path, local_id) in collect_all_node_paths(original) {
let mut child = network_path.clone();
child.push(local_id);
if original.nested_network(&child).is_some() {
network_paths_to_check.push(child);
}
}
let mut checked_any_reference = false;
for path in &network_paths_to_check {
assert_eq!(rebuilt_view.reference(path), original_view.reference(path), "reference mismatch for network {path:?}");
if original_view.reference(path).is_some() {
checked_any_reference = true;
}
}
assert!(checked_any_reference, "demo artwork produced no reference metadata — fixture is wrong or extraction is broken");
}
/// Per-peer view settings (`ui::doc::*`) survive the `session.json` round-trip: serialize them into
/// the view map, then apply it onto a fresh handler and confirm each field matches.
#[test]
fn document_settings_round_trip() {
let mut document = load_demo("changing-seasons.graphite");
// Set distinctive, non-default values so the round-trip proves real data moved, not defaults.
document.render_mode = RenderMode::Outline;
document.rulers_visible = false;
document.collapsed = CollapsedLayers(vec![vec![NodeId(7)], vec![NodeId(7), NodeId(42)]]);
let view_settings = DocumentSettings {
document_ptz: &document.document_ptz,
render_mode: &document.render_mode,
overlays_visibility: &document.overlays_visibility_settings,
rulers_visible: document.rulers_visible,
snapping_state: &document.snapping_state,
collapsed: &document.collapsed,
}
.to_view_map();
// Apply the serialized view settings onto a fresh handler and compare each field's serialized
// form (avoids requiring `PartialEq` on every setting type).
let mut restored = DocumentMessageHandler::default();
restored.apply_stored_document_settings(&view_settings);
assert_eq!(serde_json::to_value(restored.render_mode).unwrap(), serde_json::to_value(document.render_mode).unwrap(), "render_mode");
assert_eq!(
serde_json::to_value(restored.rulers_visible).unwrap(),
serde_json::to_value(document.rulers_visible).unwrap(),
"rulers_visible"
);
assert_eq!(
serde_json::to_value(restored.document_ptz).unwrap(),
serde_json::to_value(document.document_ptz).unwrap(),
"document_ptz"
);
assert_eq!(
serde_json::to_value(restored.overlays_visibility_settings).unwrap(),
serde_json::to_value(document.overlays_visibility_settings).unwrap(),
"overlays"
);
assert_eq!(
serde_json::to_value(restored.snapping_state).unwrap(),
serde_json::to_value(document.snapping_state).unwrap(),
"snapping_state"
);
assert_eq!(serde_json::to_value(restored.collapsed).unwrap(), serde_json::to_value(document.collapsed).unwrap(), "collapsed");
}
}
@@ -14,6 +14,7 @@ use graphene_std::ProtoNodeIdentifier;
use graphene_std::text::{TextAlign, TypesettingConfig};
use graphene_std::transform::ScaleType;
use graphene_std::uuid::NodeId;
use graphene_std::vector::graphic_types;
use graphene_std::vector::style::{PaintOrder, StrokeAlign};
use std::collections::HashMap;
use std::f64::consts::PI;
@@ -1121,9 +1122,6 @@ 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;
let network = document.network_interface.document_network().clone();
// Apply string and node replacements to each node
@@ -1574,6 +1572,101 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
inputs_count = 5;
}
// Upgrade the legacy 4-input Fill node (content, fill: Fill, _backup_color, _backup_gradient: Gradient) to the
// value-model 7-input shape (content, fill: generic paint list, _backup_color, _backup_gradient, _gradient_type, _spread_method, _transform).
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER) && inputs_count == 4 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
// Content: no change
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
// Fill: a literal Fill value is decomposed, and a wired input (`List<GradientStops> / List<Color>`) is kept as-is
match old_inputs[1].as_value() {
Some(TaggedValue::LegacyFill(old_fill)) => {
let exposed = old_inputs[1].is_exposed();
let fill_value = match old_fill {
graphic_types::migrations::legacy::Fill::None => TaggedValue::Color(None),
graphic_types::migrations::legacy::Fill::Solid(color) => TaggedValue::Color(Some(*color)),
graphic_types::migrations::legacy::Fill::Gradient(gradient) => TaggedValue::Gradient(gradient.stops.clone()),
};
document
.network_interface
.set_input(&InputConnector::node(*node_id, 1), NodeInput::value(fill_value, exposed), network_path);
// Gradient metadata (4, 5, 6): applies only to a literal gradient, solids/none keep the template defaults
if let graphic_types::migrations::legacy::Fill::Gradient(gradient) = old_fill {
document.network_interface.set_input(
&InputConnector::node(*node_id, 4),
NodeInput::value(TaggedValue::GradientType(gradient.gradient_type), false),
network_path,
);
document.network_interface.set_input(
&InputConnector::node(*node_id, 5),
NodeInput::value(TaggedValue::GradientSpreadMethod(gradient.spread_method), false),
network_path,
);
let transform = if gradient.absolute {
Some(gradient.transform * gradient.to_transform())
} else {
// Baking a legacy bounding-box-relative gradient is deferred until the measurement pre-pass can supply the paint target's bounds
document.pending_gradient_bbox_bake.push((network_path.to_vec(), *node_id, gradient.clone()));
None
};
document
.network_interface
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::OptionalDAffine2(transform), false), network_path);
}
}
// Wired/exposed fill keeps the connection.
// The generic paint connector accepts the existing `List<Color>`/`List<GradientStops>` paint sources directly.
_ => {
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
}
}
// Color backup: no change
document.network_interface.set_input(&InputConnector::node(*node_id, 2), old_inputs[2].clone(), network_path);
// Gradient backup: extract stops
if let Some(TaggedValue::LegacyGradient(g)) = old_inputs[3].as_value() {
document
.network_interface
.set_input(&InputConnector::node(*node_id, 3), NodeInput::value(TaggedValue::Gradient(g.stops.clone()), false), network_path);
// A solid/no-fill node leaves the gradient metadata inputs unused, so seed them from the backup gradient for a later Solid -> Gradient toggle to restore
if matches!(
old_inputs[1].as_value(),
Some(TaggedValue::LegacyFill(
graphic_types::migrations::legacy::Fill::None | graphic_types::migrations::legacy::Fill::Solid(_)
))
) {
document
.network_interface
.set_input(&InputConnector::node(*node_id, 4), NodeInput::value(TaggedValue::GradientType(g.gradient_type), false), network_path);
document.network_interface.set_input(
&InputConnector::node(*node_id, 5),
NodeInput::value(TaggedValue::GradientSpreadMethod(g.spread_method), false),
network_path,
);
let transform = if g.absolute {
Some(g.transform * g.to_transform())
} else {
document.pending_gradient_bbox_bake.push((network_path.to_vec(), *node_id, g.clone()));
None
};
document
.network_interface
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::OptionalDAffine2(transform), false), network_path);
}
}
inputs_count = 7;
}
// Upgrade Stroke node to reorder parameters and add "Align" and "Paint Order" (#2644)
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 8 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
@@ -0,0 +1,231 @@
//! Asynchronous `.gdd` working-copy IO, spawned by `PortfolioMessageHandler` as `FutureMessage`s:
//! building/opening containers, opening `.gdd` archives into documents, and rebuilding the interface
//! from the undo/redo cursor. The `validate` flag is the `validate_storage_round_trip` preference; when
//! set, the registry build is compared against the legacy oracle (logged, not fatal) for the soak.
use document_container::AnyContainer;
use document_format::{Error as DocumentFormatError, GddV1, GddV1Layout};
use graph_craft::application_io::resource::{LoadResource, ResourceStorage};
use graph_craft::document::NodeNetwork;
use super::document::DocumentMessageHandler;
use super::document::diff_networks;
use super::document::utility_types::network_interface::storage_metadata::{apply_network_view_settings, build_interface_from_storage, network_ids_from_entries};
use super::document_migration::document_migration_string_preprocessing;
use super::portfolio_message::PortfolioMessage;
use crate::messages::message::Message;
use crate::messages::portfolio::document::utility_types::misc::DocumentId;
use crate::messages::resource_storage::ResourcesHandle;
/// Build the container backend at `path` (folder on native, OPFS directory name on web) or in-memory
/// when `None`. Also returns whether an existing working copy was found (its `manifest.json` is present).
async fn build_per_document_container(path: Option<&std::path::Path>) -> Result<(AnyContainer, bool), DocumentFormatError> {
let Some(path) = path else {
return Ok((AnyContainer::Memory(document_container::backends::memory::MemoryBackend::new()), false));
};
#[cfg(not(target_family = "wasm"))]
{
use document_container::backends::folder::FolderBackend;
let exists = path.join("manifest.json").is_file();
let backend = if exists { FolderBackend::open(path)? } else { FolderBackend::create(path)? };
Ok((AnyContainer::Folder(backend), exists))
}
#[cfg(target_family = "wasm")]
{
use document_container::AsyncContainer;
use document_container::backends::opfs::OpfsBackend;
let directory_name = path
.to_str()
.ok_or(DocumentFormatError::Container(document_container::ContainerError::InvalidPath(path.display().to_string())))?;
let backend = OpfsBackend::open(directory_name).await?;
let exists = backend.exists("manifest.json").await;
Ok((AnyContainer::Opfs(backend), exists))
}
}
/// Open the existing working copy at `path`, or create a fresh one bound to `peer` (in-memory when
/// `path` is `None`). Returns the working copy plus whether it was reopened (vs freshly created); only a
/// reopen has independently-stored state worth comparing against the legacy load.
pub(super) async fn build_or_open_working_copy(path: Option<&std::path::Path>, peer: graph_storage::PeerId, document_uuid: u64, version: String) -> Result<(GddV1, bool), DocumentFormatError> {
let (container, exists) = build_per_document_container(path).await?;
let gdd = if exists {
GddV1::open_in(container, GddV1Layout).await?
} else {
GddV1::create_in(container, GddV1Layout, peer, document_uuid, version.clone(), version).await?
};
Ok((gdd, exists))
}
/// `FutureMessage` that opens a `.gdd` archive into a document, delivered via
/// [`PortfolioMessage::GddDocumentLoaded`]. See [`build_document_from_gdd`] for the build itself.
pub(super) async fn open_gdd_document(
working_copy_root: Option<std::path::PathBuf>,
document_id: DocumentId,
document_name: Option<String>,
document_path: Option<std::path::PathBuf>,
content: Vec<u8>,
store_handle: ResourcesHandle,
validate: bool,
) -> Message {
let path = working_copy_root.map(|root| root.join(format!("{:x}", document_id.0)));
let document = build_document_from_gdd(path.as_deref(), &content, &store_handle, document_id, validate).await;
Message::Portfolio(PortfolioMessage::GddDocumentLoaded {
document_id,
document_name,
document_path,
document: document.map(Box::new),
})
}
/// `FutureMessage` that rebuilds a document's interface from a post-move `Gdd` cursor snapshot and
/// delivers it via [`PortfolioMessage::GddUndoRedoRebuilt`] (`None` interface on failure, logged here).
pub(crate) async fn rebuild_gdd_cursor(gdd: GddV1, store_handle: ResourcesHandle, document_id: DocumentId, had_oracle: bool) -> Message {
let declarations = gdd.declarations(&store_handle).await;
let interface = match gdd.registry().to_runtime_with_full_metadata(&declarations) {
Ok((network, node_entries, network_entries)) => match build_interface_from_storage(network, node_entries, network_entries) {
Ok(interface) => Some(Box::new(interface)),
Err(error) => {
log::error!("Gdd undo/redo rebuild for {document_id:?}: failed to build interface: {error}");
None
}
},
Err(error) => {
log::error!("Gdd undo/redo rebuild for {document_id:?}: failed to convert registry to runtime: {error}");
None
}
};
Message::Portfolio(PortfolioMessage::GddUndoRedoRebuilt { document_id, had_oracle, interface })
}
/// Core of the `.gdd` open: archive -> working copy -> `Gdd` -> runtime interface. The registry build is
/// authoritative; the embedded legacy blob is the soak oracle and the fallback if the build fails.
/// Returns `None` only if neither the build nor the legacy fallback worked.
async fn build_document_from_gdd(path: Option<&std::path::Path>, content: &[u8], store_handle: &impl ResourceStorage, document_id: DocumentId, validate: bool) -> Option<DocumentMessageHandler> {
let (container, _exists) = match build_per_document_container(path).await {
Ok(result) => result,
Err(error) => {
log::error!("Opening .gdd for {document_id:?}: failed to build working copy container: {error}");
return None;
}
};
let gdd = match GddV1::open_from_archive(content, container, GddV1Layout).await {
Ok(gdd) => gdd,
Err(error) => {
log::error!("Opening .gdd for {document_id:?}: failed to open archive: {error}");
return None;
}
};
// Extract archived resource bytes into the global cache so declarations + runtime resolve.
match gdd.resource_hashes().await {
Ok(hashes) => {
for hash in hashes {
match gdd.read_resource(&hash).await {
Ok(holder) => {
store_handle.store(holder.as_slice());
}
Err(error) => log::error!("Opening .gdd for {document_id:?}: failed to read resource {hash}: {error}"),
}
}
}
Err(error) => log::error!("Opening .gdd for {document_id:?}: failed to list resources: {error}"),
}
let legacy_document = gdd
.read_legacy_document()
.await
.and_then(|holder| String::from_utf8(holder.as_slice().to_vec()).ok())
.and_then(|serialized| DocumentMessageHandler::deserialize_document(&document_migration_string_preprocessing(serialized)).ok());
let declarations = gdd.declarations(store_handle).await;
let interface = match gdd.registry().to_runtime_with_full_metadata(&declarations) {
Ok((network, node_entries, network_entries)) => {
let network_ids = network_ids_from_entries(&network_entries);
match build_interface_from_storage(network, node_entries, network_entries) {
Ok(mut interface) => {
// Per-network view state lives in `session.json`, not the registry, so restore it here.
apply_network_view_settings(&mut interface, &network_ids, gdd.network_view_settings());
Some(interface)
}
Err(error) => {
log::error!("Opening .gdd for {document_id:?}: failed to build interface: {error}");
None
}
}
}
Err(error) => {
log::error!("Opening .gdd for {document_id:?}: failed to convert registry to runtime: {error}");
None
}
};
// Soak compare against the legacy oracle, normalizing the benign generic-vs-resolved `call_argument`.
if let Some(interface) = interface {
if validate && let Some(legacy) = &legacy_document {
let mut built = interface.document_network().clone();
let mut oracle = legacy.network_interface.document_network().clone();
normalize_call_arguments_for_compare(&mut built);
normalize_call_arguments_for_compare(&mut oracle);
if built != oracle {
log::error!(
"Open-.gdd divergence for {document_id:?}: registry-built document differs from the embedded legacy blob\n{}",
diff_networks(&oracle, &built)
);
}
}
return Some(DocumentMessageHandler::from_storage(interface, gdd, String::new(), None));
}
log::warn!("Opening .gdd for {document_id:?}: registry build failed, falling back to embedded legacy document");
if legacy_document.is_none() {
log::error!("Opening .gdd for {document_id:?}: no embedded legacy document to fall back to");
}
legacy_document
}
/// Soak check that the reopened `.gdd`'s stored registry, converted back to a runtime network, matches
/// the legacy load. Logs divergence only (legacy stays authoritative); runs once per open.
pub(super) async fn compare_storage_against_runtime(gdd: &GddV1, legacy_network: &NodeNetwork, byte_store: &dyn LoadResource, document_id: DocumentId) {
let declarations = gdd.declarations(byte_store).await;
let mut candidate = match gdd.registry().to_runtime_with_metadata(&declarations) {
Ok((network, _entries)) => network,
Err(error) => {
log::error!("Compare-on-open for {document_id:?}: .gdd registry failed to convert to runtime: {error}");
return;
}
};
// Normalize the benign generic-vs-resolved `call_argument` on both sides before comparing.
let mut legacy = legacy_network.clone();
normalize_call_arguments_for_compare(&mut legacy);
normalize_call_arguments_for_compare(&mut candidate);
if candidate != legacy {
log::error!(
"Compare-on-open divergence for {document_id:?}: the reopened .gdd does not match the legacy load\n{}",
diff_networks(&legacy, &candidate)
);
}
}
/// Recursively rewrite a concrete `Context` `call_argument` back to the generic `T` storage authored, so
/// the generic-vs-resolved difference (recomputed during compilation) compares equal. Other types untouched.
fn normalize_call_arguments_for_compare(network: &mut NodeNetwork) {
use graph_craft::Type;
let context = graph_craft::concrete!(graphene_std::Context);
for node in network.nodes.values_mut() {
if node.call_argument == context {
node.call_argument = Type::Generic(std::borrow::Cow::Borrowed("T"));
}
if let graph_craft::document::DocumentNodeImplementation::Network(inner) = &mut node.implementation {
normalize_call_arguments_for_compare(inner);
}
}
}
+1
View File
@@ -3,6 +3,7 @@ mod portfolio_message_handler;
pub mod document;
pub mod document_migration;
pub mod document_storage_io;
pub mod fonts;
pub mod persistent_state;
pub mod utility_types;
@@ -2,7 +2,6 @@ use super::document::utility_types::document_metadata::LayerNodeIdentifier;
use super::persistent_state::PersistentStateMessage;
use super::utility_types::{DockingSplitDirection, PanelGroupId, PanelType};
use crate::messages::frontend::utility_types::{ExportBounds, FileType, PersistedState};
use crate::messages::portfolio::document::utility_types::clipboards::Clipboard;
use crate::messages::prelude::*;
use graphene_std::Color;
use graphene_std::raster::Image;
@@ -40,22 +39,14 @@ pub enum PortfolioMessage {
CloseDocumentWithConfirmation {
document_id: DocumentId,
},
Copy {
clipboard: Clipboard,
},
Cut {
clipboard: Clipboard,
},
DeleteDocument {
document_id: DocumentId,
},
/// Delivers an asynchronously-built `Gdd` working copy into its document. Emitted by the mount
/// future spawned in `load_document` once the working-copy container is ready. The payload is
/// not serializable and a clone carries no `Gdd` (`clone_to_none`); it only ever travels once,
/// from the mount future to the receiving handler. `reopened` is true when an existing working copy
/// was opened (not freshly created): the persisted cursor is trusted as-is and the mount-time
/// re-commit is skipped, since re-committing the legacy runtime would stack a spurious interaction on the
/// restored cursor and make the first undo a no-op.
/// Delivers an asynchronously-built `Gdd` working copy into its document, emitted by the mount future
/// spawned in `load_document`. The `gdd` payload is non-serializable and a clone carries none
/// (`clone_to_none`), so it travels exactly once. `reopened` is true when an existing working copy was
/// opened: the persisted cursor is trusted as-is and the mount-time re-commit is skipped, since
/// re-committing would stack a spurious interaction on the restored cursor and make the first undo a no-op.
DocumentStorageMounted {
document_id: DocumentId,
reopened: bool,
@@ -119,7 +110,7 @@ pub enum PortfolioMessage {
content: Vec<u8>,
},
/// Delivers a document built asynchronously from a `.gdd` archive (registry → runtime, working copy
/// mounted) into the portfolio. Non-serializable payload that travels once, like `DocumentStorageMounted`.
/// mounted) into the portfolio. Travels once like [`DocumentStorageMounted`](Self::DocumentStorageMounted).
GddDocumentLoaded {
document_id: DocumentId,
document_name: Option<String>,
@@ -128,11 +119,10 @@ pub enum PortfolioMessage {
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
document: Option<Box<DocumentMessageHandler>>,
},
/// Delivers the interface rebuilt from the `Gdd` undo/redo cursor (which moved + persisted synchronously),
/// so the async registry rebuild can swap into the live document. `interface` is `None` if the rebuild
/// failed (logged at the source). `had_oracle` records whether the legacy snapshot applied synchronously,
/// so the swap can debug-compare the rebuild against it. Non-serializable payload that travels once, like
/// `GddDocumentLoaded`.
/// Delivers the interface rebuilt from the `Gdd` undo/redo cursor so the async rebuild can swap into the
/// live document. `interface` is `None` if the rebuild failed (logged at the source). `had_oracle` records
/// whether the legacy snapshot applied synchronously, so the swap can debug-compare against it. Travels
/// once like [`DocumentStorageMounted`](Self::DocumentStorageMounted).
GddUndoRedoRebuilt {
document_id: DocumentId,
had_oracle: bool,
@@ -156,31 +146,19 @@ pub enum PortfolioMessage {
name: Option<String>,
svg: String,
},
PasteSerializedData {
data: String,
},
PasteSerializedVector {
data: String,
},
PasteImage {
InsertImage {
name: Option<String>,
image: Image<Color>,
mouse: Option<(f64, f64)>,
parent_and_insert_index: Option<(LayerNodeIdentifier, usize)>,
},
PasteSvg {
InsertSvg {
name: Option<String>,
svg: String,
mouse: Option<(f64, f64)>,
parent_and_insert_index: Option<(LayerNodeIdentifier, usize)>,
},
// TODO: Unused except by tests, remove?
PasteIntoFolder {
clipboard: Clipboard,
parent: LayerNodeIdentifier,
insert_index: usize,
},
CenterPastedLayers {
CenterLayers {
layers: Vec<LayerNodeIdentifier>,
},
PrevDocument,
@@ -1,11 +1,9 @@
use super::document::utility_types::document_metadata::LayerNodeIdentifier;
use super::document::utility_types::network_interface;
use super::persistent_state::{PersistentStateMessage, PersistentStateMessageContext, PersistentStateMessageHandler};
use super::utility_types::{PanelLayoutSubdivision, PanelType, WorkspacePanelLayout};
use crate::application::{Editor, generate_uuid};
use crate::consts::{DEFAULT_DOCUMENT_NAME, DEFAULT_STROKE_WIDTH, FILE_EXTENSION, GDD_FILE_EXTENSION};
use crate::consts::{DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, GDD_FILE_EXTENSION};
use crate::messages::animation::TimingInformation;
use crate::messages::clipboard::utility_types::ClipboardContent;
use crate::messages::dialog::simple_dialogs;
use crate::messages::frontend::utility_types::{DocumentInfo, PersistedState};
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
@@ -13,15 +11,13 @@ use crate::messages::input_mapper::utility_types::macros::{action_shortcut, acti
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::DocumentMessageContext;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{self, resolve_network_node_type};
use crate::messages::portfolio::document::utility_types::clipboards::{Clipboard, CopyBufferEntry, INTERNAL_CLIPBOARD_COUNT};
use crate::messages::portfolio::document::node_graph::document_node_definitions;
use crate::messages::portfolio::document::utility_types::network_interface::OutputConnector;
use crate::messages::portfolio::document::utility_types::nodes::SelectedNodes;
use crate::messages::portfolio::document_migration::*;
use crate::messages::portfolio::document_storage_io::{build_or_open_working_copy, compare_storage_against_runtime, open_gdd_document};
use crate::messages::portfolio::utility_types::FileContent;
use crate::messages::preferences::SelectionMode;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::utility_types::{HintData, ToolType};
use crate::messages::viewport::ToPhysical;
use crate::node_graph_executor::{ExportConfig, NodeGraphExecutor};
@@ -31,9 +27,6 @@ use graph_craft::document::NodeId;
use graphene_std::Color;
use graphene_std::raster_types::Image;
use graphene_std::renderer::Quad;
use graphene_std::subpath::BezierHandles;
use graphene_std::vector::misc::HandleId;
use graphene_std::vector::{PointId, SegmentId, Vector, VectorModificationType};
use std::path::PathBuf;
use std::sync::Arc;
use std::vec;
@@ -68,21 +61,13 @@ pub struct PortfolioMessageHandler {
pub(crate) active_document_id: Option<DocumentId>,
persistent_state: PersistentStateMessageHandler,
pub fonts: FontsMessageHandler,
copy_buffer: [Vec<CopyBufferEntry>; INTERNAL_CLIPBOARD_COUNT as usize],
pub executor: NodeGraphExecutor,
pub selection_mode: SelectionMode,
pub reset_node_definitions_on_open: bool,
pub workspace_panel_layout: WorkspacePanelLayout,
/// Parent directory that holds every document's `Gdd` working copy; a given document mounts at
/// `working_copy_root.join(format!("{id:x}"))`. A filesystem path on native; on web it is
/// converted to an OPFS directory name at the container-construction seam. `None` means no
/// persistent location is configured (tests, headless) — documents mount an in-memory working
/// copy instead, so the mount path still runs but writes nowhere durable.
working_copy_root: Option<PathBuf>,
/// Number of `.gdd` opens whose async build is in flight. While non-zero, resource GC is skipped:
/// the opening document's resources are being extracted into the cache but it isn't in `documents`
/// yet, so GC would wrongly evict them (notably proto-node declaration bytes).
pending_gdd_opens: usize,
/// Number of document not fully loaded. While non-zero, resource GC is skipped.
pending_opens: usize,
}
#[message_handler_data]
@@ -216,9 +201,11 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(PortfolioMessage::GarbageCollectResources);
}
PortfolioMessage::AutoSaveDocument { document_id } => {
let Some(byte_store) = resource_storage.storage() else { return };
let validate = preferences.validate_storage_round_trip;
let Some(document) = self.documents.get_mut(&document_id) else { return };
document.commit_storage_snapshot(byte_store);
document.commit_storage_snapshot(&resource_storage.resources_mut(), validate);
responses.add(PersistentStateMessage::WriteDocument {
document_id,
document: document.serialize_document(),
@@ -293,86 +280,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(PortfolioMessage::SelectDocument { document_id });
}
}
PortfolioMessage::Copy { clipboard } => {
if context.current_tool == &ToolType::Path {
responses.add(PathToolMessage::Copy { clipboard });
return;
}
// We can't use `self.active_document()` because it counts as an immutable borrow of the entirety of `self`
let Some(active_document) = self.active_document_id.and_then(|id| self.documents.get_mut(&id)) else {
return;
};
if active_document.graph_view_overlay_open() {
responses.add(NodeGraphMessage::Copy);
return;
}
let mut copy_val = |buffer: &mut Vec<CopyBufferEntry>| {
let mut ordered_last_elements = active_document.network_interface.shallowest_unique_layers(&[]).collect::<Vec<_>>();
ordered_last_elements.sort_by_key(|layer| {
let Some(parent) = layer.parent(active_document.metadata()) else { return usize::MAX };
DocumentMessageHandler::get_calculated_insert_index(active_document.metadata(), &SelectedNodes(vec![layer.to_node()]), parent)
});
for layer in ordered_last_elements.into_iter() {
let layer_node_id = layer.to_node();
let mut copy_ids = HashMap::new();
copy_ids.insert(layer_node_id, NodeId(0));
active_document
.network_interface
.upstream_flow_back_from_nodes(vec![layer_node_id], &[], network_interface::FlowType::LayerChildrenUpstreamFlow)
.enumerate()
.for_each(|(index, node_id)| {
copy_ids.insert(node_id, NodeId((index + 1) as u64));
});
buffer.push(CopyBufferEntry {
nodes: active_document.network_interface.copy_nodes(&copy_ids, &[]).collect(),
selected: active_document.network_interface.selected_nodes().selected_layers_contains(layer, active_document.metadata()),
visible: active_document.network_interface.selected_nodes().layer_visible(layer, &active_document.network_interface),
locked: active_document.network_interface.selected_nodes().layer_locked(layer, &active_document.network_interface),
collapsed: false,
});
}
};
if clipboard == Clipboard::Device {
let mut buffer = Vec::new();
copy_val(&mut buffer);
let Ok(data) = serde_json::to_string(&buffer) else {
log::error!("Failed to serialize nodes for clipboard");
return;
};
responses.add(ClipboardMessage::Write {
content: ClipboardContent::Layer(data),
});
} else {
let copy_buffer = &mut self.copy_buffer;
copy_buffer[clipboard as usize].clear();
copy_val(&mut copy_buffer[clipboard as usize]);
}
}
PortfolioMessage::Cut { clipboard } => {
if context.current_tool == &ToolType::Path {
responses.add(PathToolMessage::Cut { clipboard });
return;
}
if let Some(active_document) = self.active_document()
&& active_document.graph_view_overlay_open()
{
responses.add(NodeGraphMessage::Cut);
return;
}
responses.add(PortfolioMessage::Copy { clipboard });
responses.add(DocumentMessage::DeleteSelectedLayers);
}
PortfolioMessage::DeleteDocument { document_id } => {
let document_index = self.document_index(document_id);
self.documents.remove(&document_id);
@@ -395,20 +302,12 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
}
PortfolioMessage::DocumentStorageMounted { document_id, reopened, gdd } => {
let Some(document) = self.documents.get_mut(&document_id) else {
// Document was closed before its working copy finished mounting; drop the `Gdd`.
// Document was closed before its working copy finished mounting.
return;
};
document.storage = gdd;
// On a fresh mount, capture the current runtime state into the working copy: edits made
// during the mount window were skipped by `commit_storage_snapshot` (no-op while unmounted),
// so this initial commit brings the working copy up to date. On a reopen the working copy
// already holds the persisted cursor; re-committing here would stack a spurious interaction on it
// and make the first undo a no-op, so trust the restored cursor and skip the commit.
if !reopened && let Some(byte_store) = resource_storage.storage() {
document.commit_storage_snapshot(byte_store);
// Seal the freshly-converted document as the base revision: the conversion is a completed
// import, not an in-progress interaction, so retire it into history rather than leaving it in
// the hot log (where it would never reach an interaction boundary on a save without edits).
document.set_storage(gdd);
if !reopened {
document.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
document.retire_storage_interaction();
}
}
@@ -427,9 +326,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
// We don't know what can be safely garbage collected
return;
}
if self.pending_gdd_opens > 0 {
// A .gdd open is extracting its resources into the cache but isn't in `documents` yet,
// so its hashes would look unused. Skip this cycle; GC resumes once the open lands.
if self.pending_opens > 0 {
// A document not fully loaded, skip garbage collection.
return;
}
@@ -445,11 +343,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
for document in self.documents.values_mut() {
document.garbage_collect_resources();
used_resources.extend(document.resources.registry.resolved().filter_map(|info| info.hash.cloned()));
// Also keep resources referenced by the `.gdd` storage anywhere in history (notably proto-node
// declaration bytes), which the runtime resource registry doesn't track but the working copy
// and `.gdd` export need in the global cache. History-wide, not just the current registry:
// an undo drops an interaction's resources from the working registry, but redo still needs them.
if let Some(storage) = &document.storage {
if let Some(storage) = document.storage() {
used_resources.extend(storage.all_referenced_resource_hashes());
}
}
@@ -637,7 +532,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(NavigationMessage::CanvasPan { delta: (0., 0.).into() });
}
self.load_document(new_document, document_id, resource_storage, responses);
self.load_document(new_document, document_id, resource_storage, preferences.validate_storage_round_trip, responses);
responses.add(PortfolioMessage::SelectDocument { document_id });
}
PortfolioMessage::MoveAllPanelTabs {
@@ -810,7 +705,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
});
}
FileContent::GddDocument(content) => {
// Treat importing a `.gdd` document as opening it (same as the legacy path above).
responses.add(PortfolioMessage::OpenGddDocument {
document_name: name,
document_path: Some(path),
@@ -818,7 +712,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
});
}
FileContent::Svg(svg) => {
responses.add(PortfolioMessage::PasteSvg {
responses.add(PortfolioMessage::InsertSvg {
name,
svg,
mouse: None,
@@ -826,7 +720,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
});
}
FileContent::Image(image) => {
responses.add(PortfolioMessage::PasteImage {
responses.add(PortfolioMessage::InsertImage {
name,
image,
mouse: None,
@@ -864,20 +758,18 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
content,
} => {
let document_id = DocumentId(generate_uuid());
let Some(store_handle) = resource_storage.store_handle() else {
log::error!("Cannot open .gdd: resource storage not initialized");
return;
};
// Suppress resource GC until the open completes: the document's resources are extracted
// into the cache before it joins `documents`, so GC would otherwise evict them mid-open.
self.pending_gdd_opens += 1;
responses.add(open_gdd_document_future(
// Suppress resource GC until the open completes
self.pending_opens += 1;
responses.add(open_gdd_document(
self.working_copy_root.clone(),
document_id,
document_name,
document_path,
content,
store_handle,
resource_storage.resources_mut(),
preferences.validate_storage_round_trip,
));
}
PortfolioMessage::GddDocumentLoaded {
@@ -886,10 +778,14 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document_path,
document,
} => {
self.pending_gdd_opens = self.pending_gdd_opens.saturating_sub(1);
self.pending_opens = self.pending_opens.saturating_sub(1);
let Some(mut document) = document.map(|boxed| *boxed) else {
// The build failed and already logged; nothing to insert.
let name = document_name
.filter(|name| !name.trim().is_empty())
.or_else(|| document_path.as_ref().and_then(|path| path.file_stem()).map(|stem| stem.to_string_lossy().into_owned()))
.unwrap_or_default();
simple_dialogs::FailedToOpenDocumentDialog { document_name: name }.send_dialog_to_frontend(responses);
return;
};
document.finalize_storage_load();
@@ -903,7 +799,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document.path = document_path;
// The working copy is already mounted (we opened the .gdd), so skip the async re-mount.
self.load_document(document, document_id, resource_storage, responses);
self.load_document(document, document_id, resource_storage, preferences.validate_storage_round_trip, responses);
responses.add(PortfolioMessage::SelectDocument { document_id });
}
PortfolioMessage::GddUndoRedoRebuilt { document_id, had_oracle, interface } => {
@@ -916,7 +812,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
return;
};
document.apply_gdd_cursor_rebuild(interface, had_oracle, responses);
document.apply_gdd_cursor_rebuild(interface, had_oracle, preferences.validate_storage_round_trip, responses);
}
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
@@ -1044,8 +940,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document.set_save_state(document_is_saved);
let document_name_from_path = document_path.as_ref().and_then(|path| {
if path.extension().is_some_and(|e| e == FILE_EXTENSION) {
path.file_stem().map(|n| n.to_string_lossy().to_string())
if path.extension().is_some_and(|extension| extension == FILE_EXTENSION || extension == GDD_FILE_EXTENSION) {
path.file_stem().map(|stem| stem.to_string_lossy().to_string())
} else {
None
}
@@ -1063,7 +959,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document.name = self.resolve_document_name(candidate_name, None);
// Load the document into the portfolio so it opens in the editor
self.load_document(document, document_id, resource_storage, responses);
self.load_document(document, document_id, resource_storage, preferences.validate_storage_round_trip, responses);
responses.add(AppWindowMessage::Focus);
@@ -1078,7 +974,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
name: name.clone().unwrap_or_default(),
});
responses.add(DocumentMessage::PasteImage {
responses.add(DocumentMessage::InsertImage {
name,
image,
mouse: None,
@@ -1133,7 +1029,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
})
});
responses.add(DocumentMessage::PasteSvg {
responses.add(DocumentMessage::InsertSvg {
name,
svg,
mouse: None,
@@ -1155,153 +1051,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
messages: vec![DocumentMessage::ZoomCanvasToFitAll.into()],
});
}
// TODO: Unused except by tests, remove?
PortfolioMessage::PasteIntoFolder { clipboard, parent, insert_index } => {
let mut all_new_ids = Vec::new();
let paste = |entry: &CopyBufferEntry, responses: &mut VecDeque<_>, all_new_ids: &mut Vec<NodeId>| {
if self.active_document().is_some() {
trace!("Pasting into folder {parent:?} as index: {insert_index}");
let nodes = entry.clone().nodes;
let new_ids: HashMap<_, _> = nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect();
let layer = LayerNodeIdentifier::new_unchecked(new_ids[&NodeId(0)]);
all_new_ids.extend(new_ids.values().cloned());
responses.add(NodeGraphMessage::AddNodes { nodes, new_ids: new_ids.clone() });
responses.add(NodeGraphMessage::MoveLayerToStack { layer, parent, insert_index });
}
};
responses.add(DocumentMessage::DeselectAllLayers);
for entry in self.copy_buffer[clipboard as usize].iter().rev() {
paste(entry, responses, &mut all_new_ids)
}
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: all_new_ids });
}
PortfolioMessage::PasteSerializedData { data } => {
if let Some(document) = self.active_document() {
let mut all_new_ids = Vec::new();
if let Ok(data) = serde_json::from_str::<Vec<CopyBufferEntry>>(&data) {
let parent = document.new_layer_parent(false);
let mut layers = Vec::new();
let mut added_nodes = false;
for entry in data.into_iter().rev() {
if !added_nodes {
responses.add(DocumentMessage::DeselectAllLayers);
responses.add(DocumentMessage::AddTransaction);
added_nodes = true;
}
let new_ids: HashMap<_, _> = entry.nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect();
let layer = LayerNodeIdentifier::new_unchecked(new_ids[&NodeId(0)]);
all_new_ids.extend(new_ids.values().cloned());
responses.add(NodeGraphMessage::AddNodes { nodes: entry.nodes, new_ids });
responses.add(NodeGraphMessage::MoveLayerToStack { layer, parent, insert_index: 0 });
layers.push(layer);
}
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: all_new_ids });
responses.add(DeferMessage::AfterGraphRun {
messages: vec![PortfolioMessage::CenterPastedLayers { layers }.into()],
});
}
}
}
// Custom paste implementation for Path tool
PortfolioMessage::PasteSerializedVector { data } => {
// If using Path tool then send the operation to Path tool
if *current_tool == ToolType::Path {
responses.add(PathToolMessage::Paste { data });
return;
}
// If not using Path tool, create new layers and add paths into those
if let Some(document) = self.active_document() {
let Ok(data) = serde_json::from_str::<Vec<(LayerNodeIdentifier, Vector, DAffine2)>>(&data) else {
return;
};
let mut layers = Vec::new();
for (_, new_vector, transform) in data {
let Some(node_type) = resolve_network_node_type("Path") else {
error!("Path node does not exist");
continue;
};
let nodes = vec![(NodeId(0), node_type.default_node_template())];
let parent = document.new_layer_parent(false);
let layer = graph_modification_utils::new_custom(NodeId::new(), nodes, parent, responses);
layers.push(layer);
// Adding the transform back into the layer
responses.add(GraphOperationMessage::TransformSet {
layer,
transform,
transform_in: TransformIn::Local,
skip_rerender: false,
});
// Add default fill and stroke to the layer
let fill = graphene_std::vector::style::Fill::solid(Color::WHITE);
responses.add(GraphOperationMessage::FillSet { layer, fill });
let stroke = graphene_std::vector::style::Stroke::new(Some(Color::BLACK), DEFAULT_STROKE_WIDTH);
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
// Create new point ids and add those into the existing Vector path
let mut points_map = HashMap::new();
for (point, position) in new_vector.point_domain.iter() {
let new_point_id = PointId::generate();
points_map.insert(point, new_point_id);
let modification_type = VectorModificationType::InsertPoint { id: new_point_id, position };
responses.add(GraphOperationMessage::Vector { layer, modification_type });
}
// Create new segment ids and add the segments into the existing Vector path
let mut segments_map = HashMap::new();
for (segment_id, bezier, start, end) in new_vector.segment_bezier_iter() {
let new_segment_id = SegmentId::generate();
segments_map.insert(segment_id, new_segment_id);
let handles = match bezier.handles {
BezierHandles::Linear => [None, None],
BezierHandles::Quadratic { handle } => [Some(handle - bezier.start), None],
BezierHandles::Cubic { handle_start, handle_end } => [Some(handle_start - bezier.start), Some(handle_end - bezier.end)],
};
let points = [points_map[&start], points_map[&end]];
let modification_type = VectorModificationType::InsertSegment { id: new_segment_id, points, handles };
responses.add(GraphOperationMessage::Vector { layer, modification_type });
}
// Set G1 continuity
for handles in new_vector.colinear_manipulators {
let to_new_handle = |handle: HandleId| -> HandleId {
HandleId {
ty: handle.ty,
segment: segments_map[&handle.segment],
}
};
let new_handles = [to_new_handle(handles[0]), to_new_handle(handles[1])];
let modification_type = VectorModificationType::SetG1Continuous { handles: new_handles, enabled: true };
responses.add(GraphOperationMessage::Vector { layer, modification_type });
}
}
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(Message::Defer(DeferMessage::AfterGraphRun {
messages: vec![PortfolioMessage::CenterPastedLayers { layers }.into()],
}));
}
}
PortfolioMessage::CenterPastedLayers { layers } => {
PortfolioMessage::CenterLayers { layers } => {
if let Some(document) = self.active_document_mut() {
let viewport_bounds_quad_pixels = Quad::from_box([DVec2::ZERO, viewport.size().into_dvec2()]); // In viewport pixel coordinates
let viewport_center_pixels = viewport_bounds_quad_pixels.center(); // In viewport pixel coordinates
@@ -1406,7 +1156,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(NodeGraphMessage::RunDocumentGraph);
}
}
PortfolioMessage::PasteImage {
PortfolioMessage::InsertImage {
name,
image,
mouse,
@@ -1415,7 +1165,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
if self.document_ids.is_empty() {
responses.add(PortfolioMessage::OpenImage { name, image });
} else {
responses.add(DocumentMessage::PasteImage {
responses.add(DocumentMessage::InsertImage {
name,
image,
mouse,
@@ -1424,7 +1174,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
});
}
}
PortfolioMessage::PasteSvg {
PortfolioMessage::InsertSvg {
name,
svg,
mouse,
@@ -1433,7 +1183,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
if self.document_ids.is_empty() {
responses.add(PortfolioMessage::OpenSvg { name, svg });
} else {
responses.add(DocumentMessage::PasteSvg {
responses.add(DocumentMessage::InsertSvg {
name,
svg,
mouse,
@@ -1537,7 +1287,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
}
PortfolioMessage::RequestStatusBarInfoLayout => {
#[cfg(not(target_family = "wasm"))]
let widgets = vec![TextLabel::new("Graphite 1.0.0-RC5").disabled(true).widget_instance()]; // TODO: After the RCs, call this "Graphite (beta) x.y.z"
let widgets = vec![TextLabel::new("Graphite 1.0.0-RC6").disabled(true).widget_instance()]; // TODO: After the RCs, call this "Graphite (beta) x.y.z"
#[cfg(target_family = "wasm")]
let widgets = vec![];
@@ -1740,6 +1490,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 (whether newly decomposed or persisted from a save made before every bake landed) runs a
// one-time measurement pre-pass instead of rendering, until every gradient's transform is baked into absolute space
if !document.pending_gradient_bbox_bake.is_empty() && 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"))]
@@ -1928,14 +1685,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
PrevDocument,
Import,
));
// Extend with actions that must have a selected layer
if document.network_interface.selected_nodes().selected_layers(document.metadata()).next().is_some() {
common.extend(actions!(PortfolioMessageDiscriminant;
Copy,
Cut,
));
}
}
// Extend with actions that are disabled when focusing the document
@@ -1956,8 +1705,6 @@ impl PortfolioMessageHandler {
Self { executor, ..Default::default() }
}
/// Set the parent directory under which each document's `Gdd` working copy is mounted. `None`
/// mounts in-memory working copies (no durable location configured).
pub fn set_working_copy_root(&mut self, root: Option<PathBuf>) {
self.working_copy_root = root;
}
@@ -2079,7 +1826,14 @@ impl PortfolioMessageHandler {
}
}
fn load_document(&mut self, mut new_document: DocumentMessageHandler, document_id: DocumentId, resource_storage: &ResourceStorageMessageHandler, responses: &mut VecDeque<Message>) {
fn load_document(
&mut self,
mut new_document: DocumentMessageHandler,
document_id: DocumentId,
resource_storage: &ResourceStorageMessageHandler,
validate: bool,
responses: &mut VecDeque<Message>,
) {
let is_new_document = !self.document_ids.contains(&document_id);
if is_new_document {
self.document_ids.push_back(document_id);
@@ -2107,35 +1861,40 @@ impl PortfolioMessageHandler {
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
}
// Mount the per-document `Gdd` working copy asynchronously (its container is built off-thread).
// The document is already usable; the working copy attaches once the future resolves. With no
// configured root the working copy is in-memory, so the mount path still runs uniformly.
// Pass the just-loaded runtime network + a resource handle so a reopen can compare the stored
// `.gdd` against this legacy load (compare-on-open).
let legacy_network = self
.documents
.get(&document_id)
.map(|document| document.network_interface.document_network().clone())
.unwrap_or_default();
responses.add(Self::mount_document_storage(self.working_copy_root.clone(), document_id, legacy_network, resource_storage.resources()));
// Mount the per-document `Gdd` working copy asynchronously.
//
// Only mount for legacy loads: a `.gdd` open already mounted its working copy
// and remounting would overwrite it and drop that history state.
if self.documents.get(&document_id).and_then(|document| document.storage()).is_none() {
let legacy_network = self
.documents
.get(&document_id)
.map(|document| document.network_interface.document_network().clone())
.unwrap_or_default();
responses.add(Self::mount_document_storage(
self.working_copy_root.clone(),
document_id,
legacy_network,
resource_storage.resources(),
validate,
));
}
}
/// Build the `FutureMessage` that constructs (or reopens) the document's `Gdd` working copy and
/// delivers it back via [`PortfolioMessage::DocumentStorageMounted`]. With a configured root the
/// working copy lives at `<root>/<id_hex>`; without one it is in-memory.
/// With a configured root the working copy lives at `<root>/<id_hex>`; without one it is in-memory.
///
/// On a *reopen* (existing working copy), the freshly-read `.gdd` is converted back to a runtime
/// network and compared against `legacy_network` (the document the user actually loaded) before
/// the working copy attaches. This is the dual-write soak's compare-on-open: it validates the
/// `.gdd` *read* path (deserialize + hot-log replay), which the in-process `verify_storage_round_trip`
/// can't, since that never touches persisted bytes. Legacy stays authoritative; divergence is logged.
/// network and compared against `legacy_network` before
/// the working copy attaches. It validates the `.gdd` *read* path.
fn mount_document_storage(
working_copy_root: Option<std::path::PathBuf>,
document_id: DocumentId,
legacy_network: graph_craft::document::NodeNetwork,
byte_store: Box<dyn graph_craft::application_io::resource::LoadResource>,
validate: bool,
) -> Message {
let path = working_copy_root.map(|root| root.join(format!("{:x}", document_id.0)));
let path = working_copy_root.map(|root| root.join(format!("{:016x}", document_id.0)));
let editor_version = crate::application::GRAPHITE_GIT_COMMIT_HASH.to_string();
let peer = graph_storage::PeerId(generate_uuid());
@@ -2148,7 +1907,7 @@ impl PortfolioMessageHandler {
}
};
if reopened {
if validate && reopened {
compare_storage_against_runtime(&gdd, &legacy_network, byte_store.as_ref(), document_id).await;
}
@@ -2178,7 +1937,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)" />
@@ -2325,301 +2084,6 @@ fn display_name_with_fallback(info: &DocumentInfo) -> String {
}
}
/// Build a document's `Gdd` working copy. With `Some(path)` it opens an existing on-disk working
/// copy (reopen / autosave recovery) or creates a fresh one bound to `peer`, choosing the backend
/// per platform: a folder on native, an OPFS directory on web (where `path` is the OPFS directory
/// name). With `None` it creates a fresh in-memory working copy (tests, headless) that persists
/// nowhere durable.
///
/// Returns the working copy plus whether it was reopened from an existing on-disk working copy
/// (`true`) versus freshly created (`false`). Only a reopen has independently-read stored state and
/// an embedded legacy blob worth comparing against the legacy load (compare-on-open).
async fn build_or_open_working_copy(
path: Option<&std::path::Path>,
peer: graph_storage::PeerId,
document_uuid: u64,
version: String,
) -> Result<(document_format::GddV1, bool), document_format::Error> {
use document_container::AnyContainer;
use document_format::{GddV1, GddV1Layout};
let Some(path) = path else {
let container = AnyContainer::Memory(document_container::backends::memory::MemoryBackend::new());
let gdd = GddV1::create_in(container, GddV1Layout, peer, document_uuid, version.clone(), version).await?;
return Ok((gdd, false));
};
#[cfg(not(target_family = "wasm"))]
let (container, exists) = {
use document_container::backends::folder::FolderBackend;
let exists = path.join("manifest.json").is_file();
let backend = if exists { FolderBackend::open(path)? } else { FolderBackend::create(path)? };
(AnyContainer::Folder(backend), exists)
};
#[cfg(target_family = "wasm")]
let (container, exists) = {
use document_container::AsyncContainer;
use document_container::backends::opfs::OpfsBackend;
let directory_name = path
.to_str()
.ok_or(document_format::Error::Container(document_container::ContainerError::InvalidPath(path.display().to_string())))?;
let backend = OpfsBackend::open(directory_name).await?;
let exists = backend.exists("manifest.json").await;
(AnyContainer::Opfs(backend), exists)
};
let gdd = if exists {
GddV1::open_in(container, GddV1Layout).await?
} else {
GddV1::create_in(container, GddV1Layout, peer, document_uuid, version.clone(), version).await?
};
Ok((gdd, exists))
}
/// Build the per-document container for a working copy at `path` (folder native, OPFS web), or an
/// in-memory container when `path` is `None`. Does not open or create a `Gdd` — just the backend.
async fn build_per_document_container(path: Option<&std::path::Path>) -> Result<document_container::AnyContainer, document_format::Error> {
use document_container::AnyContainer;
let Some(path) = path else {
return Ok(AnyContainer::Memory(document_container::backends::memory::MemoryBackend::new()));
};
#[cfg(not(target_family = "wasm"))]
{
use document_container::backends::folder::FolderBackend;
let backend = if path.join("manifest.json").is_file() {
FolderBackend::open(path)?
} else {
FolderBackend::create(path)?
};
Ok(AnyContainer::Folder(backend))
}
#[cfg(target_family = "wasm")]
{
use document_container::backends::opfs::OpfsBackend;
let directory_name = path
.to_str()
.ok_or(document_format::Error::Container(document_container::ContainerError::InvalidPath(path.display().to_string())))?;
let backend = OpfsBackend::open(directory_name).await?;
Ok(AnyContainer::Opfs(backend))
}
}
/// Build the `FutureMessage` that opens a `.gdd` archive: materialize it into the per-document working
/// copy, build the runtime from the stored registry, validate it against the embedded legacy blob, and
/// deliver the finished document via [`PortfolioMessage::GddDocumentLoaded`]. Resource bytes carried in
/// the archive are extracted into `store_handle` (the app-global cache) so declarations and the runtime
/// resolve. The registry build is authoritative; the embedded legacy blob is the always-checked oracle
/// and the fallback if the build fails.
fn open_gdd_document_future(
working_copy_root: Option<std::path::PathBuf>,
document_id: DocumentId,
document_name: Option<String>,
document_path: Option<std::path::PathBuf>,
content: Vec<u8>,
store_handle: crate::messages::resource_storage::ResourcesHandle,
) -> Message {
let path = working_copy_root.map(|root| root.join(format!("{:x}", document_id.0)));
let future = async move {
let document = build_document_from_gdd(path.as_deref(), &content, &store_handle, document_id).await;
Message::Portfolio(PortfolioMessage::GddDocumentLoaded {
document_id,
document_name,
document_path,
document: document.map(Box::new),
})
};
future.into()
}
/// Build the `FutureMessage` that rebuilds a document's interface from its `Gdd` undo/redo cursor. The
/// cursor already moved and persisted synchronously in the handler; `gdd` is a snapshot clone at that
/// post-move position. This loads the cursor's declarations, converts the registry back to a runtime
/// network with full metadata, builds the interface, and delivers it via [`PortfolioMessage::GddUndoRedoRebuilt`]
/// so the handler can swap it in (preserving transients) and compare against the legacy oracle. `interface`
/// is `None` on failure (logged here), in which case the handler leaves the live document untouched.
pub(crate) fn rebuild_gdd_cursor_future(gdd: document_format::GddV1, store_handle: crate::messages::resource_storage::ResourcesHandle, document_id: DocumentId, had_oracle: bool) -> Message {
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::build_interface_from_storage;
let future = async move {
let declarations = gdd.declarations(&store_handle).await;
let interface = match gdd.registry().to_runtime_with_full_metadata(&declarations) {
Ok((network, node_entries, network_entries)) => match build_interface_from_storage(network, node_entries, network_entries) {
Ok(interface) => Some(Box::new(interface)),
Err(error) => {
log::error!("Gdd undo/redo rebuild for {document_id:?}: failed to build interface: {error}");
None
}
},
Err(error) => {
log::error!("Gdd undo/redo rebuild for {document_id:?}: failed to convert registry to runtime: {error}");
None
}
};
Message::Portfolio(PortfolioMessage::GddUndoRedoRebuilt { document_id, had_oracle, interface })
};
future.into()
}
/// Core of the `.gdd` open: archive -> working copy -> `Gdd` -> runtime interface, with the embedded
/// legacy blob loaded for validation (always compared) and fallback (used if the registry build fails).
/// Returns the built document, or `None` if neither the registry build nor the legacy fallback worked.
async fn build_document_from_gdd(
path: Option<&std::path::Path>,
content: &[u8],
store_handle: &impl graph_craft::application_io::resource::ResourceStorage,
document_id: DocumentId,
) -> Option<DocumentMessageHandler> {
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::{apply_network_view_settings, build_interface_from_storage, network_ids_from_entries};
use document_format::{GddV1, GddV1Layout};
let container = match build_per_document_container(path).await {
Ok(container) => container,
Err(error) => {
log::error!("Opening .gdd for {document_id:?}: failed to build working copy container: {error}");
return None;
}
};
let gdd = match GddV1::open_from_archive(content, container, GddV1Layout).await {
Ok(gdd) => gdd,
Err(error) => {
log::error!("Opening .gdd for {document_id:?}: failed to open archive: {error}");
return None;
}
};
// Extract resource bytes carried in the archive into the global cache so declarations + runtime resolve.
match gdd.resource_hashes().await {
Ok(hashes) => {
for hash in hashes {
match gdd.read_resource(&hash).await {
Ok(holder) => {
store_handle.store(holder.as_slice());
}
Err(error) => log::error!("Opening .gdd for {document_id:?}: failed to read resource {hash}: {error}"),
}
}
}
Err(error) => log::error!("Opening .gdd for {document_id:?}: failed to list resources: {error}"),
}
// Full legacy load of the embedded blob: serves as both the validation oracle and the fallback.
let legacy_document = gdd
.read_legacy_document()
.await
.and_then(|holder| String::from_utf8(holder.as_slice().to_vec()).ok())
.and_then(|serialized| DocumentMessageHandler::deserialize_document(&document_migration_string_preprocessing(serialized)).ok());
// Build the runtime from the stored registry (authoritative).
let declarations = gdd.declarations(store_handle).await;
let interface = match gdd.registry().to_runtime_with_full_metadata(&declarations) {
Ok((network, node_entries, network_entries)) => {
let network_ids = network_ids_from_entries(&network_entries);
match build_interface_from_storage(network, node_entries, network_entries) {
Ok(mut interface) => {
// Restore the per-network, per-peer view state (node-graph nav + previewing) from
// `session.json`; it travels in the archive but isn't in the registry/history.
apply_network_view_settings(&mut interface, &network_ids, gdd.network_view_settings());
Some(interface)
}
Err(error) => {
log::error!("Opening .gdd for {document_id:?}: failed to build interface: {error}");
None
}
}
}
Err(error) => {
log::error!("Opening .gdd for {document_id:?}: failed to convert registry to runtime: {error}");
None
}
};
// Compare the registry build against the legacy oracle (always, when both are available). Normalize the
// benign generic-vs-resolved `call_argument` difference (see `normalize_call_arguments_for_compare`) so
// it doesn't flag.
if let Some(interface) = interface {
if let Some(legacy) = &legacy_document {
let mut built = interface.document_network().clone();
let mut oracle = legacy.network_interface.document_network().clone();
normalize_call_arguments_for_compare(&mut built);
normalize_call_arguments_for_compare(&mut oracle);
if built != oracle {
log::error!(
"Open-.gdd divergence for {document_id:?}: registry-built document differs from the embedded legacy blob\n{}",
crate::messages::portfolio::document::diff_networks(&oracle, &built)
);
}
}
return Some(DocumentMessageHandler::from_storage(interface, gdd, String::new(), None));
}
// Registry build failed: fall back to the embedded legacy document.
log::warn!("Opening .gdd for {document_id:?}: registry build failed, falling back to embedded legacy document");
if legacy_document.is_none() {
log::error!("Opening .gdd for {document_id:?}: no embedded legacy document to fall back to");
}
legacy_document
}
/// Compare-on-open: convert the reopened `.gdd`'s stored registry back to a runtime network and diff
/// it against `legacy_network` (the document the user actually loaded). Validates the `.gdd` read path
/// against the legacy load. Legacy is authoritative during the soak, so this only logs divergence; it
/// never swaps the candidate in. Cold-path (runs once per open, off the edit hot path).
async fn compare_storage_against_runtime(
gdd: &document_format::GddV1,
legacy_network: &graph_craft::document::NodeNetwork,
byte_store: &dyn graph_craft::application_io::resource::LoadResource,
document_id: DocumentId,
) {
let declarations = gdd.declarations(byte_store).await;
let mut candidate = match gdd.registry().to_runtime_with_metadata(&declarations) {
Ok((network, _entries)) => network,
Err(error) => {
log::error!("Compare-on-open for {document_id:?}: .gdd registry failed to convert to runtime: {error}");
return;
}
};
// One open/restore path resolves a node's generic `call_argument` (e.g. a layer's inner monitor node's
// `T`) to a concrete `Context`, while storage faithfully keeps the authored `T`. That generic-vs-resolved
// difference is benign (it's recomputed during compilation), so normalize it on both sides before
// comparing to keep the soak signal focused on real drift.
let mut legacy = legacy_network.clone();
normalize_call_arguments_for_compare(&mut legacy);
normalize_call_arguments_for_compare(&mut candidate);
if candidate != legacy {
log::error!(
"Compare-on-open divergence for {document_id:?}: the reopened .gdd does not match the legacy load\n{}",
crate::messages::portfolio::document::diff_networks(&legacy, &candidate)
);
}
}
/// Canonicalize every node's `call_argument` (recursively, including nested networks) so a generic `T`
/// and its compilation-resolved concrete `Context` compare equal. Storage keeps the authored generic
/// form, but one load/restore path resolves it to `Context`; that difference is benign for the
/// compare-on-open soak check. Concrete `call_arguments` other than `Context` are left untouched.
fn normalize_call_arguments_for_compare(network: &mut graph_craft::document::NodeNetwork) {
use graph_craft::Type;
let context = graph_craft::concrete!(graphene_std::Context);
for node in network.nodes.values_mut() {
if node.call_argument == context {
node.call_argument = Type::Generic(std::borrow::Cow::Borrowed("T"));
}
if let graph_craft::document::DocumentNodeImplementation::Network(inner) = &mut node.implementation {
normalize_call_arguments_for_compare(inner);
}
}
}
/// Returns `None` if the name has no safe filename characters left or matches a Windows reserved device name, so callers fall back to an ID-based stem.
// TODO: Eventually remove this document upgrade code
fn sanitize_filename_stem(name: &str) -> Option<String> {
@@ -36,6 +36,13 @@ pub enum PreferencesMessage {
DisableUIAcceleration {
disable_ui_acceleration: bool,
},
ValidateStorageRoundTrip {
enabled: bool,
},
SaveAsGdd {
enabled: bool,
},
ToggleShowStoragePreferences,
#[cfg(target_os = "macos")]
VSync {
vsync: bool,
@@ -23,6 +23,9 @@ pub struct PreferencesMessageHandler {
pub ui_scale: f64,
pub max_render_region_size: u32,
pub disable_ui_acceleration: bool,
pub validate_storage_round_trip: bool,
pub save_as_gdd: bool,
pub show_storage_preferences: bool,
#[cfg(target_os = "macos")]
pub vsync: bool,
}
@@ -66,6 +69,9 @@ impl Default for PreferencesMessageHandler {
ui_scale: UI_SCALE_DEFAULT,
max_render_region_size: EditorPreferences::default().max_render_region_size,
disable_ui_acceleration: cfg!(target_os = "linux"), // TODO: Set this back to false once we have ui acceleration working more reliably on linux
validate_storage_round_trip: false,
save_as_gdd: false,
show_storage_preferences: false,
#[cfg(target_os = "macos")]
vsync: false,
}
@@ -132,6 +138,16 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
PreferencesMessage::DisableUIAcceleration { disable_ui_acceleration } => {
self.disable_ui_acceleration = disable_ui_acceleration;
}
PreferencesMessage::ValidateStorageRoundTrip { enabled } => {
self.validate_storage_round_trip = enabled;
}
PreferencesMessage::SaveAsGdd { enabled } => {
self.save_as_gdd = enabled;
}
PreferencesMessage::ToggleShowStoragePreferences => {
self.show_storage_preferences = !self.show_storage_preferences;
responses.add(MenuBarMessage::SendLayout);
}
#[cfg(target_os = "macos")]
PreferencesMessage::VSync { vsync } => {
self.vsync = vsync;
+1 -1
View File
@@ -7,7 +7,7 @@ pub use crate::messages::animation::{AnimationMessage, AnimationMessageDiscrimin
pub use crate::messages::app_window::{AppWindowMessage, AppWindowMessageDiscriminant, AppWindowMessageHandler};
pub use crate::messages::broadcast::event::{EventMessage, EventMessageContext, EventMessageDiscriminant, EventMessageHandler};
pub use crate::messages::broadcast::{BroadcastMessage, BroadcastMessageDiscriminant, BroadcastMessageHandler};
pub use crate::messages::clipboard::{ClipboardMessage, ClipboardMessageDiscriminant, ClipboardMessageHandler};
pub use crate::messages::clipboard::{ClipboardMessage, ClipboardMessageContext, ClipboardMessageDiscriminant, ClipboardMessageHandler};
pub use crate::messages::color_picker::{ColorPickerMessage, ColorPickerMessageDiscriminant, ColorPickerMessageHandler};
pub use crate::messages::debug::{DebugMessage, DebugMessageDiscriminant, DebugMessageHandler};
pub use crate::messages::defer::{DeferMessage, DeferMessageDiscriminant, DeferMessageHandler};
@@ -43,16 +43,10 @@ impl ResourceStorageMessageHandler {
})
}
/// The backing store as a `&dyn ResourceStorage`, for write paths (e.g. persisting declaration
/// bytes on commit). `None` before initialization.
pub fn storage(&self) -> Option<&dyn ResourceStorage> {
self.storage.as_deref()
}
/// An owned, cloneable handle that both loads and stores, for `'static` async tasks that need to
/// read and write the cache off-thread. `None` before initialization.
pub fn store_handle(&self) -> Option<ResourcesHandle> {
self.storage.clone().map(|inner| ResourcesHandle { inner })
pub fn resources_mut(&self) -> ResourcesHandle {
ResourcesHandle {
inner: self.storage.clone().expect("Resource storage not initialized"),
}
}
}
@@ -60,8 +60,7 @@ impl ToolColorOptions {
return;
}
if let Some(FillChoice::Solid(color)) = &self.fill_choice {
let fill = graphene_std::vector::style::Fill::Solid(*color);
responses.add(GraphOperationMessage::FillSet { layer, fill });
responses.add(GraphOperationMessage::FillColorSet { layer, color: Some(*color) });
}
}
@@ -70,8 +69,9 @@ impl ToolColorOptions {
return;
}
if let Some(FillChoice::Solid(color)) = &self.fill_choice {
let stroke = graphene_std::vector::style::Stroke::new(Some(*color), weight);
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
let color = Some(*color);
let stroke = graphene_std::vector::style::Stroke::new(weight);
responses.add(GraphOperationMessage::StrokeSet { layer, color, stroke });
}
}
@@ -175,8 +175,8 @@ impl DrawingToolState {
return;
}
let Some(FillChoice::Solid(color)) = &self.stroke.fill_choice else { return };
let color = Some(*color);
let stroke = graphene_std::vector::style::Stroke {
color: Some(*color),
weight: self.effective_line_weight(),
align: self.stroke_align.unwrap_or_default(),
cap: self.stroke_cap.unwrap_or_default(),
@@ -187,7 +187,7 @@ impl DrawingToolState {
dash_offset: self.dash_offset.unwrap_or(0.),
transform: glam::DAffine2::IDENTITY,
};
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
responses.add(GraphOperationMessage::StrokeSet { layer, color, stroke });
}
}
@@ -3,11 +3,10 @@ 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::document::{DocumentNode, NodeId, NodeInput};
use graph_craft::{ProtoNodeIdentifier, concrete};
use graphene_std::Color;
use graphene_std::NodeInputDecleration;
use graphene_std::list::List;
use graphene_std::raster::BlendMode;
@@ -15,8 +14,9 @@ use graphene_std::raster_types::{CPU, GPU, Image, Raster};
use graphene_std::subpath::Subpath;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::misc::ManipulatorPointId;
use graphene_std::vector::style::{Fill, FillChoice, Gradient, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::{GradientStops, PointId, SegmentId, VectorModificationType};
use graphene_std::vector::style::{FillChoice, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, initial_gradient_transform_for_bounding_box};
use graphene_std::vector::{GradientSpreadMethod, GradientStops, GradientType, PointId, SegmentId, VectorModificationType};
use graphene_std::{Color, Graphic};
use std::collections::VecDeque;
/// Returns the ID of the first Spline node in the horizontal flow which is not followed by a `Path` node, or `None` if none exists.
@@ -271,11 +271,18 @@ pub fn get_viewport_center(layer: LayerNodeIdentifier, network_interface: &NodeN
network_interface.document_metadata().transform_to_viewport(layer).transform_point2(min + (max - min) * center)
}
/// Get the closest Fill node's ID to the provided layer, if any.
pub fn get_fill_node_id_with_direct_fill_input(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
let fill_node_id = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
let fill_node = network_interface.document_network().nodes.get(&fill_node_id)?;
matches!(fill_node.inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)?, NodeInput::Value { .. }).then_some(fill_node_id)
}
/// Determine the input connector where the gradient chain enters the layer.
/// Returns Fill's fill input if the layer has a "Fill" node, otherwise returns the layer's content input.
pub fn gradient_chain_target_input(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> InputConnector {
if let Some(fill_node_id) = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER)) {
InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::<Fill>::INDEX)
InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)
} else {
InputConnector::node(layer.to_node(), 1)
}
@@ -292,35 +299,29 @@ pub fn get_upstream_gradient_value_node_id(layer: LayerNodeIdentifier, network_i
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_value::IDENTIFIER)))
}
// TODO: Eventually remove this document upgrade code
/// Get the layer's "Fill" node itself (whose `fill` input holds the paint value), not the node feeding that input.
pub fn get_fill_node_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))
}
/// Get the node connected to Fill's fill input, if any.
pub fn get_fill_input_node_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
let fill_node_id = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
let fill_node = network_interface.document_network().nodes.get(&fill_node_id)?;
let NodeInput::Node { node_id, .. } = fill_node.inputs.get(graphene_std::vector::fill::FillInput::<Fill>::INDEX)? else {
let NodeInput::Node { node_id, .. } = fill_node.inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)? else {
return None;
};
Some(*node_id)
}
/// Get the current gradient of a layer from the closest "Fill" node.
pub fn get_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Gradient> {
let fill_index = 1;
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
let TaggedValue::Fill(Fill::Gradient(gradient)) = inputs.get(fill_index)?.as_value()? else {
return None;
};
Some(gradient.clone())
}
/// Get the gradient stops of a layer, if any.
pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<GradientStops> {
// Try to find the gradient stops value that is created by a Fill node first
if let Some(fill_node_id) = get_fill_node_id_with_direct_fill_input(layer, network_interface) {
return network_interface
.document_network()
.nodes
.get(&fill_node_id)
.and_then(|node| node.inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX))
.and_then(|input| input.as_value())
.and_then(|value| if let TaggedValue::Gradient(gradient) = value { Some(gradient.clone()) } else { None });
}
let gradient_value_node = network_interface.document_network().nodes.get(&get_upstream_gradient_value_node_id(layer, network_interface)?)?;
let TaggedValue::Gradient(stops) = gradient_value_node.inputs.get(graphene_std::math_nodes::gradient_value::GradientInput::INDEX)?.as_value()? else {
return None;
@@ -329,8 +330,8 @@ pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNe
}
/// Compute the transform from a gradient's local space to viewport space for the given layer. For a `List<GradientStops>`
/// layer this is the layer's incoming footprint transform; for the legacy `Fill::Gradient` path it composes the layer's
/// viewport transform with the [0,1]² → bounding-box mapping.
/// layer this is the layer's incoming footprint transform; for a Fill-owned gradient value it composes the layer's viewport
/// transform with the [0,1]² → bounding-box mapping.
pub fn gradient_space_transform(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> glam::DAffine2 {
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
@@ -344,22 +345,14 @@ pub fn gradient_space_transform(layer: LayerNodeIdentifier, network_interface: &
.unwrap_or(metadata.document_to_viewport);
}
// TODO: Eventually remove this document upgrade code
// Only an existing legacy `Fill::Gradient` is in (0, 0)..(1, 1) bounding-box space; migrated and newly-created gradients are absolute (layer space).
if get_gradient(layer, network_interface).is_some_and(|gradient| !gradient.absolute) {
let bounds = metadata.nonzero_bounding_box(layer);
let bound_transform = glam::DAffine2::from_scale_angle_translation(bounds[1] - bounds[0], 0., bounds[0]);
return metadata.transform_to_viewport(layer) * bound_transform;
}
metadata.transform_to_viewport(layer)
}
/// True when start→end (mapped through `transform` into viewport space) points predominantly rightward. For purely
/// vertical lines we fall back to a stable tiebreaker on (x + y) so the choice doesn't flicker between equal alternatives.
pub fn gradient_orientation_rightward(start: glam::DVec2, end: glam::DVec2, transform: glam::DAffine2) -> bool {
let viewport_start = transform.transform_point2(start);
let viewport_end = transform.transform_point2(end);
pub fn gradient_orientation_rightward(transform: glam::DAffine2) -> bool {
let viewport_start = transform.transform_point2(DVec2::ZERO);
let viewport_end = transform.transform_point2(DVec2::X);
if (viewport_end.x - viewport_start.x).abs() > f64::EPSILON * 1e6 {
viewport_end.x > viewport_start.x
} else {
@@ -369,13 +362,11 @@ pub fn gradient_orientation_rightward(start: glam::DVec2, end: glam::DVec2, tran
/// Get the current fill of a layer from the closest "Fill" node.
pub fn get_fill_color(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Color> {
let fill_index = 1;
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
let &TaggedValue::Fill(Fill::Solid(color)) = inputs.get(fill_index)?.as_value()? else {
let &TaggedValue::Color(color) = inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? else {
return None;
};
Some(color)
color
}
/// Get the current blend mode of a layer from the closest upstream "Blend Mode" node.
@@ -626,22 +617,55 @@ pub fn set_stroke_weight_for_selected_layers(weight: f64, document: &DocumentMes
let value = TaggedValue::F64(weight);
responses.add(NodeGraphMessage::SetInputValue { node_id, input_index, value });
} else if weight > 0. {
let color = Some(Color::BLACK);
let stroke = graphene_std::vector::style::Stroke::default().with_weight(weight);
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
responses.add(GraphOperationMessage::StrokeSet { layer, color, stroke });
}
}
}
/// Returns the `Fill` value from a layer's upstream Fill node.
pub fn get_fill_value(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Fill> {
let fill_index = graphene_std::vector::fill::FillInput::<Fill>::INDEX;
let tagged = NodeGraphLayer::new(layer, network_interface).find_input(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER), fill_index)?;
if let TaggedValue::Fill(fill) = tagged { Some(fill.clone()) } else { None }
/// A Fill node's decoded gradient inputs, with the transform kept in its raw form (not yet baked into `start`/`end`).
pub struct FillNodeGradient {
pub stops: GradientStops,
pub gradient_type: GradientType,
pub spread_method: GradientSpreadMethod,
pub transform: DAffine2,
/// Whether the transform input holds a plain value (so it may be written to) rather than a wire.
pub transform_is_value: bool,
}
/// Decode a Fill node's gradient metadata inputs, resolving an unset transform to the default over `bounding_box`. Returns `None` when the fill input isn't a gradient value.
pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOnce() -> [DVec2; 2]) -> Option<FillNodeGradient> {
use graphene_std::vector::fill;
let TaggedValue::Gradient(stops) = fill_node.inputs.get(fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? else {
return None;
};
let gradient_type = match fill_node.inputs.get(fill::GradientTypeInput::INDEX).and_then(|input| input.as_value()) {
Some(&TaggedValue::GradientType(value)) => value,
_ => GradientType::default(),
};
let spread_method = match fill_node.inputs.get(fill::SpreadMethodInput::INDEX).and_then(|input| input.as_value()) {
Some(&TaggedValue::GradientSpreadMethod(value)) => value,
_ => GradientSpreadMethod::default(),
};
let transform_input = fill_node.inputs.get(fill::TransformInput::INDEX).and_then(|input| input.as_value());
let transform = match transform_input {
Some(&TaggedValue::OptionalDAffine2(value)) => value.unwrap_or_else(|| initial_gradient_transform_for_bounding_box(bounding_box())),
_ => DAffine2::IDENTITY,
};
Some(FillNodeGradient {
stops: stops.clone(),
gradient_type,
spread_method,
transform,
transform_is_value: transform_input.is_some(),
})
}
/// Returns the stroke color from a layer's upstream Stroke node.
pub fn get_stroke_color(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Option<Color>> {
let color_index = graphene_std::vector::stroke::ColorInput::INDEX;
let color_index = graphene_std::vector::stroke::PaintInput::<List<Graphic>>::INDEX;
let tagged = NodeGraphLayer::new(layer, network_interface).find_input(&DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER), color_index)?;
if let TaggedValue::Color(color) = tagged { Some(*color) } else { None }
}
@@ -668,10 +692,21 @@ pub struct SelectedStrokeState {
pub fn selected_fill_state(document: &DocumentMessageHandler) -> Option<SelectedFillState> {
let selected_nodes = document.network_interface.selected_nodes();
let mut per_layer = selected_nodes.selected_layers_except_artboards(&document.network_interface).map(|layer| {
if get_fill_id(layer, &document.network_interface).is_none() {
let Some(fill_node_id) = get_fill_id(layer, &document.network_interface) else {
return (false, FillChoice::None);
}
let fill_choice = get_fill_value(layer, &document.network_interface).map_or(FillChoice::None, FillChoice::from);
};
let fill_choice = (|| {
let fill_node = document.network_interface.document_network().nodes.get(&fill_node_id)?;
match fill_node.inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? {
&TaggedValue::Color(color) => Some(color.map_or(FillChoice::None, FillChoice::Solid)),
TaggedValue::Gradient(stops) => Some(FillChoice::Gradient(stops.clone())),
_ => None,
}
})()
.unwrap_or(FillChoice::None);
(true, fill_choice)
});
@@ -746,12 +781,40 @@ pub fn selected_stroke_state(document: &DocumentMessageHandler) -> Option<Select
pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
for layer in layers {
let existing_gradient = get_fill_value(layer, &document.network_interface).and_then(|f| match f {
Fill::Gradient(g) => Some(g),
_ => None,
});
let fill = fill_choice.clone().to_fill(existing_gradient.as_ref());
responses.add(GraphOperationMessage::FillSet { layer, fill });
match &fill_choice {
FillChoice::None => responses.add(GraphOperationMessage::FillColorSet { layer, color: None }),
FillChoice::Solid(color) => responses.add(GraphOperationMessage::FillColorSet { layer, color: Some(*color) }),
FillChoice::Gradient(stops) => {
let fill_node = NodeGraphLayer::new(layer, &document.network_interface)
.upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))
.and_then(|id| document.network_interface.document_network().nodes.get(&id));
let read = |index: usize| fill_node.and_then(|node| node.inputs.get(index)).and_then(|input| input.as_value());
let gradient_type = match read(graphene_std::vector::fill::GradientTypeInput::INDEX) {
Some(TaggedValue::GradientType(value)) => *value,
_ => GradientType::default(),
};
let spread_method = match read(graphene_std::vector::fill::SpreadMethodInput::INDEX) {
Some(TaggedValue::GradientSpreadMethod(value)) => *value,
_ => GradientSpreadMethod::default(),
};
let transform = match read(graphene_std::vector::fill::TransformInput::INDEX) {
Some(TaggedValue::OptionalDAffine2(value)) => {
value.unwrap_or_else(|| initial_gradient_transform_for_bounding_box(document.network_interface.document_metadata().nonzero_bounding_box(layer)))
}
_ => DAffine2::IDENTITY,
};
responses.add(GraphOperationMessage::FillGradientSet {
layer,
gradient: stops.clone(),
gradient_type,
spread_method,
transform,
});
}
}
}
}
@@ -762,12 +825,12 @@ pub fn set_stroke_color_for_selected_layers(color: Option<Color>, weight: f64, d
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
for layer in layers {
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
let input_index = graphene_std::vector::stroke::ColorInput::INDEX;
let input_index = graphene_std::vector::stroke::PaintInput::<List<Graphic>>::INDEX;
let value = TaggedValue::Color(color);
responses.add(NodeGraphMessage::SetInputValue { node_id, input_index, value });
} else {
let stroke = graphene_std::vector::style::Stroke::new(color, weight);
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
let stroke = graphene_std::vector::style::Stroke::new(weight);
responses.add(GraphOperationMessage::StrokeSet { layer, color, stroke });
}
}
}
@@ -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));
}
}
}
@@ -4,7 +4,7 @@ use crate::messages::tool::common_functionality::color_selector::solid;
use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer;
use graphene_std::color::SRGBA8;
use graphene_std::raster::color::Color;
use graphene_std::vector::style::{Fill, FillChoiceUI};
use graphene_std::vector::style::FillChoiceUI;
#[derive(Default, ExtractField)]
pub struct FillTool {
@@ -161,14 +161,17 @@ impl Fsm for FillToolFsmState {
if NodeGraphLayer::is_raster_layer(layer_identifier, &mut document.network_interface) {
return self;
}
let fill = match color_event {
FillToolMessage::FillPrimaryColor => Fill::Solid(global_tool_data.primary_color),
FillToolMessage::FillSecondaryColor => Fill::Solid(global_tool_data.secondary_color),
let color = match color_event {
FillToolMessage::FillPrimaryColor => global_tool_data.primary_color,
FillToolMessage::FillSecondaryColor => global_tool_data.secondary_color,
_ => return self,
};
responses.add(DocumentMessage::AddTransaction);
responses.add(GraphOperationMessage::FillSet { layer: layer_identifier, fill });
responses.add(GraphOperationMessage::FillColorSet {
layer: layer_identifier,
color: Some(color),
});
FillToolFsmState::Filling
}
@@ -203,16 +206,16 @@ impl Fsm for FillToolFsmState {
mod test_fill {
pub use crate::test_utils::test_prelude::*;
use graphene_std::color::SRGBA8;
use graphene_std::list::List;
use graphene_std::vector::fill;
use graphene_std::vector::style::Fill;
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<Fill> {
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<List<Color>> {
let instrumented = match editor.eval_graph().await {
Ok(instrumented) => instrumented,
Err(e) => panic!("Failed to evaluate graph: {e}"),
};
instrumented.grab_all_input::<fill::FillInput<Fill>>(&editor.runtime).collect()
instrumented.grab_all_input::<fill::FillInput<List<Color>>>(&editor.runtime).collect()
}
#[tokio::test]
@@ -242,7 +245,8 @@ mod test_fill {
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::empty()).await;
let fills = get_fills(&mut editor).await;
assert_eq!(fills.len(), 1);
assert_eq!(SRGBA8::from(fills[0].as_solid().unwrap()), SRGBA8::from(Color::GREEN));
let color = fills.first().unwrap().element(0).expect("Color is stored in the list");
assert_eq!(SRGBA8::from(*color), SRGBA8::from(Color::GREEN));
}
#[tokio::test]
@@ -254,6 +258,7 @@ mod test_fill {
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::SHIFT).await;
let fills = get_fills(&mut editor).await;
assert_eq!(fills.len(), 1);
assert_eq!(SRGBA8::from(fills[0].as_solid().unwrap()), SRGBA8::from(Color::YELLOW));
let color = fills.first().unwrap().element(0).expect("Color is stored in the list");
assert_eq!(SRGBA8::from(*color), SRGBA8::from(Color::YELLOW));
}
}
@@ -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)
};
File diff suppressed because it is too large. Load diff
@@ -5,13 +5,12 @@ use crate::consts::{
DOUBLE_CLICK_MILLISECONDS, DRAG_DIRECTION_MODE_DETERMINATION_THRESHOLD, DRAG_THRESHOLD, DRILL_THROUGH_THRESHOLD, HANDLE_ROTATE_SNAP_ANGLE, SEGMENT_INSERTION_DISTANCE, SEGMENT_OVERLAY_SIZE,
SELECTION_THRESHOLD, SELECTION_TOLERANCE,
};
use crate::messages::clipboard::utility_types::ClipboardContent;
use crate::messages::clipboard::utility_types::{ClipboardItem, ClipboardVectorEntry};
use crate::messages::input_mapper::utility_types::macros::action_shortcut_manual;
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, selected_segments};
use crate::messages::portfolio::document::overlays::utility_types::{DrawHandles, OverlayContext};
use crate::messages::portfolio::document::utility_types::clipboards::Clipboard;
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
use crate::messages::portfolio::document::utility_types::transformation::Axis;
@@ -141,14 +140,11 @@ pub enum PathToolMessage {
overlay_context: OverlayContext,
},
StartSlidingPoint,
Copy {
clipboard: Clipboard,
},
Cut {
clipboard: Clipboard,
},
Copy,
Cut,
Paste {
data: String,
#[cfg_attr(feature = "wasm", tsify(type = "unknown"))]
paths: Vec<ClipboardVectorEntry>,
},
DeleteSelected,
Duplicate,
@@ -2749,7 +2745,7 @@ impl Fsm for PathToolFsmState {
PathToolFsmState::Ready
}
}
(_, PathToolMessage::Copy { clipboard }) => {
(_, PathToolMessage::Copy) => {
// TODO: Add support for selected segments
let mut buffer = Vec::new();
@@ -2808,131 +2804,121 @@ impl Fsm for PathToolFsmState {
buffer.push((layer, new_vector, transform));
}
if clipboard == Clipboard::Device {
if let Ok(data) = serde_json::to_string(&buffer) {
responses.add(ClipboardMessage::Write {
content: ClipboardContent::Vector(data),
});
} else {
log::error!("Failed to serialize nodes for clipboard");
}
}
// TODO: Add implementation for internal clipboard
responses.add(ClipboardMessage::WriteItems {
items: vec![ClipboardItem::Vector(buffer)],
});
PathToolFsmState::Ready
}
(_, PathToolMessage::Cut { clipboard }) => {
responses.add(PathToolMessage::Copy { clipboard });
(_, PathToolMessage::Cut) => {
responses.add(PathToolMessage::Copy);
// Delete the selected points/segments
responses.add(PathToolMessage::DeleteSelected);
PathToolFsmState::Ready
}
(_, PathToolMessage::Paste { data }) => {
// Deserialize the data
if let Ok(data) = serde_json::from_str::<Vec<(LayerNodeIdentifier, Vector, DAffine2)>>(&data) {
shape_editor.deselect_all_points();
responses.add(DocumentMessage::AddTransaction);
let mut new_layers = Vec::new();
for (layer, new_vector, transform) in data {
// If layer is not selected then create a new selected layer
let layer = if shape_editor.selected_shape_state.contains_key(&layer) {
layer
} else {
let Some(node_type) = resolve_network_node_type("Path") else {
error!("Could not resolve node type for Path");
continue;
};
let nodes = vec![(NodeId(0), node_type.default_node_template())];
let parent = document.new_layer_parent(false);
let layer = graph_modification_utils::new_custom(NodeId::new(), nodes, parent, responses);
// Defaults chosen because the pasted geometry has no inherent associated style
let stroke = graphene_std::vector::style::Stroke::new(Some(Color::BLACK), DEFAULT_STROKE_WIDTH);
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
let fill = graphene_std::vector::style::Fill::solid(Color::WHITE);
responses.add(GraphOperationMessage::FillSet { layer, fill });
new_layers.push(layer);
responses.add(GraphOperationMessage::TransformSet {
layer,
transform,
transform_in: TransformIn::Local,
skip_rerender: false,
});
layer
};
// Create new point ids and add those into the existing vector content
let mut points_map = HashMap::new();
for (point, position) in new_vector.point_domain.iter() {
let new_point_id = PointId::generate();
points_map.insert(point, new_point_id);
let modification_type = VectorModificationType::InsertPoint { id: new_point_id, position };
responses.add(GraphOperationMessage::Vector { layer, modification_type });
}
// Create new segment ids and add the segments into the existing vector content
let mut segments_map = HashMap::new();
for (segment_id, bezier, start, end) in new_vector.segment_iter() {
let new_segment_id = SegmentId::generate();
segments_map.insert(segment_id, new_segment_id);
let points = pathseg_points(bezier);
let handles = [points.p1.map(|handle| handle - points.p0), points.p2.map(|handle| handle - points.p3)];
let points = [points_map[&start], points_map[&end]];
let modification_type = VectorModificationType::InsertSegment { id: new_segment_id, points, handles };
responses.add(GraphOperationMessage::Vector { layer, modification_type });
}
// Set G1 continuity
for handles in new_vector.colinear_manipulators {
let to_new_handle = |handle: HandleId| -> HandleId {
HandleId {
ty: handle.ty,
segment: segments_map[&handle.segment],
}
};
let new_handles = [to_new_handle(handles[0]), to_new_handle(handles[1])];
let modification_type = VectorModificationType::SetG1Continuous { handles: new_handles, enabled: true };
responses.add(GraphOperationMessage::Vector { layer, modification_type });
}
shape_editor.selected_shape_state.entry(layer).or_insert(Default::default());
// Set selection to newly inserted points
let Some(state) = shape_editor.selected_shape_state.get_mut(&layer) else {
error!("No state for layer: {layer:?}");
(_, PathToolMessage::Paste { paths }) => {
shape_editor.deselect_all_points();
responses.add(DocumentMessage::AddTransaction);
let mut new_layers = Vec::new();
for (layer, new_vector, transform) in paths {
// If layer is not selected then create a new selected layer
let layer = if shape_editor.selected_shape_state.contains_key(&layer) {
layer
} else {
let Some(node_type) = resolve_network_node_type("Path") else {
error!("Could not resolve node type for Path");
continue;
};
let nodes = vec![(NodeId(0), node_type.default_node_template())];
// If point editing mode is enabled, select all the pasted points
if tool_options.path_editing_mode.point_editing_mode {
points_map.values().for_each(|point| state.select_point(ManipulatorPointId::Anchor(*point)));
}
// If segment editing mode is enabled, select all the pasted segments
if tool_options.path_editing_mode.segment_editing_mode {
segments_map.values().for_each(|segment| state.select_segment(*segment));
}
let parent = document.new_layer_parent(false);
let layer = graph_modification_utils::new_custom(NodeId::new(), nodes, parent, responses);
// Defaults chosen because the pasted geometry has no inherent associated style
let color = Some(Color::BLACK);
let stroke = graphene_std::vector::style::Stroke::new(DEFAULT_STROKE_WIDTH);
responses.add(GraphOperationMessage::StrokeSet { layer, color, stroke });
responses.add(GraphOperationMessage::FillColorSet { layer, color: Some(Color::WHITE) });
new_layers.push(layer);
responses.add(GraphOperationMessage::TransformSet {
layer,
transform,
transform_in: TransformIn::Local,
skip_rerender: false,
});
layer
};
// Create new point ids and add those into the existing vector content
let mut points_map = HashMap::new();
for (point, position) in new_vector.point_domain.iter() {
let new_point_id = PointId::generate();
points_map.insert(point, new_point_id);
let modification_type = VectorModificationType::InsertPoint { id: new_point_id, position };
responses.add(GraphOperationMessage::Vector { layer, modification_type });
}
// If there are new layers created, we need to center them in the viewport
if !new_layers.is_empty() {
responses.add(Message::Defer(DeferMessage::AfterGraphRun {
messages: vec![PortfolioMessage::CenterPastedLayers { layers: new_layers }.into()],
}));
// Create new segment ids and add the segments into the existing vector content
let mut segments_map = HashMap::new();
for (segment_id, bezier, start, end) in new_vector.segment_iter() {
let new_segment_id = SegmentId::generate();
segments_map.insert(segment_id, new_segment_id);
let points = pathseg_points(bezier);
let handles = [points.p1.map(|handle| handle - points.p0), points.p2.map(|handle| handle - points.p3)];
let points = [points_map[&start], points_map[&end]];
let modification_type = VectorModificationType::InsertSegment { id: new_segment_id, points, handles };
responses.add(GraphOperationMessage::Vector { layer, modification_type });
}
// Set G1 continuity
for handles in new_vector.colinear_manipulators {
let to_new_handle = |handle: HandleId| -> HandleId {
HandleId {
ty: handle.ty,
segment: segments_map[&handle.segment],
}
};
let new_handles = [to_new_handle(handles[0]), to_new_handle(handles[1])];
let modification_type = VectorModificationType::SetG1Continuous { handles: new_handles, enabled: true };
responses.add(GraphOperationMessage::Vector { layer, modification_type });
}
shape_editor.selected_shape_state.entry(layer).or_insert(Default::default());
// Set selection to newly inserted points
let Some(state) = shape_editor.selected_shape_state.get_mut(&layer) else {
error!("No state for layer: {layer:?}");
continue;
};
// If point editing mode is enabled, select all the pasted points
if tool_options.path_editing_mode.point_editing_mode {
points_map.values().for_each(|point| state.select_point(ManipulatorPointId::Anchor(*point)));
}
// If segment editing mode is enabled, select all the pasted segments
if tool_options.path_editing_mode.segment_editing_mode {
segments_map.values().for_each(|segment| state.select_segment(*segment));
}
}
// If there are new layers created, we need to center them in the viewport
if !new_layers.is_empty() {
responses.add(Message::Defer(DeferMessage::AfterGraphRun {
messages: vec![PortfolioMessage::CenterLayers { layers: new_layers }.into()],
}));
}
PathToolFsmState::Ready
@@ -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;
@@ -24,7 +24,7 @@ use graphene_std::choice_type::ChoiceTypeStatic;
use graphene_std::color::SRGBA8;
use graphene_std::renderer::Quad;
use graphene_std::text::{Font, TextAlign, TypesettingConfig, lines_clipping};
use graphene_std::vector::style::{Fill, FillChoice, FillChoiceUI};
use graphene_std::vector::style::{FillChoice, FillChoiceUI};
use graphene_std::{Color, NodeInputDecleration};
#[derive(Default, ExtractField)]
@@ -571,9 +571,9 @@ impl TextToolData {
parent: document.new_layer_parent(true),
insert_index: 0,
});
responses.add(GraphOperationMessage::FillSet {
responses.add(GraphOperationMessage::FillColorSet {
layer: self.layer,
fill: editing_text.color.map_or(Fill::None, Fill::Solid),
color: editing_text.color,
});
let transform = editing_text.transform;
self.editing_text = Some(editing_text);
@@ -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,
Loaded 100 of 188 files, more files were not shown because too many files have changed in this diff. Show more