mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
43c780c5c0 | ||
|
|
3c04c2bb8b | ||
|
|
e0d3c21429 | ||
|
|
96b18d2552 | ||
|
|
7afa1ced37 | ||
|
|
adee7fc46f | ||
|
|
9e2a274453 | ||
|
|
97f44e8915 |
No files matched your search
@@ -1,2 +1,2 @@
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/0d004aa61e6b48d316e8e5db6d59ccc4788f192d.tar.gz
|
||||
772d64518be43c99977ba56f69e574531c56e83d2df2f42ab066f77f74b0dd1f
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/1509880500e32cb21235343ba865adcf0579133f.tar.gz
|
||||
89b4c58aee186b0c1610a8778bd199c9bdaf1191b4006e6b007dc40a402f4aa7
|
||||
@@ -1,7 +1,3 @@
|
||||
[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.
|
||||
rustflags = ["--cfg=web_sys_unstable_apis"]
|
||||
|
||||
[target.wasm32-unknown-unknown]
|
||||
rustflags = [
|
||||
# Currently disabled because of https://github.com/GraphiteEditor/Graphite/issues/1262
|
||||
@@ -13,9 +9,6 @@ rustflags = [
|
||||
"-C",
|
||||
"link-arg=--max-memory=4294967296",
|
||||
"--cfg=web_sys_unstable_apis",
|
||||
# TODO: Remove this and find a better way to stay within the 25MB limit of cloudflare pages
|
||||
"-C",
|
||||
"opt-level=s",
|
||||
]
|
||||
|
||||
[env]
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
},
|
||||
"ghcr.io/devcontainers/features/node:1": {}
|
||||
},
|
||||
"onCreateCommand": "cargo install cargo-watch wasm-pack cargo-about && cargo install -f [email protected]21",
|
||||
"onCreateCommand": "cargo install cargo-watch wasm-pack cargo-about && cargo install -f [email protected]00",
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
// NOTE: Keep this in sync with `.vscode/extensions.json`
|
||||
|
||||
+12
-38
@@ -153,38 +153,22 @@ jobs:
|
||||
if [ "${{ github.ref }}" = "refs/tags/latest-stable" ]; then
|
||||
REF="latest-stable"
|
||||
ENVIRONMENT="graphite-editor (Production)"
|
||||
AUTO_INACTIVE="true"
|
||||
TRANSIENT_ENVIRONMENT="false"
|
||||
elif [ "${{ github.event_name }}" = "push" ]; then
|
||||
REF="master"
|
||||
ENVIRONMENT="graphite-dev (Production)"
|
||||
AUTO_INACTIVE="true"
|
||||
TRANSIENT_ENVIRONMENT="false"
|
||||
else
|
||||
REF="${{ inputs.checkout_ref || github.head_ref || github.ref_name }}"
|
||||
REF="$(git rev-parse HEAD)"
|
||||
ENVIRONMENT="graphite-dev (Preview)"
|
||||
AUTO_INACTIVE="false"
|
||||
TRANSIENT_ENVIRONMENT="true"
|
||||
fi
|
||||
create_deployment() {
|
||||
gh api \
|
||||
-X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
repos/${{ github.repository }}/deployments \
|
||||
--input - \
|
||||
--jq '.id' <<EOF
|
||||
{
|
||||
"ref": "$1",
|
||||
"environment": "$ENVIRONMENT",
|
||||
"auto_merge": false,
|
||||
"required_contexts": [],
|
||||
"auto_inactive": $AUTO_INACTIVE,
|
||||
"transient_environment": $TRANSIENT_ENVIRONMENT
|
||||
}
|
||||
DEPLOY_ID=$(gh api \
|
||||
-X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
repos/${{ github.repository }}/deployments \
|
||||
--input - \
|
||||
--jq '.id' <<EOF
|
||||
{"ref":"$REF","environment":"$ENVIRONMENT","auto_merge":false,"required_contexts":[]}
|
||||
EOF
|
||||
}
|
||||
# Try branch name first (needed for GitHub's PR "View deployment" button), fall back to commit SHA if the branch was deleted
|
||||
DEPLOY_ID=$(create_deployment "$REF" 2>/dev/null) || DEPLOY_ID=$(create_deployment "$(git rev-parse HEAD)")
|
||||
)
|
||||
gh api \
|
||||
-X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
@@ -204,19 +188,9 @@ jobs:
|
||||
exit 0
|
||||
fi
|
||||
|
||||
size_of() { find frontend/dist/assets "$@" -printf '%s\n' | awk '{s+=$1} END {printf "%.2f MB", s/1048576}'; }
|
||||
WASM_SIZE=$(size_of -name '*.wasm')
|
||||
JS_SIZE=$(size_of -name '*.js')
|
||||
CSS_SIZE=$(size_of -name '*.css')
|
||||
FONT_SIZE=$(size_of \( -name '*.woff2' -o -name '*.woff' -o -name '*.ttf' -o -name '*.otf' \))
|
||||
IMAGE_SIZE=$(size_of \( -name '*.png' -o -name '*.jpg' -o -name '*.svg' \))
|
||||
ALL_SIZE=$(size_of -type f)
|
||||
|
||||
COMMENT_BODY="| 📦 **Web Build Complete for** $(git rev-parse HEAD) |
|
||||
|-|
|
||||
| $CF_URL |
|
||||
|
||||
Wasm: **$WASM_SIZE** — JS: **$JS_SIZE** — CSS: **$CSS_SIZE** — Fonts: **$FONT_SIZE** — Images: **$IMAGE_SIZE** — All Assets: **$ALL_SIZE**"
|
||||
| $CF_URL |"
|
||||
|
||||
if [ "${{ github.ref }}" = "refs/tags/latest-stable" ]; then
|
||||
# Push tag: skip commenting (commit was already commented on master merge)
|
||||
@@ -283,7 +257,7 @@ jobs:
|
||||
pull-requests: write
|
||||
|
||||
env:
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.121"
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.100"
|
||||
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
@@ -474,7 +448,7 @@ jobs:
|
||||
pull-requests: write
|
||||
|
||||
env:
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.121"
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.100"
|
||||
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
|
||||
@@ -57,8 +57,7 @@ jobs:
|
||||
|
||||
- name: 🧪 Run Rust tests
|
||||
env:
|
||||
# `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml`
|
||||
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
|
||||
RUSTFLAGS: -Dwarnings
|
||||
run: mold -run cargo test --all-features
|
||||
|
||||
# Rust format check on GitHub runner
|
||||
|
||||
@@ -22,14 +22,27 @@ jobs:
|
||||
- name: Install Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Install Valgrind
|
||||
run: |
|
||||
sudo apt update
|
||||
sudo apt install -y valgrind
|
||||
|
||||
- name: Cache Rust dependencies
|
||||
uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
# Cache on Cargo.lock file
|
||||
cache-on-failure: true
|
||||
|
||||
- name: Install gungraun-runner and valgrind
|
||||
uses: gungraun/setup-gungraun@v1
|
||||
- name: Cache iai-callgrind binary
|
||||
id: cache-iai
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: ~/.cargo/bin/iai-callgrind-runner
|
||||
key: ${{ runner.os }}-iai-callgrind-runner-0.16.1
|
||||
|
||||
- name: Install iai-callgrind
|
||||
if: steps.cache-iai.outputs.cache-hit != 'true'
|
||||
run: cargo install [email protected]
|
||||
|
||||
- name: Checkout master branch
|
||||
run: |
|
||||
@@ -53,21 +66,21 @@ jobs:
|
||||
id: cache-benchmark-baselines
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: target/gungraun
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-gungraun-benchmark-baselines-master-${{ steps.master-sha.outputs.sha }}
|
||||
path: target/iai
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-benchmark-baselines-master-${{ steps.master-sha.outputs.sha }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-gungraun-benchmark-baselines-master-
|
||||
${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-benchmark-baselines-master-
|
||||
|
||||
- name: Run baseline benchmarks
|
||||
if: steps.cache-benchmark-baselines.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
# Compile benchmarks
|
||||
cargo bench --bench compile_demo_art_gungraun -- --save-baseline=master
|
||||
cargo bench --bench compile_demo_art_iai -- --save-baseline=master
|
||||
|
||||
# Runtime benchmarks
|
||||
cargo bench --bench update_executor_gungraun -- --save-baseline=master
|
||||
cargo bench --bench run_once_gungraun -- --save-baseline=master
|
||||
cargo bench --bench run_cached_gungraun -- --save-baseline=master
|
||||
cargo bench --bench update_executor_iai -- --save-baseline=master
|
||||
cargo bench --bench run_once_iai -- --save-baseline=master
|
||||
cargo bench --bench run_cached_iai -- --save-baseline=master
|
||||
|
||||
- name: Checkout PR branch
|
||||
run: git checkout ${{ github.event.pull_request.head.sha }}
|
||||
@@ -75,12 +88,12 @@ jobs:
|
||||
- name: Run PR benchmarks
|
||||
run: |
|
||||
# Compile benchmarks
|
||||
cargo bench --bench compile_demo_art_gungraun -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/compile_output.json
|
||||
cargo bench --bench compile_demo_art_iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/compile_output.json
|
||||
|
||||
# Runtime benchmarks
|
||||
cargo bench --bench update_executor_gungraun -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/update_output.json
|
||||
cargo bench --bench run_once_gungraun -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/run_once_output.json
|
||||
cargo bench --bench run_cached_gungraun -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/run_cached_output.json
|
||||
cargo bench --bench update_executor_iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/update_output.json
|
||||
cargo bench --bench run_once_iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/run_once_output.json
|
||||
cargo bench --bench run_cached_iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/run_cached_output.json
|
||||
|
||||
- name: Make old comments collapsed by default
|
||||
# Only run if we have write permissions (not a fork)
|
||||
|
||||
@@ -12,4 +12,3 @@ flamegraph.svg
|
||||
.idea/
|
||||
.direnv
|
||||
.DS_Store
|
||||
.nvim.lua
|
||||
+5
-2
@@ -61,10 +61,13 @@ in
|
||||
graphite-bundle = (lib.call ./pkgs/graphite-bundle.nix) { };
|
||||
graphite-bundle-dev = (lib.call ./pkgs/graphite-bundle.nix) { graphite = graphite-dev; };
|
||||
graphite-flatpak-manifest = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { };
|
||||
graphite-flatpak-manifest-dev = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { graphite-bundle = graphite-bundle-dev; };
|
||||
graphite-cef = lib.call ./pkgs/graphite-cef.nix;
|
||||
graphite-flatpak-manifest-dev = (lib.call ./pkgs/graphite-flatpak-manifest.nix) {
|
||||
graphite-bundle = graphite-bundle-dev;
|
||||
};
|
||||
|
||||
# TODO: graphene-cli = lib.call ./pkgs/graphene-cli.nix;
|
||||
|
||||
graphite-cef = lib.call ./pkgs/graphite-cef/package.nix;
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
+4
-1
@@ -29,7 +29,7 @@ pkgs.mkShell (
|
||||
pkgs.lld
|
||||
pkgs.nodejs
|
||||
pkgs.binaryen
|
||||
pkgs.wasm-bindgen-cli_0_2_121
|
||||
pkgs.wasm-bindgen-cli_0_2_100
|
||||
pkgs.wasm-pack
|
||||
pkgs.cargo-about
|
||||
|
||||
@@ -61,6 +61,9 @@ pkgs.mkShell (
|
||||
LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libs}:${self.packages.${system}.graphite-cef}";
|
||||
XDG_DATA_DIRS = "${pkgs.gsettings-desktop-schemas}/share/gsettings-schemas/${pkgs.gsettings-desktop-schemas.name}:${pkgs.gtk3}/share/gsettings-schemas/${pkgs.gtk3.name}:$XDG_DATA_DIRS";
|
||||
|
||||
# shellHook = ''
|
||||
# alias cargo='mold --run cargo'
|
||||
# '';
|
||||
}
|
||||
// deps.rustGPU.env
|
||||
)
|
||||
@@ -1,11 +1,10 @@
|
||||
{ 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=";
|
||||
};
|
||||
versionFile = builtins.fromJSON (builtins.readFile ./version.json);
|
||||
|
||||
version = versionFile.version;
|
||||
hash = selectSystem versionFile.hashes;
|
||||
|
||||
selectSystem =
|
||||
attrs:
|
||||
@@ -19,7 +18,7 @@ let
|
||||
x86_64-linux = "linux64";
|
||||
}
|
||||
}_minimal.tar.bz2";
|
||||
hash = selectSystem hashes;
|
||||
hash = hash;
|
||||
};
|
||||
in
|
||||
pkgs.cef-binary.overrideAttrs (finalAttrs: {
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"version": "146.0.12+g6214c8e+chromium-146.0.7680.179",
|
||||
"hashes": {
|
||||
"aarch64-linux": "sha256-pi3fV3O31YMHcOh+/lnk2gWI6/MaSNAiUgFhD09d7u0=",
|
||||
"x86_64-linux": "sha256-b2HKaSEEXkZsnsBw9bL2JGmKWwRN5l2wu/O1DxfhAgE="
|
||||
}
|
||||
}
|
||||
@@ -83,7 +83,7 @@ deps.crane.lib.buildPackage (
|
||||
pkgs.lld
|
||||
pkgs.nodejs
|
||||
pkgs.binaryen
|
||||
pkgs.wasm-bindgen-cli_0_2_121
|
||||
pkgs.wasm-bindgen-cli_0_2_100
|
||||
pkgs.wasm-pack
|
||||
pkgs.cargo-about
|
||||
pkgs.removeReferencesTo
|
||||
@@ -152,7 +152,6 @@ deps.crane.lib.buildPackage (
|
||||
patchelf \
|
||||
--set-rpath "${pkgs.lib.makeLibraryPath libs}:${self.packages.${system}.graphite-cef}" \
|
||||
--add-needed libGL.so \
|
||||
--add-needed libEGL.so \
|
||||
$out/bin/graphite
|
||||
'';
|
||||
|
||||
|
||||
Vendored
+1
-2
@@ -70,6 +70,5 @@
|
||||
"*.graphite": "json"
|
||||
},
|
||||
"editor.renderWhitespace": "boundary",
|
||||
"editor.minimap.markSectionHeaderRegex": "// ===+\\n\\s*//\\s*(?<label>[^\\n]{1,18})[^\\n]*(\\n\\s*//[^\\n]*)*\\n\\s*// ===+",
|
||||
"git.addAICoAuthor": "off"
|
||||
"editor.minimap.markSectionHeaderRegex": "// ===+\\n\\s*//\\s*(?<label>[^\\n]{1,18})[^\\n]*(\\n\\s*//[^\\n]*)*\\n\\s*// ===+"
|
||||
}
|
||||
Generated
+400
-506
File diff suppressed because it is too large.
Load diff
+11
-20
@@ -11,7 +11,6 @@ members = [
|
||||
"frontend/wrapper",
|
||||
"libraries/dyn-any",
|
||||
"libraries/math-parser",
|
||||
"node-graph/libraries/graphene-hash",
|
||||
"node-graph/libraries/*",
|
||||
"node-graph/nodes/*",
|
||||
"node-graph/nodes/raster/shaders",
|
||||
@@ -64,7 +63,6 @@ dyn-any = { path = "libraries/dyn-any", features = [
|
||||
"log-bad-types",
|
||||
"rc",
|
||||
] }
|
||||
graphene-hash = { path = "node-graph/libraries/graphene-hash", features = ["derive"] }
|
||||
preprocessor = { path = "node-graph/preprocessor" }
|
||||
math-parser = { path = "libraries/math-parser" }
|
||||
graphene-application-io = { path = "node-graph/libraries/application-io" }
|
||||
@@ -108,9 +106,6 @@ log = "0.4"
|
||||
bitflags = { version = "2.4", features = ["serde"] }
|
||||
ctor = "0.2"
|
||||
convert_case = "0.8"
|
||||
titlecase = "3.6"
|
||||
fancy-regex = "0.18.0"
|
||||
unicode-segmentation = "1.13.2"
|
||||
indoc = "2.0.5"
|
||||
derivative = "2.2"
|
||||
thiserror = "2"
|
||||
@@ -120,17 +115,17 @@ quote = "1.0"
|
||||
chrono = "0.4"
|
||||
ron = "0.12"
|
||||
fastnoise-lite = "1.1"
|
||||
wgpu = { version = "29.0", features = [
|
||||
wgpu = { version = "28.0", features = [
|
||||
# We don't have wgpu on multiple threads (yet) https://github.com/gfx-rs/wgpu/blob/trunk/CHANGELOG.md#wgpu-types-now-send-sync-on-wasm
|
||||
"fragile-send-sync-non-atomic-wasm",
|
||||
"spirv",
|
||||
"strict_asserts",
|
||||
] }
|
||||
once_cell = "1.13" # Remove and replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>)
|
||||
wasm-bindgen = "=0.2.121" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned across CI workflows, devcontainer, Nix, and the `cargo-run` tool. We pin this version because wasm-bindgen upgrades may break various things.
|
||||
wasm-bindgen = "=0.2.100" # NOTICE: ensure this stays in sync with the `wasm-bindgen-cli` version in `website/content/volunteer/guide/project-setup/_index.md`. We pin this version because wasm-bindgen upgrades may break various things.
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "=0.3.98"
|
||||
web-sys = { version = "=0.3.98", features = [
|
||||
js-sys = "=0.3.77"
|
||||
web-sys = { version = "=0.3.77", features = [
|
||||
"Document",
|
||||
"DomRect",
|
||||
"Element",
|
||||
@@ -154,14 +149,13 @@ url = "2.5"
|
||||
tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-multi-thread"] }
|
||||
# Linebender ecosystem (BEGIN)
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
vello = "0.9"
|
||||
vello_encoding = "0.9"
|
||||
vello = "0.8"
|
||||
vello_encoding = "0.8"
|
||||
resvg = "0.47"
|
||||
usvg = "0.47"
|
||||
parley = { version = "0.9", default-features = false, features = ["std"] }
|
||||
skrifa = "0.42"
|
||||
parley = "0.6"
|
||||
skrifa = "0.40"
|
||||
polycool = "0.4"
|
||||
color = "0.3"
|
||||
# Linebender ecosystem (END)
|
||||
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
|
||||
rand_chacha = "0.9"
|
||||
@@ -199,12 +193,12 @@ petgraph = { version = "0.7", default-features = false, features = ["graphmap"]
|
||||
half = { version = "2.4", default-features = false, features = ["bytemuck"] }
|
||||
tinyvec = { version = "1", features = ["std"] }
|
||||
criterion = { version = "0.7", features = ["html_reports"] }
|
||||
gungraun = { version = "0.18" }
|
||||
iai-callgrind = { version = "0.16" }
|
||||
ndarray = "0.16"
|
||||
strum = { version = "0.27", features = ["derive"] }
|
||||
dirs = "6.0"
|
||||
cef = "148"
|
||||
cef-dll-sys = "148"
|
||||
cef = "146"
|
||||
cef-dll-sys = "146"
|
||||
include_dir = "0.7"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
tracing = "0.1"
|
||||
@@ -219,7 +213,6 @@ lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "e
|
||||
scraper = "0.25"
|
||||
linesweeper = "0.3"
|
||||
smallvec = "1.13.2"
|
||||
zip = { version = "8", default-features = false }
|
||||
|
||||
[workspace.lints.rust]
|
||||
unexpected_cfgs = { level = "allow", check-cfg = ['cfg(target_arch, values("spirv"))'] }
|
||||
@@ -246,5 +239,3 @@ 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" }
|
||||
@@ -1,5 +1,4 @@
|
||||
accepted = [
|
||||
"0BSD", # Keep this list in sync with those in `/deny.toml`
|
||||
"Apache-2.0 WITH LLVM-exception", # Keep this list in sync with those in `/deny.toml`
|
||||
"Apache-2.0", # Keep this list in sync with those in `/deny.toml`
|
||||
"BSD-2-Clause", # Keep this list in sync with those in `/deny.toml`
|
||||
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Fill":{"Solid":{"red":0.9765625,"green":0.7715821,"blue":0.2861023,"alpha":1.0}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.9765625,"green":0.7715821,"blue":0.2861023,"alpha":1.0}},"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},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}]},"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":0}},{"Value":{"tagged_value":{"Fill":{"Solid":{"red":0.9921Line truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[10316247453530667000,{"inputs":[{"Node":{"node_id":9079109751490757000,"output_index":0}},{"Node":{"node_id":1250460246919467000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"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>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::SourceNodeIdNode"}},"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>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":false,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[7954638344846060000,{"inputs":[{"Node":{"node_id":5991296268862790000,"output_index":0}},{"Value":{"tagged_value":{"Fill":{"Solid":{"red":0.1875,"green":0.0,"blue":0.0,"alpha":0.203125}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"element":[{"red":0.19140625,"green":0.0,"blue":0.0,"alpha":0.203125}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]},"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5]}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[17021405646895729000,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"GradientTable":{"element":[{"position":[0.0,0.5,1.0],"midpoint":[0.5,0.5,0.5],"color":[{"red":1.0,"green":0.31764707,"blue":0.15686275,"alpha":1.0},{"red":1.0,"green":0.5686275,"blue":0.25490198,"alpha":1.0},{"red":1.0,"green":0.7294118,"blue":0.16078432,"alpha":1.0}]}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"math_nodes::GradientValueNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[8366826746721323000,{"inputs":[{"Node":{"node_id":5591755359500854000,"output_index":0}},{"Node":{"node_id":13846904447064916285,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"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>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":3Line truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::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":[[10507084483235320484,{"inputs":[{"Node":{"node_id":9157963288496356916,"output_index":0}},{"Node":{"node_id":1396768435017101055,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"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>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::SourceNodeIdNode"}},"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>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4741515246389989284,{"inputs":[{"Node":{"node_id":14255588039347536657,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[-261.2435565297001,-70.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"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","alias":null}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"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":""}}],[4105329493214975815,{"inputs":[{"Node":{"node_id":12931264630175648107,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[-261.24355652969916,-70.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::conteLine truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5],"color":[{"red":0.28211805,"green":0.0,"blue":0.3046875,"alpha":1.0},{"red":0.13647461,"green":0.3989315,"blue":0.8125,"alpha":1.0},{"red":1.0,"green":0.9409449,"blue":0.625,"alpha":1.0},{"red":0.58431375,"green":0.92941177,"blue":0.92941177,"alpha":0.01}]}},"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},{"red":0.23828125,"green":0.0,"blue":0.08377075,"alpha":1.0},{"red":0.92578125,"green":0.8676921,"blue":0.5569153,"alpha":1.0},{"red":0.17333984,"green":0.625,"blue":0.625,"alpha":1.0},{"red":0.106292725,"green":0.3359375,"blue":0.3359375,"alpha":1.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":"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_value":{"CellularReturnType":"CellValue"},"exposed":false}},{"Value":{"tagged_value":{"F64":1.0},"exposed":false}}],"call_argument":{"Concrete":{"nameLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientTable":{"element":[{"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},{"red":0.23828125,"green":0.0,"blue":0.08377075,"alpha":1.0},{"red":0.92578125,"green":0.8676921,"blue":0.5569153,"alpha":1.0},{"red":0.17333984,"green":0.625,"blue":0.625,"alpha":1.0},{"red":0.106292725,"green":0.3359375,"blue":0.3359375,"alpha":1.0}]}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","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>>","alias":null}},"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","alias":null}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"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":""}}],[7624113397561636853,{"inputs":[{"Value":{"tagged_value":{"Graphic":{"element":[],"transform":[],"alpha_blending":[],"source_node_id":[]}},"exposed":true}},{"Node":{"node_id":3606681156406984991,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"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>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc:Line truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"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.92156863,"green":0.6039216,"blue":0.18039216,"alpha":1.0}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8509804,"green":0.24313726,"blue":0.18431373,"alpha":1.0}},"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},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]},"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.93333334,"green":0.8627451,"blue":0.7254902,"alpha":1.0}},"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":[{"Node":{"node_id":0,"output_index":0}},{"Value":{"tagged_value":{"String":"ediLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[13353438235848911576,{"inputs":[{"Value":{"tagged_value":{"Vector":{"element":[{"style":{"stroke":{"color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},"weight":0.0,"dash_lengths":[],"dash_offset":0.0,"cap":"Butt","join":"Miter","join_miter_limit":4.0,"align":"Center","transform":[1.0,0.0,0.0,1.0,0.0,0.0],"non_scaling":false,"paint_order":"StrokeAbove"},"fill":"None"},"colinear_manipulators":[],"point_domain":{"id":[],"position":[]},"segment_domain":{"id":[],"start_point":[],"end_point":[],"handles":[],"stroke":[]},"region_domain":{"id":[],"segment_range":[],"fill":[]},"upstream_data":null}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[6379137305818664393,18442321214082298093,18118267825025549699,6351696498298648253,17863574903157697896,4691860614575868200,301778328144628917,10625296323957562985,533731991408535384,13357220652574593654,15992617814592812350],"remove":[],"delta":[[18442321214082298093,[565.6296296296297,122.96296296296298]],[13357220652574593654,[574.2222222222222,108.44444444444449]],[6351696498298648253,[646.8148148148149,0.0]],[6379137305818664393,[625.4814814814813,0.0]],[17863574903157697896,[606.8148151308641,95.19407372365433]],[18118267825025549699,[642.0740740740741,0.0]],[10625296323957562985,[473.4814814814815,272.5925925925926]],[533731991408535384,[501.6296296296296,175.40740740740742]],[4691860614575868200,[528.2962962962963,283.8518518518518]],[15992617814592812350,[621.0370370370368,0.0]],[301778328144628917,[493.5149940383244,200.29629629629628]]]},"segments":{"add":[13662059715350867364,3384102572540409881,12035095010819582754,10146665273368938971,318560030360358929,8462655819889292900,3303411878775644985,8661113083384527971,2035327810332855521,11346538709718766144,3710133387837274291],"remove":[],"start_point":[[3303411878775644985,301778328144628917],[13662059715350867364,6379137305818664393],[318560030360358929,17863574903157697896],[3384102572540409881,18442321214082298093],[12035095010819582754,18118267825025549699],[10146665273368938971,6351696498298648253],[11346538709718766144,13357220652574593654],[8462655819889292900,4691860614575868200],[8661113083384527971,10625296323957562985],[3710133387837274291,15992617814592812350],[2035327810332855521,533731991408535384]],"end_point":[[2035327810332855521,13357220652574593654],[12035095010819582754,6351696498298648253],[10146665273368938971,17863574903157697896],[318560030360358929,4691860614575868200],[11346538709718766144,15992617814592812350],[3303411878775644985,10625296323957562985],[3710133387837274291,6379137305818664393],[8462655819889292900,301778328144628917],[13662059715350867364,18442321214082298093],[8661113083384527971,533731991408535384],[3384102572540409881,18118267825025549699]],"handle_primary":[[8661113083384527971,[0.2962962962963047,0.2962962962963047]],[3710133387837274291,[0.0,0.0]],[10146665273368938971,[0.0,0.0]],[3303411878775644985,[0.0,0.0]],[13662059715350867364,[0.0,0.0]],[12035095010819582754,[0.0,0.0]],[11346538709718766144,[9.925839724176626,-9.951533978271286]],[8462655819889292900,[0.0,0.0]],[2035327810332855521,[42.96296296296293,-41.7777777777778]],[3384102572540409881,[0.0,0.0]],[318560030360358929,[-46.95465552079859,46.40007297527743]]],"handle_end":[[3384102572540409881,[0.5807410754567854,77.36888852918523]],[13662059715350867364,[68.68148181185177,-54.8859262904691]],[3710133387837274291,[0.0,0.0]],[11346538709718766144,[1.1377781018271662,63.71555518874077]],[8661113083384527971,[-42.34888386913234,41.180638796880466]],[2035327810332855521,[-8.299214014278164,8.32069754812484]],[12035095010819582754,[0.0,0.0]],[318560030360358929,[-97.48148148148152,-81.18518518518522]],[10146665273368938971,[48.16592595101224,-47.597037061827145]],[3303411878775644985,[-6.2222222222222285,-40.59259259259261]],[8462655819889292900,[-21.74426522093495,47.99999999999997]]],"stroke":[[3303411878775644985,0],[8661113083384527971,0],[12035095010819582754,0],[2035327810332855521,0],[3710133387837274291,0],[8462655819889292900,0],[3384102572540409881,0],[318560030360358929,0],[11346538709718766144,0],[10146665273368938971,0],[13662059715350867364,0]]},"regions":{"add":[],"remove":[],"segment_range":[],"fill":[]},"add_g1_continuous":[[{"ty":"End","segment":8661113083384527971},{"ty":"Primary","segment":2035327810332855521}],[{"ty":"End","segment":10146665273368938971},{"ty":"Primary","segment":318560030360358929}],[{"ty":"Primary","segment":11346538709718766144},{"ty":"End","segment":2035327810332855521}],[{"ty":"End","segment":12035095010819582754},{"ty":"Primary","segment":10146665273368938971}]],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exportsLine truncated
|
||||
+1
-1
@@ -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.21176471,"green":0.21568628,"blue":0.23137255,"alpha":1.0}},"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.99607843,"green":0.827451,"blue":0.65882355,"alpha":1.0}},"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},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]},"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":{"ProtoNode":{"name":"core_types::vector::SplineNode"}},"visible":truLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[17154757625902243313,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"element":[{"red":0.23529412,"green":0.23529412,"blue":0.24313726,"alpha":1.0}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}},{"Value":{"tagged_value":{"F64":1670.79570439},"exposed":false}},{"Value":{"tagged_value":{"F64":24.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"core_types::vector::SplineNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[14158287945315818946,{"inputs":[{"Node":{"node_id":16943732999059587742,"output_index":0}},{"Node":{"node_id":14577956936089455769,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.6181095265062186,3.496297826945966]},"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>>","alias":null}},"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","alias":null}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"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":""}}],[11731553664207576737,{"inputs":[{"Node":{"node_id":757876048866560520,"output_index":0}},{"Value":{"tagged_value":{"F64":48.900000000000006},"exposed":false}},{"Node":{"node_id":7828034197076821310,"output_index":0}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"core_types::vector::JitterPointsNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[7828034197076821310,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":3}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"math_nodes::ToU32Node"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[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>>","alias":null}},"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":{"element":[{"red":0.99607843,"green":0.827451,"blue":0.65882355,"alpha":1.0}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_nLine truncated
|
||||
+1
-1
@@ -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},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01}]},"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}},"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},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01}]},"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.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0Line truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[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":4,"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>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::SourceNodeIdNode"}},"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>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[665049002420596400,{"inputs":[{"Value":{"tagged_value":{"Vector":{"element":[{"style":{"stroke":{"color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},"weight":0.0,"dash_lengths":[],"dash_offset":0.0,"cap":"Butt","join":"Miter","join_miter_limit":4.0,"align":"Center","transform":[1.0,0.0,0.0,1.0,0.0,0.0],"non_scaling":false,"paint_order":"StrokeAbove"},"fill":"None"},"colinear_manipulators":[],"point_domain":{"id":[],"position":[]},"segment_domain":{"id":[],"start_point":[],"end_point":[],"handles":[],"stroke":[]},"region_domain":{"id":[],"segment_range":[],"fill":[]},"upstream_data":null}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"remove":[],"delta":[[3,[45.77777777777777,145.33333333333331]],[18,[145.77777777777777,-97.7777777777778]],[9,[156.4444444444444,97.33333333333331]],[21,[76.0,-202.22222222222223]],[28,[39.111111111111086,-58.22222222222226]],[23,[19.555555555555543,-139.55555555555557]],[6,[123.99999999999994,148.4444444444444]],[30,[-9.333333333333371,0.0]],[16,[159.5555555555555,-75.55555555555557]],[29,[-32.888888888888914,-14.666666666666686]],[20,[128.4444444444444,-142.22222222222223]],[13,[153.77777777777777,-1.3333333333333712]],[27,[-11.111111111111144,-72.00000000000003]],[4,[18.66666666666663,157.77777777777771]],[25,[0.8888888888888573,-94.66666666666669]],[11,[136.88888888888886,39.111111111111086]],[8,[252.4444444444444,124.88888888888886]],[32,[9.333333333333314,38.66666666666663]],[17,[123.99999999999994,-84.00000000000003]],[15,[111.11111111111114,-60.888888888888914]],[5,[66.22222222222223,152.88888888888886]],[33,[-78.22222222222223,75.55555555555554]],[24,[57.77777777777777,-129.33333333333334]],[19,[90.66666666666664,-129.33333333333334]],[12,[199.5555555555555,10.666666666666629]],[31,[-53.33333333333337,13.777777777777771]],[34,[-5.333333333333371,99.11111111111109]],[10,[216.4444444444444,72.4444444444444]],[14,[183.11111111111103,-19.111111111111143]],[26,[22.66666666666663,-81.33333333333337]],[7,[229.33333333333331,152.4444444444444]],[2,[-67.55555555555554,158.22222222222217]],[22,[71.11111111111109,-201.7777777777778]],[1,[-103.55555555555554,126.66666666666664]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"remove":[],"start_point":[[1,1],[14,14],[8,8],[33,33],[30,30],[9,9],[1Line truncated
|
||||
Generated
+1
-1
@@ -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.8980392,"green":0.8,"blue":0.6117647,"alpha":1.0}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8980392,"green":0.8,"blue":0.6117647,"alpha":1.0}},"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},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]},"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::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[10127467043900015225,{"inputs":[{"Value":{"tagged_value":{"Vector":{"element":[{"style":{"stroke":{"color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},"weight":0.0,"dash_lengths":[],"dash_offset":0.0,"cap":"Butt","join":"Miter","join_miter_limit":4.0,"align":"Center","transform":[1.0,0.0,0.0,1.0,0.0,0.0],"non_scaling":false,"paint_order":"StrokeAbove"},"fill":"None"},"colinear_manipulators":[],"point_domain":{"id":[],"position":[]},"segment_domain":{"id":[],"start_point":[],"end_point":[],"handles":[],"stroke":[]},"region_domain":{"id":[],"segment_range":[],"fill":[]},"upstream_data":null}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2],"remove":[],"delta":[[1,[258.00000000000006,994.6666666666664]],[2,[644.0,726.6666666666666]]]},"segments":{"add":[1],"remove":[],"start_point":[[1,1]],"end_point":[[1,2]],"handle_primary":[[1,[0.0,0.0]]],"handle_end":[[1,[-328.66666666666674,129.33333333333337]]],"stroke":[[1,0]]},"regions":{"add":[],"remove":[],"segment_range":[],"fill":[]},"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":"graphene_core::table::Table<graphene_core::vector::vector_types::Vector>","alias":null}},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"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":"graphene_core::vector::vector_modification::VectorModification","alias":null}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"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":""}}],[15961046538654083626,{"inputs":[{"Node":{"node_id":1889157037801767612,"output_index":0}},{"Node":{"node_id":4332145463108161926,"output_index":0}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":10.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"core_types::vector::CopyToPointsNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[17378885078543074499,{"inputs":[{"Value":{"tagged_value":{"Vector":{"element":[{"style":{"stroke":{"color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},"weight":0.0,"dash_lengths":[],"dash_offset":0.0,"cap":"Butt","join":"Miter","join_miter_limit":4.0,"align":"Center","transform":[1.0,0.0,0.0,1.0,0.0,0.0],"non_scaling":false,"paint_order":"StrokeAbove"},"fill":"None"},"colinear_manipulators":[],"point_domain":{"id":[],"position":[]},"segment_domain":{"id":[],"start_point":[],"end_point":[],"handles":[],"stroke":[]},"region_domain":{"id":[],"segment_range":[],"fill":[]},"upstream_data":null}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8],"remove":[],"delta":[[5,[740.4444444444443,857.1111111111111]],[3,[707.5,1026.5]],[7,[727.5555555555554,1026.6666666666663]],[2,[745.5,826.0]],[1,[823.2222222222221,660.4444444444445]],[6,[725.7777777777779,1026.370370370371]],[4,[709.5555555555554,1026.6666666666667]],[8,[746.0000000000001,842.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8],"remove":[],"start_point":[[5,5],[2,2],[6,6],[8,8],[3,3],[4,4],[1,1],[7,7]],"end_point":[[6,7],[8,1],[2,3],[5,6],[1,2],[3,4],[4,5],[7,8]],"handle_primary":[[6,[0.0,0.0]],[8,[17.33333333333337,-84.99999999999989]],[3,[0.0,0.0]],[7,[0.0,0.0]],[5,[0.0,0.0]],[1,[0.0,0.0]],[4,[0.0,0.0]],[2,[-24.5,85.0]]],"handle_end":[[7,[-26.8034437596026,131.4399645903585]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[-23.11111111111109,Line truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::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":[[202,{"inputs":[{"Node":{"node_id":206,"output_index":0}},{"Value":{"tagged_value":{"Fill":{"Solid":{"red":0.5058824,"green":0.26666668,"blue":0.20392157,"alpha":1.0}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"element":[{"red":0.5058824,"green":0.26666668,"blue":0.20392157,"alpha":1.0}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]},"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5]}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[404,{"inputs":[{"Node":{"node_id":402,"output_index":0}},{"Value":{"tagged_value":{"Color":{"element":[{"red":0.24313726,"green":0.18431373,"blue":0.19215687,"alpha":1.0}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"StrokeAlign":"Center"},"exposed":false}},{"Value":{"tagged_value":{"StrokeCap":"Butt"},"exposed":false}},{"Value":{"tagged_value":{"StrokeJoin":"Miter"},"exposed":false}},{"Value":{"tagged_value":{"F64":4.0},"exposed":false}},{"Value":{"tagged_value":{"PaintOrder":"StrokeAbove"},"exposed":false}},{"Value":{"tagged_value":{"VecF64":[]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::StrokeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[93,{"inputs":[{"Node":{"node_id":94,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[851.1666666666667,668.5377104806669]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[39.677869315599935,39.67786931560005]},"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>>","alias":null}},"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","alias":null}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"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":""}}],[155,{"inputs":[{"Node":{"node_id":159,"output_index":0}},{"Value":{"tagged_value":{"Fill":{"Gradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.7529412,"green":0.34117648,"blue":0.2,"alpha":1.0},{"red":0.6431373,"green":0.31764707,"blue":0.21176471,"alpha":1.0}]},"gradient_type":"Linear","start":[0.9001916129448388,0.7881778212017586],"end":[0.8902470335613286,0.6662432828529555]}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"element":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.7529412,"green":0.34117648,"blue":0.2,"alpha":1.0},{"red":0.6431373,"greeLine truncated
|
||||
@@ -42,7 +42,7 @@ ignore = [
|
||||
"RUSTSEC-2024-0388", # Unmaintained `derivative`, used directly by graphite-editor and graphite-desktop
|
||||
"RUSTSEC-2024-0436", # Unmaintained `paste`, pulled in by dependencies `metal` and `wgpu-hal`
|
||||
"RUSTSEC-2025-0134", # Unmaintained `rustls-pemfile`, pulled in by build dependency `download-cef`
|
||||
"RUSTSEC-2025-0141", # Unmaintained `bincode`, pulled in by dev dependency `gungraun`
|
||||
"RUSTSEC-2025-0141", # Unmaintained `bincode`, pulled in by dev dependency `iai-callgrind`
|
||||
]
|
||||
# Threshold for security vulnerabilities, any vulnerability with a CVSS score
|
||||
# lower than the range specified will be ignored. Note that ignored advisories
|
||||
@@ -63,7 +63,6 @@ ignore = [
|
||||
# [possible values: any SPDX 3.11 short identifier (+ optional exception)].
|
||||
#
|
||||
allow = [
|
||||
"0BSD", # Keep this list in sync with those in `/about.toml`
|
||||
"Apache-2.0 WITH LLVM-exception", # Keep this list in sync with those in `/about.toml`
|
||||
"Apache-2.0", # Keep this list in sync with those in `/about.toml`
|
||||
"BSD-2-Clause", # Keep this list in sync with those in `/about.toml`
|
||||
|
||||
@@ -48,7 +48,6 @@ lzma-rust2 = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
rand = { workspace = true, features = ["thread_rng"] }
|
||||
clap = { workspace = true, features = ["derive"] }
|
||||
interprocess = "2.4.2"
|
||||
fd-lock = "4.0.4"
|
||||
ctrlc = "3.5.1"
|
||||
window_clipboard = "0.5"
|
||||
|
||||
@@ -13,9 +13,6 @@ const EXEC_PATH: &str = "Contents/MacOS";
|
||||
const FRAMEWORKS_PATH: &str = "Contents/Frameworks";
|
||||
const RESOURCES_PATH: &str = "Contents/Resources";
|
||||
const CEF_FRAMEWORK: &str = "Chromium Embedded Framework.framework";
|
||||
const GRAPHITE_DOCUMENT_TYPE: &str = "art.graphite.document";
|
||||
const GRAPHITE_FILE_EXTENSION: &str = "graphite";
|
||||
const GRAPHITE_MIME_TYPE: &str = "application/graphite+json";
|
||||
|
||||
pub fn main() -> Result<(), Box<dyn Error>> {
|
||||
let app_bin = build_bin("graphite-desktop-platform-mac", None)?;
|
||||
@@ -76,7 +73,7 @@ fn create_info_plist(dir: &Path, id: &str, exec_name: &str, is_helper: bool) ->
|
||||
cf_bundle_identifier: id.to_string(),
|
||||
cf_bundle_display_name: exec_name.to_string(),
|
||||
cf_bundle_executable: exec_name.to_string(),
|
||||
cf_bundle_icon_file: if is_helper { None } else { Some(ICONS_FILE_NAME.to_string()) },
|
||||
cf_bundle_icon_file: ICONS_FILE_NAME.to_string(),
|
||||
cf_bundle_info_dictionary_version: "6.0".to_string(),
|
||||
cf_bundle_package_type: "APPL".to_string(),
|
||||
cf_bundle_signature: "????".to_string(),
|
||||
@@ -88,8 +85,6 @@ fn create_info_plist(dir: &Path, id: &str, exec_name: &str, is_helper: bool) ->
|
||||
ls_minimum_system_version: "11.0".to_string(),
|
||||
ls_ui_element: if is_helper { Some("1".to_string()) } else { None },
|
||||
ns_supports_automatic_graphics_switching: true,
|
||||
cf_bundle_document_types: (!is_helper).then(document_types),
|
||||
ut_exported_type_declarations: (!is_helper).then(exported_type_declarations),
|
||||
};
|
||||
|
||||
let plist_file = dir.join("Info.plist");
|
||||
@@ -97,47 +92,6 @@ fn create_info_plist(dir: &Path, id: &str, exec_name: &str, is_helper: bool) ->
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn document_types() -> Vec<DocumentType> {
|
||||
vec![
|
||||
DocumentType {
|
||||
cf_bundle_type_name: "Graphite Document".to_string(),
|
||||
cf_bundle_type_role: "Editor".to_string(),
|
||||
cf_bundle_type_extensions: Some(vec![GRAPHITE_FILE_EXTENSION.to_string()]),
|
||||
cf_bundle_type_icon_file: Some(ICONS_FILE_NAME.to_string()),
|
||||
ls_handler_rank: Some("Owner".to_string()),
|
||||
ls_item_content_types: vec![GRAPHITE_DOCUMENT_TYPE.to_string()],
|
||||
},
|
||||
DocumentType {
|
||||
cf_bundle_type_name: "SVG Image".to_string(),
|
||||
cf_bundle_type_role: "Editor".to_string(),
|
||||
cf_bundle_type_extensions: Some(vec!["svg".to_string()]),
|
||||
cf_bundle_type_icon_file: None,
|
||||
ls_handler_rank: Some("Alternate".to_string()),
|
||||
ls_item_content_types: vec!["public.svg-image".to_string()],
|
||||
},
|
||||
DocumentType {
|
||||
cf_bundle_type_name: "Image".to_string(),
|
||||
cf_bundle_type_role: "Editor".to_string(),
|
||||
cf_bundle_type_extensions: None,
|
||||
cf_bundle_type_icon_file: None,
|
||||
ls_handler_rank: Some("Alternate".to_string()),
|
||||
ls_item_content_types: vec!["public.image".to_string()],
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn exported_type_declarations() -> Vec<ExportedTypeDeclaration> {
|
||||
vec![ExportedTypeDeclaration {
|
||||
ut_type_identifier: GRAPHITE_DOCUMENT_TYPE.to_string(),
|
||||
ut_type_description: "Graphite Document".to_string(),
|
||||
ut_type_conforms_to: vec!["public.json".to_string()],
|
||||
ut_type_tag_specification: TypeTagSpecification {
|
||||
public_filename_extension: vec![GRAPHITE_FILE_EXTENSION.to_string()],
|
||||
public_mime_type: GRAPHITE_MIME_TYPE.to_string(),
|
||||
},
|
||||
}]
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
struct InfoPlist {
|
||||
#[serde(rename = "CFBundleName")]
|
||||
@@ -149,8 +103,7 @@ struct InfoPlist {
|
||||
#[serde(rename = "CFBundleExecutable")]
|
||||
cf_bundle_executable: String,
|
||||
#[serde(rename = "CFBundleIconFile")]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
cf_bundle_icon_file: Option<String>,
|
||||
cf_bundle_icon_file: String,
|
||||
#[serde(rename = "CFBundleInfoDictionaryVersion")]
|
||||
cf_bundle_info_dictionary_version: String,
|
||||
#[serde(rename = "CFBundlePackageType")]
|
||||
@@ -170,53 +123,7 @@ struct InfoPlist {
|
||||
#[serde(rename = "LSMinimumSystemVersion")]
|
||||
ls_minimum_system_version: String,
|
||||
#[serde(rename = "LSUIElement")]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
ls_ui_element: Option<String>,
|
||||
#[serde(rename = "NSSupportsAutomaticGraphicsSwitching")]
|
||||
ns_supports_automatic_graphics_switching: bool,
|
||||
#[serde(rename = "CFBundleDocumentTypes")]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
cf_bundle_document_types: Option<Vec<DocumentType>>,
|
||||
#[serde(rename = "UTExportedTypeDeclarations")]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
ut_exported_type_declarations: Option<Vec<ExportedTypeDeclaration>>,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
struct DocumentType {
|
||||
#[serde(rename = "CFBundleTypeName")]
|
||||
cf_bundle_type_name: String,
|
||||
#[serde(rename = "CFBundleTypeRole")]
|
||||
cf_bundle_type_role: String,
|
||||
#[serde(rename = "CFBundleTypeExtensions")]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
cf_bundle_type_extensions: Option<Vec<String>>,
|
||||
#[serde(rename = "CFBundleTypeIconFile")]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
cf_bundle_type_icon_file: Option<String>,
|
||||
#[serde(rename = "LSHandlerRank")]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
ls_handler_rank: Option<String>,
|
||||
#[serde(rename = "LSItemContentTypes")]
|
||||
ls_item_content_types: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
struct ExportedTypeDeclaration {
|
||||
#[serde(rename = "UTTypeIdentifier")]
|
||||
ut_type_identifier: String,
|
||||
#[serde(rename = "UTTypeDescription")]
|
||||
ut_type_description: String,
|
||||
#[serde(rename = "UTTypeConformsTo")]
|
||||
ut_type_conforms_to: Vec<String>,
|
||||
#[serde(rename = "UTTypeTagSpecification")]
|
||||
ut_type_tag_specification: TypeTagSpecification,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
struct TypeTagSpecification {
|
||||
#[serde(rename = "public.filename-extension")]
|
||||
public_filename_extension: Vec<String>,
|
||||
#[serde(rename = "public.mime-type")]
|
||||
public_mime_type: String,
|
||||
}
|
||||
+34
-61
@@ -2,7 +2,6 @@ use rand::Rng;
|
||||
use rfd::AsyncFileDialog;
|
||||
use std::fs;
|
||||
use std::io::Read;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{Receiver, Sender, SyncSender};
|
||||
@@ -15,6 +14,7 @@ use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
|
||||
use winit::window::WindowId;
|
||||
|
||||
use crate::cef;
|
||||
use crate::cli::Cli;
|
||||
use crate::consts::CEF_MESSAGE_LOOP_MAX_ITERATIONS;
|
||||
use crate::event::{AppEvent, AppEventScheduler};
|
||||
use crate::persist;
|
||||
@@ -45,8 +45,9 @@ pub(crate) struct App {
|
||||
start_render_sender: SyncSender<()>,
|
||||
web_communication_initialized: bool,
|
||||
web_communication_startup_buffer: Vec<Vec<u8>>,
|
||||
#[cfg_attr(not(target_os = "macos"), expect(unused))]
|
||||
preferences: Preferences,
|
||||
launch_documents: Option<Vec<PathBuf>>,
|
||||
cli: Cli,
|
||||
startup_time: Option<Instant>,
|
||||
exiting: Arc<AtomicBool>,
|
||||
exit_reason: ExitReason,
|
||||
@@ -57,7 +58,6 @@ impl App {
|
||||
Window::init();
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn new(
|
||||
cef_context: Box<dyn cef::CefContext>,
|
||||
cef_view_info_sender: Sender<cef::ViewInfoUpdate>,
|
||||
@@ -65,7 +65,7 @@ impl App {
|
||||
app_event_receiver: Receiver<AppEvent>,
|
||||
app_event_scheduler: AppEventScheduler,
|
||||
preferences: Preferences,
|
||||
launch_documents: Vec<PathBuf>,
|
||||
cli: Cli,
|
||||
) -> Self {
|
||||
let ctrlc_app_event_scheduler = app_event_scheduler.clone();
|
||||
ctrlc::set_handler(move || {
|
||||
@@ -115,7 +115,7 @@ impl App {
|
||||
web_communication_initialized: false,
|
||||
web_communication_startup_buffer: Vec::new(),
|
||||
preferences,
|
||||
launch_documents: Some(launch_documents),
|
||||
cli,
|
||||
startup_time: None,
|
||||
exiting,
|
||||
exit_reason: ExitReason::Shutdown,
|
||||
@@ -197,7 +197,7 @@ impl App {
|
||||
};
|
||||
self.send_or_queue_web_message(bytes);
|
||||
}
|
||||
DesktopFrontendMessage::OpenFileDialog { title, filters, multiple, context } => {
|
||||
DesktopFrontendMessage::OpenFileDialog { title, filters, context } => {
|
||||
let app_event_scheduler = self.app_event_scheduler.clone();
|
||||
let _ = thread::spawn(move || {
|
||||
let mut dialog = AsyncFileDialog::new().set_title(title);
|
||||
@@ -205,21 +205,13 @@ impl App {
|
||||
dialog = dialog.add_filter(filter.name, &filter.extensions);
|
||||
}
|
||||
|
||||
let handles = if multiple {
|
||||
futures::executor::block_on(dialog.pick_files()).unwrap_or_default()
|
||||
} else {
|
||||
futures::executor::block_on(dialog.pick_file()).into_iter().collect()
|
||||
};
|
||||
let show_dialog = async move { dialog.pick_file().await.map(|f| f.path().to_path_buf()) };
|
||||
|
||||
for handle in handles {
|
||||
let path = handle.path().to_path_buf();
|
||||
match fs::read(&path) {
|
||||
Ok(content) => {
|
||||
let message = DesktopWrapperMessage::FileDialogResult { path, content, context };
|
||||
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
Err(e) => tracing::error!("Failed to read file {}: {}", path.display(), e),
|
||||
}
|
||||
if let Some(path) = futures::executor::block_on(show_dialog)
|
||||
&& let Ok(content) = fs::read(&path)
|
||||
{
|
||||
let message = DesktopWrapperMessage::FileDialogResult { path, content, context };
|
||||
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -249,12 +241,6 @@ impl App {
|
||||
});
|
||||
}
|
||||
DesktopFrontendMessage::WriteFile { path, content } => {
|
||||
if let Some(parent) = path.parent()
|
||||
&& !parent.as_os_str().is_empty()
|
||||
&& let Err(e) = fs::create_dir_all(parent)
|
||||
{
|
||||
tracing::error!("Failed to create parent directory {}: {}", parent.display(), e);
|
||||
}
|
||||
if let Err(e) = fs::write(&path, content) {
|
||||
tracing::error!("Failed to write file {}: {}", path.display(), e);
|
||||
}
|
||||
@@ -321,11 +307,22 @@ impl App {
|
||||
responses.push(message);
|
||||
}
|
||||
DesktopFrontendMessage::OpenLaunchDocuments => {
|
||||
let Some(launch_documents) = std::mem::take(&mut self.launch_documents) else {
|
||||
tracing::error!("OpenLaunchDocuments should only be sent once");
|
||||
if self.cli.files.is_empty() {
|
||||
return;
|
||||
};
|
||||
self.app_event_scheduler.schedule(AppEvent::OpenFiles(launch_documents));
|
||||
}
|
||||
let app_event_scheduler = self.app_event_scheduler.clone();
|
||||
let launch_documents = std::mem::take(&mut self.cli.files);
|
||||
let _ = thread::spawn(move || {
|
||||
for path in launch_documents {
|
||||
tracing::info!("Opening file from command line: {}", path.display());
|
||||
if let Ok(content) = fs::read(&path) {
|
||||
let message = DesktopWrapperMessage::OpenFile { path, content };
|
||||
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
} else {
|
||||
tracing::error!("Failed to read file: {}", path.display());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
DesktopFrontendMessage::UpdateMenu { entries } => {
|
||||
if let Some(window) = &self.window {
|
||||
@@ -373,11 +370,6 @@ impl App {
|
||||
window.start_drag();
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::WindowFocus => {
|
||||
if let Some(window) = &self.window {
|
||||
window.focus();
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::WindowHide => {
|
||||
if let Some(window) = &self.window {
|
||||
window.hide();
|
||||
@@ -483,29 +475,6 @@ impl App {
|
||||
tracing::info!("Exiting main event loop");
|
||||
event_loop.exit();
|
||||
}
|
||||
AppEvent::OpenFiles(paths) => {
|
||||
// Accumulate launch documents until OpenLaunchDocuments message is received
|
||||
if let Some(launch_documents) = &mut self.launch_documents {
|
||||
launch_documents.extend(paths);
|
||||
return;
|
||||
}
|
||||
|
||||
if paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
let app_event_scheduler = self.app_event_scheduler.clone();
|
||||
let _ = thread::spawn(move || {
|
||||
for path in paths {
|
||||
tracing::info!("Opening file: {}", path.display());
|
||||
if let Ok(content) = fs::read(&path) {
|
||||
let message = DesktopWrapperMessage::OpenFile { path, content };
|
||||
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
} else {
|
||||
tracing::error!("Failed to read file: {}", path.display());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
AppEvent::MenuEvent { id } => {
|
||||
self.dispatch_desktop_wrapper_message(DesktopWrapperMessage::MenuEvent { id });
|
||||
@@ -588,16 +557,20 @@ impl ApplicationHandler for App {
|
||||
Err(RenderError::OutdatedUITextureError) => {
|
||||
self.cef_context.notify_view_info_changed();
|
||||
}
|
||||
Err(RenderError::SurfaceLost) => {
|
||||
Err(RenderError::SurfaceError(wgpu::SurfaceError::Lost)) => {
|
||||
tracing::warn!("lost surface");
|
||||
}
|
||||
Err(other) => tracing::error!("Render error: {:?}", other),
|
||||
Err(RenderError::SurfaceError(wgpu::SurfaceError::OutOfMemory)) => {
|
||||
tracing::error!("GPU out of memory");
|
||||
self.exit(None);
|
||||
}
|
||||
Err(RenderError::SurfaceError(e)) => tracing::error!("Render error: {:?}", e),
|
||||
}
|
||||
let _ = self.start_render_sender.try_send(());
|
||||
}
|
||||
|
||||
if !self.cef_init_successful
|
||||
&& !self.preferences.disable_ui_acceleration
|
||||
&& !self.cli.disable_ui_acceleration
|
||||
&& self.web_communication_initialized
|
||||
&& let Some(startup_time) = self.startup_time
|
||||
&& startup_time.elapsed() > Duration::from_secs(3)
|
||||
|
||||
+34
-2
@@ -190,8 +190,40 @@ impl CefEventHandler for CefHandler {
|
||||
#[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));
|
||||
Ok(src) => {
|
||||
let desc = wgpu::TextureDescriptor {
|
||||
label: Some("duplicated_texture"),
|
||||
usage: wgpu::TextureUsages::COPY_DST | src.usage(),
|
||||
size: src.size(),
|
||||
mip_level_count: src.mip_level_count(),
|
||||
sample_count: src.sample_count(),
|
||||
dimension: src.dimension(),
|
||||
format: src.format(),
|
||||
view_formats: &[],
|
||||
};
|
||||
|
||||
let copy = self.wgpu_context.device.create_texture(&desc);
|
||||
|
||||
let mut encoder = self.wgpu_context.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("texture_copy_encoder"),
|
||||
});
|
||||
|
||||
encoder.copy_texture_to_texture(
|
||||
src.as_image_copy(),
|
||||
copy.as_image_copy(),
|
||||
desc.size,
|
||||
);
|
||||
|
||||
// Wait for the GPU to finish the copy before allowing the source texture to be released by CEF
|
||||
let submission_index = self.wgpu_context.queue.submit([encoder.finish()]);
|
||||
if let Err(error) = self.wgpu_context.device.poll(wgpu::PollType::Wait {
|
||||
submission_index: Some(submission_index),
|
||||
timeout: None,
|
||||
}) {
|
||||
tracing::error!("Failed while waiting for texture copy completion: {error}");
|
||||
}
|
||||
|
||||
self.app_event_scheduler.schedule(AppEvent::UiUpdate(copy));
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to import shared texture: {}", e);
|
||||
|
||||
@@ -24,13 +24,14 @@ unsafe impl<H: CefEventHandler> Send for CefContextBuilder<H> {}
|
||||
|
||||
impl<H: CefEventHandler> CefContextBuilder<H> {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self::new_impl(false)
|
||||
}
|
||||
pub(crate) fn new_helper() -> Self {
|
||||
Self::new_impl(true)
|
||||
Self::new_inner(false)
|
||||
}
|
||||
|
||||
fn new_impl(helper: bool) -> Self {
|
||||
pub(crate) fn new_helper() -> Self {
|
||||
Self::new_inner(true)
|
||||
}
|
||||
|
||||
fn new_inner(helper: bool) -> Self {
|
||||
#[cfg(target_os = "macos")]
|
||||
let _loader = {
|
||||
let loader = cef::library_loader::LibraryLoader::new(&std::env::current_exe().unwrap(), helper);
|
||||
@@ -41,8 +42,11 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
|
||||
let _ = helper;
|
||||
|
||||
let _ = api_hash(CEF_API_VERSION_LAST, 0);
|
||||
|
||||
let args = Args::new();
|
||||
let is_sub_process = args.as_cmd_line().unwrap().has_switch(Some(&"type".into())) == 1;
|
||||
let cmd = args.as_cmd_line().unwrap();
|
||||
let is_sub_process = cmd.has_switch(Some(&"type".into())) == 1;
|
||||
|
||||
Self {
|
||||
args,
|
||||
is_sub_process,
|
||||
@@ -66,96 +70,103 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
|
||||
}
|
||||
}
|
||||
|
||||
fn common_settings(instance_dir: &Path) -> Settings {
|
||||
let log_severity = match std::env::var("GRAPHITE_BROWSER_LOG") {
|
||||
Ok(level) => match level.to_lowercase().as_str() {
|
||||
"debug" => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_VERBOSE),
|
||||
"info" => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_INFO),
|
||||
"warn" => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_WARNING),
|
||||
"error" => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_ERROR),
|
||||
"none" => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_DISABLE),
|
||||
_ => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_FATAL),
|
||||
},
|
||||
Err(_) => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_FATAL),
|
||||
};
|
||||
|
||||
Settings {
|
||||
windowless_rendering_enabled: 1,
|
||||
root_cache_path: instance_dir.to_str().map(CefString::from).unwrap(),
|
||||
cache_path: "".into(),
|
||||
disable_signal_handlers: 1,
|
||||
log_severity,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) fn create(self, event_handler: H, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
|
||||
pub(crate) fn initialize(self, event_handler: H, 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)
|
||||
|
||||
let exe = std::env::current_exe().expect("cannot get current exe path");
|
||||
let app_root = exe.parent().and_then(|p| p.parent()).expect("bad path structure").parent().expect("bad path structure");
|
||||
|
||||
let settings = Settings {
|
||||
main_bundle_path: app_root.to_str().map(CefString::from).unwrap(),
|
||||
multi_threaded_message_loop: 0,
|
||||
external_message_pump: 1,
|
||||
no_sandbox: 1, // GPU helper crashes when running with sandbox
|
||||
..Self::common_settings(instance_dir.as_ref())
|
||||
};
|
||||
|
||||
self.initialize_inner(&event_handler, settings)?;
|
||||
|
||||
create_browser(event_handler, instance_dir, disable_gpu_acceleration)
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub(crate) fn create(self, event_handler: H, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
|
||||
pub(crate) fn initialize(self, event_handler: H, 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) {
|
||||
Ok(context) => super::multithreaded::CONTEXT.with(|b| *b.borrow_mut() = Some(context)),
|
||||
Err(e) => panic!("Failed to initialize CEF context: {:?}", e),
|
||||
|
||||
let settings = Settings {
|
||||
multi_threaded_message_loop: 1,
|
||||
#[cfg(target_os = "linux")]
|
||||
no_sandbox: 1,
|
||||
..Self::common_settings(instance_dir.as_ref())
|
||||
};
|
||||
|
||||
self.initialize_inner(&event_handler, settings)?;
|
||||
|
||||
super::multithreaded::run_on_ui_thread(move || match create_browser(event_handler, instance_dir, disable_gpu_acceleration) {
|
||||
Ok(context) => {
|
||||
super::multithreaded::CONTEXT.with(|b| {
|
||||
*b.borrow_mut() = Some(context);
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
panic!("Failed to initialize CEF context: {:?}", e);
|
||||
}
|
||||
});
|
||||
|
||||
Ok(super::multithreaded::MultiThreadedCefContextProxy)
|
||||
}
|
||||
|
||||
fn build_inner(self, event_handler: &H, instance_dir: &Path, accelerated_paint: bool) -> Result<(), InitError> {
|
||||
let mut cef_app = App::new(BrowserProcessAppImpl::new(event_handler.duplicate(), accelerated_paint));
|
||||
let result = cef::initialize(Some(self.args.as_main_args()), Some(&platform_settings(instance_dir)), Some(&mut cef_app), std::ptr::null_mut());
|
||||
fn initialize_inner(self, event_handler: &H, settings: Settings) -> Result<(), InitError> {
|
||||
// Attention! Wrapping this in an extra App is necessary, otherwise the program still compiles but segfaults
|
||||
let mut cef_app = App::new(BrowserProcessAppImpl::new(event_handler.duplicate()));
|
||||
|
||||
let result = cef::initialize(Some(self.args.as_main_args()), Some(&settings), Some(&mut cef_app), std::ptr::null_mut());
|
||||
if result != 1 {
|
||||
return Err(InitError::InitializationFailureCode(cef::get_exit_code() as u32));
|
||||
let cef_exit_code = cef::get_exit_code() as u32;
|
||||
return Err(InitError::InitializationFailureCode(cef_exit_code));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn accelerated_paint(disable_gpu_acceleration: bool) -> bool {
|
||||
#[cfg(feature = "accelerated_paint")]
|
||||
{
|
||||
!disable_gpu_acceleration && crate::cef::platform::should_enable_hardware_acceleration()
|
||||
}
|
||||
#[cfg(not(feature = "accelerated_paint"))]
|
||||
{
|
||||
let _ = disable_gpu_acceleration;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn platform_settings(instance_dir: &Path) -> Settings {
|
||||
let log_severity = match std::env::var("GRAPHITE_BROWSER_LOG").unwrap_or_default().to_lowercase().as_str() {
|
||||
"debug" => cef_log_severity_t::LOGSEVERITY_VERBOSE,
|
||||
"info" => cef_log_severity_t::LOGSEVERITY_INFO,
|
||||
"warn" => cef_log_severity_t::LOGSEVERITY_WARNING,
|
||||
"error" => cef_log_severity_t::LOGSEVERITY_ERROR,
|
||||
"none" => cef_log_severity_t::LOGSEVERITY_DISABLE,
|
||||
_ => cef_log_severity_t::LOGSEVERITY_FATAL,
|
||||
};
|
||||
|
||||
let base = Settings {
|
||||
windowless_rendering_enabled: 1,
|
||||
root_cache_path: instance_dir.to_str().map(CefString::from).unwrap(),
|
||||
cache_path: "".into(),
|
||||
disable_signal_handlers: 1,
|
||||
log_severity: LogSeverity::from(log_severity),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let exe = std::env::current_exe().expect("cannot get current exe path");
|
||||
let app_root = exe.parent().and_then(|p| p.parent()).expect("bad path structure").parent().expect("bad path structure");
|
||||
Settings {
|
||||
main_bundle_path: app_root.to_str().map(CefString::from).unwrap(),
|
||||
multi_threaded_message_loop: 0,
|
||||
external_message_pump: 1,
|
||||
no_sandbox: 1, // GPU helper crashes when running with sandbox
|
||||
..base
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
Settings {
|
||||
multi_threaded_message_loop: 1,
|
||||
#[cfg(target_os = "linux")]
|
||||
no_sandbox: 1,
|
||||
..base
|
||||
}
|
||||
}
|
||||
|
||||
fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: TempDir, accelerated_paint: bool) -> Result<SingleThreadedCefContext, InitError> {
|
||||
fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: TempDir, disable_gpu_acceleration: bool) -> Result<SingleThreadedCefContext, InitError> {
|
||||
let mut client = Client::new(BrowserProcessClientImpl::new(&event_handler));
|
||||
|
||||
#[cfg(feature = "accelerated_paint")]
|
||||
let use_accelerated_paint = if disable_gpu_acceleration {
|
||||
false
|
||||
} else {
|
||||
crate::cef::platform::should_enable_hardware_acceleration()
|
||||
};
|
||||
|
||||
let window_info = WindowInfo {
|
||||
windowless_rendering_enabled: 1,
|
||||
#[cfg(feature = "accelerated_paint")]
|
||||
shared_texture_enabled: accelerated_paint as i32,
|
||||
shared_texture_enabled: use_accelerated_paint as i32,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
@@ -181,24 +192,27 @@ fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: TempDir, a
|
||||
incognito_request_context.register_scheme_handler_factory(Some(&RESOURCE_SCHEME.into()), Some(&RESOURCE_DOMAIN.into()), Some(&mut scheme_handler_factory));
|
||||
|
||||
let url = format!("{RESOURCE_SCHEME}://{RESOURCE_DOMAIN}/");
|
||||
browser_host_create_browser_sync(
|
||||
|
||||
let browser = browser_host_create_browser_sync(
|
||||
Some(&window_info),
|
||||
Some(&mut client),
|
||||
Some(&url.as_str().into()),
|
||||
Some(&settings),
|
||||
Option::<&mut DictionaryValue>::None,
|
||||
Some(&mut incognito_request_context),
|
||||
)
|
||||
.map(|browser| SingleThreadedCefContext {
|
||||
event_handler: Box::new(event_handler),
|
||||
browser,
|
||||
input_state: InputState::default(),
|
||||
_instance_dir: instance_dir,
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
);
|
||||
|
||||
if let Some(browser) = browser {
|
||||
Ok(SingleThreadedCefContext {
|
||||
event_handler: Box::new(event_handler),
|
||||
browser,
|
||||
input_state: InputState::default(),
|
||||
_instance_dir: instance_dir,
|
||||
})
|
||||
} else {
|
||||
tracing::error!("Failed to create browser");
|
||||
InitError::BrowserCreationFailed
|
||||
})
|
||||
Err(InitError::BrowserCreationFailed)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
|
||||
@@ -9,14 +9,12 @@ use crate::cef::CefEventHandler;
|
||||
pub(crate) struct BrowserProcessAppImpl<H: CefEventHandler> {
|
||||
object: *mut RcImpl<_cef_app_t, Self>,
|
||||
event_handler: H,
|
||||
accelerated_paint: bool,
|
||||
}
|
||||
impl<H: CefEventHandler> BrowserProcessAppImpl<H> {
|
||||
pub(crate) fn new(event_handler: H, accelerated_paint: bool) -> Self {
|
||||
pub(crate) fn new(event_handler: H) -> Self {
|
||||
Self {
|
||||
object: std::ptr::null_mut(),
|
||||
event_handler,
|
||||
accelerated_paint,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -54,41 +52,37 @@ impl<H: CefEventHandler> ImplApp for BrowserProcessAppImpl<H> {
|
||||
|
||||
let extra_disabled_features = ["OptimizationHints", "OnDeviceModelService", "TranslateUI"];
|
||||
let disabled_features_switch = Some(&"disable-features".into());
|
||||
let mut disabled_features: Vec<String> = CefString::from(&cmd.switch_value(disabled_features_switch))
|
||||
let disabled_features: String = CefString::from(&cmd.switch_value(disabled_features_switch))
|
||||
.to_string()
|
||||
.split(',')
|
||||
.filter(|feature| !feature.is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
.collect();
|
||||
disabled_features.extend(extra_disabled_features.into_iter().map(ToOwned::to_owned));
|
||||
cmd.append_switch_with_value(disabled_features_switch, Some(&disabled_features.join(",").as_str().into()));
|
||||
.chain(extra_disabled_features)
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
cmd.append_switch_with_value(disabled_features_switch, Some(&disabled_features.as_str().into()));
|
||||
|
||||
if self.accelerated_paint {
|
||||
cmd.append_switch(Some(&"enable-gpu".into()));
|
||||
cmd.append_switch(Some(&"enable-gpu-compositing".into()));
|
||||
cmd.append_switch(Some(&"enable-begin-frame-scheduling".into()));
|
||||
cmd.append_switch(Some(&"off-screen-rendering-enabled".into()));
|
||||
cmd.append_switch(Some(&"enable-accelerated-2d-canvas".into()));
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
cmd.append_switch_with_value(Some(&"use-angle".into()), Some(&"gl-egl".into()));
|
||||
|
||||
let use_wayland = std::env::var("WAYLAND_DISPLAY")
|
||||
.ok()
|
||||
.filter(|var| !var.is_empty())
|
||||
.or_else(|| std::env::var("WAYLAND_SOCKET").ok())
|
||||
.filter(|var| !var.is_empty())
|
||||
.is_some();
|
||||
if use_wayland {
|
||||
cmd.append_switch_with_value(Some(&"ozone-platform".into()), Some(&"wayland".into()));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
#[cfg(not(feature = "accelerated_paint"))]
|
||||
{
|
||||
// Disable GPU acceleration when accelerated_paint feature is not enabled
|
||||
cmd.append_switch(Some(&"disable-gpu".into()));
|
||||
cmd.append_switch(Some(&"disable-gpu-compositing".into()));
|
||||
}
|
||||
|
||||
#[cfg(feature = "accelerated_paint")]
|
||||
{
|
||||
// cmd.append_switch(Some(&"transparent-painting-enabled".into()));
|
||||
cmd.append_switch(Some(&"enable-zero-copy".into()));
|
||||
// cmd.append_switch(Some(&"off-screen-rendering-enabled".into()));
|
||||
// cmd.append_switch(Some(&"use-views".into()));
|
||||
cmd.append_switch(Some(&"enable-gpu-rasterization".into()));
|
||||
cmd.append_switch(Some(&"enable-accelerated-2d-canvas".into()));
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "accelerated_paint", target_os = "linux"))]
|
||||
{
|
||||
cmd.append_switch_with_value(Some(&"use-angle".into()), Some(&"gl-egl".into()));
|
||||
cmd.append_switch_with_value(Some(&"ozone-platform".into()), Some(&"headless".into()));
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
// Hide user prompt asking for keychain access
|
||||
@@ -119,7 +113,6 @@ impl<H: CefEventHandler> Clone for BrowserProcessAppImpl<H> {
|
||||
Self {
|
||||
object: self.object,
|
||||
event_handler: self.event_handler.duplicate(),
|
||||
accelerated_paint: self.accelerated_paint,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +52,11 @@ impl ImplRenderProcessHandler for RenderProcessHandlerImpl {
|
||||
|
||||
let function_call = format!("window.{function_name}(window.{property_name})");
|
||||
|
||||
global.set_value_bykey(Some(&property_name.into()), Some(&mut value), cef_v8_propertyattribute_t::V8_PROPERTY_ATTRIBUTE_READONLY.wrap_result());
|
||||
global.set_value_bykey(
|
||||
Some(&property_name.into()),
|
||||
Some(&mut value),
|
||||
cef_v8_propertyattribute_t::V8_PROPERTY_ATTRIBUTE_READONLY.wrap_result(),
|
||||
);
|
||||
|
||||
if global.value_bykey(Some(&function_name.into())).is_some() {
|
||||
frame.execute_java_script(Some(&function_call.as_str().into()), None, 0);
|
||||
|
||||
@@ -7,7 +7,6 @@ pub(crate) const APP_DIRECTORY_NAME: &str = "graphite";
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub(crate) const APP_DIRECTORY_NAME: &str = "Graphite";
|
||||
pub(crate) const APP_LOCK_FILE_NAME: &str = "instance.lock";
|
||||
pub(crate) const APP_SOCKET_FILE_NAME: &str = "instance.sock";
|
||||
pub(crate) const APP_STATE_FILE_NAME: &str = "state.ron";
|
||||
pub(crate) const APP_PREFERENCES_FILE_NAME: &str = "preferences.ron";
|
||||
pub(crate) const APP_DOCUMENTS_DIRECTORY_NAME: &str = "documents";
|
||||
|
||||
@@ -9,7 +9,6 @@ pub(crate) enum AppEvent {
|
||||
DesktopWrapperMessage(DesktopWrapperMessage),
|
||||
NodeGraphExecutionResult(NodeGraphExecutionResult),
|
||||
Exit,
|
||||
OpenFiles(Vec<std::path::PathBuf>),
|
||||
#[cfg(target_os = "macos")]
|
||||
MenuEvent {
|
||||
id: String,
|
||||
|
||||
+6
-17
@@ -19,7 +19,6 @@ mod gpu_context;
|
||||
mod persist;
|
||||
mod preferences;
|
||||
mod render;
|
||||
mod socket;
|
||||
mod window;
|
||||
|
||||
pub(crate) mod consts;
|
||||
@@ -59,13 +58,7 @@ pub fn start() {
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::error!("Another instance is already running, Exiting.");
|
||||
if !cli.files.is_empty()
|
||||
&& let Err(error) = socket::send(socket::Message::OpenFiles(cli.files))
|
||||
{
|
||||
tracing::error!("Failed to send socket message to running instance: {}", error);
|
||||
std::process::exit(1);
|
||||
}
|
||||
return;
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -74,7 +67,7 @@ pub fn start() {
|
||||
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory
|
||||
dirs::delete_old_cef_browser_directory();
|
||||
|
||||
let mut prefs = preferences::read();
|
||||
let prefs = preferences::read();
|
||||
|
||||
// Must be called before event loop initialization or native window integrations will break
|
||||
App::init();
|
||||
@@ -85,19 +78,15 @@ pub fn start() {
|
||||
let (app_event_sender, app_event_receiver) = std::sync::mpsc::channel();
|
||||
let app_event_scheduler = event_loop.create_app_event_scheduler(app_event_sender);
|
||||
|
||||
let _socket_handle = socket::start(app_event_scheduler.clone());
|
||||
|
||||
let (cef_view_info_sender, cef_view_info_receiver) = std::sync::mpsc::channel();
|
||||
|
||||
if cli.disable_ui_acceleration {
|
||||
prefs.disable_ui_acceleration = true;
|
||||
}
|
||||
if prefs.disable_ui_acceleration {
|
||||
let disable_ui_acceleration = prefs.disable_ui_acceleration || cli.disable_ui_acceleration;
|
||||
if disable_ui_acceleration {
|
||||
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_context = match cef_context_builder.initialize(cef_handler, disable_ui_acceleration) {
|
||||
Ok(context) => {
|
||||
tracing::info!("CEF initialized successfully");
|
||||
context
|
||||
@@ -113,7 +102,7 @@ pub fn start() {
|
||||
}
|
||||
};
|
||||
|
||||
let app = App::new(Box::new(cef_context), cef_view_info_sender, wgpu_context, app_event_receiver, app_event_scheduler, prefs, cli.files);
|
||||
let app = App::new(Box::new(cef_context), cef_view_info_sender, wgpu_context, app_event_receiver, app_event_scheduler, prefs, cli);
|
||||
|
||||
let exit_reason = app.run(event_loop);
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ pub(crate) fn write_state(state: PersistedState) {
|
||||
if let Err(e) = std::fs::write(state_file_path(), data) {
|
||||
tracing::error!("Failed to write persistent data to disk: {e}");
|
||||
}
|
||||
garbage_collect_document_files(state);
|
||||
garbage_collect_document_files(&state);
|
||||
}
|
||||
|
||||
pub(crate) fn write_document_content(id: DocumentId, document_content: String) {
|
||||
|
||||
+16
-35
@@ -1,7 +1,8 @@
|
||||
use std::borrow::Cow;
|
||||
use wgpu::PresentMode;
|
||||
|
||||
use crate::window::Window;
|
||||
use crate::wrapper::{WgpuContext, WgpuExecutor};
|
||||
use crate::wrapper::{TargetTexture, WgpuContext, WgpuExecutor};
|
||||
|
||||
#[derive(derivative::Derivative)]
|
||||
#[derivative(Debug)]
|
||||
@@ -18,7 +19,7 @@ pub(crate) struct RenderState {
|
||||
viewport_scale: [f32; 2],
|
||||
viewport_offset: [f32; 2],
|
||||
viewport_texture: Option<std::sync::Arc<wgpu::Texture>>,
|
||||
overlays_texture: Option<std::sync::Arc<wgpu::Texture>>,
|
||||
overlays_texture: Option<TargetTexture>,
|
||||
ui_texture: Option<wgpu::Texture>,
|
||||
bind_group: Option<wgpu::BindGroup>,
|
||||
#[derivative(Debug = "ignore")]
|
||||
@@ -120,7 +121,7 @@ impl RenderState {
|
||||
|
||||
let render_pipeline_layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Render Pipeline Layout"),
|
||||
bind_group_layouts: &[Some(&texture_bind_group_layout)],
|
||||
bind_group_layouts: &[&texture_bind_group_layout],
|
||||
immediate_size: size_of::<Immediates>() as u32,
|
||||
});
|
||||
|
||||
@@ -232,17 +233,11 @@ impl RenderState {
|
||||
return;
|
||||
};
|
||||
let size = glam::UVec2::new(viewport_texture.width(), viewport_texture.height());
|
||||
let result = futures::executor::block_on(self.executor.render_vello_scene(&scene, size, &Default::default(), None));
|
||||
match result {
|
||||
Ok(texture) => {
|
||||
self.overlays_texture = Some(texture);
|
||||
}
|
||||
Err(e) => {
|
||||
self.overlays_texture = None;
|
||||
tracing::error!("Error rendering overlays: {:?}", e);
|
||||
}
|
||||
let result = futures::executor::block_on(self.executor.render_vello_scene_to_target_texture(&scene, size, &Default::default(), &mut self.overlays_texture));
|
||||
if let Err(e) = result {
|
||||
tracing::error!("Error rendering overlays: {:?}", e);
|
||||
return;
|
||||
}
|
||||
|
||||
self.update_bindgroup();
|
||||
}
|
||||
|
||||
@@ -262,17 +257,7 @@ impl RenderState {
|
||||
self.render_overlays(scene);
|
||||
}
|
||||
|
||||
let (output, suboptimal) = match self.surface.get_current_texture() {
|
||||
wgpu::CurrentSurfaceTexture::Success(t) => (t, false),
|
||||
// wgpu reports the swapchain no longer matches the underlying surface; present this frame and reconfigure after present, since `Surface::configure` panics while an acquired `SurfaceTexture` is still alive
|
||||
wgpu::CurrentSurfaceTexture::Suboptimal(t) => (t, true),
|
||||
// Window is minimized or behind another window: skip the frame silently and try again once it becomes visible
|
||||
wgpu::CurrentSurfaceTexture::Occluded => return Ok(()),
|
||||
wgpu::CurrentSurfaceTexture::Lost => return Err(RenderError::SurfaceLost),
|
||||
wgpu::CurrentSurfaceTexture::Outdated => return Err(RenderError::SurfaceOutdated),
|
||||
wgpu::CurrentSurfaceTexture::Timeout => return Err(RenderError::SurfaceTimeout),
|
||||
wgpu::CurrentSurfaceTexture::Validation => return Err(RenderError::SurfaceValidation),
|
||||
};
|
||||
let output = self.surface.get_current_texture().map_err(RenderError::SurfaceError)?;
|
||||
|
||||
let view = output.texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
@@ -318,10 +303,6 @@ impl RenderState {
|
||||
window.pre_present_notify();
|
||||
output.present();
|
||||
|
||||
if suboptimal {
|
||||
self.surface.configure(&self.context.device, &self.config);
|
||||
}
|
||||
|
||||
if ui_scale.is_some() {
|
||||
return Err(RenderError::OutdatedUITextureError);
|
||||
}
|
||||
@@ -333,7 +314,11 @@ impl RenderState {
|
||||
fn update_bindgroup(&mut self) {
|
||||
self.surface_outdated = true;
|
||||
let viewport_texture_view = self.viewport_texture.as_ref().unwrap_or(&self.transparent_texture).create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let overlays_texture_view = self.overlays_texture.as_ref().unwrap_or(&self.transparent_texture).create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let overlays_texture_view = self
|
||||
.overlays_texture
|
||||
.as_ref()
|
||||
.map(|target| Cow::Borrowed(target.view()))
|
||||
.unwrap_or_else(|| Cow::Owned(self.transparent_texture.create_view(&wgpu::TextureViewDescriptor::default())));
|
||||
let ui_texture_view = self.ui_texture.as_ref().unwrap_or(&self.transparent_texture).create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
let bind_group = self.context.device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
@@ -345,7 +330,7 @@ impl RenderState {
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::TextureView(&overlays_texture_view),
|
||||
resource: wgpu::BindingResource::TextureView(overlays_texture_view.as_ref()),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
@@ -363,13 +348,9 @@ impl RenderState {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum RenderError {
|
||||
OutdatedUITextureError,
|
||||
SurfaceLost,
|
||||
SurfaceOutdated,
|
||||
SurfaceTimeout,
|
||||
SurfaceValidation,
|
||||
SurfaceError(wgpu::SurfaceError),
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
use interprocess::local_socket::{GenericFilePath, GenericNamespaced, ListenerNonblockingMode, ListenerOptions, Name, prelude::*};
|
||||
use std::io::{ErrorKind, Read, Write};
|
||||
use std::sync::mpsc;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::consts::APP_SOCKET_FILE_NAME;
|
||||
use crate::event::{AppEvent, AppEventScheduler};
|
||||
|
||||
// TODO: Needs to be integrated/replaced with the action system.
|
||||
// TODO: At that point this should just wrap the action, meaning all actions bindable by the user can also be accessed via the socket.
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) enum Message {
|
||||
OpenFiles(Vec<std::path::PathBuf>),
|
||||
}
|
||||
|
||||
fn handle_message(message: Message, app_event_scheduler: &AppEventScheduler) {
|
||||
match message {
|
||||
Message::OpenFiles(paths) => {
|
||||
app_event_scheduler.schedule(AppEvent::OpenFiles(paths));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn send(message: Message) -> std::io::Result<()> {
|
||||
let data = ron::ser::to_string(&message).map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
|
||||
let mut connection = interprocess::local_socket::Stream::connect(socket_name())?;
|
||||
connection.write_all(data.as_bytes())
|
||||
}
|
||||
|
||||
pub(crate) struct SocketHandle {
|
||||
thread: Option<thread::JoinHandle<()>>,
|
||||
shutdown_sender: mpsc::Sender<()>,
|
||||
}
|
||||
impl Drop for SocketHandle {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.shutdown_sender.send(());
|
||||
let _ = self.thread.take().expect("SocketHandle can only be dropped once").join();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn start(app_event_scheduler: AppEventScheduler) -> SocketHandle {
|
||||
let (shutdown_sender, shutdown_receiver) = mpsc::channel();
|
||||
|
||||
let thread = thread::Builder::new()
|
||||
.name("socket".to_string())
|
||||
.spawn(move || run(app_event_scheduler, shutdown_receiver))
|
||||
.expect("Failed to spawn socket thread");
|
||||
|
||||
SocketHandle {
|
||||
shutdown_sender,
|
||||
thread: Some(thread),
|
||||
}
|
||||
}
|
||||
|
||||
fn run(app_event_scheduler: AppEventScheduler, shutdown_receiver: mpsc::Receiver<()>) {
|
||||
let listener = match ListenerOptions::new()
|
||||
.name(socket_name())
|
||||
.nonblocking(ListenerNonblockingMode::Accept)
|
||||
.try_overwrite(true)
|
||||
.max_spin_time(Duration::from_millis(100))
|
||||
.create_sync()
|
||||
{
|
||||
Ok(listener) => listener,
|
||||
Err(error) => {
|
||||
tracing::error!("Failed to bind socket: {}", error);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let max_backoff = Duration::from_millis(100);
|
||||
let mut backoff = Duration::ZERO;
|
||||
|
||||
loop {
|
||||
if backoff.is_zero() {
|
||||
match shutdown_receiver.try_recv() {
|
||||
Ok(()) | Err(mpsc::TryRecvError::Disconnected) => break,
|
||||
Err(mpsc::TryRecvError::Empty) => {}
|
||||
}
|
||||
backoff = Duration::from_nanos(1);
|
||||
} else {
|
||||
match shutdown_receiver.recv_timeout(backoff) {
|
||||
Ok(()) | Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => {}
|
||||
}
|
||||
backoff = (backoff * 2).min(max_backoff);
|
||||
}
|
||||
|
||||
match listener.accept() {
|
||||
Ok(mut connection) => {
|
||||
backoff = Duration::ZERO;
|
||||
|
||||
let app_event_scheduler = app_event_scheduler.clone();
|
||||
let spawn_result = thread::Builder::new().name("socket-connection".to_string()).spawn(move || {
|
||||
let mut data = String::new();
|
||||
if let Err(error) = connection.read_to_string(&mut data) {
|
||||
tracing::error!("Failed to read socket message: {}", error);
|
||||
return;
|
||||
}
|
||||
|
||||
match ron::de::from_str(&data) {
|
||||
Ok(message) => handle_message(message, &app_event_scheduler),
|
||||
Err(error) => tracing::error!("Failed to deserialize socket message: {}", error),
|
||||
}
|
||||
});
|
||||
if let Err(error) = spawn_result {
|
||||
tracing::error!("Failed to spawn socket connection thread: {}", error);
|
||||
}
|
||||
}
|
||||
Err(error) if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted) => {}
|
||||
Err(error) => {
|
||||
tracing::error!("Failed to accept socket connection: {}", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn socket_name() -> Name<'static> {
|
||||
if cfg!(target_os = "windows") {
|
||||
let user = std::env::var("USERNAME").unwrap_or_default();
|
||||
let name = format!("{user}-{app}-{APP_SOCKET_FILE_NAME}", app = crate::consts::APP_NAME);
|
||||
name.to_ns_name::<GenericNamespaced>().expect("valid named pipe name")
|
||||
} else {
|
||||
crate::dirs::app_data_dir().join(APP_SOCKET_FILE_NAME).to_fs_name::<GenericFilePath>().expect("valid socket path")
|
||||
}
|
||||
}
|
||||
@@ -140,11 +140,6 @@ impl Window {
|
||||
let _ = self.winit_window.drag_window();
|
||||
}
|
||||
|
||||
pub(crate) fn focus(&self) {
|
||||
self.winit_window.set_minimized(false);
|
||||
self.winit_window.focus_window();
|
||||
}
|
||||
|
||||
pub(crate) fn hide(&self) {
|
||||
self.native_handle.hide();
|
||||
}
|
||||
|
||||
@@ -26,8 +26,8 @@ impl super::NativeWindow for NativeWindowImpl {
|
||||
}
|
||||
|
||||
fn new(_window: &dyn Window, app_event_scheduler: AppEventScheduler) -> Self {
|
||||
app::setup(app_event_scheduler.clone());
|
||||
let menu = menu::Menu::new(app_event_scheduler);
|
||||
|
||||
NativeWindowImpl { menu }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,75 +1,6 @@
|
||||
use std::ffi::CStr;
|
||||
use std::ffi::OsStr;
|
||||
use std::ops::Deref;
|
||||
use std::ops::DerefMut;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Mutex, Once};
|
||||
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::ProtocolObject;
|
||||
use objc2::{ClassType, MainThreadMarker, MainThreadOnly, define_class, msg_send};
|
||||
use objc2_app_kit::{NSApplication, NSApplicationDelegate, NSEvent, NSEventType, NSResponder};
|
||||
use objc2_foundation::{NSArray, NSObject, NSObjectProtocol, NSURL};
|
||||
|
||||
use crate::event::{AppEvent, AppEventScheduler};
|
||||
|
||||
static APP_EVENT_SCHEDULER: Mutex<Option<AppEventScheduler>> = Mutex::new(None);
|
||||
static PENDING_EVENTS: Mutex<Option<Vec<AppEvent>>> = Mutex::new(Some(Vec::new()));
|
||||
|
||||
fn dispatch_event(event: AppEvent) {
|
||||
let app_event_scheduler_guard = APP_EVENT_SCHEDULER.lock().unwrap();
|
||||
if let Some(app_event_scheduler) = app_event_scheduler_guard.deref() {
|
||||
app_event_scheduler.schedule(event);
|
||||
} else if let Some(pending_events) = PENDING_EVENTS.lock().unwrap().deref_mut() {
|
||||
pending_events.push(event);
|
||||
} else {
|
||||
tracing::error!("Failed to dispatch event");
|
||||
}
|
||||
}
|
||||
|
||||
fn instance() -> objc2::rc::Retained<NSApplication> {
|
||||
unsafe { msg_send![GraphiteApplication::class(), sharedApplication] }
|
||||
}
|
||||
|
||||
static INSTALL_DELEGATE: Once = Once::new();
|
||||
|
||||
pub(super) fn init() {
|
||||
let _ = instance();
|
||||
|
||||
INSTALL_DELEGATE.call_once(|| {
|
||||
let mtm = MainThreadMarker::new().expect("should only ever be called from main thread");
|
||||
let delegate: Retained<GraphiteApplicationDelegate> = unsafe { msg_send![super(GraphiteApplicationDelegate::alloc(mtm).set_ivars(())), init] };
|
||||
instance().setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
|
||||
std::mem::forget(delegate);
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn setup(app_event_scheduler: AppEventScheduler) {
|
||||
let mut app_event_scheduler_guard = APP_EVENT_SCHEDULER.lock().unwrap();
|
||||
|
||||
if let Some(mut pending_events) = PENDING_EVENTS.lock().unwrap().take() {
|
||||
pending_events.drain(..).for_each(|event| {
|
||||
app_event_scheduler.schedule(event);
|
||||
});
|
||||
} else {
|
||||
tracing::error!("Failed to take PENDING_EVENTS and schedule them. This a bug.");
|
||||
}
|
||||
|
||||
*app_event_scheduler_guard = Some(app_event_scheduler);
|
||||
}
|
||||
|
||||
pub(super) fn hide() {
|
||||
instance().hide(None);
|
||||
}
|
||||
|
||||
pub(super) fn hide_others() {
|
||||
instance().hideOtherApplications(None);
|
||||
}
|
||||
|
||||
pub(super) fn show_all() {
|
||||
instance().unhideAllApplications(None);
|
||||
}
|
||||
use objc2::{ClassType, define_class, msg_send};
|
||||
use objc2_app_kit::{NSApplication, NSEvent, NSEventType, NSResponder};
|
||||
use objc2_foundation::NSObject;
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super(NSApplication, NSResponder, NSObject))]
|
||||
@@ -89,31 +20,22 @@ define_class!(
|
||||
}
|
||||
);
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super(NSObject))]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[name = "GraphiteApplicationDelegate"]
|
||||
struct GraphiteApplicationDelegate;
|
||||
fn instance() -> objc2::rc::Retained<NSApplication> {
|
||||
unsafe { msg_send![GraphiteApplication::class(), sharedApplication] }
|
||||
}
|
||||
|
||||
unsafe impl NSObjectProtocol for GraphiteApplicationDelegate {}
|
||||
pub(super) fn init() {
|
||||
let _ = instance();
|
||||
}
|
||||
|
||||
unsafe impl NSApplicationDelegate for GraphiteApplicationDelegate {
|
||||
#[unsafe(method(application:openURLs:))]
|
||||
fn application_open_urls(&self, _application: &NSApplication, urls: &NSArray<NSURL>) {
|
||||
let paths = (0..urls.count())
|
||||
.filter_map(|index| {
|
||||
let url = urls.objectAtIndex(index);
|
||||
if !url.isFileURL() {
|
||||
tracing::error!("Ignoring open URL event for non-file URL: {:?}", url);
|
||||
return None;
|
||||
}
|
||||
let cstr = unsafe { CStr::from_ptr(url.fileSystemRepresentation().as_ptr()) };
|
||||
let path = PathBuf::from(OsStr::from_bytes(cstr.to_bytes()));
|
||||
Some(path)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
pub(super) fn hide() {
|
||||
instance().hide(None);
|
||||
}
|
||||
|
||||
dispatch_event(AppEvent::OpenFiles(paths));
|
||||
}
|
||||
}
|
||||
);
|
||||
pub(super) fn hide_others() {
|
||||
instance().hideOtherApplications(None);
|
||||
}
|
||||
|
||||
pub(super) fn show_all() {
|
||||
instance().unhideAllApplications(None);
|
||||
}
|
||||
@@ -31,20 +31,6 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
||||
SaveFileDialogContext::File { content } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::WriteFile { path, content });
|
||||
}
|
||||
SaveFileDialogContext::MultipleFiles { files, expected_extension } => {
|
||||
// Treat the chosen path as the folder name. Strip only the export's expected extension (e.g. ".png" for a
|
||||
// PNG animation export) so that arbitrary dotted folder names like `v1.0` are preserved as-is, while a user
|
||||
// who typed `MyAnim.png` still gets a `MyAnim/` folder rather than a `MyAnim.png/` folder.
|
||||
// The `WriteFile` handler creates parent directories if they don't exist, so the folder is materialized on first write.
|
||||
let folder = match path.extension().and_then(|e| e.to_str()) {
|
||||
Some(ext) if ext.eq_ignore_ascii_case(&expected_extension) => path.with_extension(""),
|
||||
_ => path,
|
||||
};
|
||||
for (filename, content) in files {
|
||||
let file_path = folder.join(&filename);
|
||||
dispatcher.respond(DesktopFrontendMessage::WriteFile { path: file_path, content });
|
||||
}
|
||||
}
|
||||
},
|
||||
DesktopWrapperMessage::OpenFile { path, content } => {
|
||||
let message = PortfolioMessage::OpenFile { path, content };
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
use graphite_editor::messages::frontend::utility_types::ExportAnimationFrame;
|
||||
#[cfg(target_os = "macos")]
|
||||
use graphite_editor::messages::layout::utility_types::layout_widget::LayoutTarget;
|
||||
use graphite_editor::messages::prelude::FrontendMessage;
|
||||
@@ -15,7 +14,6 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
|
||||
title: "Open Document".to_string(),
|
||||
filters: vec![],
|
||||
multiple: true,
|
||||
context: OpenFileDialogContext::Open,
|
||||
});
|
||||
}
|
||||
@@ -23,7 +21,6 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
|
||||
title: "Import File".to_string(),
|
||||
filters: vec![],
|
||||
multiple: false,
|
||||
context: OpenFileDialogContext::Import,
|
||||
});
|
||||
}
|
||||
@@ -60,61 +57,6 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
context: SaveFileDialogContext::File { content },
|
||||
});
|
||||
}
|
||||
FrontendMessage::TriggerExportAnimation {
|
||||
name,
|
||||
extension,
|
||||
mime,
|
||||
size,
|
||||
folder,
|
||||
frames,
|
||||
} => {
|
||||
// Materialize each frame to bytes; SVG strings are encoded as UTF-8.
|
||||
// Raster-needs-canvas-rasterize frames can't be encoded here without a Rust SVG rasterizer,
|
||||
// so fall through to the frontend zip path in that case.
|
||||
// TODO: This fallback is inconsistent with the desktop folder-save flow for the rest of the animation
|
||||
// export — desktop users will see a .zip download instead of a folder. Once SVG rasterization moves to
|
||||
// Rust (resvg), this fallback can be removed and all frame paths can save into the chosen folder.
|
||||
let mut needs_frontend_rasterization = false;
|
||||
let mut materialized = Vec::with_capacity(frames.len());
|
||||
// Dynamic zero-pad width so files keep sorting in playback order beyond 9,999 frames.
|
||||
let pad_width = frames.len().to_string().len().max(4);
|
||||
let safe_base = graphite_editor::messages::frontend::utility_types::sanitize_filename_component(&name);
|
||||
for (index, frame) in frames.iter().enumerate() {
|
||||
let filename = format!("{safe_base}_{:0pad$}.{extension}", index + 1, pad = pad_width);
|
||||
let bytes = match frame {
|
||||
ExportAnimationFrame::Svg(svg) if extension == "svg" => svg.as_bytes().to_vec(),
|
||||
ExportAnimationFrame::Bytes(bytes) => bytes.to_vec(),
|
||||
ExportAnimationFrame::Svg(_) => {
|
||||
needs_frontend_rasterization = true;
|
||||
break;
|
||||
}
|
||||
};
|
||||
materialized.push((filename, bytes));
|
||||
}
|
||||
|
||||
if needs_frontend_rasterization {
|
||||
return Some(FrontendMessage::TriggerExportAnimation {
|
||||
name,
|
||||
extension,
|
||||
mime,
|
||||
size,
|
||||
folder,
|
||||
frames,
|
||||
});
|
||||
}
|
||||
|
||||
// The dialog name is the folder the frames go into (analogous to the .zip on web).
|
||||
dispatcher.respond(DesktopFrontendMessage::SaveFileDialog {
|
||||
title: "Save Animation Frames Folder As".to_string(),
|
||||
default_filename: safe_base,
|
||||
default_folder: folder,
|
||||
filters: Vec::new(),
|
||||
context: SaveFileDialogContext::MultipleFiles {
|
||||
files: materialized,
|
||||
expected_extension: extension,
|
||||
},
|
||||
});
|
||||
}
|
||||
FrontendMessage::TriggerVisitLink { url } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::OpenUrl(url));
|
||||
}
|
||||
@@ -195,9 +137,6 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
FrontendMessage::WindowDrag => {
|
||||
dispatcher.respond(DesktopFrontendMessage::WindowDrag);
|
||||
}
|
||||
FrontendMessage::WindowFocus => {
|
||||
dispatcher.respond(DesktopFrontendMessage::WindowFocus);
|
||||
}
|
||||
FrontendMessage::WindowHide => {
|
||||
dispatcher.respond(DesktopFrontendMessage::WindowHide);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ use message_dispatcher::DesktopWrapperMessageDispatcher;
|
||||
use messages::{DesktopFrontendMessage, DesktopWrapperMessage};
|
||||
|
||||
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
|
||||
pub use wgpu_executor::TargetTexture;
|
||||
pub use wgpu_executor::WgpuContext;
|
||||
pub use wgpu_executor::WgpuContextBuilder;
|
||||
pub use wgpu_executor::WgpuExecutor;
|
||||
|
||||
@@ -16,7 +16,6 @@ pub enum DesktopFrontendMessage {
|
||||
OpenFileDialog {
|
||||
title: String,
|
||||
filters: Vec<FileFilter>,
|
||||
multiple: bool,
|
||||
context: OpenFileDialogContext,
|
||||
},
|
||||
SaveFileDialog {
|
||||
@@ -72,7 +71,6 @@ pub enum DesktopFrontendMessage {
|
||||
WindowMaximize,
|
||||
WindowFullscreen,
|
||||
WindowDrag,
|
||||
WindowFocus,
|
||||
WindowHide,
|
||||
WindowHideOthers,
|
||||
WindowShowAll,
|
||||
@@ -104,28 +102,14 @@ pub struct FileFilter {
|
||||
pub extensions: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum OpenFileDialogContext {
|
||||
Open,
|
||||
Import,
|
||||
}
|
||||
|
||||
pub enum SaveFileDialogContext {
|
||||
Document {
|
||||
document_id: DocumentId,
|
||||
content: Vec<u8>,
|
||||
},
|
||||
File {
|
||||
content: Vec<u8>,
|
||||
},
|
||||
/// Multiple files written into a folder whose path is the user-chosen path with the matching `expected_extension`
|
||||
/// stripped (e.g. for a PNG animation export, picking `MyAnim.png` yields a `MyAnim/` folder, while picking `v1.0`
|
||||
/// is preserved as `v1.0/` because `.0` isn't the expected extension). Each `(filename, content)` entry is written
|
||||
/// inside that folder, which is created if it doesn't exist.
|
||||
MultipleFiles {
|
||||
files: Vec<(String, Vec<u8>)>,
|
||||
expected_extension: String,
|
||||
},
|
||||
Document { document_id: DocumentId, content: Vec<u8> },
|
||||
File { content: Vec<u8> },
|
||||
}
|
||||
|
||||
pub enum MenuItem {
|
||||
|
||||
@@ -19,7 +19,6 @@ gpu = ["interpreted-executor/gpu", "dep:wgpu-executor"]
|
||||
# Local dependencies
|
||||
graphite-proc-macros = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
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 }
|
||||
@@ -46,7 +45,6 @@ vello = { workspace = true }
|
||||
base64 = { workspace = true }
|
||||
spin = { workspace = true }
|
||||
image = { workspace = true }
|
||||
color = { workspace = true }
|
||||
|
||||
# Optional local dependencies
|
||||
wgpu-executor = { workspace = true, optional = true }
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
// GRAPH
|
||||
pub const GRID_SIZE: u32 = 24;
|
||||
pub const HALF_GRID_SIZE: u32 = GRID_SIZE / 2;
|
||||
pub const EXPORTS_TO_TOP_EDGE_PIXEL_GAP: u32 = 72;
|
||||
pub const EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP: u32 = 120;
|
||||
pub const IMPORTS_TO_TOP_EDGE_PIXEL_GAP: u32 = 72;
|
||||
|
||||
@@ -21,7 +21,6 @@ pub struct DispatcherMessageHandlers {
|
||||
app_window_message_handler: AppWindowMessageHandler,
|
||||
broadcast_message_handler: BroadcastMessageHandler,
|
||||
clipboard_message_handler: ClipboardMessageHandler,
|
||||
color_picker_message_handler: ColorPickerMessageHandler,
|
||||
debug_message_handler: DebugMessageHandler,
|
||||
defer_message_handler: DeferMessageHandler,
|
||||
dialog_message_handler: DialogMessageHandler,
|
||||
@@ -165,7 +164,6 @@ impl Dispatcher {
|
||||
}
|
||||
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::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, ());
|
||||
}
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
// Bumped past the default 128 because the deeply-generic message-passing types pull in wgpu/naga
|
||||
// trait chains that overflow the trait resolver under `--tests`. Set to the same value the compiler suggests.
|
||||
#![recursion_limit = "256"]
|
||||
|
||||
extern crate graphite_proc_macros;
|
||||
|
||||
// `macro_use` puts these macros into scope for all descendant code files
|
||||
|
||||
@@ -11,7 +11,6 @@ pub enum AppWindowMessage {
|
||||
Maximize,
|
||||
Fullscreen,
|
||||
Drag,
|
||||
Focus,
|
||||
Hide,
|
||||
HideOthers,
|
||||
ShowAll,
|
||||
|
||||
@@ -36,10 +36,6 @@ impl MessageHandler<AppWindowMessage, ()> for AppWindowMessageHandler {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
responses.add(FrontendMessage::WindowDrag);
|
||||
}
|
||||
AppWindowMessage::Focus => {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
responses.add(FrontendMessage::WindowFocus);
|
||||
}
|
||||
AppWindowMessage::Hide => {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
responses.add(FrontendMessage::WindowHide);
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
use crate::messages::layout::utility_types::widgets::input_widgets::{SpectrumInputUpdate, VisualColorPickersInputUpdate};
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
|
||||
/// Identifies which RGB channel a numeric input change targets.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum RgbChannel {
|
||||
Red,
|
||||
Green,
|
||||
Blue,
|
||||
}
|
||||
|
||||
/// Identifies which HSV channel a numeric input change targets.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum HsvChannel {
|
||||
Hue,
|
||||
Saturation,
|
||||
Value,
|
||||
}
|
||||
|
||||
#[impl_message(Message, ColorPicker)]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ColorPickerMessage {
|
||||
/// Initialize the picker state from an external color/gradient and announce its options. Called by the frontend when a `<ColorPicker />` opens.
|
||||
Open { initial_value: FillChoice, allow_none: bool, disabled: bool },
|
||||
/// Clear the picker state. Called by the frontend when the popover closes.
|
||||
Close,
|
||||
|
||||
/// Visual sat/val/hue/alpha drag updates from `VisualColorPickersInput`.
|
||||
VisualUpdate { update: VisualColorPickersInputUpdate },
|
||||
/// Numeric RGB channel update.
|
||||
SetChannelRgb { channel: RgbChannel, value: Option<f64> },
|
||||
/// Numeric HSV channel update.
|
||||
SetChannelHsv { channel: HsvChannel, value: Option<f64> },
|
||||
/// Alpha percentage update from the alpha slider numeric input.
|
||||
SetAlphaPercent { value: Option<f64> },
|
||||
/// CSS / hex color string from the hex `TextInput`.
|
||||
SetHexCode { code: String },
|
||||
|
||||
/// Pick a preset (specific solid color or "None").
|
||||
PickPreset { preset: FillChoice },
|
||||
/// Color picked via the browser-native eyedropper. The string is the eyedropper's returned hex code.
|
||||
EyedropperColorCode { code: String },
|
||||
|
||||
/// Swap the current "new" color with the captured "old" color.
|
||||
SwapNewWithOld,
|
||||
|
||||
/// `SpectrumInput` change: marker move/insert/delete, midpoint move/reset, or active marker selection changed.
|
||||
GradientUpdate { update: SpectrumInputUpdate },
|
||||
|
||||
/// Tell the frontend to start an undo transaction (forwarded as a `FrontendMessage` it bridges out to the picker's parent).
|
||||
StartTransaction,
|
||||
/// Tell the frontend to commit the in-flight undo transaction.
|
||||
CommitTransaction,
|
||||
}
|
||||
@@ -1,664 +0,0 @@
|
||||
use crate::messages::color_picker::color_picker_message::{HsvChannel, RgbChannel};
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::layout::utility_types::widgets::input_widgets::{ColorPresetsInputUpdate, SpectrumInputUpdate, SpectrumMarker, VisualColorPickersInputUpdate};
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::core_types::misc::parse_css_color;
|
||||
use graphene_std::vector::style::{FillChoice, FillChoiceUI, GradientStops, GradientStopsUI};
|
||||
|
||||
/// Bounds for a midpoint position (relative to the interval between two adjacent gradient stops).
|
||||
const MIN_MIDPOINT: f64 = 0.01;
|
||||
const MAX_MIDPOINT: f64 = 0.99;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, ExtractField)]
|
||||
pub struct ColorPickerMessageHandler {
|
||||
// HSV is the source of truth so the hue is preserved when the user desaturates the color (or drives the value to black) and back.
|
||||
hue: f64,
|
||||
saturation: f64,
|
||||
value: f64,
|
||||
alpha: f64,
|
||||
is_none: bool,
|
||||
|
||||
// Snapshot of the color when the picker opened, used by the new/old comparison swatch and the swap button.
|
||||
old_hue: f64,
|
||||
old_saturation: f64,
|
||||
old_value: f64,
|
||||
old_alpha: f64,
|
||||
old_is_none: bool,
|
||||
|
||||
// When set, the picker is editing a gradient: the visual pickers and inputs target the active stop's color.
|
||||
gradient: Option<GradientStops>,
|
||||
active_marker_index: Option<u32>,
|
||||
active_marker_is_midpoint: bool,
|
||||
|
||||
allow_none: bool,
|
||||
disabled: bool,
|
||||
}
|
||||
|
||||
impl Default for ColorPickerMessageHandler {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
hue: 0.,
|
||||
saturation: 0.,
|
||||
value: 0.,
|
||||
alpha: 1.,
|
||||
is_none: true,
|
||||
old_hue: 0.,
|
||||
old_saturation: 0.,
|
||||
old_value: 0.,
|
||||
old_alpha: 1.,
|
||||
old_is_none: true,
|
||||
gradient: None,
|
||||
active_marker_index: None,
|
||||
active_marker_is_midpoint: false,
|
||||
allow_none: true,
|
||||
disabled: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<ColorPickerMessage, ()> for ColorPickerMessageHandler {
|
||||
fn process_message(&mut self, message: ColorPickerMessage, responses: &mut VecDeque<Message>, _context: ()) {
|
||||
match message {
|
||||
ColorPickerMessage::Open { initial_value, allow_none, disabled } => {
|
||||
self.allow_none = allow_none;
|
||||
self.disabled = disabled;
|
||||
|
||||
match initial_value {
|
||||
FillChoice::None => {
|
||||
self.set_new_hsva(0., 0., 0., 1., true);
|
||||
self.gradient = None;
|
||||
self.active_marker_index = None;
|
||||
self.active_marker_is_midpoint = false;
|
||||
}
|
||||
FillChoice::Solid(color) => {
|
||||
self.gradient = None;
|
||||
self.active_marker_index = None;
|
||||
self.active_marker_is_midpoint = false;
|
||||
self.adopt_color(color);
|
||||
}
|
||||
FillChoice::Gradient(stops) => {
|
||||
self.active_marker_index = Some(0);
|
||||
self.active_marker_is_midpoint = false;
|
||||
let first_color = stops.color.first().copied().unwrap_or(Color::BLACK);
|
||||
self.gradient = Some(stops);
|
||||
self.adopt_color(first_color);
|
||||
}
|
||||
}
|
||||
|
||||
self.snapshot_old();
|
||||
self.send_layouts(responses);
|
||||
}
|
||||
ColorPickerMessage::Close => {
|
||||
responses.add(DocumentMessage::EndTransaction);
|
||||
}
|
||||
ColorPickerMessage::VisualUpdate { update } => {
|
||||
self.hue = update.hue;
|
||||
self.saturation = update.saturation;
|
||||
self.value = update.value;
|
||||
self.alpha = update.alpha;
|
||||
self.is_none = false;
|
||||
self.emit_color(responses);
|
||||
self.send_layouts(responses);
|
||||
}
|
||||
ColorPickerMessage::SetChannelRgb { channel, value } => {
|
||||
let Some(strength) = value else { return };
|
||||
let Some(current) = self.current_color() else { return };
|
||||
// The RGB inputs are 0..255 sRGB display values; substitute the new channel into the gamma triple and lift back to linear for storage.
|
||||
let new_gamma_channel = (strength / 255.) as f32;
|
||||
let [cur_r, cur_g, cur_b, cur_a] = current.to_gamma_srgb_channels();
|
||||
let updated = match channel {
|
||||
RgbChannel::Red => Color::from_gamma_srgb_channels(new_gamma_channel, cur_g, cur_b, cur_a),
|
||||
RgbChannel::Green => Color::from_gamma_srgb_channels(cur_r, new_gamma_channel, cur_b, cur_a),
|
||||
RgbChannel::Blue => Color::from_gamma_srgb_channels(cur_r, cur_g, new_gamma_channel, cur_a),
|
||||
};
|
||||
self.adopt_color(updated);
|
||||
self.emit_color(responses);
|
||||
self.send_layouts(responses);
|
||||
}
|
||||
ColorPickerMessage::SetChannelHsv { channel, value } => {
|
||||
let Some(strength) = value else { return };
|
||||
match channel {
|
||||
HsvChannel::Hue => self.hue = strength / 360.,
|
||||
HsvChannel::Saturation => self.saturation = strength / 100.,
|
||||
HsvChannel::Value => self.value = strength / 100.,
|
||||
}
|
||||
self.is_none = false;
|
||||
self.emit_color(responses);
|
||||
self.send_layouts(responses);
|
||||
}
|
||||
ColorPickerMessage::SetAlphaPercent { value } => {
|
||||
let Some(strength) = value else { return };
|
||||
self.alpha = strength / 100.;
|
||||
self.is_none = false;
|
||||
self.emit_color(responses);
|
||||
self.send_layouts(responses);
|
||||
}
|
||||
ColorPickerMessage::SetHexCode { code } => {
|
||||
let Some(color) = parse_css_color(&code) else {
|
||||
// Parse failed: re-send the layouts so the TextInput's displayed value reverts from the user's bad input
|
||||
// back to the current color's hex string. The TextInput dispatch arm has already mutated the stored
|
||||
// widget's `value` to the bad input, so the diff between (stored = bad) and (new = correct) sends an update.
|
||||
self.send_layouts(responses);
|
||||
return;
|
||||
};
|
||||
responses.add(FrontendMessage::ColorPickerStartHistoryTransaction);
|
||||
self.adopt_color(color);
|
||||
self.emit_color(responses);
|
||||
self.send_layouts(responses);
|
||||
}
|
||||
ColorPickerMessage::PickPreset { preset } => {
|
||||
responses.add(FrontendMessage::ColorPickerStartHistoryTransaction);
|
||||
match preset {
|
||||
FillChoice::None => {
|
||||
self.set_new_hsva(0., 0., 0., 1., true);
|
||||
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoiceUI::None });
|
||||
}
|
||||
FillChoice::Solid(color) => {
|
||||
self.adopt_color(color);
|
||||
self.emit_color(responses);
|
||||
}
|
||||
FillChoice::Gradient(_) => {
|
||||
// The presets row only emits solid colors or "None"; the gradient case is unreachable, so safely ignore.
|
||||
}
|
||||
}
|
||||
self.send_layouts(responses);
|
||||
}
|
||||
ColorPickerMessage::EyedropperColorCode { code } => {
|
||||
let Some(color) = parse_css_color(&code) else { return };
|
||||
responses.add(FrontendMessage::ColorPickerStartHistoryTransaction);
|
||||
self.adopt_color(color);
|
||||
self.emit_color(responses);
|
||||
self.send_layouts(responses);
|
||||
}
|
||||
ColorPickerMessage::SwapNewWithOld => {
|
||||
let temp = (self.hue, self.saturation, self.value, self.alpha, self.is_none);
|
||||
self.set_new_hsva(self.old_hue, self.old_saturation, self.old_value, self.old_alpha, self.old_is_none);
|
||||
self.set_old_hsva(temp.0, temp.1, temp.2, temp.3, temp.4);
|
||||
|
||||
if self.is_none {
|
||||
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoiceUI::None });
|
||||
} else {
|
||||
self.emit_color(responses);
|
||||
}
|
||||
self.send_layouts(responses);
|
||||
}
|
||||
ColorPickerMessage::GradientUpdate { update } => self.apply_gradient_update(update, responses),
|
||||
ColorPickerMessage::StartTransaction => {
|
||||
responses.add(FrontendMessage::ColorPickerStartHistoryTransaction);
|
||||
}
|
||||
ColorPickerMessage::CommitTransaction => {
|
||||
responses.add(FrontendMessage::ColorPickerCommitHistoryTransaction);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn actions(&self) -> ActionList {
|
||||
actions!(ColorPickerMessageDiscriminant;)
|
||||
}
|
||||
}
|
||||
|
||||
impl ColorPickerMessageHandler {
|
||||
// The picker's internal HSV state is HSV of sRGB display values
|
||||
fn current_color(&self) -> Option<Color> {
|
||||
if self.is_none {
|
||||
None
|
||||
} else {
|
||||
Some(Color::from_hsva(self.hue as f32, self.saturation as f32, self.value as f32, self.alpha as f32))
|
||||
}
|
||||
}
|
||||
|
||||
fn old_color(&self) -> Option<Color> {
|
||||
if self.old_is_none {
|
||||
None
|
||||
} else {
|
||||
Some(Color::from_hsva(self.old_hue as f32, self.old_saturation as f32, self.old_value as f32, self.old_alpha as f32))
|
||||
}
|
||||
}
|
||||
|
||||
fn set_new_hsva(&mut self, h: f64, s: f64, v: f64, a: f64, is_none: bool) {
|
||||
self.hue = h;
|
||||
self.saturation = s;
|
||||
self.value = v;
|
||||
self.alpha = a;
|
||||
self.is_none = is_none;
|
||||
}
|
||||
|
||||
fn set_old_hsva(&mut self, h: f64, s: f64, v: f64, a: f64, is_none: bool) {
|
||||
self.old_hue = h;
|
||||
self.old_saturation = s;
|
||||
self.old_value = v;
|
||||
self.old_alpha = a;
|
||||
self.old_is_none = is_none;
|
||||
}
|
||||
|
||||
fn snapshot_old(&mut self) {
|
||||
self.old_hue = self.hue;
|
||||
self.old_saturation = self.saturation;
|
||||
self.old_value = self.value;
|
||||
self.old_alpha = self.alpha;
|
||||
self.old_is_none = self.is_none;
|
||||
}
|
||||
|
||||
/// Set HSV state from a Color, preserving hue and saturation in degenerate cases.
|
||||
fn adopt_color(&mut self, color: Color) {
|
||||
let [target_h, target_s, target_v, target_a] = color.to_hsva();
|
||||
let (target_h, target_s, target_v, target_a) = (target_h as f64, target_s as f64, target_v as f64, target_a as f64);
|
||||
|
||||
// Preserve hue: avoid jumping from 360° (top) to 0° (bottom) and don't reset hue when the color is desaturated or fully dark.
|
||||
if !(target_h == 0. && self.hue == 1.) && target_s > 0. && target_v > 0. {
|
||||
self.hue = target_h;
|
||||
}
|
||||
// Preserve saturation when value is black (saturation is meaningless on the bottom edge of the saturation-value box).
|
||||
if target_v != 0. {
|
||||
self.saturation = target_s;
|
||||
}
|
||||
self.value = target_v;
|
||||
self.alpha = target_a;
|
||||
self.is_none = false;
|
||||
}
|
||||
|
||||
/// Compute the FillChoice and forward it via `FrontendMessage::ColorPickerColorChanged`. In gradient mode, the active stop's color is updated in place.
|
||||
fn emit_color(&mut self, responses: &mut VecDeque<Message>) {
|
||||
let Some(color) = self.current_color() else { return };
|
||||
|
||||
if let Some(gradient) = &mut self.gradient
|
||||
&& let Some(active_index) = self.active_marker_index
|
||||
&& let Some(stop_color) = gradient.color.get_mut(active_index as usize)
|
||||
{
|
||||
*stop_color = color;
|
||||
let stops = gradient.clone();
|
||||
let fill_choice = FillChoice::Gradient(stops);
|
||||
responses.add(FrontendMessage::ColorPickerColorChanged {
|
||||
value: FillChoiceUI::from(&fill_choice),
|
||||
});
|
||||
} else {
|
||||
let fill_choice = FillChoice::Solid(color);
|
||||
responses.add(FrontendMessage::ColorPickerColorChanged {
|
||||
value: FillChoiceUI::from(&fill_choice),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn send_layouts(&self, responses: &mut VecDeque<Message>) {
|
||||
responses.add(LayoutMessage::SendLayout {
|
||||
layout: self.pickers_and_gradient_layout(),
|
||||
layout_target: LayoutTarget::ColorPickerPickersAndGradient,
|
||||
});
|
||||
responses.add(LayoutMessage::SendLayout {
|
||||
layout: self.details_layout(),
|
||||
layout_target: LayoutTarget::ColorPickerDetails,
|
||||
});
|
||||
}
|
||||
|
||||
/// Apply an incoming `SpectrumInput` intent to the gradient state and broadcast the result.
|
||||
fn apply_gradient_update(&mut self, update: SpectrumInputUpdate, responses: &mut VecDeque<Message>) {
|
||||
// Active marker selection is the one update that doesn't mutate the gradient
|
||||
if let SpectrumInputUpdate::ActiveMarker {
|
||||
active_marker_index,
|
||||
active_marker_is_midpoint,
|
||||
} = update
|
||||
{
|
||||
self.active_marker_index = active_marker_index;
|
||||
self.active_marker_is_midpoint = active_marker_is_midpoint;
|
||||
if let Some(index) = active_marker_index
|
||||
&& let Some(gradient) = &self.gradient
|
||||
&& let Some(color) = gradient.color.get(index as usize).copied()
|
||||
{
|
||||
self.adopt_color(color);
|
||||
self.snapshot_old();
|
||||
}
|
||||
self.send_layouts(responses);
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(mut gradient) = self.gradient.clone() else { return };
|
||||
|
||||
match update {
|
||||
SpectrumInputUpdate::MoveMarker { index, position } => {
|
||||
let new_index = gradient.move_stop(index as usize, position);
|
||||
if Some(index) == self.active_marker_index {
|
||||
self.active_marker_index = Some(new_index as u32);
|
||||
}
|
||||
}
|
||||
SpectrumInputUpdate::MoveMidpoint { index, position } => {
|
||||
if let Some(midpoint) = gradient.midpoint.get_mut(index as usize) {
|
||||
*midpoint = position.clamp(MIN_MIDPOINT, MAX_MIDPOINT);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
SpectrumInputUpdate::InsertMarker { position } => {
|
||||
let new_index = gradient.insert_stop(position);
|
||||
self.active_marker_index = Some(new_index as u32);
|
||||
self.active_marker_is_midpoint = false;
|
||||
if let Some(color) = gradient.color.get(new_index).copied() {
|
||||
self.adopt_color(color);
|
||||
self.snapshot_old();
|
||||
}
|
||||
}
|
||||
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() {
|
||||
return;
|
||||
}
|
||||
gradient.remove(index as usize);
|
||||
let new_active = (index as usize).min(gradient.position.len() - 1);
|
||||
self.active_marker_index = Some(new_active as u32);
|
||||
self.active_marker_is_midpoint = false;
|
||||
if let Some(color) = gradient.color.get(new_active).copied() {
|
||||
self.adopt_color(color);
|
||||
self.snapshot_old();
|
||||
}
|
||||
}
|
||||
SpectrumInputUpdate::ResetMidpoint { index } => {
|
||||
gradient.reset_midpoint(index as usize);
|
||||
}
|
||||
SpectrumInputUpdate::ResetMarker { index } => {
|
||||
let i = index as usize;
|
||||
let count = gradient.position.len();
|
||||
if i >= count {
|
||||
return;
|
||||
}
|
||||
// Each stop's "natural" position is its evenly-spaced fraction along 0..1, e.g., for 5 stops: 0, 0.25, 0.5, 0.75, 1. Falls back to the midpoint between neighbors when the natural position would push the stop past another.
|
||||
let left = if i == 0 { 0. } else { gradient.position[i - 1] };
|
||||
let right = gradient.position.get(i + 1).copied().unwrap_or(1.);
|
||||
let natural = if count <= 1 { 0. } else { i as f64 / (count - 1) as f64 };
|
||||
let new_position = if (left..=right).contains(&natural) { natural } else { (left + right) / 2. };
|
||||
let new_index = gradient.move_stop(i, new_position);
|
||||
if Some(index) == self.active_marker_index {
|
||||
self.active_marker_index = Some(new_index as u32);
|
||||
}
|
||||
}
|
||||
SpectrumInputUpdate::ActiveMarker { .. } => unreachable!("handled above"),
|
||||
}
|
||||
|
||||
self.gradient = Some(gradient.clone());
|
||||
let fill_choice = FillChoice::Gradient(gradient);
|
||||
responses.add(FrontendMessage::ColorPickerColorChanged {
|
||||
value: FillChoiceUI::from(&fill_choice),
|
||||
});
|
||||
self.send_layouts(responses);
|
||||
}
|
||||
|
||||
fn pickers_and_gradient_layout(&self) -> Layout {
|
||||
let mut groups = Vec::new();
|
||||
|
||||
// Visual H/S/V/A pickers
|
||||
groups.push(LayoutGroup::row(vec![
|
||||
VisualColorPickersInput::default()
|
||||
.hue(self.hue)
|
||||
.saturation(self.saturation)
|
||||
.value(self.value)
|
||||
.alpha(self.alpha)
|
||||
.is_none(self.is_none)
|
||||
.disabled(self.disabled)
|
||||
.on_update(|update: &VisualColorPickersInputUpdate| ColorPickerMessage::VisualUpdate { update: update.clone() }.into())
|
||||
.on_commit(|_| ColorPickerMessage::CommitTransaction.into())
|
||||
.widget_instance(),
|
||||
]));
|
||||
|
||||
// Gradient editor (only present when the picker is in gradient mode)
|
||||
if let Some(gradient) = &self.gradient {
|
||||
// For gradient editing, the markers' handle colors mirror their gradient stop colors
|
||||
let markers = gradient.iter().map(|stop| SpectrumMarker::new(stop.position, stop.midpoint, stop.color)).collect();
|
||||
let mut row_widgets = vec![
|
||||
SpectrumInput::new(GradientStopsUI::from(gradient))
|
||||
.markers(markers)
|
||||
.active_marker_index(self.active_marker_index)
|
||||
.active_marker_is_midpoint(self.active_marker_is_midpoint)
|
||||
.show_midpoints(true)
|
||||
.allow_insert(!self.disabled)
|
||||
.allow_delete(!self.disabled)
|
||||
.allow_reorder(true)
|
||||
.disabled(self.disabled)
|
||||
.on_update(|update: &SpectrumInputUpdate| ColorPickerMessage::GradientUpdate { update: update.clone() }.into())
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
if let Some(active) = self.active_marker_index {
|
||||
let active_index = active as usize;
|
||||
let position_value = if self.active_marker_is_midpoint {
|
||||
gradient.midpoint.get(active_index).copied().unwrap_or(0.)
|
||||
} else {
|
||||
gradient.position.get(active_index).copied().unwrap_or(0.)
|
||||
};
|
||||
let is_midpoint = self.active_marker_is_midpoint;
|
||||
let captured_index = active;
|
||||
row_widgets.push(
|
||||
NumberInput::new(Some(position_value * 100.))
|
||||
.disabled(self.disabled)
|
||||
.display_decimal_places(0)
|
||||
.min(if is_midpoint { 1. } else { 0. })
|
||||
.max(if is_midpoint { 99. } else { 100. })
|
||||
.unit("%")
|
||||
.on_update(move |widget: &NumberInput| {
|
||||
let Some(new_value) = widget.value else {
|
||||
return Message::NoOp;
|
||||
};
|
||||
let update = if is_midpoint {
|
||||
SpectrumInputUpdate::MoveMidpoint {
|
||||
index: captured_index,
|
||||
position: new_value / 100.,
|
||||
}
|
||||
} else {
|
||||
SpectrumInputUpdate::MoveMarker {
|
||||
index: captured_index,
|
||||
position: new_value / 100.,
|
||||
}
|
||||
};
|
||||
ColorPickerMessage::GradientUpdate { update }.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
);
|
||||
}
|
||||
|
||||
groups.push(LayoutGroup::row(row_widgets));
|
||||
}
|
||||
|
||||
Layout(groups)
|
||||
}
|
||||
|
||||
fn details_layout(&self) -> Layout {
|
||||
let new_color = self.current_color();
|
||||
let old_color = self.old_color();
|
||||
|
||||
let hex_value = new_color.map(|c| color_to_hex_optional_alpha(&c)).unwrap_or_else(|| "-".to_string());
|
||||
// RGB readouts display sRGB byte values to the user, so we convert from linear-light to gamma here before quantizing.
|
||||
let rgb_255 = new_color.map(|c| {
|
||||
let [r, g, b, _] = c.to_gamma_srgb_channels();
|
||||
(r as f64 * 255., g as f64 * 255., b as f64 * 255.)
|
||||
});
|
||||
|
||||
// Epsilon comparison since the picker round-trips through HSV
|
||||
let differs = match (new_color, old_color) {
|
||||
(Some(a), Some(b)) => {
|
||||
const EPSILON: f32 = 1e-6;
|
||||
(a.r() - b.r()).abs() >= EPSILON || (a.g() - b.g()).abs() >= EPSILON || (a.b() - b.b()).abs() >= EPSILON || (a.a() - b.a()).abs() >= EPSILON
|
||||
}
|
||||
(None, None) => false,
|
||||
_ => true,
|
||||
};
|
||||
let outline_amount = contrasting_outline_factor(new_color).max(contrasting_outline_factor(old_color));
|
||||
|
||||
let mut groups = Vec::new();
|
||||
|
||||
// New/old comparison swatch with swap button
|
||||
groups.push(LayoutGroup::row(vec![
|
||||
ColorComparisonInput::new(new_color.map(SRGBA8::from), old_color.map(SRGBA8::from))
|
||||
.is_none(self.is_none)
|
||||
.old_is_none(self.old_is_none)
|
||||
.disabled(self.disabled)
|
||||
.differs(differs)
|
||||
.outline_amount(outline_amount)
|
||||
.on_update(|_: &()| ColorPickerMessage::SwapNewWithOld.into())
|
||||
.widget_instance(),
|
||||
]));
|
||||
|
||||
// Hex
|
||||
groups.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("Hex").tooltip_label("Hex Color Code").tooltip_description(HEX_DESCRIPTION).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
TextInput::new(hex_value)
|
||||
.centered(true)
|
||||
.disabled(self.disabled)
|
||||
.tooltip_label("Hex Color Code")
|
||||
.tooltip_description(HEX_DESCRIPTION)
|
||||
.on_update(|widget: &TextInput| ColorPickerMessage::SetHexCode { code: widget.value.clone() }.into())
|
||||
.widget_instance(),
|
||||
]));
|
||||
|
||||
// RGB
|
||||
groups.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("RGB").tooltip_label("Red/Green/Blue").tooltip_description("Integers 0–255.").widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
rgb_input(RgbChannel::Red, rgb_255.map(|(r, _, _)| r), "Red Channel", self.disabled),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
rgb_input(RgbChannel::Green, rgb_255.map(|(_, g, _)| g), "Green Channel", self.disabled),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
rgb_input(RgbChannel::Blue, rgb_255.map(|(_, _, b)| b), "Blue Channel", self.disabled),
|
||||
]));
|
||||
|
||||
// HSV
|
||||
groups.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("HSV")
|
||||
.tooltip_label("Hue/Saturation/Value")
|
||||
.tooltip_description("Also known as Hue/Saturation/Brightness (HSB). Not to be confused with Hue/Saturation/Lightness (HSL), a different color model.")
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
hsv_input(
|
||||
HsvChannel::Hue,
|
||||
if self.is_none { None } else { Some(self.hue * 360.) },
|
||||
360.,
|
||||
"°",
|
||||
"Hue Component",
|
||||
HUE_DESCRIPTION,
|
||||
self.disabled,
|
||||
),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
hsv_input(
|
||||
HsvChannel::Saturation,
|
||||
if self.is_none { None } else { Some(self.saturation * 100.) },
|
||||
100.,
|
||||
"%",
|
||||
"Saturation Component",
|
||||
SATURATION_DESCRIPTION,
|
||||
self.disabled,
|
||||
),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
hsv_input(
|
||||
HsvChannel::Value,
|
||||
if self.is_none { None } else { Some(self.value * 100.) },
|
||||
100.,
|
||||
"%",
|
||||
"Value Component",
|
||||
VALUE_DESCRIPTION,
|
||||
self.disabled,
|
||||
),
|
||||
]));
|
||||
|
||||
// Alpha
|
||||
groups.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("Alpha").tooltip_label("Alpha").tooltip_description(ALPHA_DESCRIPTION).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
NumberInput::new(if self.is_none { None } else { Some(self.alpha * 100.) })
|
||||
.disabled(self.disabled)
|
||||
.min(0.)
|
||||
.max(100.)
|
||||
.mode_range()
|
||||
.unit("%")
|
||||
.display_decimal_places(1)
|
||||
.tooltip_label("Alpha")
|
||||
.tooltip_description(ALPHA_DESCRIPTION)
|
||||
.on_update(|widget: &NumberInput| ColorPickerMessage::SetAlphaPercent { value: widget.value }.into())
|
||||
.on_commit(|_| ColorPickerMessage::StartTransaction.into())
|
||||
.widget_instance(),
|
||||
]));
|
||||
|
||||
// Color presets (None / Black / White / pure colors / eyedropper)
|
||||
groups.push(LayoutGroup::row(vec![
|
||||
ColorPresetsInput::default()
|
||||
.disabled(self.disabled)
|
||||
.show_none_option(self.allow_none && self.gradient.is_none())
|
||||
.on_update(|update: &ColorPresetsInputUpdate| match update {
|
||||
ColorPresetsInputUpdate::Preset(fill_choice) => ColorPickerMessage::PickPreset {
|
||||
preset: FillChoice::from(fill_choice),
|
||||
}
|
||||
.into(),
|
||||
ColorPresetsInputUpdate::EyedropperColorCode(code) => ColorPickerMessage::EyedropperColorCode { code: code.clone() }.into(),
|
||||
})
|
||||
.widget_instance(),
|
||||
]));
|
||||
|
||||
Layout(groups)
|
||||
}
|
||||
}
|
||||
|
||||
fn rgb_input(channel: RgbChannel, value: Option<f64>, tooltip_label: &'static str, disabled: bool) -> WidgetInstance {
|
||||
NumberInput::new(value)
|
||||
.disabled(disabled)
|
||||
.min(0.)
|
||||
.max(255.)
|
||||
.min_width(1)
|
||||
.display_decimal_places(0)
|
||||
.tooltip_label(tooltip_label)
|
||||
.tooltip_description("Integers 0–255.")
|
||||
.on_update(move |widget: &NumberInput| ColorPickerMessage::SetChannelRgb { channel, value: widget.value }.into())
|
||||
.on_commit(|_| ColorPickerMessage::StartTransaction.into())
|
||||
.widget_instance()
|
||||
}
|
||||
|
||||
fn hsv_input(channel: HsvChannel, value: Option<f64>, max: f64, unit: &'static str, tooltip_label: &'static str, tooltip_description: &'static str, disabled: bool) -> WidgetInstance {
|
||||
NumberInput::new(value)
|
||||
.disabled(disabled)
|
||||
.min(0.)
|
||||
.max(max)
|
||||
.min_width(1)
|
||||
.unit(unit)
|
||||
.display_decimal_places(1)
|
||||
.tooltip_label(tooltip_label)
|
||||
.tooltip_description(tooltip_description)
|
||||
.on_update(move |widget: &NumberInput| ColorPickerMessage::SetChannelHsv { channel, value: widget.value }.into())
|
||||
.on_commit(|_| ColorPickerMessage::StartTransaction.into())
|
||||
.widget_instance()
|
||||
}
|
||||
|
||||
const HEX_DESCRIPTION: &str = "Color code in hexadecimal format. 6 digits if opaque, 8 with alpha. Accepts input of CSS color values including named colors.";
|
||||
const HUE_DESCRIPTION: &str = "The shade along the spectrum of the rainbow.";
|
||||
const SATURATION_DESCRIPTION: &str = "The vividness from grayscale to full color.";
|
||||
const VALUE_DESCRIPTION: &str = "The brightness from black to full color.";
|
||||
const ALPHA_DESCRIPTION: &str = "The level of translucency, from transparent (0%) to opaque (100%).";
|
||||
|
||||
/// The popover's background color as sRGB gamma-encoded channels (the `--color-2-mildblack` design token, `#222`).
|
||||
/// Used by the comparison swatch's outline computation to brighten the inset border for colors close to this background.
|
||||
const POPOVER_BACKGROUND_GAMMA_CHANNELS: [f32; 4] = [0x22 as f32 / 255., 0x22 as f32 / 255., 0x22 as f32 / 255., 1.];
|
||||
/// The luminance window within which a color is considered close enough to the popover background
|
||||
/// to warrant an outline. Mirrors the `proximityRange` argument the legacy frontend passed to `contrastingOutlineFactor`.
|
||||
const OUTLINE_PROXIMITY_RANGE: f64 = 0.01;
|
||||
|
||||
/// Returns a 0..1 outline strength for the comparison swatch, growing toward 1 as the color's luminance and saturation
|
||||
/// both approach the popover background's luminance, when a color would otherwise visually blend into the popover.
|
||||
fn contrasting_outline_factor(color: Option<Color>) -> f64 {
|
||||
let Some(color) = color else { return 0. };
|
||||
|
||||
// WCAG-style relative luminance, with alpha composited over white in sRGB gamma space (matching the perceptual intent of `SRGBA8::contrasting_text_color`).
|
||||
let luminance_from_gamma_channels = |[r, g, b, a]: [f32; 4]| -> f64 {
|
||||
let inv_a = 1. - a;
|
||||
Color::from_gamma_srgb_channels(inv_a + r * a, inv_a + g * a, inv_a + b * a, 1.).luminance_rec_709() as f64
|
||||
};
|
||||
|
||||
let color_gamma_channels = color.to_gamma_srgb_channels();
|
||||
let distance = (luminance_from_gamma_channels(POPOVER_BACKGROUND_GAMMA_CHANNELS) - luminance_from_gamma_channels(color_gamma_channels))
|
||||
.abs()
|
||||
.max(0.);
|
||||
let proximity = 1. - (distance / OUTLINE_PROXIMITY_RANGE).min(1.);
|
||||
let [_, saturation, _, _] = color.to_hsva();
|
||||
proximity * (1. - saturation as f64)
|
||||
}
|
||||
|
||||
/// Format a linear `Color` as a `#`-prefixed hex string, including the alpha component only if it's not fully opaque.
|
||||
fn color_to_hex_optional_alpha(color: &Color) -> String {
|
||||
SRGBA8::from(*color).to_css_hex()
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
mod color_picker_message;
|
||||
pub mod color_picker_message_handler;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use color_picker_message::{ColorPickerMessage, ColorPickerMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use color_picker_message_handler::ColorPickerMessageHandler;
|
||||
@@ -126,7 +126,7 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
||||
DialogMessage::RequestNewDocumentDialog => {
|
||||
self.on_dismiss = Some(DialogMessage::Close.into());
|
||||
self.new_document_dialog = NewDocumentDialogMessageHandler {
|
||||
name: portfolio.generate_new_document_name(None),
|
||||
name: portfolio.generate_new_document_name(),
|
||||
infinite: false,
|
||||
dimensions: glam::UVec2::new(1920, 1080),
|
||||
};
|
||||
|
||||
@@ -7,10 +7,6 @@ pub enum ExportDialogMessage {
|
||||
FileType { file_type: FileType },
|
||||
ScaleFactor { factor: f64 },
|
||||
ExportBounds { bounds: ExportBounds },
|
||||
Animated { animated: bool },
|
||||
Fps { fps: f64 },
|
||||
StartSeconds { start: f64 },
|
||||
EndSeconds { end: f64 },
|
||||
|
||||
Submit,
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::messages::frontend::utility_types::{AnimationExport, ExportBounds, FileType};
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::prelude::*;
|
||||
@@ -16,10 +16,6 @@ pub struct ExportDialogMessageHandler {
|
||||
pub bounds: ExportBounds,
|
||||
pub artboards: HashMap<LayerNodeIdentifier, String>,
|
||||
pub has_selection: bool,
|
||||
pub animated: bool,
|
||||
pub fps: f64,
|
||||
pub start_seconds: f64,
|
||||
pub end_seconds: f64,
|
||||
}
|
||||
|
||||
impl Default for ExportDialogMessageHandler {
|
||||
@@ -30,32 +26,10 @@ impl Default for ExportDialogMessageHandler {
|
||||
bounds: Default::default(),
|
||||
artboards: Default::default(),
|
||||
has_selection: false,
|
||||
animated: false,
|
||||
fps: 30.,
|
||||
start_seconds: 0.,
|
||||
end_seconds: 1.,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Upper bound on how many frames a single animation export will queue. Each frame is rendered then held
|
||||
/// in memory until the whole batch ships to the frontend, so we cap to avoid pathological allocations from
|
||||
/// large time ranges. Tuned for typical animation lengths (10k frames is ~5.5 min at 30 fps, ~2.8 min at 60 fps).
|
||||
pub const ANIMATION_EXPORT_MAX_FRAMES: u32 = 10_000;
|
||||
|
||||
impl ExportDialogMessageHandler {
|
||||
fn total_frames(&self) -> u32 {
|
||||
// Sanitize against non-finite values that could otherwise propagate into `Duration::from_secs_f64` and panic.
|
||||
if !self.fps.is_finite() || self.fps <= 0. || !self.start_seconds.is_finite() || !self.end_seconds.is_finite() {
|
||||
return 1;
|
||||
}
|
||||
let duration = (self.end_seconds - self.start_seconds).max(0.);
|
||||
// `ceil` so a duration slightly longer than a frame multiple still gets the trailing frame.
|
||||
let raw = (duration * self.fps).ceil() as i64;
|
||||
raw.clamp(1, ANIMATION_EXPORT_MAX_FRAMES as i64) as u32
|
||||
}
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for ExportDialogMessageHandler {
|
||||
fn process_message(&mut self, message: ExportDialogMessage, responses: &mut VecDeque<Message>, context: ExportDialogMessageContext) {
|
||||
@@ -65,20 +39,6 @@ impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for Exp
|
||||
ExportDialogMessage::FileType { file_type } => self.file_type = file_type,
|
||||
ExportDialogMessage::ScaleFactor { factor } => self.scale_factor = factor,
|
||||
ExportDialogMessage::ExportBounds { bounds } => self.bounds = bounds,
|
||||
ExportDialogMessage::Animated { animated } => self.animated = animated,
|
||||
ExportDialogMessage::Fps { fps } => {
|
||||
// Reject non-finite/non-positive values so we never feed NaN or infinity into duration math downstream.
|
||||
self.fps = if fps.is_finite() && fps > 0. { fps } else { 0.001 };
|
||||
}
|
||||
ExportDialogMessage::StartSeconds { start } => {
|
||||
self.start_seconds = if start.is_finite() { start.max(0.) } else { 0. };
|
||||
if self.end_seconds < self.start_seconds {
|
||||
self.end_seconds = self.start_seconds;
|
||||
}
|
||||
}
|
||||
ExportDialogMessage::EndSeconds { end } => {
|
||||
self.end_seconds = if end.is_finite() { end.max(self.start_seconds) } else { self.start_seconds };
|
||||
}
|
||||
|
||||
ExportDialogMessage::Submit => {
|
||||
// Fall back to "All Artwork" if "Selection" was chosen but nothing is currently selected
|
||||
@@ -92,13 +52,6 @@ impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for Exp
|
||||
ExportBounds::Artboard(layer) => self.artboards.get(&layer).cloned(),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let animation = self.animated.then(|| AnimationExport {
|
||||
fps: self.fps,
|
||||
start_seconds: self.start_seconds,
|
||||
total_frames: self.total_frames(),
|
||||
});
|
||||
|
||||
responses.add_front(PortfolioMessage::SubmitDocumentExport {
|
||||
name: portfolio.active_document().map(|document| document.name.clone()).unwrap_or_default(),
|
||||
file_type: self.file_type,
|
||||
@@ -106,7 +59,6 @@ impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for Exp
|
||||
bounds,
|
||||
artboard_name,
|
||||
artboard_count: self.artboards.len(),
|
||||
animation,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -211,74 +163,6 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
||||
DropdownInput::new(entries).selected_index(Some(index as u32)).widget_instance(),
|
||||
];
|
||||
|
||||
let animation_checkbox_id = CheckboxId::new();
|
||||
let animation_toggle = vec![
|
||||
TextLabel::new("Animation").table_align(true).min_width(100).for_checkbox(animation_checkbox_id).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
CheckboxInput::new(self.animated)
|
||||
.on_update(|checkbox_input: &CheckboxInput| ExportDialogMessage::Animated { animated: checkbox_input.checked }.into())
|
||||
.for_label(animation_checkbox_id)
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let mut layout_groups = vec![
|
||||
LayoutGroup::row(export_type),
|
||||
LayoutGroup::row(resolution),
|
||||
LayoutGroup::row(export_area),
|
||||
LayoutGroup::row(animation_toggle),
|
||||
];
|
||||
|
||||
if self.animated {
|
||||
let fps_row = vec![
|
||||
TextLabel::new("FPS").table_align(true).min_width(100).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(self.fps))
|
||||
.unit(" fps")
|
||||
.min(0.001)
|
||||
.max(1000.)
|
||||
.increment_step(1.)
|
||||
.on_update(|number_input: &NumberInput| ExportDialogMessage::Fps { fps: number_input.value.unwrap() }.into())
|
||||
.min_width(200)
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let start_row = vec![
|
||||
TextLabel::new("Start").table_align(true).min_width(100).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(self.start_seconds))
|
||||
.unit(" sec")
|
||||
.min(0.)
|
||||
.increment_step(0.1)
|
||||
.on_update(|number_input: &NumberInput| ExportDialogMessage::StartSeconds { start: number_input.value.unwrap() }.into())
|
||||
.min_width(200)
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let end_row = vec![
|
||||
TextLabel::new("End").table_align(true).min_width(100).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(self.end_seconds))
|
||||
.unit(" sec")
|
||||
.min(self.start_seconds)
|
||||
.increment_step(0.1)
|
||||
.on_update(|number_input: &NumberInput| ExportDialogMessage::EndSeconds { end: number_input.value.unwrap() }.into())
|
||||
.min_width(200)
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let frame_count = self.total_frames();
|
||||
let frames_row = vec![
|
||||
TextLabel::new("Frames").table_align(true).min_width(100).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextLabel::new(format!("{frame_count} frame{}", if frame_count == 1 { "" } else { "s" })).widget_instance(),
|
||||
];
|
||||
|
||||
layout_groups.push(LayoutGroup::row(fps_row));
|
||||
layout_groups.push(LayoutGroup::row(start_row));
|
||||
layout_groups.push(LayoutGroup::row(end_row));
|
||||
layout_groups.push(LayoutGroup::row(frames_row));
|
||||
}
|
||||
|
||||
Layout(layout_groups)
|
||||
Layout(vec![LayoutGroup::row(export_type), LayoutGroup::row(resolution), LayoutGroup::row(export_area)])
|
||||
}
|
||||
}
|
||||
+8
-14
@@ -1,7 +1,7 @@
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::prelude::*;
|
||||
use glam::UVec2;
|
||||
use glam::{IVec2, UVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
|
||||
@@ -35,22 +35,14 @@ impl MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHa
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetDisplayNameImpl {
|
||||
node_id,
|
||||
network_path: Vec::new(),
|
||||
alias: "Background".to_string(),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetLocked {
|
||||
node_id,
|
||||
network_path: Vec::new(),
|
||||
locked: true,
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetLocked { node_id, locked: true });
|
||||
} else if self.dimensions.x > 0 && self.dimensions.y > 0 {
|
||||
// Finite canvas: create an artboard with the specified dimensions
|
||||
responses.add(GraphOperationMessage::NewArtboard {
|
||||
id: NodeId::new(),
|
||||
location: glam::DVec2::ZERO,
|
||||
dimensions: self.dimensions.as_dvec2(),
|
||||
background: Color::WHITE,
|
||||
clip: true,
|
||||
artboard: graphene_std::Artboard::new(IVec2::ZERO, self.dimensions.as_ivec2()),
|
||||
});
|
||||
responses.add(NavigationMessage::CanvasPan { delta: self.dimensions.as_dvec2() });
|
||||
}
|
||||
@@ -58,10 +50,12 @@ impl MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHa
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(ViewportMessage::RepropagateUpdate);
|
||||
|
||||
responses.add(DocumentMessage::DeselectAllLayers);
|
||||
|
||||
responses.add(DeferMessage::AfterNavigationReady {
|
||||
messages: vec![DocumentMessage::ZoomCanvasToFitAll.into(), PortfolioMessage::AutoSaveActiveDocument.into()],
|
||||
messages: vec![
|
||||
DocumentMessage::ZoomCanvasToFitAll.into(),
|
||||
DocumentMessage::DeselectAllLayers.into(),
|
||||
PortfolioMessage::AutoSaveActiveDocument.into(),
|
||||
],
|
||||
});
|
||||
|
||||
responses.add(DocumentMessage::MarkAsSaved);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::IconName;
|
||||
use super::utility_types::{MouseCursorIcon, PersistedState};
|
||||
use crate::messages::app_window::app_window_message_handler::AppWindowPlatform;
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, ExportAnimationFrame, EyedropperPreviewImage};
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage};
|
||||
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{
|
||||
@@ -13,10 +13,9 @@ use crate::messages::portfolio::utility_types::WorkspacePanelLayout;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::tool_messages::eyedropper_tool::PrimarySecondary;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::text::Font;
|
||||
use graphene_std::vector::style::FillChoiceUI;
|
||||
use graphene_std::raster::color::Color;
|
||||
use graphene_std::text::{Font, TextAlign};
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
@@ -51,9 +50,7 @@ pub enum FrontendMessage {
|
||||
max_width: Option<f64>,
|
||||
#[serde(rename = "maxHeight")]
|
||||
max_height: Option<f64>,
|
||||
align: String,
|
||||
#[serde(rename = "alignLast")]
|
||||
align_last: String,
|
||||
align: TextAlign,
|
||||
},
|
||||
DisplayEditableTextboxUpdateFontData {
|
||||
#[serde(rename = "fontData")]
|
||||
@@ -107,23 +104,6 @@ pub enum FrontendMessage {
|
||||
mime: String,
|
||||
size: (f64, f64),
|
||||
},
|
||||
/// Export one or more animation frames as a bundle.
|
||||
/// On web, the frontend zips the frames into an uncompressed `.zip` and triggers a single download.
|
||||
/// On desktop, the wrapper intercepts this and writes each frame as a separate file to a user-chosen folder.
|
||||
TriggerExportAnimation {
|
||||
/// Base name without the index suffix or extension (e.g. "MyDocument" or "MyDocument - Artboard 1").
|
||||
name: String,
|
||||
/// File extension without leading dot ("png", "jpg", "svg").
|
||||
extension: String,
|
||||
/// MIME type matching the extension (e.g. "image/png").
|
||||
mime: String,
|
||||
/// Pixel size of each rasterized frame, used when the frontend needs to canvas-rasterize from SVG.
|
||||
size: (f64, f64),
|
||||
/// Document folder, used as a default location for the desktop save dialog.
|
||||
folder: Option<PathBuf>,
|
||||
/// One entry per frame, in playback order. Each frame is either an SVG string or pre-encoded bytes.
|
||||
frames: Vec<ExportAnimationFrame>,
|
||||
},
|
||||
TriggerFetchAndOpenDocument {
|
||||
name: String,
|
||||
filename: String,
|
||||
@@ -159,11 +139,6 @@ pub enum FrontendMessage {
|
||||
preferences: PreferencesMessageHandler,
|
||||
},
|
||||
TriggerTextCommit,
|
||||
/// Asks the frontend to enter inline-rename mode for a layer in the graph view.
|
||||
TriggerEditLayerNameInGraph {
|
||||
#[serde(rename = "nodeId")]
|
||||
node_id: NodeId,
|
||||
},
|
||||
TriggerVisitLink {
|
||||
url: String,
|
||||
},
|
||||
@@ -184,17 +159,9 @@ pub enum FrontendMessage {
|
||||
document_id: DocumentId,
|
||||
},
|
||||
UpdateGradientStopColorPickerPosition {
|
||||
color: SRGBA8, // TODO: Color (without `none`) -> Color (with `none`)
|
||||
color: Color, // TODO: Color (without `none`) -> Color (with `none`)
|
||||
position: (f64, f64),
|
||||
},
|
||||
/// The Rust color picker handler picked a new color/gradient. The frontend `<ColorPicker />` forwards this as its `colorOrGradient` event.
|
||||
ColorPickerColorChanged {
|
||||
value: FillChoiceUI,
|
||||
},
|
||||
/// The Rust color picker handler is starting an undo transaction. The frontend `<ColorPicker />` forwards this as its `startHistoryTransaction` event.
|
||||
ColorPickerStartHistoryTransaction,
|
||||
/// The Rust color picker handler is committing the in-flight undo transaction. The frontend `<ColorPicker />` forwards this as its `commitHistoryTransaction` event.
|
||||
ColorPickerCommitHistoryTransaction,
|
||||
UpdateImportsExports {
|
||||
/// If the primary import is not visible, then it is None.
|
||||
imports: Vec<Option<FrontendGraphOutput>>,
|
||||
@@ -258,7 +225,7 @@ pub enum FrontendMessage {
|
||||
svg: String,
|
||||
},
|
||||
UpdateImageData {
|
||||
image_data: Vec<(u64, Image<SRGBA8>)>,
|
||||
image_data: Vec<(u64, Image<Color>)>,
|
||||
},
|
||||
UpdateDocumentLayerDetails {
|
||||
data: LayerPanelEntry,
|
||||
@@ -272,10 +239,6 @@ pub enum FrontendMessage {
|
||||
spacing: f64,
|
||||
interval: f64,
|
||||
visible: bool,
|
||||
tilt: f64,
|
||||
flip: bool,
|
||||
#[serde(rename = "selectionQuad")]
|
||||
selection_quad: Option<[(f64, f64); 4]>,
|
||||
},
|
||||
UpdateDocumentScrollbars {
|
||||
position: (f64, f64),
|
||||
@@ -379,8 +342,6 @@ pub enum FrontendMessage {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
WindowHide,
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
WindowFocus,
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
WindowHideOthers,
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
WindowShowAll,
|
||||
|
||||
@@ -14,7 +14,7 @@ pub struct DocumentInfo {
|
||||
pub is_saved: bool,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints, from_wasm_abi))]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
|
||||
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PersistedState {
|
||||
pub documents: Vec<DocumentInfo>,
|
||||
@@ -59,14 +59,6 @@ impl FileType {
|
||||
FileType::Svg => "image/svg+xml",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_extension(self) -> &'static str {
|
||||
match self {
|
||||
FileType::Png => "png",
|
||||
FileType::Jpg => "jpg",
|
||||
FileType::Svg => "svg",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -78,56 +70,6 @@ pub enum ExportBounds {
|
||||
Artboard(LayerNodeIdentifier),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct AnimationExport {
|
||||
pub fps: f64,
|
||||
pub start_seconds: f64,
|
||||
pub total_frames: u32,
|
||||
}
|
||||
|
||||
impl Default for AnimationExport {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
fps: 30.,
|
||||
start_seconds: 0.,
|
||||
total_frames: 30,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AnimationExport {
|
||||
pub fn frame_time_seconds(&self, frame_index: u32) -> f64 {
|
||||
self.start_seconds + frame_index as f64 / self.fps
|
||||
}
|
||||
}
|
||||
|
||||
/// One frame of a multi-frame animation export, in playback order.
|
||||
/// `Svg` is text that the frontend can save directly (for SVG export) or rasterize via canvas (for PNG/JPG export).
|
||||
/// `Bytes` is already-encoded image bytes from the GPU export path, ready to write directly.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ExportAnimationFrame {
|
||||
Svg(String),
|
||||
Bytes(serde_bytes::ByteBuf),
|
||||
}
|
||||
|
||||
/// Replace characters that have special meaning in filesystem paths (or are otherwise unsafe in filenames) with `_`.
|
||||
/// Used to neutralize user-controlled strings — document names, artboard names — before they become export filenames,
|
||||
/// so a name like `..\evil` or `foo/bar` can't escape the export folder or create nested zip entries.
|
||||
pub fn sanitize_filename_component(name: &str) -> String {
|
||||
let cleaned: String = name
|
||||
.chars()
|
||||
.map(|c| match c {
|
||||
'/' | '\\' | ':' | '*' | '?' | '<' | '>' | '|' | '"' | '\0' => '_',
|
||||
c if c.is_control() => '_',
|
||||
c => c,
|
||||
})
|
||||
.collect();
|
||||
// Strip leading/trailing dots and whitespace; Windows treats trailing `.` / ` ` as hidden and `..` is the parent dir.
|
||||
let trimmed = cleaned.trim().trim_matches('.').trim();
|
||||
if trimmed.is_empty() { "Untitled".to_string() } else { trimmed.to_string() }
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct EyedropperPreviewImage {
|
||||
|
||||
@@ -26,8 +26,4 @@ pub enum LayoutMessage {
|
||||
widget_id: WidgetId,
|
||||
value: serde_json::Value,
|
||||
},
|
||||
WidgetValueDragDrop {
|
||||
layout_target: LayoutTarget,
|
||||
widget_id: WidgetId,
|
||||
},
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::vector::style::FillChoiceUI;
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -62,19 +61,6 @@ impl MessageHandler<LayoutMessage, LayoutMessageContext<'_>> for LayoutMessageHa
|
||||
LayoutMessage::WidgetValueUpdate { layout_target, widget_id, value } => {
|
||||
self.handle_widget_callback(layout_target, widget_id, value, WidgetValueAction::Update, responses);
|
||||
}
|
||||
LayoutMessage::WidgetValueDragDrop { layout_target, widget_id } => {
|
||||
let Some(layout) = self.layouts.get_mut(layout_target as usize) else {
|
||||
warn!("WidgetValueDragDrop referenced an invalid layout. `widget_id: {widget_id}`, `layout_target: {layout_target:?}`");
|
||||
return;
|
||||
};
|
||||
let Some(widget_instance) = layout.iter_mut().find(|widget| widget.widget_id == widget_id) else {
|
||||
warn!("WidgetValueDragDrop referenced an invalid widget ID. `widget_id: {widget_id}`, `layout_target: {layout_target:?}`");
|
||||
return;
|
||||
};
|
||||
if let Widget::IconButton(icon_button) = &mut *widget_instance.widget {
|
||||
responses.add((icon_button.on_drag_drop.callback)(icon_button));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,22 +102,22 @@ impl LayoutMessageHandler {
|
||||
}
|
||||
LayoutGroup::Table(WidgetTable { rows, .. }) => {
|
||||
for (row_index, row) in rows.iter().enumerate() {
|
||||
for (value_index, value) in row.iter().enumerate() {
|
||||
for (cell_index, cell) in row.iter().enumerate() {
|
||||
// Return if this is the correct ID
|
||||
if value.widget_id == widget_id {
|
||||
if cell.widget_id == widget_id {
|
||||
widget_path.push(row_index);
|
||||
widget_path.push(value_index);
|
||||
return Some((value, widget_path));
|
||||
widget_path.push(cell_index);
|
||||
return Some((cell, widget_path));
|
||||
}
|
||||
|
||||
if let Widget::PopoverButton(popover) = &*value.widget {
|
||||
if let Widget::PopoverButton(popover) = &*cell.widget {
|
||||
stack.extend(
|
||||
popover
|
||||
.popover_layout
|
||||
.0
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(child, val)| ([widget_path.as_slice(), &[row_index, value_index, child]].concat(), val)),
|
||||
.map(|(child, val)| ([widget_path.as_slice(), &[row_index, cell_index, child]].concat(), val)),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -181,38 +167,31 @@ impl LayoutMessageHandler {
|
||||
};
|
||||
responses.add(callback_message);
|
||||
}
|
||||
Widget::ColorComparisonInput(color_comparison_input) => {
|
||||
let callback_message = match action {
|
||||
WidgetValueAction::Commit => (color_comparison_input.on_commit.callback)(&()),
|
||||
WidgetValueAction::Update => (color_comparison_input.on_update.callback)(&()),
|
||||
};
|
||||
|
||||
responses.add(callback_message);
|
||||
}
|
||||
Widget::ColorInput(color_button) => {
|
||||
let callback_message = match action {
|
||||
WidgetValueAction::Commit => (color_button.on_commit.callback)(&()),
|
||||
WidgetValueAction::Update => {
|
||||
let Ok(fill_choice_ui) = serde_json::from_value::<FillChoiceUI>(value) else {
|
||||
warn!("ColorInput update was not able to be parsed as FillChoiceUI: {color_button:?}");
|
||||
let Ok(fill_choice) = serde_json::from_value::<FillChoice>(value) else {
|
||||
warn!("ColorInput update was not able to be parsed as FillChoice: {color_button:?}");
|
||||
return;
|
||||
};
|
||||
color_button.value = fill_choice_ui;
|
||||
color_button.value = fill_choice;
|
||||
(color_button.on_update.callback)(color_button)
|
||||
}
|
||||
};
|
||||
|
||||
responses.add(callback_message);
|
||||
}
|
||||
Widget::ColorPresetsInput(color_presets_input) => {
|
||||
Widget::CurveInput(curve_input) => {
|
||||
let callback_message = match action {
|
||||
WidgetValueAction::Commit => (color_presets_input.on_commit.callback)(&()),
|
||||
WidgetValueAction::Commit => (curve_input.on_commit.callback)(&()),
|
||||
WidgetValueAction::Update => {
|
||||
let Ok(update) = serde_json::from_value::<ColorPresetsInputUpdate>(value) else {
|
||||
warn!("ColorPresetsInput update was not able to be parsed as ColorPresetsInputUpdate");
|
||||
let Some(curve) = serde_json::from_value(value).ok() else {
|
||||
error!("CurveInput event data could not be deserialized");
|
||||
return;
|
||||
};
|
||||
(color_presets_input.on_update.callback)(&update)
|
||||
curve_input.value = curve;
|
||||
(curve_input.on_update.callback)(curve_input)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -247,25 +226,6 @@ impl LayoutMessageHandler {
|
||||
|
||||
responses.add(callback_message);
|
||||
}
|
||||
Widget::SpectrumInput(spectrum_input) => {
|
||||
let callback_message = match action {
|
||||
WidgetValueAction::Commit => (spectrum_input.on_commit.callback)(&()),
|
||||
WidgetValueAction::Update => {
|
||||
let Ok(update) = serde_json::from_value::<SpectrumInputUpdate>(value) else {
|
||||
warn!("SpectrumInput update was not able to be parsed as SpectrumInputUpdate");
|
||||
return;
|
||||
};
|
||||
// Don't mutate the stored widget here: leaving its old values lets the layout diff detect a change
|
||||
// when the new layout is rebuilt with the updated state. Otherwise the frontend's stored layout
|
||||
// keeps stale values for `activeMarkerIndex`, etc., and any other widget's diff (e.g. the position
|
||||
// NumberInput) will trigger Svelte to re-spread those stale props onto SpectrumInput, clobbering
|
||||
// its local `activeMarkerIndex` and making subsequent drags target the wrong stop.
|
||||
(spectrum_input.on_update.callback)(&update)
|
||||
}
|
||||
};
|
||||
|
||||
responses.add(callback_message);
|
||||
}
|
||||
Widget::IconButton(icon_button) => {
|
||||
let callback_message = match action {
|
||||
WidgetValueAction::Commit => (icon_button.on_commit.callback)(&()),
|
||||
@@ -423,23 +383,6 @@ impl LayoutMessageHandler {
|
||||
responses.add(callback_message);
|
||||
}
|
||||
Widget::TextLabel(_) => {}
|
||||
Widget::VisualColorPickersInput(visual_color_pickers_input) => {
|
||||
let callback_message = match action {
|
||||
WidgetValueAction::Commit => (visual_color_pickers_input.on_commit.callback)(&()),
|
||||
WidgetValueAction::Update => {
|
||||
let Ok(update) = serde_json::from_value::<VisualColorPickersInputUpdate>(value) else {
|
||||
warn!("VisualColorPickersInput update was not able to be parsed as VisualColorPickersInputUpdate");
|
||||
return;
|
||||
};
|
||||
// Don't mutate the stored widget here: leaving its old values lets the layout diff detect a change
|
||||
// when the new layout is rebuilt with the updated state, so the visual indicators (selection circle,
|
||||
// hue/alpha needles, saturation-val ue gradient background) actually re-render after a drag.
|
||||
(visual_color_pickers_input.on_update.callback)(&update)
|
||||
}
|
||||
};
|
||||
|
||||
responses.add(callback_message);
|
||||
}
|
||||
Widget::WorkingColorsInput(_) => {}
|
||||
};
|
||||
}
|
||||
@@ -452,17 +395,14 @@ impl LayoutMessageHandler {
|
||||
responses: &mut VecDeque<Message>,
|
||||
action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>,
|
||||
) {
|
||||
// Collect CheckboxId mappings from new layout
|
||||
// Step 1: Collect CheckboxId mappings from new layout
|
||||
let mut checkbox_map = HashMap::new();
|
||||
new_layout.collect_checkbox_ids(layout_target, &mut Vec::new(), &mut checkbox_map);
|
||||
|
||||
// Replace all IDs in new layout with deterministic ones
|
||||
// Step 2: Replace all IDs in new layout with deterministic ones
|
||||
new_layout.replace_widget_ids(layout_target, &mut Vec::new(), &checkbox_map);
|
||||
|
||||
// Populate computed display fields on widgets that need derived values
|
||||
populate_computed_display_fields(&mut new_layout);
|
||||
|
||||
// Diff with deterministic IDs
|
||||
// Step 3: Diff with deterministic IDs
|
||||
let mut widget_diffs = Vec::new();
|
||||
|
||||
self.layouts[layout_target as usize].diff(new_layout, &mut Vec::new(), &mut widget_diffs);
|
||||
@@ -500,27 +440,3 @@ enum WidgetValueAction {
|
||||
Commit,
|
||||
Update,
|
||||
}
|
||||
|
||||
/// Walk all widgets in the layout and populate computed display fields (e.g., precomputed CSS gradient strings) so the frontend can render them without making Wasm round-trip calls. Mutates fields in place.
|
||||
fn populate_computed_display_fields(layout: &mut Layout) {
|
||||
for instance in layout.iter_mut() {
|
||||
match &mut *instance.widget {
|
||||
Widget::ColorInput(color_input) => {
|
||||
color_input.chosen_gradient = color_input.value.to_css_background_image();
|
||||
}
|
||||
Widget::SpectrumInput(spectrum_input) => {
|
||||
spectrum_input.track_css = spectrum_input.track.to_css_linear_gradient();
|
||||
spectrum_input.track_start_css = spectrum_input.track.color.first().map(|color| color.to_css_hex()).unwrap_or_else(|| "black".to_string());
|
||||
spectrum_input.track_end_css = spectrum_input.track.color.last().map(|color| color.to_css_hex()).unwrap_or_else(|| "black".to_string());
|
||||
}
|
||||
Widget::ColorComparisonInput(comparison) => {
|
||||
let contrasting = |color: Option<SRGBA8>| color.map_or(SRGBA8::BLACK, |color| color.contrasting_text_color()).to_css_hex();
|
||||
comparison.new_color_css = comparison.new_color.map(|color| color.to_css_hex()).unwrap_or_default();
|
||||
comparison.new_color_contrasting = contrasting(comparison.new_color);
|
||||
comparison.old_color_css = comparison.old_color.map(|color| color.to_css_hex()).unwrap_or_default();
|
||||
comparison.old_color_contrasting = contrasting(comparison.old_color);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,7 @@ impl core::fmt::Display for WidgetId {
|
||||
|
||||
macro_rules! define_layout_target {
|
||||
($($(#[$attr:meta])* $variant:ident),* $(,)?) => {
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(PartialEq, Clone, Debug, Hash, Eq, Copy, serde::Serialize, serde::Deserialize)]
|
||||
#[repr(u8)]
|
||||
pub enum LayoutTarget {
|
||||
@@ -44,11 +44,7 @@ macro_rules! define_layout_target {
|
||||
};
|
||||
}
|
||||
define_layout_target!(
|
||||
/// Left column of the color picker popover, containing the visual H/S/V/A sliders and (optionally) the gradient editor.
|
||||
ColorPickerPickersAndGradient,
|
||||
/// Right column of the color picker popover, containing the new/old color comparison swatch, hex/RGB/HSV/alpha numeric inputs, and color preset buttons.
|
||||
ColorPickerDetails,
|
||||
/// The Data panel visualizes the output data flowing through the selected node in the graph.
|
||||
/// The spreadsheet panel allows for the visualisation of data in the graph.
|
||||
DataPanel,
|
||||
/// Contains the action buttons at the bottom of the dialog. Must be shown with the `FrontendMessage::DisplayDialog` message.
|
||||
DialogButtons,
|
||||
@@ -428,6 +424,7 @@ impl LayoutGroup {
|
||||
let val = match &mut *widget.widget {
|
||||
Widget::CheckboxInput(x) => &mut x.tooltip_description,
|
||||
Widget::ColorInput(x) => &mut x.tooltip_description,
|
||||
Widget::CurveInput(x) => &mut x.tooltip_description,
|
||||
Widget::DropdownInput(x) => &mut x.tooltip_description,
|
||||
Widget::IconButton(x) => &mut x.tooltip_description,
|
||||
Widget::IconLabel(x) => &mut x.tooltip_description,
|
||||
@@ -446,11 +443,7 @@ impl LayoutGroup {
|
||||
| Widget::ShortcutLabel(_)
|
||||
| Widget::WorkingColorsInput(_)
|
||||
| Widget::NodeCatalog(_)
|
||||
| Widget::ParameterExposeButton(_)
|
||||
| Widget::ColorComparisonInput(_)
|
||||
| Widget::ColorPresetsInput(_)
|
||||
| Widget::SpectrumInput(_)
|
||||
| Widget::VisualColorPickersInput(_) => continue,
|
||||
| Widget::ParameterExposeButton(_) => continue,
|
||||
};
|
||||
if val.is_empty() {
|
||||
val.clone_from(&description);
|
||||
@@ -668,7 +661,6 @@ impl Diffable for WidgetInstance {
|
||||
&& button1.tooltip_description == button2.tooltip_description
|
||||
&& button1.tooltip_shortcut == button2.tooltip_shortcut
|
||||
&& button1.popover_min_width == button2.popover_min_width
|
||||
&& button1.popover_layout.0.len() == button2.popover_layout.0.len()
|
||||
{
|
||||
// Only the popover layout differs, diff it recursively
|
||||
for (i, (a, b)) in button1.popover_layout.0.iter_mut().zip(button2.popover_layout.0.iter()).enumerate() {
|
||||
@@ -766,9 +758,8 @@ impl<T> Default for WidgetCallback<T> {
|
||||
pub enum Widget {
|
||||
BreadcrumbTrailButtons(BreadcrumbTrailButtons),
|
||||
CheckboxInput(CheckboxInput),
|
||||
ColorComparisonInput(ColorComparisonInput),
|
||||
ColorInput(ColorInput),
|
||||
ColorPresetsInput(ColorPresetsInput),
|
||||
CurveInput(CurveInput),
|
||||
DropdownInput(DropdownInput),
|
||||
IconButton(IconButton),
|
||||
IconLabel(IconLabel),
|
||||
@@ -782,12 +773,10 @@ pub enum Widget {
|
||||
PopoverButton(PopoverButton),
|
||||
RadioInput(RadioInput),
|
||||
Separator(Separator),
|
||||
SpectrumInput(SpectrumInput),
|
||||
TextAreaInput(TextAreaInput),
|
||||
TextButton(TextButton),
|
||||
TextInput(TextInput),
|
||||
TextLabel(TextLabel),
|
||||
VisualColorPickersInput(VisualColorPickersInput),
|
||||
WorkingColorsInput(WorkingColorsInput),
|
||||
}
|
||||
|
||||
@@ -796,7 +785,7 @@ pub enum Widget {
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct WidgetDiff {
|
||||
/// A path to the change
|
||||
/// e.g. [0, 1, 2] in the Properties panel is the first section, second row and third widget.
|
||||
/// e.g. [0, 1, 2] in the properties panel is the first section, second row and third widget.
|
||||
/// An empty path [] shows that the entire panel has changed and is sent when the UI is first created.
|
||||
#[serde(rename = "widgetPath")]
|
||||
pub widget_path: Vec<usize>,
|
||||
@@ -837,6 +826,7 @@ impl DiffUpdate {
|
||||
Widget::ShortcutLabel(widget) => widget.shortcut.as_mut(),
|
||||
Widget::IconLabel(_)
|
||||
| Widget::ImageLabel(_)
|
||||
| Widget::CurveInput(_)
|
||||
| Widget::NodeCatalog(_)
|
||||
| Widget::ReferencePointInput(_)
|
||||
| Widget::RadioInput(_)
|
||||
@@ -844,11 +834,7 @@ impl DiffUpdate {
|
||||
| Widget::TextAreaInput(_)
|
||||
| Widget::TextInput(_)
|
||||
| Widget::TextLabel(_)
|
||||
| Widget::WorkingColorsInput(_)
|
||||
| Widget::ColorComparisonInput(_)
|
||||
| Widget::ColorPresetsInput(_)
|
||||
| Widget::SpectrumInput(_)
|
||||
| Widget::VisualColorPickersInput(_) => None,
|
||||
| Widget::WorkingColorsInput(_) => None,
|
||||
};
|
||||
|
||||
// Convert `ActionShortcut::Action` to `ActionShortcut::Shortcut`
|
||||
|
||||
@@ -4,7 +4,7 @@ use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::WidgetCallback;
|
||||
use derivative::*;
|
||||
use graphene_std::vector::style::FillChoiceUI;
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
use graphite_proc_macros::WidgetBuilder;
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -39,9 +39,6 @@ pub struct IconButton {
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_drag_drop: WidgetCallback<IconButton>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -190,13 +187,9 @@ pub struct ImageButton {
|
||||
#[derivative(Debug, PartialEq, Default)]
|
||||
pub struct ColorInput {
|
||||
// Content
|
||||
/// WARNING: The colors are gamma, not linear!
|
||||
#[widget_builder(constructor)]
|
||||
pub value: FillChoiceUI,
|
||||
/// CSS `linear-gradient(...)` (or solid-color stand-in) for the swatch's `background-image`. Auto-populated from `value` at layout-send time.
|
||||
/// `None` when `value` is `FillChoiceUI::None`, in which case the frontend uses its "none" fallback styling.
|
||||
#[serde(rename = "chosenGradient")]
|
||||
#[widget_builder(skip)]
|
||||
pub chosen_gradient: Option<String>,
|
||||
pub value: FillChoice,
|
||||
#[serde(rename = "allowNone")]
|
||||
#[derivative(Default(value = "true"))]
|
||||
pub allow_none: bool,
|
||||
@@ -204,13 +197,6 @@ pub struct ColorInput {
|
||||
#[serde(rename = "menuDirection")]
|
||||
pub menu_direction: Option<MenuDirection>,
|
||||
pub disabled: bool,
|
||||
pub mixed: bool,
|
||||
|
||||
// Sizing
|
||||
#[serde(rename = "minWidth")]
|
||||
pub min_width: u32,
|
||||
#[serde(rename = "maxWidth")]
|
||||
pub max_width: u32,
|
||||
|
||||
// Styling
|
||||
pub narrow: bool,
|
||||
|
||||
@@ -4,9 +4,8 @@ use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use derivative::*;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::raster::curve::Curve;
|
||||
use graphene_std::transform::ReferencePoint;
|
||||
use graphene_std::vector::style::{FillChoiceUI, GradientStopsUI};
|
||||
use graphite_proc_macros::WidgetBuilder;
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -21,7 +20,6 @@ pub struct CheckboxInput {
|
||||
#[serde(rename = "forLabel")]
|
||||
pub for_label: CheckboxId,
|
||||
pub disabled: bool,
|
||||
pub mixed: bool,
|
||||
|
||||
// Tooltips
|
||||
#[serde(rename = "tooltipLabel")]
|
||||
@@ -350,9 +348,9 @@ pub struct RadioEntryData {
|
||||
pub struct WorkingColorsInput {
|
||||
// Content
|
||||
#[widget_builder(constructor)]
|
||||
pub primary: SRGBA8,
|
||||
pub primary: Color,
|
||||
#[widget_builder(constructor)]
|
||||
pub secondary: SRGBA8,
|
||||
pub secondary: Color,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -364,7 +362,6 @@ pub struct TextAreaInput {
|
||||
pub value: String,
|
||||
pub label: Option<String>,
|
||||
pub disabled: bool,
|
||||
pub monospace: bool,
|
||||
|
||||
// Tooltips
|
||||
#[serde(rename = "tooltipLabel")]
|
||||
@@ -421,237 +418,31 @@ pub struct TextInput {
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
}
|
||||
|
||||
// #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
// #[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder)]
|
||||
// #[derivative(Debug, PartialEq, Default)]
|
||||
// pub struct CurveInput {
|
||||
// // Content
|
||||
// #[widget_builder(constructor)]
|
||||
// pub value: Curve,
|
||||
|
||||
// // Tooltips
|
||||
// #[serde(rename = "tooltipLabel")]
|
||||
// pub tooltip_label: String,
|
||||
// #[serde(rename = "tooltipDescription")]
|
||||
// pub tooltip_description: String,
|
||||
// #[serde(rename = "tooltipShortcut")]
|
||||
// pub tooltip_shortcut: Option<ActionShortcut>,
|
||||
|
||||
// // Callbacks
|
||||
// #[serde(skip)]
|
||||
// #[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
// pub on_update: WidgetCallback<CurveInput>,
|
||||
// #[serde(skip)]
|
||||
// #[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
// pub on_commit: WidgetCallback<()>,
|
||||
// }
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Default, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder)]
|
||||
#[derivative(Debug, PartialEq)]
|
||||
pub struct VisualColorPickersInput {
|
||||
// Content
|
||||
pub hue: f64,
|
||||
pub saturation: f64,
|
||||
pub value: f64,
|
||||
pub alpha: f64,
|
||||
#[serde(rename = "isNone")]
|
||||
pub is_none: bool,
|
||||
pub disabled: bool,
|
||||
|
||||
// Callbacks
|
||||
// `on_update` receives the raw `VisualColorPickersInputUpdate` (not the mutated widget) so the layout diffing can still detect a change between the stored layout and the rebuilt one, otherwise the selection circle and slider needles never re-render after a drag.
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_update: WidgetCallback<VisualColorPickersInputUpdate>,
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct VisualColorPickersInputUpdate {
|
||||
pub hue: f64,
|
||||
pub saturation: f64,
|
||||
pub value: f64,
|
||||
pub alpha: f64,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Default, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder)]
|
||||
#[derivative(Debug, PartialEq)]
|
||||
pub struct ColorComparisonInput {
|
||||
// Content
|
||||
#[widget_builder(constructor)]
|
||||
#[serde(rename = "newColor")]
|
||||
pub new_color: Option<SRGBA8>,
|
||||
#[widget_builder(constructor)]
|
||||
#[serde(rename = "oldColor")]
|
||||
pub old_color: Option<SRGBA8>,
|
||||
#[serde(rename = "isNone")]
|
||||
pub is_none: bool,
|
||||
#[serde(rename = "oldIsNone")]
|
||||
pub old_is_none: bool,
|
||||
pub disabled: bool,
|
||||
pub differs: bool,
|
||||
#[serde(rename = "outlineAmount")]
|
||||
pub outline_amount: f64,
|
||||
/// Hex CSS string for the new color (with alpha if not fully opaque), or empty when `is_none`. Auto-populated from `new_color` at layout-send time.
|
||||
#[serde(rename = "newColorCSS")]
|
||||
#[widget_builder(skip)]
|
||||
pub new_color_css: String,
|
||||
/// Black or white, whichever contrasts the new color for legible label text. Auto-populated.
|
||||
#[serde(rename = "newColorContrasting")]
|
||||
#[widget_builder(skip)]
|
||||
pub new_color_contrasting: String,
|
||||
/// Hex CSS string for the old color (with alpha if not fully opaque), or empty when `old_is_none`. Auto-populated.
|
||||
#[serde(rename = "oldColorCSS")]
|
||||
#[widget_builder(skip)]
|
||||
pub old_color_css: String,
|
||||
/// Black or white, whichever contrasts the old color for legible label text. Auto-populated.
|
||||
#[serde(rename = "oldColorContrasting")]
|
||||
#[widget_builder(skip)]
|
||||
pub old_color_contrasting: String,
|
||||
|
||||
// Callbacks
|
||||
// The `swap` event has no payload — it just signals the user requested a swap.
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_update: WidgetCallback<()>,
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Default, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder)]
|
||||
#[derivative(Debug, PartialEq)]
|
||||
pub struct ColorPresetsInput {
|
||||
// Content
|
||||
pub disabled: bool,
|
||||
#[serde(rename = "showNoneOption")]
|
||||
pub show_none_option: bool,
|
||||
|
||||
// Callbacks
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_update: WidgetCallback<ColorPresetsInputUpdate>,
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ColorPresetsInputUpdate {
|
||||
Preset(FillChoiceUI),
|
||||
EyedropperColorCode(String),
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder)]
|
||||
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder)]
|
||||
#[derivative(Debug, PartialEq, Default)]
|
||||
pub struct SpectrumInput {
|
||||
pub struct CurveInput {
|
||||
// Content
|
||||
/// The colored gradient drawn behind the markers (display-only, caller-owned).
|
||||
#[widget_builder(constructor)]
|
||||
pub track: GradientStopsUI,
|
||||
/// CSS `linear-gradient(...)` string for the track strip's `background-image`. Auto-populated from `track` at layout-send time.
|
||||
#[serde(rename = "trackCSS")]
|
||||
#[widget_builder(skip)]
|
||||
pub track_css: String,
|
||||
/// Hex string for the track strip's leftmost solid-color end-cap. Auto-populated from `track`'s first stop.
|
||||
#[serde(rename = "trackStartCSS")]
|
||||
#[widget_builder(skip)]
|
||||
pub track_start_css: String,
|
||||
/// Hex string for the track strip's rightmost solid-color end-cap. Auto-populated from `track`'s last stop.
|
||||
#[serde(rename = "trackEndCSS")]
|
||||
#[widget_builder(skip)]
|
||||
pub track_end_css: String,
|
||||
/// The handles the user can drag along the track. Their handle colors are caller-owned (e.g., for a gradient editor they follow the stop colors, for a "Shadows/Midpoints/Highlights" widget they're hardcoded).
|
||||
pub markers: Vec<SpectrumMarker>,
|
||||
#[serde(rename = "activeMarkerIndex")]
|
||||
pub active_marker_index: Option<u32>,
|
||||
#[serde(rename = "activeMarkerIsMidpoint")]
|
||||
pub active_marker_is_midpoint: bool,
|
||||
/// Whether to render midpoint diamonds between adjacent markers (only meaningful for gradient-like uses).
|
||||
#[serde(rename = "showMidpoints")]
|
||||
pub show_midpoints: bool,
|
||||
/// Whether clicking the track inserts a new marker at the click position.
|
||||
#[serde(rename = "allowInsert")]
|
||||
pub allow_insert: bool,
|
||||
/// Whether right-click or pressing Delete removes a marker. The handler still has the final say on whether the deletion goes through (e.g., enforcing a minimum count).
|
||||
#[serde(rename = "allowDelete")]
|
||||
pub allow_delete: bool,
|
||||
/// Whether dragging a marker past another reorders them. If false, the dragged marker is clamped between its neighbors.
|
||||
#[serde(rename = "allowReorder")]
|
||||
pub allow_reorder: bool,
|
||||
/// Compact mode: 8px track height with 8px top padding, for use in rows alongside other widgets.
|
||||
pub narrow: bool,
|
||||
/// Whether the input is disabled (dimmed and read-only).
|
||||
pub disabled: bool,
|
||||
pub value: Curve,
|
||||
|
||||
// Tooltips
|
||||
#[serde(rename = "tooltipLabel")]
|
||||
pub tooltip_label: String,
|
||||
#[serde(rename = "tooltipDescription")]
|
||||
pub tooltip_description: String,
|
||||
#[serde(rename = "tooltipShortcut")]
|
||||
pub tooltip_shortcut: Option<ActionShortcut>,
|
||||
|
||||
// Callbacks
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_update: WidgetCallback<SpectrumInputUpdate>,
|
||||
pub on_update: WidgetCallback<CurveInput>,
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct SpectrumMarker {
|
||||
/// Position (0..1) of the marker along the spectrum track.
|
||||
position: f64,
|
||||
/// Position (0..1) of the midpoint between this marker and the next, used only if `show_midpoints` is true. The last marker's value is ignored.
|
||||
midpoint: f64,
|
||||
/// CSS color string for the marker handle's fill. Set via `SpectrumMarker::new` from a linear [`Color`].
|
||||
#[serde(rename = "handleColorCSS")]
|
||||
handle_color_css: String,
|
||||
}
|
||||
|
||||
impl SpectrumMarker {
|
||||
pub fn new(position: f64, midpoint: f64, handle_color: Color) -> Self {
|
||||
let handle_color_css = SRGBA8::from(handle_color).to_css_hex();
|
||||
Self { position, midpoint, handle_color_css }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum SpectrumInputUpdate {
|
||||
MoveMarker {
|
||||
index: u32,
|
||||
position: f64,
|
||||
},
|
||||
MoveMidpoint {
|
||||
index: u32,
|
||||
position: f64,
|
||||
},
|
||||
InsertMarker {
|
||||
position: f64,
|
||||
},
|
||||
DeleteMarker {
|
||||
index: u32,
|
||||
},
|
||||
/// Emitted when the user double-clicks a marker. The consumer decides what (if anything) to reset the marker to.
|
||||
ResetMarker {
|
||||
index: u32,
|
||||
},
|
||||
ResetMidpoint {
|
||||
index: u32,
|
||||
},
|
||||
ActiveMarker {
|
||||
#[serde(rename = "activeMarkerIndex")]
|
||||
active_marker_index: Option<u32>,
|
||||
#[serde(rename = "activeMarkerIsMidpoint")]
|
||||
active_marker_is_midpoint: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Default, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder)]
|
||||
#[derivative(Debug, PartialEq)]
|
||||
|
||||
@@ -72,8 +72,6 @@ pub struct TextLabel {
|
||||
// Sizing
|
||||
#[serde(rename = "minWidth")]
|
||||
pub min_width: u32,
|
||||
#[serde(rename = "maxWidth")]
|
||||
pub max_width: u32,
|
||||
#[serde(rename = "minWidthCharacters")]
|
||||
pub min_width_characters: u32,
|
||||
|
||||
|
||||
@@ -514,11 +514,6 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon("NodeShape")
|
||||
.on_commit(|_| NodeGraphMessage::AddPathNode.into())
|
||||
.disabled(!make_path_editable_is_allowed),
|
||||
MenuListEntry::new("Expand Fill/Stroke")
|
||||
.label("Expand Fill/Stroke")
|
||||
.icon("ExpandFillStroke")
|
||||
.on_commit(|_| DocumentMessage::ExpandFillStrokeOnSelectedLayers.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
],
|
||||
])
|
||||
.widget_instance(),
|
||||
|
||||
@@ -14,8 +14,6 @@ pub enum Message {
|
||||
#[child]
|
||||
Clipboard(ClipboardMessage),
|
||||
#[child]
|
||||
ColorPicker(ColorPickerMessage),
|
||||
#[child]
|
||||
Debug(DebugMessage),
|
||||
#[child]
|
||||
Defer(DeferMessage),
|
||||
|
||||
@@ -4,7 +4,6 @@ pub mod animation;
|
||||
pub mod app_window;
|
||||
pub mod broadcast;
|
||||
pub mod clipboard;
|
||||
pub mod color_picker;
|
||||
pub mod debug;
|
||||
pub mod defer;
|
||||
pub mod dialog;
|
||||
|
||||
@@ -10,12 +10,9 @@ pub enum DataPanelMessage {
|
||||
inspect_result: InspectResult,
|
||||
},
|
||||
ClearLayout,
|
||||
/// Re-render the existing layout against the latest network interface state. Use this when node metadata
|
||||
/// (display name, visibility, locked, etc.) changes but the introspected output value hasn't.
|
||||
Refresh,
|
||||
|
||||
PushToElementPath {
|
||||
step: PathStep,
|
||||
index: usize,
|
||||
},
|
||||
TruncateElementPath {
|
||||
len: usize,
|
||||
@@ -26,14 +23,6 @@ pub enum DataPanelMessage {
|
||||
},
|
||||
}
|
||||
|
||||
/// One hop in the breadcrumb path through nested data the Data panel is displaying.
|
||||
/// Drilling into an item's element produces an `Element` step; drilling into one of an item's attributes produces an `Attribute` step.
|
||||
#[derive(PartialEq, Eq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum PathStep {
|
||||
Element(usize),
|
||||
Attribute { row: usize, key: String },
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, Clone, Copy, Default, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum VectorTableTab {
|
||||
#[default]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -86,8 +86,6 @@ pub enum DocumentMessage {
|
||||
},
|
||||
BlendSelectedLayers,
|
||||
MorphSelectedLayers,
|
||||
ExpandFillStrokeOnSelectedLayers,
|
||||
ExpandFillStrokeOnSelectedLayersNoTransaction,
|
||||
GroupSelectedLayers {
|
||||
group_folder_type: GroupFolderType,
|
||||
},
|
||||
@@ -201,7 +199,7 @@ pub enum DocumentMessage {
|
||||
undo_count: usize,
|
||||
},
|
||||
ToggleLayerExpansion {
|
||||
tree_path: Vec<NodeId>,
|
||||
instance_path: Vec<NodeId>,
|
||||
recursive: bool,
|
||||
},
|
||||
ToggleSelectedVisibility,
|
||||
@@ -217,12 +215,6 @@ pub enum DocumentMessage {
|
||||
UpdateClickTargets {
|
||||
click_targets: HashMap<NodeId, Vec<Arc<ClickTarget>>>,
|
||||
},
|
||||
UpdateOutlines {
|
||||
outlines: HashMap<NodeId, Vec<Arc<ClickTarget>>>,
|
||||
},
|
||||
UpdateTextFrames {
|
||||
text_frames: HashMap<NodeId, DAffine2>,
|
||||
},
|
||||
UpdateClipTargets {
|
||||
clip_targets: HashSet<NodeId>,
|
||||
},
|
||||
|
||||
@@ -11,7 +11,7 @@ use crate::consts::{
|
||||
use crate::messages::input_mapper::utility_types::macros::action_shortcut;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::data_panel::{DataPanelMessageContext, DataPanelMessageHandler};
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::{ModifyInputsContext, TransformIn};
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::node_graph::NodeGraphMessageContext;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
||||
@@ -20,7 +20,7 @@ use crate::messages::portfolio::document::overlays::utility_types::{OverlaysType
|
||||
use crate::messages::portfolio::document::properties_panel::properties_panel_message_handler::PropertiesPanelMessageContext;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
|
||||
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, PTZ};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate, OutputConnector};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate};
|
||||
use crate::messages::portfolio::utility_types::{CachedData, PanelType};
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{self, get_blend_mode, get_fill, get_opacity};
|
||||
@@ -28,19 +28,20 @@ use crate::messages::tool::tool_messages::select_tool::SelectToolPointerKeys;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::Key;
|
||||
use crate::messages::tool::utility_types::ToolType;
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::descriptor;
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork};
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::path_bool_nodes::boolean_intersect;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster_types::Raster;
|
||||
use graphene_std::render_node::wgpu_available;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::table::Table;
|
||||
use graphene_std::vector::PointId;
|
||||
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
|
||||
use graphene_std::vector::misc::dvec2_to_point;
|
||||
use graphene_std::vector::style::{Fill, RenderMode};
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
use kurbo::{Affine, BezPath, Line, PathSeg};
|
||||
use std::collections::HashSet;
|
||||
use std::path::PathBuf;
|
||||
@@ -85,7 +86,7 @@ pub struct DocumentMessageHandler {
|
||||
//
|
||||
// Contains the NodeNetwork and acts an an interface to manipulate the NodeNetwork with custom setters in order to keep NetworkMetadata in sync
|
||||
pub network_interface: NodeNetworkInterface,
|
||||
/// Tracks which layer occurrences are collapsed in the Layers panel, keyed by tree path.
|
||||
/// Tracks which layer instances are collapsed in the Layers panel, keyed by instance path.
|
||||
#[serde(deserialize_with = "deserialize_collapsed_layers", default)]
|
||||
pub collapsed: CollapsedLayers,
|
||||
/// The full Git commit hash of the Graphite repository that was used to build the editor.
|
||||
@@ -631,24 +632,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
DocumentMessage::MorphSelectedLayers => {
|
||||
self.handle_group_selected_layers(GroupFolderType::Morph, responses);
|
||||
}
|
||||
DocumentMessage::ExpandFillStrokeOnSelectedLayers => {
|
||||
// Snapshot must be taken before the mutations, so the actual work runs as a separate message
|
||||
// queued after AddTransaction (which prepends StartTransaction/CommitTransaction to the queue).
|
||||
// All mutations currently target the root document network, so guard against being invoked from inside a nested network.
|
||||
if !self.selection_network_path.is_empty() {
|
||||
log::error!("Expanding fill/stroke is only supported for the document network");
|
||||
return;
|
||||
}
|
||||
if self.network_interface.selected_nodes().selected_layers(self.metadata()).next().is_none() {
|
||||
return;
|
||||
}
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(DocumentMessage::ExpandFillStrokeOnSelectedLayersNoTransaction);
|
||||
}
|
||||
DocumentMessage::ExpandFillStrokeOnSelectedLayersNoTransaction => {
|
||||
// Mutates the network directly, so it must be queued to run after `AddTransaction` has snapshotted the document
|
||||
self.handle_expand_fill_stroke_on_selected_layers(responses);
|
||||
}
|
||||
DocumentMessage::GroupSelectedLayers { group_folder_type } => {
|
||||
self.handle_group_selected_layers(group_folder_type, responses);
|
||||
}
|
||||
@@ -713,12 +696,11 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
|
||||
let layer = graph_modification_utils::new_image_layer(image, layer_node_id, layer_parent, responses);
|
||||
let layer = graph_modification_utils::new_image_layer(Table::new_from_element(Raster::new_cpu(image)), layer_node_id, layer_parent, responses);
|
||||
|
||||
if let Some(name) = name {
|
||||
responses.add(NodeGraphMessage::SetDisplayName {
|
||||
node_id: layer.to_node(),
|
||||
network_path: Vec::new(),
|
||||
alias: name,
|
||||
skip_adding_history_step: false,
|
||||
});
|
||||
@@ -776,7 +758,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
if let Some(name) = name {
|
||||
responses.add(NodeGraphMessage::SetDisplayName {
|
||||
node_id: layer.to_node(),
|
||||
network_path: Vec::new(),
|
||||
alias: name,
|
||||
skip_adding_history_step: false,
|
||||
});
|
||||
@@ -803,15 +784,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
responses.add(EventMessage::SelectionChanged);
|
||||
}
|
||||
DocumentMessage::RenameDocument { new_name } => {
|
||||
let new_name = new_name.trim().to_string();
|
||||
|
||||
// No-op when the resolved name is unchangedL committing the rename field without edits (or with
|
||||
// only whitespace edits) shouldn't dissociate the document from its file on disk or mark it unsaved.
|
||||
if new_name == self.name {
|
||||
return;
|
||||
}
|
||||
|
||||
self.name = new_name;
|
||||
self.name = new_name.clone();
|
||||
|
||||
self.path = None;
|
||||
self.set_save_state(false);
|
||||
@@ -857,31 +830,11 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
|
||||
let ruler_spacing = ruler_interval * ruler_scale;
|
||||
|
||||
// Compute the selection bounding box as 4 viewport-space corners preserving orientation
|
||||
let selection_quad = if !self.graph_view_overlay_open {
|
||||
self.network_interface
|
||||
.selected_nodes()
|
||||
.0
|
||||
.iter()
|
||||
.filter(|node| self.network_interface.is_layer(node, &[]))
|
||||
.filter_map(|layer| self.metadata().bounding_box_document(LayerNodeIdentifier::new(*layer, &self.network_interface)))
|
||||
.reduce(Quad::combine_bounds)
|
||||
.map(|[min, max]| {
|
||||
let corners = [DVec2::new(min.x, min.y), DVec2::new(max.x, min.y), DVec2::new(max.x, max.y), DVec2::new(min.x, max.y)];
|
||||
corners.map(|c| document_to_viewport.transform_point2(c).into())
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
responses.add(FrontendMessage::UpdateDocumentRulers {
|
||||
origin: ruler_origin.into(),
|
||||
spacing: ruler_spacing,
|
||||
interval: ruler_interval,
|
||||
visible: self.rulers_visible,
|
||||
tilt: if self.graph_view_overlay_open { 0. } else { current_ptz.tilt() },
|
||||
flip: !self.graph_view_overlay_open && current_ptz.flip,
|
||||
selection_quad,
|
||||
});
|
||||
}
|
||||
DocumentMessage::RenderScrollbars => {
|
||||
@@ -1222,27 +1175,27 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
}
|
||||
DocumentMessage::ToggleLayerExpansion { tree_path, recursive } => {
|
||||
let is_collapsed = self.collapsed.0.contains(&tree_path);
|
||||
DocumentMessage::ToggleLayerExpansion { instance_path, recursive } => {
|
||||
let is_collapsed = self.collapsed.0.contains(&instance_path);
|
||||
|
||||
if is_collapsed {
|
||||
if recursive {
|
||||
// Remove this path and all descendant paths (paths that start with this one)
|
||||
self.collapsed.0.retain(|path| !path.starts_with(&tree_path));
|
||||
self.collapsed.0.retain(|path| !path.starts_with(&instance_path));
|
||||
} else {
|
||||
self.collapsed.0.retain(|path| *path != tree_path);
|
||||
self.collapsed.0.retain(|path| *path != instance_path);
|
||||
}
|
||||
} else {
|
||||
if recursive {
|
||||
// Collapse all expanded descendant occurrences by collecting their tree paths from the structure tree
|
||||
let descendant_paths = self.collect_descendant_tree_paths(&tree_path);
|
||||
// Collapse all expanded descendant instances by collecting their paths from the structure tree
|
||||
let descendant_paths = self.collect_descendant_instance_paths(&instance_path);
|
||||
for path in descendant_paths {
|
||||
if !self.collapsed.0.contains(&path) {
|
||||
self.collapsed.0.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.collapsed.0.push(tree_path);
|
||||
self.collapsed.0.push(instance_path);
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
@@ -1289,32 +1242,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
.collect();
|
||||
self.network_interface.update_click_targets(layer_click_targets);
|
||||
}
|
||||
DocumentMessage::UpdateOutlines { outlines } => {
|
||||
let layer_outlines = outlines
|
||||
.into_iter()
|
||||
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id))
|
||||
.filter_map(|(node_id, outlines)| {
|
||||
self.network_interface.is_layer(&node_id, &[]).then(|| {
|
||||
let layer = LayerNodeIdentifier::new(node_id, &self.network_interface);
|
||||
(layer, outlines)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
self.network_interface.update_outlines(layer_outlines);
|
||||
}
|
||||
DocumentMessage::UpdateTextFrames { text_frames } => {
|
||||
let layer_text_frames = text_frames
|
||||
.into_iter()
|
||||
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id))
|
||||
.filter_map(|(node_id, frame)| {
|
||||
self.network_interface.is_layer(&node_id, &[]).then(|| {
|
||||
let layer = LayerNodeIdentifier::new(node_id, &self.network_interface);
|
||||
(layer, frame)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
self.network_interface.update_text_frames(layer_text_frames);
|
||||
}
|
||||
DocumentMessage::UpdateClipTargets { clip_targets } => {
|
||||
self.network_interface.update_clip_targets(clip_targets);
|
||||
}
|
||||
@@ -1461,11 +1388,11 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
// When artboard_canvas is provided (SVG file-open flow), use the declared canvas origin and dimensions;
|
||||
// no content-shift Transform node needed since the SVG was already placed at its natural coordinates.
|
||||
let (artboard_location, artboard_dimensions, content_shift) = if let Some((origin, dimensions)) = artboard_canvas {
|
||||
(origin.as_dvec2(), dimensions.as_dvec2(), DVec2::ZERO)
|
||||
(origin, dimensions, DVec2::ZERO)
|
||||
} else {
|
||||
// No declared canvas (image or clipboard paste): derive location and dimensions from the content bounding box.
|
||||
let location = if place_artboard_at_origin { DVec2::ZERO } else { bounds[0].round() };
|
||||
(location, (bounds[1] - bounds[0]).round(), -bounds[0].round())
|
||||
let location = if place_artboard_at_origin { IVec2::ZERO } else { bounds[0].round().as_ivec2() };
|
||||
(location, (bounds[1] - bounds[0]).round().as_ivec2(), -bounds[0].round())
|
||||
};
|
||||
|
||||
// Create an artboard and set its dimensions to the bounding box size and location
|
||||
@@ -1668,11 +1595,6 @@ impl DocumentMessageHandler {
|
||||
subpath.apply_transform(layer_transform);
|
||||
subpath.is_inside_subpath(&viewport_polygon, None, None)
|
||||
}
|
||||
ClickTargetType::CompoundPath(subpaths) => subpaths.iter().all(|subpath| {
|
||||
let mut subpath = subpath.clone();
|
||||
subpath.apply_transform(layer_transform);
|
||||
subpath.is_inside_subpath(&viewport_polygon, None, None)
|
||||
}),
|
||||
ClickTargetType::FreePoint(point) => {
|
||||
let mut point = *point;
|
||||
point.apply_transform(layer_transform);
|
||||
@@ -1766,12 +1688,6 @@ impl DocumentMessageHandler {
|
||||
self.network_interface.document_metadata()
|
||||
}
|
||||
|
||||
/// Path to the subnetwork that the user's selection is currently scoped to.
|
||||
/// Empty when the selection lives in the root document network.
|
||||
pub fn selection_network_path(&self) -> &[NodeId] {
|
||||
&self.selection_network_path
|
||||
}
|
||||
|
||||
pub fn serialize_document(&self) -> String {
|
||||
let val = serde_json::to_string(self);
|
||||
// We fully expect the serialization to succeed
|
||||
@@ -1852,11 +1768,11 @@ impl DocumentMessageHandler {
|
||||
let selected_layers: HashSet<NodeId> = network.selected_nodes().selected_layers(self.metadata()).map(LayerNodeIdentifier::to_node).collect();
|
||||
|
||||
let ancestors = HashSet::new();
|
||||
let tree_path = Vec::new();
|
||||
let instance_path = Vec::new();
|
||||
let mut root_entries = Vec::new();
|
||||
|
||||
// The first root layer is the topmost entry
|
||||
root_entries.push(self.build_layer_entry(first_root_layer_id, &ancestors, &selected_layers, &tree_path));
|
||||
root_entries.push(self.build_layer_entry(first_root_layer_id, &ancestors, &selected_layers, &instance_path));
|
||||
|
||||
// Layers in the primary flow (input[0] chain) from the first root layer are root-level siblings
|
||||
let mut root_ancestors = HashSet::new();
|
||||
@@ -1864,7 +1780,7 @@ impl DocumentMessageHandler {
|
||||
|
||||
for sibling_id in network.upstream_flow_back_from_nodes(vec![first_root_layer_id], &[], FlowType::PrimaryFlow).skip(1) {
|
||||
if network.is_layer(&sibling_id, &[]) && !root_ancestors.contains(&sibling_id) {
|
||||
root_entries.push(self.build_layer_entry(sibling_id, &root_ancestors, &selected_layers, &tree_path));
|
||||
root_entries.push(self.build_layer_entry(sibling_id, &root_ancestors, &selected_layers, &instance_path));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1873,19 +1789,19 @@ impl DocumentMessageHandler {
|
||||
|
||||
/// Builds a single `LayerStructureEntry` for the given layer, including its `children_present` flag,
|
||||
/// `descendant_selected` flag, and (if expanded) its children collected from the graph.
|
||||
fn build_layer_entry(&self, layer_id: NodeId, ancestors: &HashSet<NodeId>, selected_layers: &HashSet<NodeId>, parent_tree_path: &[NodeId]) -> LayerStructureEntry {
|
||||
let mut tree_path = parent_tree_path.to_vec();
|
||||
tree_path.push(layer_id);
|
||||
fn build_layer_entry(&self, layer_id: NodeId, ancestors: &HashSet<NodeId>, selected_layers: &HashSet<NodeId>, parent_instance_path: &[NodeId]) -> LayerStructureEntry {
|
||||
let mut instance_path = parent_instance_path.to_vec();
|
||||
instance_path.push(layer_id);
|
||||
|
||||
let mut child_ancestors = ancestors.clone();
|
||||
child_ancestors.insert(layer_id);
|
||||
|
||||
let children_present = self.has_layer_children_in_graph(layer_id, &child_ancestors);
|
||||
|
||||
let collapsed = self.collapsed.0.contains(&tree_path);
|
||||
let collapsed = self.collapsed.0.contains(&instance_path);
|
||||
|
||||
let children = if children_present && !collapsed {
|
||||
self.collect_layer_children(layer_id, &child_ancestors, selected_layers, &tree_path)
|
||||
self.collect_layer_children(layer_id, &child_ancestors, selected_layers, &instance_path)
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
@@ -1966,7 +1882,7 @@ impl DocumentMessageHandler {
|
||||
/// The horizontal flow (a layer's secondary input chain) finds nested content layers, and the
|
||||
/// primary flow from those (their stack's top output) finds stacked siblings at the same depth.
|
||||
/// `ancestors` contains layer IDs in the current path from root, used for cycle prevention.
|
||||
fn collect_layer_children(&self, layer_id: NodeId, ancestors: &HashSet<NodeId>, selected_layers: &HashSet<NodeId>, tree_path: &[NodeId]) -> Vec<LayerStructureEntry> {
|
||||
fn collect_layer_children(&self, layer_id: NodeId, ancestors: &HashSet<NodeId>, selected_layers: &HashSet<NodeId>, instance_path: &[NodeId]) -> Vec<LayerStructureEntry> {
|
||||
let network = &self.network_interface;
|
||||
|
||||
// Find the first nested layer via horizontal flow (content inside this layer)
|
||||
@@ -1984,22 +1900,22 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
// The nested layer is the first child at this depth level
|
||||
let mut children = vec![self.build_layer_entry(nested_id, ancestors, selected_layers, tree_path)];
|
||||
let mut children = vec![self.build_layer_entry(nested_id, ancestors, selected_layers, instance_path)];
|
||||
|
||||
// Primary flow from the nested layer finds stacked siblings (more children of this layer)
|
||||
for sibling_id in network.upstream_flow_back_from_nodes(vec![nested_id], &[], FlowType::PrimaryFlow).skip(1) {
|
||||
if network.is_layer(&sibling_id, &[]) && !ancestors.contains(&sibling_id) {
|
||||
children.push(self.build_layer_entry(sibling_id, ancestors, selected_layers, tree_path));
|
||||
children.push(self.build_layer_entry(sibling_id, ancestors, selected_layers, instance_path));
|
||||
}
|
||||
}
|
||||
|
||||
children
|
||||
}
|
||||
|
||||
/// Collects tree paths for all descendant layers of the given tree path by traversing the graph.
|
||||
/// Collects instance paths for all descendant layers of the given instance path by traversing the graph.
|
||||
/// Used for recursive collapse to find all expandable descendants.
|
||||
fn collect_descendant_tree_paths(&self, tree_path: &[NodeId]) -> Vec<Vec<NodeId>> {
|
||||
let Some(&layer_id) = tree_path.last() else { return Vec::new() };
|
||||
fn collect_descendant_instance_paths(&self, instance_path: &[NodeId]) -> Vec<Vec<NodeId>> {
|
||||
let Some(&layer_id) = instance_path.last() else { return Vec::new() };
|
||||
let network = &self.network_interface;
|
||||
|
||||
let mut paths = Vec::new();
|
||||
@@ -2008,7 +1924,7 @@ impl DocumentMessageHandler {
|
||||
// Seed with child layers via horizontal flow
|
||||
for node_id in network.upstream_flow_back_from_nodes(vec![layer_id], &[], FlowType::HorizontalFlow).skip(1) {
|
||||
if network.is_layer(&node_id, &[]) {
|
||||
let mut child_path = tree_path.to_vec();
|
||||
let mut child_path = instance_path.to_vec();
|
||||
child_path.push(node_id);
|
||||
stack.push((node_id, child_path));
|
||||
}
|
||||
@@ -2016,14 +1932,14 @@ impl DocumentMessageHandler {
|
||||
|
||||
let mut visited = HashSet::new();
|
||||
|
||||
// Depth-first traversal collecting all unique descendant tree paths
|
||||
// Depth-first traversal collecting all unique descendant instance paths
|
||||
while let Some((current_id, current_path)) = stack.pop() {
|
||||
// Skip paths we've already visited to prevent cycles
|
||||
if !visited.insert(current_path.clone()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Record this descendant's tree path for collapsing
|
||||
// Record this descendant's instance path for collapsing
|
||||
paths.push(current_path.clone());
|
||||
|
||||
// Add nested content layers found via horizontal flow
|
||||
@@ -2230,7 +2146,7 @@ impl DocumentMessageHandler {
|
||||
network_interface.upstream_flow_back_from_nodes(vec![selected_id.to_node()], &[], FlowType::HorizontalFlow).find(|id| {
|
||||
network_interface
|
||||
.reference(id, &[])
|
||||
.is_some_and(|reference| reference == DefinitionIdentifier::ProtoNode(graphene_std::path_bool_nodes::boolean_operation::IDENTIFIER))
|
||||
.is_some_and(|reference| reference == DefinitionIdentifier::Network("Boolean Operation".into()))
|
||||
})
|
||||
});
|
||||
|
||||
@@ -2288,18 +2204,18 @@ impl DocumentMessageHandler {
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
|
||||
// The control path layer (Blend Path / Morph Path) should start collapsed.
|
||||
let tree_path = {
|
||||
// Build tree path from root down to the control path layer, which is a sibling of the main layer under `parent`.
|
||||
let mut tree_path: Vec<NodeId> = parent
|
||||
let instance_path = {
|
||||
// Build instance path from root down to the control path layer, which is a sibling of the main layer under `parent`.
|
||||
let mut instance_path: Vec<NodeId> = parent
|
||||
.ancestors(network_interface.document_metadata())
|
||||
.take_while(|&ancestor| ancestor != LayerNodeIdentifier::ROOT_PARENT)
|
||||
.map(LayerNodeIdentifier::to_node)
|
||||
.collect();
|
||||
tree_path.reverse();
|
||||
tree_path.push(control_path_id);
|
||||
tree_path
|
||||
instance_path.reverse();
|
||||
instance_path.push(control_path_id);
|
||||
instance_path
|
||||
};
|
||||
responses.add(DocumentMessage::ToggleLayerExpansion { tree_path, recursive: false });
|
||||
responses.add(DocumentMessage::ToggleLayerExpansion { instance_path, recursive: false });
|
||||
|
||||
return folder_id;
|
||||
}
|
||||
@@ -2368,86 +2284,6 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// For each selected layer, splits its fill and stroke into two stacked layers connected
|
||||
/// to a shared `Solidify Stroke` node via two `Index Elements` nodes (indices 0 and 1).
|
||||
/// Layers with only a stroke get just a `Solidify Stroke` added.
|
||||
/// Layers with only a fill, or neither, are left untouched.
|
||||
fn handle_expand_fill_stroke_on_selected_layers(&mut self, responses: &mut VecDeque<Message>) {
|
||||
let selected_layers: Vec<LayerNodeIdentifier> = self.network_interface.selected_nodes().selected_layers(self.metadata()).collect();
|
||||
if selected_layers.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let solidify_stroke_definition = document_node_definitions::resolve_proto_node_type(graphene_std::vector::solidify_stroke::IDENTIFIER).expect("Solidify Stroke node should exist");
|
||||
let index_elements_definition = document_node_definitions::resolve_proto_node_type(graphene_std::graphic::index_elements::IDENTIFIER).expect("Index Elements node should exist");
|
||||
|
||||
let mut resulting_layers: Vec<NodeId> = Vec::new();
|
||||
|
||||
for layer in selected_layers {
|
||||
let style = self.network_interface.document_metadata().layer_vector_data.get(&layer).map(|arc| arc.style.clone());
|
||||
let Some(style) = style else {
|
||||
resulting_layers.push(layer.to_node());
|
||||
continue;
|
||||
};
|
||||
|
||||
let has_fill = !matches!(style.fill, Fill::None);
|
||||
// `style.stroke` is `Some` whenever a `Stroke` node is in the chain, even with weight 0 or a transparent color.
|
||||
// So `is_some()` would treat invisibly-stroked fill-only layers as having a stroke.
|
||||
let has_stroke = style.stroke.as_ref().is_some_and(|s| s.has_renderable_stroke());
|
||||
|
||||
// No stroke means there's nothing to solidify. Fill-only layers are already in the desired form, so skip.
|
||||
if !has_stroke {
|
||||
resulting_layers.push(layer.to_node());
|
||||
continue;
|
||||
}
|
||||
|
||||
let solidify_id = NodeId::new();
|
||||
self.network_interface.insert_node(solidify_id, solidify_stroke_definition.default_node_template(), &[]);
|
||||
self.network_interface.move_node_to_chain_start(&solidify_id, layer, &[], false);
|
||||
|
||||
if has_fill && has_stroke {
|
||||
let (existing_index, new_index) = (0_f64, 1_f64);
|
||||
|
||||
let existing_index_template = index_elements_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(existing_index), false))]);
|
||||
let existing_index_id = NodeId::new();
|
||||
self.network_interface.insert_node(existing_index_id, existing_index_template, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&existing_index_id, layer, &[], false);
|
||||
|
||||
let parent = layer.parent(self.metadata()).unwrap_or(LayerNodeIdentifier::ROOT_PARENT);
|
||||
let insert_index = parent.children(self.metadata()).position(|c| c == layer).unwrap_or(0);
|
||||
|
||||
let new_layer_id = NodeId::new();
|
||||
let new_layer = ModifyInputsContext::new(&mut self.network_interface, responses).create_layer(new_layer_id);
|
||||
self.network_interface.move_layer_to_stack(new_layer, parent, insert_index, &[]);
|
||||
|
||||
// Copy the original layer's stored name so the new layer shares it
|
||||
let original_name = self
|
||||
.network_interface
|
||||
.node_metadata(&layer.to_node(), &[])
|
||||
.map(|m| m.persistent_metadata.display_name.clone())
|
||||
.unwrap_or_default();
|
||||
if !original_name.is_empty() {
|
||||
self.network_interface.set_display_name(&new_layer_id, original_name, &[]);
|
||||
}
|
||||
|
||||
let new_index_template = index_elements_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(new_index), false))]);
|
||||
let new_index_id = NodeId::new();
|
||||
self.network_interface.insert_node(new_index_id, new_index_template, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&new_index_id, new_layer, &[], false);
|
||||
|
||||
self.network_interface.create_wire(&OutputConnector::node(solidify_id, 0), &InputConnector::node(new_index_id, 0), &[]);
|
||||
|
||||
resulting_layers.push(layer.to_node());
|
||||
resulting_layers.push(new_layer.to_node());
|
||||
} else {
|
||||
resulting_layers.push(layer.to_node());
|
||||
}
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: resulting_layers });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
/// Helper method for MoveSelectedLayersTo message.
|
||||
/// Handles moving selected layers to a new parent with proper transform preservation.
|
||||
fn handle_move_selected_layers_to(&mut self, parent: LayerNodeIdentifier, insert_index: usize, responses: &mut VecDeque<Message>) {
|
||||
@@ -2525,7 +2361,7 @@ impl DocumentMessageHandler {
|
||||
});
|
||||
|
||||
if layer_to_move.parent(self.metadata()) != Some(parent) {
|
||||
// TODO: Fix this so it works when dragging a layer into a group parent which has a Transform node, which used to work before #2689 caused this regression by removing the empty `List<Vector>` item.
|
||||
// TODO: Fix this so it works when dragging a layer into a group parent which has a Transform node, which used to work before #2689 caused this regression by removing the empty vector table row.
|
||||
// TODO: See #2688 for this issue.
|
||||
let layer_local_transform = self.network_interface.document_metadata().transform_to_viewport(layer_to_move);
|
||||
let undo_transform = self.network_interface.document_metadata().transform_to_viewport(parent).inverse();
|
||||
@@ -3288,23 +3124,17 @@ impl DocumentMessageHandler {
|
||||
let group_folder_type = GroupFolderType::Layer;
|
||||
DocumentMessage::GroupSelectedLayers { group_folder_type }.into()
|
||||
})
|
||||
.on_drag_drop(|_| {
|
||||
let group_folder_type = GroupFolderType::Layer;
|
||||
DocumentMessage::GroupSelectedLayers { group_folder_type }.into()
|
||||
})
|
||||
.disabled(!has_selection)
|
||||
.widget_instance(),
|
||||
IconButton::new("NewLayer", 24)
|
||||
.tooltip_label("New Layer")
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::CreateEmptyFolder))
|
||||
.on_update(|_| DocumentMessage::CreateEmptyFolder.into())
|
||||
.on_drag_drop(|_| DocumentMessage::DuplicateSelectedLayers.into())
|
||||
.widget_instance(),
|
||||
IconButton::new("Trash", 24)
|
||||
.tooltip_label("Delete Selected")
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::DeleteSelectedLayers))
|
||||
.on_update(|_| DocumentMessage::DeleteSelectedLayers.into())
|
||||
.on_drag_drop(|_| DocumentMessage::DeleteSelectedLayers.into())
|
||||
.disabled(!has_selection)
|
||||
.widget_instance(),
|
||||
];
|
||||
@@ -3449,7 +3279,7 @@ impl DocumentMessageHandler {
|
||||
/// Create a network interface with a single export
|
||||
fn default_document_network_interface() -> NodeNetworkInterface {
|
||||
let mut network_interface = NodeNetworkInterface::default();
|
||||
network_interface.add_export(TaggedValue::TypeDefault(descriptor!(graphene_std::list::List<graphene_std::Artboard>)), -1, "", &[]);
|
||||
network_interface.add_export(TaggedValue::Artboard(Default::default()), -1, "", &[]);
|
||||
network_interface
|
||||
}
|
||||
|
||||
|
||||
@@ -2,16 +2,18 @@ use super::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use glam::{DAffine2, IVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::brush::brush_stroke::BrushStroke;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster_types::Image;
|
||||
use graphene_std::raster_types::{CPU, Raster};
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::table::Table;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{Fill, GradientSpreadMethod, GradientType, Stroke};
|
||||
use graphene_std::vector::{GradientStops, PointId, VectorModificationType};
|
||||
use graphene_std::vector::PointId;
|
||||
use graphene_std::vector::VectorModificationType;
|
||||
use graphene_std::vector::style::{Fill, Stroke};
|
||||
use graphene_std::{Artboard, Color};
|
||||
|
||||
#[impl_message(Message, DocumentMessage, GraphOperation)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
@@ -24,23 +26,6 @@ pub enum GraphOperationMessage {
|
||||
layer: LayerNodeIdentifier,
|
||||
fill: f64,
|
||||
},
|
||||
GradientStopsSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
stops: GradientStops,
|
||||
},
|
||||
GradientLineSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
start: DVec2,
|
||||
end: DVec2,
|
||||
},
|
||||
GradientTypeSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
gradient_type: GradientType,
|
||||
},
|
||||
GradientSpreadMethodSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
spread_method: GradientSpreadMethod,
|
||||
},
|
||||
OpacitySet {
|
||||
layer: LayerNodeIdentifier,
|
||||
opacity: f64,
|
||||
@@ -81,14 +66,11 @@ pub enum GraphOperationMessage {
|
||||
},
|
||||
NewArtboard {
|
||||
id: NodeId,
|
||||
location: DVec2,
|
||||
dimensions: DVec2,
|
||||
background: Color,
|
||||
clip: bool,
|
||||
artboard: Artboard,
|
||||
},
|
||||
NewBitmapLayer {
|
||||
id: NodeId,
|
||||
image: Image<Color>,
|
||||
image_frame: Table<Raster<CPU>>,
|
||||
parent: LayerNodeIdentifier,
|
||||
insert_index: usize,
|
||||
},
|
||||
@@ -137,8 +119,8 @@ pub enum GraphOperationMessage {
|
||||
},
|
||||
ResizeArtboard {
|
||||
layer: LayerNodeIdentifier,
|
||||
location: DVec2,
|
||||
dimensions: DVec2,
|
||||
location: IVec2,
|
||||
dimensions: IVec2,
|
||||
},
|
||||
RemoveArtboards,
|
||||
NewSvg {
|
||||
|
||||
+23
-47
@@ -8,14 +8,14 @@ use crate::messages::portfolio::document::utility_types::nodes::CollapsedLayers;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_clip_mode;
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::descriptor;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
|
||||
use graphene_std::table::Table;
|
||||
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::{Artboard, Color};
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct GraphOperationMessageContext<'a> {
|
||||
@@ -27,7 +27,7 @@ pub struct GraphOperationMessageContext<'a> {
|
||||
#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, serde::Deserialize, ExtractField)]
|
||||
pub struct GraphOperationMessageHandler {}
|
||||
|
||||
// GraphOperationMessageHandler always modified the document network. This is so changes to the Layers panel will only affect the document network.
|
||||
// GraphOperationMessageHandler always modified the document network. This is so changes to the layers panel will only affect the document network.
|
||||
// For changes to the selected network, use NodeGraphMessageHandler. No NodeGraphMessage's should be added here, since they will affect the selected nested network.
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for GraphOperationMessageHandler {
|
||||
@@ -42,27 +42,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
}
|
||||
GraphOperationMessage::BlendingFillSet { layer, fill } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.opacity_fill_set(fill);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::GradientStopsSet { layer, stops } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.gradient_stops_set(stops);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::GradientLineSet { layer, start, end } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.gradient_line_set(start, end);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::GradientTypeSet { layer, gradient_type } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.gradient_type_set(gradient_type);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::GradientSpreadMethodSet { layer, spread_method } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.gradient_spread_method_set(spread_method);
|
||||
modify_inputs.blending_fill_set(fill);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::OpacitySet { layer, opacity } => {
|
||||
@@ -128,16 +108,11 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
|
||||
network_interface.force_set_upstream_to_chain(&first_chain_node, &[]);
|
||||
}
|
||||
GraphOperationMessage::NewArtboard {
|
||||
id,
|
||||
location,
|
||||
dimensions,
|
||||
background,
|
||||
clip,
|
||||
} => {
|
||||
GraphOperationMessage::NewArtboard { id, artboard } => {
|
||||
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
|
||||
|
||||
let artboard_layer = modify_inputs.create_artboard(id, location, dimensions, background, clip);
|
||||
let artboard_location = artboard.location;
|
||||
let artboard_layer = modify_inputs.create_artboard(id, artboard);
|
||||
network_interface.move_layer_to_stack(artboard_layer, LayerNodeIdentifier::ROOT_PARENT, 0, &[]);
|
||||
|
||||
// If there is a non artboard feeding into the primary input of the artboard, move it to the secondary input
|
||||
@@ -163,14 +138,14 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
// Apply a translation to prevent the content from shifting
|
||||
responses.add(GraphOperationMessage::TransformChange {
|
||||
layer,
|
||||
transform: DAffine2::from_translation(-location),
|
||||
transform: DAffine2::from_translation(-artboard_location.as_dvec2()),
|
||||
transform_in: TransformIn::Local,
|
||||
skip_rerender: true,
|
||||
});
|
||||
}
|
||||
|
||||
// Set the bottom input of the artboard back to artboard
|
||||
let bottom_input = NodeInput::type_default(descriptor!(List<Artboard>), true);
|
||||
let bottom_input = NodeInput::value(TaggedValue::Artboard(Table::new()), true);
|
||||
network_interface.set_input(&InputConnector::node(artboard_layer.to_node(), 0), bottom_input, &[]);
|
||||
} else {
|
||||
// We have some non layers (e.g. just a rectangle node). We disconnect the bottom input and connect it to the left input.
|
||||
@@ -178,17 +153,22 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
network_interface.set_input(&InputConnector::node(artboard_layer.to_node(), 1), primary_input, &[]);
|
||||
|
||||
// Set the bottom input of the artboard back to artboard
|
||||
let bottom_input = NodeInput::type_default(descriptor!(List<Artboard>), true);
|
||||
let bottom_input = NodeInput::value(TaggedValue::Artboard(Table::new()), true);
|
||||
network_interface.set_input(&InputConnector::node(artboard_layer.to_node(), 0), bottom_input, &[]);
|
||||
}
|
||||
}
|
||||
responses.add_front(NodeGraphMessage::SelectedNodesSet { nodes: vec![id] });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
GraphOperationMessage::NewBitmapLayer { id, image, parent, insert_index } => {
|
||||
GraphOperationMessage::NewBitmapLayer {
|
||||
id,
|
||||
image_frame,
|
||||
parent,
|
||||
insert_index,
|
||||
} => {
|
||||
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
|
||||
let layer = modify_inputs.create_layer(id);
|
||||
modify_inputs.insert_image_data(image, layer);
|
||||
modify_inputs.insert_image_data(image_frame, layer);
|
||||
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
@@ -222,12 +202,10 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
|
||||
responses.add(NodeGraphMessage::SetDisplayNameImpl {
|
||||
node_id: id,
|
||||
network_path: Vec::new(),
|
||||
alias: layer_alias.to_string(),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetDisplayNameImpl {
|
||||
node_id: control_path_id,
|
||||
network_path: Vec::new(),
|
||||
alias: path_alias.to_string(),
|
||||
});
|
||||
}
|
||||
@@ -272,7 +250,6 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
|
||||
responses.add(NodeGraphMessage::SetDisplayNameImpl {
|
||||
node_id: id,
|
||||
network_path: Vec::new(),
|
||||
alias: "Boolean Operation".to_string(),
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
@@ -323,6 +300,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
let layer = modify_inputs.create_layer(id);
|
||||
modify_inputs.insert_text(text, font, typesetting, layer);
|
||||
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
|
||||
responses.add(GraphOperationMessage::StrokeSet { layer, stroke: Stroke::default() });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
GraphOperationMessage::ResizeArtboard { layer, location, dimensions } => {
|
||||
@@ -370,7 +348,6 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
|
||||
responses.add(NodeGraphMessage::SetDisplayName {
|
||||
node_id,
|
||||
network_path: Vec::new(),
|
||||
alias: network_interface.display_name(&artboard.to_node(), &[]),
|
||||
skip_adding_history_step: true,
|
||||
});
|
||||
@@ -485,8 +462,7 @@ struct ArtboardInfo {
|
||||
}
|
||||
|
||||
fn usvg_color(c: usvg::Color, a: f32) -> Color {
|
||||
// `usvg::Color` channels are u8 sRGB display values (gamma-encoded); lift to linear-light for the internal `Color`
|
||||
Color::from_gamma_srgb_channels(c.red as f32 / 255., c.green as f32 / 255., c.blue as f32 / 255., a)
|
||||
Color::from_rgbaf32_unchecked(c.red as f32 / 255., c.green as f32 / 255., c.blue as f32 / 255., a)
|
||||
}
|
||||
|
||||
fn usvg_transform(c: usvg::Transform) -> DAffine2 {
|
||||
@@ -692,7 +668,7 @@ fn import_usvg_path(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node,
|
||||
|
||||
modify_inputs.insert_vector(subpaths, layer, has_transform, path.fill().is_some(), path.stroke().is_some());
|
||||
|
||||
if has_transform && let Some(transform_node_id) = modify_inputs.existing_proto_node_id(graphene_std::transform_nodes::transform::IDENTIFIER, false) {
|
||||
if has_transform && let Some(transform_node_id) = modify_inputs.existing_network_node_id("Transform", false) {
|
||||
transform_utils::update_transform(modify_inputs.network_interface, &transform_node_id, node_transform);
|
||||
}
|
||||
|
||||
@@ -742,10 +718,10 @@ fn set_import_child_positions(
|
||||
let child_pos = IVec2::new(child_x, current_y);
|
||||
|
||||
if i == 0 {
|
||||
// Top of stack: set to `Absolute` position
|
||||
// Top of stack — set to `Absolute` position
|
||||
network_interface.set_layer_position_for_import(&child_layer.to_node(), LayerPosition::Absolute(child_pos), &[]);
|
||||
} else {
|
||||
// Below top: set `Stack` with `y_offset` based on previous sibling's subtree extent
|
||||
// Below top — set `Stack` with `y_offset` based on previous sibling's subtree extent
|
||||
let prev_sibling_svg_index = n - i;
|
||||
let y_offset = child_extents_svg_order[prev_sibling_svg_index] + STACK_VERTICAL_GAP as u32;
|
||||
network_interface.set_layer_position_for_import(&child_layer.to_node(), LayerPosition::Stack(y_offset), &[]);
|
||||
|
||||
@@ -3,18 +3,19 @@ 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::{self, InputConnector, NodeNetworkInterface, OutputConnector};
|
||||
use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use glam::{DAffine2, IVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graph_craft::{ProtoNodeIdentifier, concrete, descriptor};
|
||||
use graph_craft::{ProtoNodeIdentifier, concrete};
|
||||
use graphene_std::brush::brush_stroke::BrushStroke;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster_types::Image;
|
||||
use graphene_std::raster_types::{CPU, Raster};
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::table::Table;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{Fill, GradientSpreadMethod, GradientType, Stroke};
|
||||
use graphene_std::vector::{GradientStops, PointId, Vector, VectorModification, VectorModificationType};
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::vector::style::{Fill, Stroke};
|
||||
use graphene_std::vector::{PointId, VectorModificationType};
|
||||
use graphene_std::{Artboard, Color, Graphic, NodeInputDecleration};
|
||||
|
||||
#[derive(PartialEq, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
|
||||
@@ -129,27 +130,25 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
LayerNodeIdentifier::new(new_id, self.network_interface)
|
||||
}
|
||||
|
||||
/// Creates an artboard as the primary export for the document network.
|
||||
pub fn create_artboard(&mut self, new_id: NodeId, location: DVec2, dimensions: DVec2, background: Color, clip: bool) -> LayerNodeIdentifier {
|
||||
/// Creates an artboard as the primary export for the document network
|
||||
pub fn create_artboard(&mut self, new_id: NodeId, artboard: Artboard) -> LayerNodeIdentifier {
|
||||
let artboard_node_template = resolve_network_node_type("Artboard").expect("Node").node_template_input_override([
|
||||
Some(NodeInput::type_default(descriptor!(List<Artboard>), true)),
|
||||
Some(NodeInput::type_default(descriptor!(List<Graphic>), true)),
|
||||
Some(NodeInput::value(TaggedValue::DVec2(location), false)),
|
||||
Some(NodeInput::value(TaggedValue::DVec2(dimensions), false)),
|
||||
Some(NodeInput::value(TaggedValue::Color(Some(background)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Bool(clip), false)),
|
||||
Some(NodeInput::value(TaggedValue::Artboard(Default::default()), true)),
|
||||
Some(NodeInput::value(TaggedValue::Graphic(Default::default()), true)),
|
||||
Some(NodeInput::value(TaggedValue::DVec2(artboard.location.into()), false)),
|
||||
Some(NodeInput::value(TaggedValue::DVec2(artboard.dimensions.into()), false)),
|
||||
Some(NodeInput::value(TaggedValue::Color(Table::new_from_element(artboard.background)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Bool(artboard.clip), false)),
|
||||
]);
|
||||
self.network_interface.insert_node(new_id, artboard_node_template, &[]);
|
||||
LayerNodeIdentifier::new(new_id, self.network_interface)
|
||||
}
|
||||
|
||||
pub fn insert_boolean_data(&mut self, operation: graphene_std::vector::misc::BooleanOperation, layer: LayerNodeIdentifier) {
|
||||
let boolean = resolve_proto_node_type(graphene_std::path_bool_nodes::boolean_operation::IDENTIFIER)
|
||||
.expect("Boolean node does not exist")
|
||||
.node_template_input_override([
|
||||
Some(NodeInput::type_default(descriptor!(List<Graphic>), true)),
|
||||
Some(NodeInput::value(TaggedValue::BooleanOperation(operation), false)),
|
||||
]);
|
||||
let boolean = resolve_network_node_type("Boolean Operation").expect("Boolean node does not exist").node_template_input_override([
|
||||
Some(NodeInput::value(TaggedValue::Graphic(Default::default()), true)),
|
||||
Some(NodeInput::value(TaggedValue::BooleanOperation(operation), false)),
|
||||
]);
|
||||
|
||||
let boolean_id = NodeId::new();
|
||||
self.network_interface.insert_node(boolean_id, boolean, &[]);
|
||||
@@ -157,9 +156,10 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
pub fn insert_blend_data(&mut self, layer: LayerNodeIdentifier, count: f64) -> NodeId {
|
||||
let blend = resolve_network_node_type("Blend")
|
||||
.expect("Blend node does not exist")
|
||||
.node_template_input_override([Some(NodeInput::type_default(descriptor!(List<Graphic>), true)), Some(NodeInput::value(TaggedValue::F64(count), false))]);
|
||||
let blend = resolve_network_node_type("Blend").expect("Blend node does not exist").node_template_input_override([
|
||||
Some(NodeInput::value(TaggedValue::Graphic(Default::default()), true)),
|
||||
Some(NodeInput::value(TaggedValue::F64(count), false)),
|
||||
]);
|
||||
|
||||
let blend_id = NodeId::new();
|
||||
self.network_interface.insert_node(blend_id, blend, &[]);
|
||||
@@ -171,7 +171,10 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
pub fn insert_morph_data(&mut self, layer: LayerNodeIdentifier) -> NodeId {
|
||||
let morph = resolve_proto_node_type(graphene_std::vector::morph::IDENTIFIER)
|
||||
.expect("Morph node does not exist")
|
||||
.node_template_input_override([Some(NodeInput::type_default(descriptor!(List<Graphic>), true)), Some(NodeInput::value(TaggedValue::F64(0.5), false))]);
|
||||
.node_template_input_override([
|
||||
Some(NodeInput::value(TaggedValue::Graphic(Default::default()), true)),
|
||||
Some(NodeInput::value(TaggedValue::F64(0.5), false)),
|
||||
]);
|
||||
|
||||
let morph_id = NodeId::new();
|
||||
self.network_interface.insert_node(morph_id, morph, &[]);
|
||||
@@ -208,21 +211,17 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
pub fn insert_vector(&mut self, subpaths: Vec<Subpath<PointId>>, layer: LayerNodeIdentifier, include_transform: bool, include_fill: bool, include_stroke: bool) {
|
||||
// Build a VectorModification that reproduces the geometry (same format the Pen tool uses)
|
||||
let vector = Vector::from_subpaths(subpaths, true);
|
||||
let modification = Box::new(VectorModification::create_from_vector(&vector));
|
||||
let vector = Table::new_from_element(Vector::from_subpaths(subpaths, true));
|
||||
|
||||
let shape = resolve_network_node_type("Path")
|
||||
.expect("Path node does not exist")
|
||||
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::VectorModification(modification), false))]);
|
||||
.node_template_input_override([Some(NodeInput::value(TaggedValue::Vector(vector), false))]);
|
||||
let shape_id = NodeId::new();
|
||||
self.network_interface.insert_node(shape_id, shape, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&shape_id, layer, &[], self.import);
|
||||
|
||||
if include_transform {
|
||||
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
|
||||
.expect("Transform node does not exist")
|
||||
.default_node_template();
|
||||
let transform = resolve_network_node_type("Transform").expect("Transform node does not exist").default_node_template();
|
||||
let transform_id = NodeId::new();
|
||||
self.network_interface.insert_node(transform_id, transform, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[], self.import);
|
||||
@@ -264,8 +263,9 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.tilt), false)),
|
||||
Some(NodeInput::value(TaggedValue::TextAlign(typesetting.align), false)),
|
||||
]);
|
||||
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
|
||||
.expect("Transform node does not exist")
|
||||
let transform = resolve_network_node_type("Transform").expect("Transform node does not exist").default_node_template();
|
||||
let stroke = resolve_proto_node_type(graphene_std::vector_nodes::stroke::IDENTIFIER)
|
||||
.expect("Stroke node does not exist")
|
||||
.default_node_template();
|
||||
let fill = resolve_proto_node_type(graphene_std::vector_nodes::fill::IDENTIFIER)
|
||||
.expect("Fill node does not exist")
|
||||
@@ -279,6 +279,10 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.network_interface.insert_node(transform_id, transform, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[], self.import);
|
||||
|
||||
let stroke_id = NodeId::new();
|
||||
self.network_interface.insert_node(stroke_id, stroke, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&stroke_id, layer, &[], self.import);
|
||||
|
||||
let fill_id = NodeId::new();
|
||||
self.network_interface.insert_node(fill_id, fill, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&fill_id, layer, &[], self.import);
|
||||
@@ -287,23 +291,24 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
pub fn insert_color_value(&mut self, color: Color, layer: LayerNodeIdentifier) {
|
||||
let color_value = resolve_proto_node_type(graphene_std::math_nodes::color_value::IDENTIFIER)
|
||||
.expect("Color Value node does not exist")
|
||||
.node_template_input_override([Some(NodeInput::value(TaggedValue::None, false)), Some(NodeInput::value(TaggedValue::Color(Some(color)), false))]);
|
||||
.node_template_input_override([
|
||||
Some(NodeInput::value(TaggedValue::None, false)),
|
||||
Some(NodeInput::value(TaggedValue::Color(Table::new_from_element(color)), false)),
|
||||
]);
|
||||
|
||||
let color_value_id = NodeId::new();
|
||||
self.network_interface.insert_node(color_value_id, color_value, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&color_value_id, layer, &[], self.import);
|
||||
}
|
||||
|
||||
pub fn insert_image_data(&mut self, image: Image<Color>, layer: LayerNodeIdentifier) {
|
||||
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
|
||||
.expect("Transform node does not exist")
|
||||
.default_node_template();
|
||||
let image_node = resolve_proto_node_type(graphene_std::raster_nodes::std_nodes::image::IDENTIFIER)
|
||||
.expect("Image node does not exist")
|
||||
.node_template_input_override([Some(NodeInput::value(TaggedValue::None, false)), Some(NodeInput::value(TaggedValue::ImageData(image), false))]);
|
||||
pub fn insert_image_data(&mut self, image_frame: Table<Raster<CPU>>, layer: LayerNodeIdentifier) {
|
||||
let transform = resolve_network_node_type("Transform").expect("Transform node does not exist").default_node_template();
|
||||
let image = resolve_proto_node_type(graphene_std::raster_nodes::std_nodes::image_value::IDENTIFIER)
|
||||
.expect("ImageValue node does not exist")
|
||||
.node_template_input_override([Some(NodeInput::value(TaggedValue::None, false)), Some(NodeInput::value(TaggedValue::Raster(image_frame), false))]);
|
||||
|
||||
let image_id = NodeId::new();
|
||||
self.network_interface.insert_node(image_id, image_node, &[]);
|
||||
self.network_interface.insert_node(image_id, image, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&image_id, layer, &[], self.import);
|
||||
|
||||
let transform_id = NodeId::new();
|
||||
@@ -383,10 +388,10 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
};
|
||||
|
||||
// If inserting a 'Path' node, insert a 'Flatten Path' node if the type is `Graphic`.
|
||||
// TODO: Allow the 'Path' node to operate on `List` data by utilizing the reference (index or ID?) for each item.
|
||||
// TODO: Allow the 'Path' node to operate on table data by utilizing the reference (index or ID?) for each row.
|
||||
if node_definition.identifier == "Path" {
|
||||
let layer_input_type = self.network_interface.input_type(&InputConnector::node(output_layer.to_node(), 1), &[]);
|
||||
if layer_input_type.compiled_nested_type() == Some(&concrete!(List<Graphic>)) {
|
||||
if layer_input_type.compiled_nested_type() == Some(&concrete!(Table<Graphic>)) {
|
||||
let Some(flatten_path_definition) = resolve_proto_node_type(graphene_std::vector_nodes::flatten_path::IDENTIFIER) else {
|
||||
log::error!("Flatten Path does not exist in ModifyInputsContext::existing_node_id");
|
||||
return None;
|
||||
@@ -413,15 +418,15 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
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);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(Table::new()), 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);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(Table::new_from_element(*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);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Gradient(gradient.clone()), false), true);
|
||||
}
|
||||
}
|
||||
let input_connector = InputConnector::node(fill_node_id, fill_index);
|
||||
@@ -429,160 +434,35 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
pub fn blend_mode_set(&mut self, blend_mode: BlendMode) {
|
||||
let Some(blend_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::blend_mode::IDENTIFIER, true) else {
|
||||
let Some(blend_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::blending::IDENTIFIER, true) else {
|
||||
return;
|
||||
};
|
||||
let input_connector = InputConnector::node(blend_node_id, graphene_std::blending_nodes::blend_mode::BlendModeInput::INDEX);
|
||||
let input_connector = InputConnector::node(blend_node_id, 1);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::BlendMode(blend_mode), false), false);
|
||||
}
|
||||
|
||||
pub fn opacity_set(&mut self, opacity: f64) {
|
||||
let Some(opacity_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::opacity::IDENTIFIER, true) else {
|
||||
let Some(blend_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::blending::IDENTIFIER, true) else {
|
||||
return;
|
||||
};
|
||||
// Enable the `has_opacity` checkbox so the value is applied
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::HasOpacityInput::INDEX),
|
||||
NodeInput::value(TaggedValue::Bool(true), false),
|
||||
false,
|
||||
);
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::OpacityInput::INDEX),
|
||||
NodeInput::value(TaggedValue::F64(opacity * 100.), false),
|
||||
false,
|
||||
);
|
||||
let input_connector = InputConnector::node(blend_node_id, 2);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(opacity * 100.), false), false);
|
||||
}
|
||||
|
||||
pub fn opacity_fill_set(&mut self, fill: f64) {
|
||||
// Reuse an existing Opacity node to avoid a redundant chain walk on slider drags
|
||||
let identifier = graphene_std::blending_nodes::opacity::IDENTIFIER;
|
||||
let existing = self.existing_proto_node_id(identifier.clone(), false);
|
||||
let existed = existing.is_some();
|
||||
let Some(opacity_node_id) = existing.or_else(|| self.existing_proto_node_id(identifier, true)) else {
|
||||
pub fn blending_fill_set(&mut self, fill: f64) {
|
||||
let Some(blend_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::blending::IDENTIFIER, true) else {
|
||||
return;
|
||||
};
|
||||
// Freshly-created node defaults to opacity enabled; disable it so the fill slider works independently
|
||||
if !existed {
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::HasOpacityInput::INDEX),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
false,
|
||||
);
|
||||
}
|
||||
// Enable the `has_fill` checkbox so the value is applied
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::HasFillInput::INDEX),
|
||||
NodeInput::value(TaggedValue::Bool(true), false),
|
||||
false,
|
||||
);
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::FillInput::INDEX),
|
||||
NodeInput::value(TaggedValue::F64(fill * 100.), false),
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
/// Set the GradientStops list on the 'Gradient Value' node, creating it if necessary.
|
||||
pub fn gradient_stops_set(&mut self, stops: GradientStops) {
|
||||
let Some(gradient_node_id) = self.existing_proto_node_id(graphene_std::math_nodes::gradient_value::IDENTIFIER, true) else {
|
||||
return;
|
||||
};
|
||||
let input_connector = InputConnector::node(gradient_node_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`.
|
||||
/// 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) {
|
||||
let Some(output_layer) = self.get_output_layer() else { return };
|
||||
|
||||
let transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
|
||||
let upstream_transforms: Vec<NodeId> = self
|
||||
.network_interface
|
||||
.upstream_flow_back_from_nodes(vec![output_layer.to_node()], &[], network_interface::FlowType::HorizontalFlow)
|
||||
.skip(1)
|
||||
.take_while(|node_id| !self.network_interface.is_layer(node_id, &[]))
|
||||
.filter(|node_id| self.network_interface.reference(node_id, &[]).as_ref() == Some(&transform_reference))
|
||||
.collect();
|
||||
|
||||
// Upstream walk yields downstream-to-upstream order, so the first hit is the chain's last `Transform`
|
||||
let (last_transform_node_id, prior_transforms) = match upstream_transforms.split_first() {
|
||||
Some((last, prior)) => (Some(*last), prior),
|
||||
None => (None, [].as_slice()),
|
||||
};
|
||||
|
||||
// `composed_old` = T_n * T_{n-1} * ... * T_1, `prior_combined` = same product without T_n
|
||||
let compose = |ids: &[_]| {
|
||||
ids.iter().fold(DAffine2::IDENTITY, |acc, transform_id| {
|
||||
self.network_interface
|
||||
.document_network()
|
||||
.nodes
|
||||
.get(transform_id)
|
||||
.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_x_axis = new_end - new_start;
|
||||
let preserved_y_axis = scale_y_axis_to_match_new_x(composed_old.matrix2.x_axis, composed_old.matrix2.y_axis, new_x_axis);
|
||||
let new_composed = DAffine2 {
|
||||
matrix2: glam::DMat2::from_cols(new_x_axis, preserved_y_axis),
|
||||
translation: new_start,
|
||||
};
|
||||
|
||||
let last_transform_value = new_composed * prior_combined.inverse();
|
||||
|
||||
let transform_node_id = if let Some(id) = last_transform_node_id {
|
||||
id
|
||||
} else {
|
||||
// Don't pollute the graph with an identity 'Transform' node
|
||||
if last_transform_value.abs_diff_eq(DAffine2::IDENTITY, 1e-6) {
|
||||
return;
|
||||
}
|
||||
let Some(id) = self.existing_proto_node_id(graphene_std::transform_nodes::transform::IDENTIFIER, true) else {
|
||||
return;
|
||||
};
|
||||
id
|
||||
};
|
||||
|
||||
transform_utils::update_transform(self.network_interface, &transform_node_id, last_transform_value);
|
||||
self.responses.add(PropertiesPanelMessage::Refresh);
|
||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
/// Write the gradient type to the last 'Gradient Type' node in the chain, inserting one only when the value differs
|
||||
/// from the default (`Linear`).
|
||||
pub fn gradient_type_set(&mut self, gradient_type: GradientType) {
|
||||
let identifier = graphene_std::math_nodes::gradient_type::IDENTIFIER;
|
||||
let create_if_nonexistent = gradient_type != GradientType::default();
|
||||
let Some(node_id) = self.existing_proto_node_id(identifier, create_if_nonexistent) else { return };
|
||||
|
||||
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_type::GradientTypeInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientType(gradient_type), false), false);
|
||||
}
|
||||
|
||||
/// Write the spread method to the last 'Spread Method' node in the chain, inserting one only when the value differs
|
||||
/// from the default (`Pad`).
|
||||
pub fn gradient_spread_method_set(&mut self, spread_method: GradientSpreadMethod) {
|
||||
let identifier = graphene_std::math_nodes::spread_method::IDENTIFIER;
|
||||
let create_if_nonexistent = spread_method != GradientSpreadMethod::default();
|
||||
let Some(node_id) = self.existing_proto_node_id(identifier, create_if_nonexistent) else { return };
|
||||
|
||||
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::spread_method::SpreadMethodInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientSpreadMethod(spread_method), false), false);
|
||||
let input_connector = InputConnector::node(blend_node_id, 3);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(fill * 100.), false), false);
|
||||
}
|
||||
|
||||
pub fn clip_mode_toggle(&mut self, clip_mode: Option<bool>) {
|
||||
let clip = !clip_mode.unwrap_or(false);
|
||||
let Some(clip_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::clipping_mask::IDENTIFIER, true) else {
|
||||
let Some(clip_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::blending::IDENTIFIER, true) else {
|
||||
return;
|
||||
};
|
||||
let input_connector = InputConnector::node(clip_node_id, graphene_std::blending_nodes::clipping_mask::ClipInput::INDEX);
|
||||
let input_connector = InputConnector::node(clip_node_id, 4);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Bool(clip), false), false);
|
||||
}
|
||||
|
||||
@@ -591,8 +471,10 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
return;
|
||||
};
|
||||
|
||||
let stroke_color = if let Some(color) = stroke.color { Table::new_from_element(color) } else { Table::new() };
|
||||
|
||||
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);
|
||||
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::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);
|
||||
@@ -605,8 +487,8 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.join_miter_limit), false), false);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintOrderInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::PaintOrder(stroke.paint_order), false), false);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashLengthsInput::<graphene_std::list::List<f64>>::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(stroke.dash_lengths), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashLengthsInput::<Vec<f64>>::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::VecF64(stroke.dash_lengths), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.dash_offset), false), true);
|
||||
}
|
||||
@@ -616,7 +498,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
pub fn transform_change_with_parent(&mut self, transform: DAffine2, transform_in: TransformIn, parent_transform: DAffine2, skip_rerender: bool) {
|
||||
// Get the existing upstream Transform node and its transform, if present, otherwise use the identity transform
|
||||
let (layer_transform, transform_node_id) = self
|
||||
.existing_proto_node_id(graphene_std::transform_nodes::transform::IDENTIFIER, false)
|
||||
.existing_network_node_id("Transform", false)
|
||||
.and_then(|transform_node_id| {
|
||||
let document_node = self.network_interface.document_network().nodes.get(&transform_node_id)?;
|
||||
Some((transform_utils::get_current_transform(&document_node.inputs), transform_node_id))
|
||||
@@ -640,32 +522,17 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
/// A new Transform node is created if one does not exist, unless it would be given the identity transform.
|
||||
pub fn transform_set(&mut self, transform: DAffine2, transform_in: TransformIn, skip_rerender: bool) {
|
||||
// Get the existing upstream Transform node, if present
|
||||
let transform_node_id = self.existing_proto_node_id(graphene_std::transform_nodes::transform::IDENTIFIER, false);
|
||||
let transform_node_id = self.existing_network_node_id("Transform", false);
|
||||
|
||||
// Compute the Transform node value so `transform_to_viewport` matches the target after re-render
|
||||
let final_transform = match transform_in {
|
||||
TransformIn::Local => transform,
|
||||
TransformIn::Scope { scope } => scope * transform,
|
||||
TransformIn::Viewport => {
|
||||
let Some(layer) = self.layer_node else { return };
|
||||
let metadata = self.network_interface.document_metadata();
|
||||
let parent_inverse = metadata.downstream_transform_to_viewport(layer).inverse();
|
||||
|
||||
// Compensate for item 0's baseline offset (multi-item Text only) so the layer doesn't jump by it.
|
||||
// Gated on `text_frames` because metadata can be stale mid-handler.
|
||||
if metadata.text_frames.contains_key(&layer) {
|
||||
let local_transform = metadata.local_transforms.get(&layer.to_node()).copied().unwrap_or(DAffine2::IDENTITY);
|
||||
let current_transform_node_value = transform_node_id
|
||||
.and_then(|id| self.network_interface.document_network().nodes.get(&id))
|
||||
.map(|node| transform_utils::get_current_transform(&node.inputs))
|
||||
.unwrap_or(DAffine2::IDENTITY);
|
||||
parent_inverse * transform * local_transform.inverse() * current_transform_node_value
|
||||
} else {
|
||||
parent_inverse * transform
|
||||
}
|
||||
}
|
||||
// Get a transform appropriate for the requested space
|
||||
let to_transform = match transform_in {
|
||||
TransformIn::Local => DAffine2::IDENTITY,
|
||||
TransformIn::Scope { scope } => scope,
|
||||
TransformIn::Viewport => self.network_interface.document_metadata().downstream_transform_to_viewport(self.layer_node.unwrap()).inverse(),
|
||||
};
|
||||
|
||||
// Set the transform value to the Transform node
|
||||
let final_transform = to_transform * transform;
|
||||
self.transform_set_direct(final_transform, skip_rerender, transform_node_id);
|
||||
}
|
||||
|
||||
@@ -680,7 +547,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
// Create the Transform node
|
||||
self.existing_proto_node_id(graphene_std::transform_nodes::transform::IDENTIFIER, true)
|
||||
self.existing_network_node_id("Transform", true)
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
@@ -705,13 +572,13 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
pub fn brush_modify(&mut self, strokes: Vec<BrushStroke>) {
|
||||
let Some(brush_node_id) = self.existing_proto_node_id(graphene_std::brush::brush::brush::IDENTIFIER, true) else {
|
||||
let Some(brush_node_id) = self.existing_network_node_id("Brush", true) else {
|
||||
return;
|
||||
};
|
||||
self.set_input_with_refresh(InputConnector::node(brush_node_id, 1), NodeInput::value(TaggedValue::BrushStrokes(strokes), false), false);
|
||||
}
|
||||
|
||||
pub fn resize_artboard(&mut self, location: DVec2, dimensions: DVec2) {
|
||||
pub fn resize_artboard(&mut self, location: IVec2, dimensions: IVec2) {
|
||||
let Some(artboard_node_id) = self.existing_network_node_id("Artboard", true) else {
|
||||
return;
|
||||
};
|
||||
@@ -719,19 +586,19 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
let mut dimensions = dimensions;
|
||||
let mut location = location;
|
||||
|
||||
if dimensions.x < 0. {
|
||||
dimensions.x = -dimensions.x;
|
||||
if dimensions.x < 0 {
|
||||
dimensions.x *= -1;
|
||||
location.x -= dimensions.x;
|
||||
}
|
||||
if dimensions.y < 0. {
|
||||
dimensions.y = -dimensions.y;
|
||||
if dimensions.y < 0 {
|
||||
dimensions.y *= -1;
|
||||
location.y -= dimensions.y;
|
||||
}
|
||||
self.set_input_with_refresh(InputConnector::node(artboard_node_id, 2), NodeInput::value(TaggedValue::DVec2(location), false), false);
|
||||
self.set_input_with_refresh(InputConnector::node(artboard_node_id, 3), NodeInput::value(TaggedValue::DVec2(dimensions), false), false);
|
||||
self.set_input_with_refresh(InputConnector::node(artboard_node_id, 2), NodeInput::value(TaggedValue::DVec2(location.into()), false), false);
|
||||
self.set_input_with_refresh(InputConnector::node(artboard_node_id, 3), NodeInput::value(TaggedValue::DVec2(dimensions.into()), false), false);
|
||||
}
|
||||
|
||||
/// Set the input, refresh the Properties panel, and run the document graph if skip_rerender is false
|
||||
/// Set the input, refresh the properties panel, and run the document graph if skip_rerender is false
|
||||
pub fn set_input_with_refresh(&mut self, input_connector: InputConnector, input: NodeInput, skip_rerender: bool) {
|
||||
self.network_interface.set_input(&input_connector, input, &[]);
|
||||
self.responses.add(PropertiesPanelMessage::Refresh);
|
||||
@@ -740,29 +607,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)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+14
-25
@@ -22,15 +22,8 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Add the rest of the protonodes from the macro.
|
||||
// Typed nodes are registered in `core_types::NODE_REGISTRY` via the macro's auto-generated `register_node` codegen.
|
||||
// `skip_impl` nodes (e.g. Cache, Monitor) bypass that registration but are wired up manually in
|
||||
// `interpreted_executor::node_registry::NODE_REGISTRY` via `async_node!`. We consult that extended registry as a
|
||||
// fallback when deriving `call_argument` so it reflects the impls actually registered, which will usually be `Context`.
|
||||
let extended_node_registry = &*interpreted_executor::node_registry::NODE_REGISTRY;
|
||||
// Add the rest of the protonodes from the macro
|
||||
let node_registry = NODE_REGISTRY.lock().unwrap();
|
||||
let empty_implementations: Vec<(NodeConstructor, NodeIOTypes)> = Vec::new();
|
||||
let context_type = concrete!(Context);
|
||||
for (id, metadata) in NODE_METADATA.lock().unwrap().iter() {
|
||||
let identifier = DefinitionIdentifier::ProtoNode(id.clone());
|
||||
if definitions_map.contains_key(&identifier) {
|
||||
@@ -43,28 +36,14 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
description,
|
||||
properties,
|
||||
context_features,
|
||||
memoize: _,
|
||||
} = metadata;
|
||||
|
||||
let implementations = node_registry.get(id).unwrap_or(&empty_implementations);
|
||||
let Some(implementations) = &node_registry.get(id) else { continue };
|
||||
|
||||
let first_node_io = implementations.first().map(|(_, node_io)| node_io).unwrap_or(const { &NodeIOTypes::empty() });
|
||||
|
||||
let call_arguments: Vec<&Type> = if !implementations.is_empty() {
|
||||
implementations.iter().map(|(_, io)| &io.call_argument).collect()
|
||||
} else if let Some(impls) = extended_node_registry.get(id) {
|
||||
impls.keys().map(|io| &io.call_argument).collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let valid_inputs: HashSet<&Type> = call_arguments.iter().copied().collect();
|
||||
let input_type = if valid_inputs.is_empty() {
|
||||
&context_type
|
||||
} else if valid_inputs.len() > 1 {
|
||||
&const { generic!(D) }
|
||||
} else {
|
||||
call_arguments[0]
|
||||
};
|
||||
let valid_inputs: HashSet<_> = implementations.iter().map(|(_, node_io)| node_io.call_argument.clone()).collect();
|
||||
let input_type = if valid_inputs.len() > 1 { &const { generic!(D) } } else { &first_node_io.call_argument };
|
||||
|
||||
let inputs = preprocessor::node_inputs(fields, first_node_io);
|
||||
definitions_map.insert(
|
||||
@@ -103,6 +82,16 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
);
|
||||
}
|
||||
|
||||
// If any protonode does not have metadata then set its display name to its identifier string
|
||||
for definition in definitions_map.values_mut() {
|
||||
let metadata = NODE_METADATA.lock().unwrap();
|
||||
if let DocumentNodeImplementation::ProtoNode(id) = &definition.node_template.document_node.implementation
|
||||
&& !metadata.contains_key(id)
|
||||
{
|
||||
definition.node_template.persistent_node_metadata.display_name = definition.identifier.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
// Add the rest of the network nodes to the map and add the metadata for their internal protonodes
|
||||
for mut network_node in network_nodes {
|
||||
traverse_node(&network_node.node_template.document_node, &mut network_node.node_template.persistent_node_metadata, &definitions_map);
|
||||
|
||||
@@ -155,22 +155,13 @@ pub enum NodeGraphMessage {
|
||||
input_connector: InputConnector,
|
||||
input: NodeInput,
|
||||
},
|
||||
/// Asks the frontend to enter inline-rename mode for the given layer's display name in the graph view.
|
||||
/// Triggered by double-clicking the layer's name area.
|
||||
BeginEditLayerName {
|
||||
node_id: NodeId,
|
||||
},
|
||||
SetDisplayName {
|
||||
node_id: NodeId,
|
||||
/// The path to the network containing `node_id`. Empty for nodes at the root document network.
|
||||
/// Lets the rename target a node at any nesting depth, independent of the current selection network.
|
||||
network_path: Vec<NodeId>,
|
||||
alias: String,
|
||||
skip_adding_history_step: bool,
|
||||
},
|
||||
SetDisplayNameImpl {
|
||||
node_id: NodeId,
|
||||
network_path: Vec<NodeId>,
|
||||
alias: String,
|
||||
},
|
||||
SetToNodeOrLayer {
|
||||
@@ -208,22 +199,15 @@ pub enum NodeGraphMessage {
|
||||
ToggleSelectedLocked,
|
||||
ToggleLocked {
|
||||
node_id: NodeId,
|
||||
/// The path to the network containing `node_id`. Empty for nodes at the root document network.
|
||||
/// Lets the toggle target a node at any nesting depth, independent of the current selection network.
|
||||
network_path: Vec<NodeId>,
|
||||
},
|
||||
SetLocked {
|
||||
node_id: NodeId,
|
||||
network_path: Vec<NodeId>,
|
||||
locked: bool,
|
||||
},
|
||||
ToggleSelectedIsPinned,
|
||||
ToggleSelectedVisibility,
|
||||
ToggleVisibility {
|
||||
node_id: NodeId,
|
||||
/// The path to the network containing `node_id`. Empty for nodes at the root document network.
|
||||
/// Lets the toggle target a node at any nesting depth, independent of the current selection network.
|
||||
network_path: Vec<NodeId>,
|
||||
},
|
||||
SetPinned {
|
||||
node_id: NodeId,
|
||||
@@ -231,12 +215,10 @@ pub enum NodeGraphMessage {
|
||||
},
|
||||
SetVisibility {
|
||||
node_id: NodeId,
|
||||
network_path: Vec<NodeId>,
|
||||
visible: bool,
|
||||
},
|
||||
SetLockedOrVisibilitySideEffects {
|
||||
node_ids: Vec<NodeId>,
|
||||
network_path: Vec<NodeId>,
|
||||
},
|
||||
UpdateEdges,
|
||||
UpdateBoxSelection,
|
||||
|
||||
@@ -214,11 +214,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
let mid_point = (network_interface.get_output_center(&output_connector, breadcrumb_network_path).unwrap()
|
||||
+ network_interface.get_input_center(&input_connector, breadcrumb_network_path).unwrap())
|
||||
/ 2.;
|
||||
let Some(passthrough_definition) = resolve_proto_node_type(graphene_core::ops::passthrough::IDENTIFIER) else {
|
||||
log::error!("Could not resolve passthrough node when wiring an export to an import");
|
||||
return;
|
||||
};
|
||||
let node_template = Box::new(passthrough_definition.default_node_template());
|
||||
let node_template = Box::new(resolve_proto_node_type(graphene_core::ops::identity::IDENTIFIER).unwrap().default_node_template());
|
||||
|
||||
let node_id = NodeId::new();
|
||||
responses.add(NodeGraphMessage::InsertNode { node_id, node_template });
|
||||
@@ -355,22 +351,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
responses.add(NodeGraphMessage::DeleteSelectedNodes { delete_children: true });
|
||||
}
|
||||
NodeGraphMessage::DeleteNodes { node_ids, delete_children } => {
|
||||
// Detect stroke/fill proto nodes among the doomed nodes before they're gone so the tool control bars can re-sync
|
||||
let stroke = DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
|
||||
let fill = DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER);
|
||||
let any_fill_or_stroke_deleted = node_ids.iter().any(|node_id| {
|
||||
network_interface
|
||||
.reference(node_id, selection_network_path)
|
||||
.is_some_and(|reference| reference == stroke || reference == fill)
|
||||
});
|
||||
network_interface.delete_nodes(node_ids, delete_children, selection_network_path);
|
||||
if any_fill_or_stroke_deleted {
|
||||
responses.add(PenToolMessage::SelectionChanged);
|
||||
responses.add(FreehandToolMessage::SelectionChanged);
|
||||
responses.add(SplineToolMessage::SelectionChanged);
|
||||
responses.add(ShapeToolMessage::SelectionChanged);
|
||||
responses.add(TextToolMessage::SelectionChanged);
|
||||
}
|
||||
}
|
||||
// Deletes selected_nodes. If `reconnect` is true, then all children nodes (secondary input) of the selected nodes are deleted and the siblings (primary input/output) are reconnected.
|
||||
// If `reconnect` is false, then only the selected nodes are deleted and not reconnected.
|
||||
@@ -424,18 +405,10 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
{
|
||||
return;
|
||||
};
|
||||
// Double-clicking the layer's name area triggers inline rename instead of drilling into the subgraph.
|
||||
if let Some(layer_id) = network_interface.layer_click_target_from_click(ipp.mouse.position, network_interface::LayerClickTargetTypes::Name, selection_network_path) {
|
||||
responses.add(NodeGraphMessage::BeginEditLayerName { node_id: layer_id });
|
||||
return;
|
||||
}
|
||||
if let Some(DocumentNodeImplementation::Network(_)) = network_interface.implementation(&node_id, selection_network_path) {
|
||||
responses.add(DocumentMessage::EnterNestedNetwork { node_id });
|
||||
}
|
||||
}
|
||||
NodeGraphMessage::BeginEditLayerName { node_id } => {
|
||||
responses.add(FrontendMessage::TriggerEditLayerNameInGraph { node_id });
|
||||
}
|
||||
NodeGraphMessage::ExposeInput {
|
||||
input_connector,
|
||||
set_to_exposed,
|
||||
@@ -686,7 +659,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetDisplayNameImpl {
|
||||
node_id: encapsulating_node_id,
|
||||
network_path: selection_network_path.to_vec(),
|
||||
alias: "Untitled Node".to_string(),
|
||||
});
|
||||
|
||||
@@ -937,19 +909,13 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
|
||||
// Toggle visibility of clicked node and return
|
||||
if let Some(clicked_visibility) = network_interface.layer_click_target_from_click(click, network_interface::LayerClickTargetTypes::Visibility, selection_network_path) {
|
||||
responses.add(NodeGraphMessage::ToggleVisibility {
|
||||
node_id: clicked_visibility,
|
||||
network_path: selection_network_path.to_vec(),
|
||||
});
|
||||
responses.add(NodeGraphMessage::ToggleVisibility { node_id: clicked_visibility });
|
||||
return;
|
||||
}
|
||||
|
||||
// Toggle lock of clicked node and return
|
||||
if let Some(clicked_lock) = network_interface.layer_click_target_from_click(click, network_interface::LayerClickTargetTypes::Lock, selection_network_path) {
|
||||
responses.add(NodeGraphMessage::ToggleLocked {
|
||||
node_id: clicked_lock,
|
||||
network_path: selection_network_path.to_vec(),
|
||||
});
|
||||
responses.add(NodeGraphMessage::ToggleLocked { node_id: clicked_lock });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1742,19 +1708,7 @@ 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_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()
|
||||
.any(|id| *r == DefinitionIdentifier::ProtoNode(id))
|
||||
});
|
||||
|
||||
let input = NodeInput::value(value, false);
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, input_index),
|
||||
@@ -1764,13 +1718,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
if is_fill {
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
}
|
||||
if is_stroke_node || is_fill_node || is_shape_generator_node || is_text_node {
|
||||
responses.add(PenToolMessage::SelectionChanged);
|
||||
responses.add(FreehandToolMessage::SelectionChanged);
|
||||
responses.add(SplineToolMessage::SelectionChanged);
|
||||
responses.add(ShapeToolMessage::SelectionChanged);
|
||||
responses.add(TextToolMessage::SelectionChanged);
|
||||
}
|
||||
if network_interface.connected_to_output(&node_id, selection_network_path) {
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
@@ -1869,14 +1816,13 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
}
|
||||
NodeGraphMessage::SetDisplayName {
|
||||
node_id,
|
||||
network_path,
|
||||
alias,
|
||||
skip_adding_history_step,
|
||||
} => {
|
||||
if !skip_adding_history_step {
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
}
|
||||
responses.add(NodeGraphMessage::SetDisplayNameImpl { node_id, network_path, alias });
|
||||
responses.add(NodeGraphMessage::SetDisplayNameImpl { node_id, alias });
|
||||
if !skip_adding_history_step {
|
||||
// Does not add a history step if the name was not changed
|
||||
responses.add(DocumentMessage::EndTransaction);
|
||||
@@ -1885,10 +1831,9 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
responses.add(DocumentMessage::RenderScrollbars);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
responses.add(OverlaysMessage::Draw); // Redraw overlays to update artboard names
|
||||
responses.add(DataPanelMessage::Refresh);
|
||||
}
|
||||
NodeGraphMessage::SetDisplayNameImpl { node_id, network_path, alias } => {
|
||||
network_interface.set_display_name(&node_id, alias, &network_path);
|
||||
NodeGraphMessage::SetDisplayNameImpl { node_id, alias } => {
|
||||
network_interface.set_display_name(&node_id, alias, selection_network_path);
|
||||
}
|
||||
NodeGraphMessage::SetImportExportName { name, index } => {
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
@@ -1927,34 +1872,25 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
|
||||
for node_id in &node_ids {
|
||||
responses.add(NodeGraphMessage::SetLocked {
|
||||
node_id: *node_id,
|
||||
network_path: selection_network_path.to_vec(),
|
||||
locked,
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetLocked { node_id: *node_id, locked });
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::SetLockedOrVisibilitySideEffects {
|
||||
node_ids,
|
||||
network_path: selection_network_path.to_vec(),
|
||||
})
|
||||
responses.add(NodeGraphMessage::SetLockedOrVisibilitySideEffects { node_ids })
|
||||
}
|
||||
NodeGraphMessage::ToggleLocked { node_id, network_path } => {
|
||||
let locked = !network_interface.is_locked(&node_id, &network_path);
|
||||
NodeGraphMessage::ToggleLocked { node_id } => {
|
||||
let Some(node_metadata) = network_interface.document_network_metadata().persistent_metadata.node_metadata.get(&node_id) else {
|
||||
log::error!("Cannot get node {node_id:?} in NodeGraphMessage::ToggleLocked");
|
||||
return;
|
||||
};
|
||||
|
||||
let locked = !node_metadata.persistent_metadata.locked;
|
||||
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::SetLocked {
|
||||
node_id,
|
||||
network_path: network_path.clone(),
|
||||
locked,
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetLockedOrVisibilitySideEffects {
|
||||
node_ids: vec![node_id],
|
||||
network_path,
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetLocked { node_id, locked });
|
||||
responses.add(NodeGraphMessage::SetLockedOrVisibilitySideEffects { node_ids: vec![node_id] })
|
||||
}
|
||||
NodeGraphMessage::SetLocked { node_id, network_path, locked } => {
|
||||
network_interface.set_locked(&node_id, &network_path, locked);
|
||||
NodeGraphMessage::SetLocked { node_id, locked } => {
|
||||
network_interface.set_locked(&node_id, selection_network_path, locked);
|
||||
}
|
||||
NodeGraphMessage::ToggleSelectedIsPinned => {
|
||||
let Some(selected_nodes) = network_interface.selected_nodes_in_nested_network(selection_network_path) else {
|
||||
@@ -1970,10 +1906,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
for node_id in &node_ids {
|
||||
responses.add(NodeGraphMessage::SetPinned { node_id: *node_id, pinned });
|
||||
}
|
||||
responses.add(NodeGraphMessage::SetLockedOrVisibilitySideEffects {
|
||||
node_ids,
|
||||
network_path: selection_network_path.to_vec(),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetLockedOrVisibilitySideEffects { node_ids });
|
||||
}
|
||||
NodeGraphMessage::ToggleSelectedVisibility => {
|
||||
let Some(selected_nodes) = network_interface.selected_nodes_in_nested_network(selection_network_path) else {
|
||||
@@ -1987,46 +1920,31 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
for node_id in &node_ids {
|
||||
responses.add(NodeGraphMessage::SetVisibility {
|
||||
node_id: *node_id,
|
||||
network_path: selection_network_path.to_vec(),
|
||||
visible,
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetVisibility { node_id: *node_id, visible });
|
||||
}
|
||||
responses.add(NodeGraphMessage::SetLockedOrVisibilitySideEffects {
|
||||
node_ids,
|
||||
network_path: selection_network_path.to_vec(),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetLockedOrVisibilitySideEffects { node_ids });
|
||||
}
|
||||
NodeGraphMessage::ToggleVisibility { node_id, network_path } => {
|
||||
let visible = !network_interface.is_visible(&node_id, &network_path);
|
||||
NodeGraphMessage::ToggleVisibility { node_id } => {
|
||||
let visible = !network_interface.is_visible(&node_id, selection_network_path);
|
||||
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::SetVisibility {
|
||||
node_id,
|
||||
network_path: network_path.clone(),
|
||||
visible,
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetLockedOrVisibilitySideEffects {
|
||||
node_ids: vec![node_id],
|
||||
network_path,
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetVisibility { node_id, visible });
|
||||
responses.add(NodeGraphMessage::SetLockedOrVisibilitySideEffects { node_ids: vec![node_id] });
|
||||
}
|
||||
NodeGraphMessage::SetPinned { node_id, pinned } => {
|
||||
network_interface.set_pinned(&node_id, selection_network_path, pinned);
|
||||
}
|
||||
NodeGraphMessage::SetVisibility { node_id, network_path, visible } => {
|
||||
network_interface.set_visibility(&node_id, &network_path, visible);
|
||||
NodeGraphMessage::SetVisibility { node_id, visible } => {
|
||||
network_interface.set_visibility(&node_id, selection_network_path, visible);
|
||||
}
|
||||
NodeGraphMessage::SetLockedOrVisibilitySideEffects { node_ids, network_path } => {
|
||||
if node_ids.iter().any(|node_id| network_interface.connected_to_output(node_id, &network_path)) {
|
||||
NodeGraphMessage::SetLockedOrVisibilitySideEffects { node_ids } => {
|
||||
if node_ids.iter().any(|node_id| network_interface.connected_to_output(node_id, selection_network_path)) {
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
responses.add(NodeGraphMessage::UpdateActionButtons);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
responses.add(DataPanelMessage::Refresh);
|
||||
}
|
||||
NodeGraphMessage::UpdateBoxSelection => {
|
||||
if let Some((box_selection_start, _)) = self.box_selection_start {
|
||||
@@ -2440,7 +2358,7 @@ impl NodeGraphMessageHandler {
|
||||
self.widgets[1] = LayoutGroup::row(widgets);
|
||||
}
|
||||
|
||||
/// Collate the Properties panel sections for a node graph
|
||||
/// Collate the properties panel sections for a node graph
|
||||
pub fn collate_properties(context: &mut NodePropertiesContext) -> Vec<LayoutGroup> {
|
||||
// If the selected nodes are in the document network, use the document network. Otherwise, use the nested network
|
||||
let Some(selected_nodes) = context.network_interface.selected_nodes_in_nested_network(context.selection_network_path) else {
|
||||
@@ -2479,7 +2397,6 @@ impl NodeGraphMessageHandler {
|
||||
let mut properties = Vec::new();
|
||||
|
||||
if let [node_id] = *nodes.as_slice() {
|
||||
let network_path = context.selection_network_path.to_vec();
|
||||
properties.push(LayoutGroup::row(vec![
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
IconLabel::new("Node").tooltip_description("Name of the selected node.").widget_instance(),
|
||||
@@ -2489,7 +2406,6 @@ impl NodeGraphMessageHandler {
|
||||
.on_update(move |text_input| {
|
||||
NodeGraphMessage::SetDisplayName {
|
||||
node_id,
|
||||
network_path: network_path.clone(),
|
||||
alias: text_input.value.clone(),
|
||||
skip_adding_history_step: false,
|
||||
}
|
||||
@@ -2506,14 +2422,14 @@ impl NodeGraphMessageHandler {
|
||||
}
|
||||
|
||||
// TODO: Display properties for encapsulating node when no nodes are selected in a nested network
|
||||
// This may require store a separate path for the Properties panel
|
||||
// This may require store a separate path for the properties panel
|
||||
let mut properties = vec![LayoutGroup::row(vec![
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
IconLabel::new("File").tooltip_description("Name of the current document.").widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
TextInput::new(context.document_name)
|
||||
.tooltip_description("Name of the current document.")
|
||||
.on_update(|text_input| PortfolioMessage::RenameDocument { new_name: text_input.value.clone() }.into())
|
||||
.on_update(|text_input| DocumentMessage::RenameDocument { new_name: text_input.value.clone() }.into())
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
])];
|
||||
@@ -2552,7 +2468,6 @@ impl NodeGraphMessageHandler {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let layer_network_path = context.selection_network_path.to_vec();
|
||||
let mut layer_properties = vec![LayoutGroup::row(vec![
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
IconLabel::new("Layer").tooltip_description("Name of the selected layer.").widget_instance(),
|
||||
@@ -2562,7 +2477,6 @@ impl NodeGraphMessageHandler {
|
||||
.on_update(move |text_input| {
|
||||
NodeGraphMessage::SetDisplayName {
|
||||
node_id: layer,
|
||||
network_path: layer_network_path.clone(),
|
||||
alias: text_input.value.clone(),
|
||||
skip_adding_history_step: false,
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,10 +1,6 @@
|
||||
use graph_craft::document::NodeId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::Type;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::raster_types::{CPU, Raster};
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::{Artboard, Graphic};
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
@@ -25,19 +21,22 @@ pub enum FrontendGraphDataType {
|
||||
impl FrontendGraphDataType {
|
||||
pub fn from_type(input: &Type) -> Self {
|
||||
match TaggedValue::from_type_or_none(input) {
|
||||
TaggedValue::U32(_) | TaggedValue::U64(_) | TaggedValue::F32(_) | TaggedValue::F64(_) | TaggedValue::DVec2(_) | TaggedValue::F64Array(_) | TaggedValue::DAffine2(_) => Self::Number,
|
||||
TaggedValue::U32(_)
|
||||
| TaggedValue::U64(_)
|
||||
| TaggedValue::F32(_)
|
||||
| TaggedValue::F64(_)
|
||||
| TaggedValue::DVec2(_)
|
||||
| TaggedValue::F64Array4(_)
|
||||
| TaggedValue::VecF64(_)
|
||||
| TaggedValue::VecDVec2(_)
|
||||
| TaggedValue::DAffine2(_) => Self::Number,
|
||||
TaggedValue::Artboard(_) => Self::Artboard,
|
||||
TaggedValue::Graphic(_) => Self::Graphic,
|
||||
TaggedValue::Raster(_) => Self::Raster,
|
||||
TaggedValue::Vector(_) => Self::Vector,
|
||||
TaggedValue::Color(_) => Self::Color,
|
||||
TaggedValue::FillGradient(_) | 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() {
|
||||
n if n == std::any::type_name::<List<Graphic>>() => Self::Graphic,
|
||||
n if n == std::any::type_name::<List<Artboard>>() => Self::Artboard,
|
||||
n if n == std::any::type_name::<List<Raster<CPU>>>() => Self::Raster,
|
||||
n if n == std::any::type_name::<List<Vector>>() => Self::Vector,
|
||||
n if n == std::any::type_name::<List<String>>() => Self::Typography,
|
||||
_ => Self::General,
|
||||
},
|
||||
TaggedValue::Gradient(_) | TaggedValue::GradientTable(_) => Self::Gradient,
|
||||
TaggedValue::String(_) | TaggedValue::VecString(_) => Self::Typography,
|
||||
_ => Self::General,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,9 +3,9 @@ use crate::messages::portfolio::document::overlays::utility_types::OverlayContex
|
||||
use crate::messages::portfolio::document::utility_types::misc::{GridSnapping, GridType};
|
||||
use crate::messages::prelude::*;
|
||||
use glam::DVec2;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::raster::color::Color;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::vector::style::FillChoiceUI;
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
|
||||
fn grid_overlay_rectangular(document: &DocumentMessageHandler, overlay_context: &mut OverlayContext, spacing: DVec2) {
|
||||
let origin = document.snapping_state.grid.origin;
|
||||
@@ -231,7 +231,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
|
||||
widgets.push(LayoutGroup::row(vec![TextLabel::new("Grid").bold(true).widget_instance()]));
|
||||
|
||||
widgets.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("Type").min_width(60).max_width(60).table_align(true).widget_instance(),
|
||||
TextLabel::new("Type").table_align(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
RadioInput::new(vec![
|
||||
RadioEntryData::new("rectangular").label("Rectangular").on_update(update_val(grid, |grid, _| {
|
||||
@@ -262,7 +262,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
|
||||
]));
|
||||
|
||||
let mut color_widgets = vec![
|
||||
TextLabel::new("Display").min_width(60).max_width(60).table_align(true).widget_instance(),
|
||||
TextLabel::new("Display").table_align(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
];
|
||||
color_widgets.extend([
|
||||
@@ -274,12 +274,12 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
]);
|
||||
color_widgets.push(
|
||||
ColorInput::new(FillChoiceUI::Solid(SRGBA8::from_hex_str(&grid.color).unwrap_or(SRGBA8::BLACK)))
|
||||
ColorInput::new(FillChoice::Solid(Color::from_hex_str(&grid.color).unwrap_or(Color::BLACK)))
|
||||
.tooltip_label("Grid Display Color")
|
||||
.allow_none(false)
|
||||
.on_update(update_val::<ColorInput, _>(grid, |grid, color| {
|
||||
if let Some(srgba) = color.value.as_solid() {
|
||||
grid.color = srgba.to_css_hex();
|
||||
if let Some(color) = color.value.as_solid() {
|
||||
grid.color = format!("#{}", color.to_rgba_hex_srgb_from_gamma());
|
||||
}
|
||||
}))
|
||||
.widget_instance(),
|
||||
@@ -287,7 +287,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
|
||||
widgets.push(LayoutGroup::row(color_widgets));
|
||||
|
||||
widgets.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("Origin").min_width(60).max_width(60).table_align(true).widget_instance(),
|
||||
TextLabel::new("Origin").table_align(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(grid.origin.x))
|
||||
.label("X")
|
||||
@@ -306,7 +306,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
|
||||
|
||||
match grid.grid_type {
|
||||
GridType::Rectangular { spacing } => widgets.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("Spacing").min_width(60).max_width(60).table_align(true).widget_instance(),
|
||||
TextLabel::new("Spacing").table_align(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(spacing.x))
|
||||
.label("X")
|
||||
@@ -326,7 +326,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
|
||||
])),
|
||||
GridType::Isometric { y_axis_spacing, angle_a, angle_b } => {
|
||||
widgets.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("Y Spacing").min_width(60).max_width(60).table_align(true).widget_instance(),
|
||||
TextLabel::new("Y Spacing").table_align(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(y_axis_spacing))
|
||||
.unit(" px")
|
||||
@@ -336,7 +336,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
|
||||
.widget_instance(),
|
||||
]));
|
||||
widgets.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("Angles").min_width(60).max_width(60).table_align(true).widget_instance(),
|
||||
TextLabel::new("Angles").table_align(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(angle_a))
|
||||
.unit("°")
|
||||
|
||||
@@ -29,12 +29,6 @@ impl MessageHandler<OverlaysMessage, OverlaysMessageContext<'_>> for OverlaysMes
|
||||
use crate::messages::viewport::{Position, ToPhysical};
|
||||
use wasm_bindgen::JsCast;
|
||||
|
||||
// Discard detached canvas after a panel reorganization remounts the DOM
|
||||
if self.canvas.as_ref().is_some_and(|canvas| !canvas.is_connected()) {
|
||||
self.canvas = None;
|
||||
self.context = None;
|
||||
}
|
||||
|
||||
let canvas = match &self.canvas {
|
||||
Some(canvas) => canvas,
|
||||
None => {
|
||||
|
||||
@@ -241,7 +241,7 @@ pub fn text_width(text: &str, font_size: f64) -> f64 {
|
||||
max_width: None,
|
||||
max_height: None,
|
||||
tilt: 0.0,
|
||||
align: TextAlign::AlignLeft,
|
||||
align: TextAlign::Left,
|
||||
};
|
||||
|
||||
// Load Source Sans Pro font data
|
||||
|
||||
@@ -10,10 +10,9 @@ use crate::messages::prelude::ViewportMessageHandler;
|
||||
use core::borrow::Borrow;
|
||||
use core::f64::consts::{FRAC_PI_2, PI, TAU};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_std::ATTR_TRANSFORM;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::subpath::{self, Subpath};
|
||||
use graphene_std::table::Table;
|
||||
use graphene_std::text::{Font, TextAlign, TypesettingConfig};
|
||||
use graphene_std::vector::click_target::ClickTargetType;
|
||||
use graphene_std::vector::misc::point_to_dvec2;
|
||||
@@ -1035,7 +1034,6 @@ impl OverlayContextInternal {
|
||||
self.manipulator_anchor(transform.transform_point2(point.position), false, None);
|
||||
}
|
||||
ClickTargetType::Subpath(subpath) => subpaths.push(subpath.clone()),
|
||||
ClickTargetType::CompoundPath(compound) => subpaths.extend(compound.iter().cloned()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1112,7 +1110,7 @@ impl OverlayContextInternal {
|
||||
max_width: None,
|
||||
max_height: None,
|
||||
tilt: 0.,
|
||||
align: TextAlign::AlignLeft,
|
||||
align: TextAlign::Left, // We'll handle alignment manually via pivot
|
||||
};
|
||||
|
||||
// Load Source Sans Pro font data
|
||||
@@ -1129,7 +1127,7 @@ impl OverlayContextInternal {
|
||||
let text_bounds = kurbo::Rect::new(0., 0., text_width, text_height);
|
||||
|
||||
// Convert text to vector paths for rendering
|
||||
let text_list = text_context.to_path(text, &font, &GLOBAL_FONT_CACHE, typesetting, false);
|
||||
let text_table = text_context.to_path(text, &font, &GLOBAL_FONT_CACHE, typesetting, false);
|
||||
|
||||
// Calculate position based on pivot
|
||||
let mut position = DVec2::ZERO;
|
||||
@@ -1161,25 +1159,23 @@ impl OverlayContextInternal {
|
||||
}
|
||||
|
||||
// Render the actual text paths
|
||||
self.render_text_paths(&text_list, font_color, vello_transform);
|
||||
self.render_text_paths(&text_table, font_color, vello_transform);
|
||||
}
|
||||
|
||||
// Render text paths to the vello scene using existing infrastructure
|
||||
fn render_text_paths(&mut self, text_list: &List<Vector>, font_color: &str, base_transform: kurbo::Affine) {
|
||||
fn render_text_paths(&mut self, text_table: &Table<Vector>, font_color: &str, base_transform: kurbo::Affine) {
|
||||
let color = Self::parse_color(font_color);
|
||||
|
||||
for index in 0..text_list.len() {
|
||||
for row in text_table.iter() {
|
||||
// Use the existing bezier_to_path infrastructure to convert Vector to BezPath
|
||||
let mut path = BezPath::new();
|
||||
let mut last_point = None;
|
||||
let transform: DAffine2 = text_list.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
|
||||
let Some(element) = text_list.element(index) else { continue };
|
||||
for (_, bezier, start_id, end_id) in element.segment_iter() {
|
||||
for (_, bezier, start_id, end_id) in row.element.segment_iter() {
|
||||
let move_to = last_point != Some(start_id);
|
||||
last_point = Some(end_id);
|
||||
|
||||
self.bezier_to_path(bezier, transform, move_to, &mut path);
|
||||
self.bezier_to_path(bezier, *row.transform, move_to, &mut path);
|
||||
}
|
||||
|
||||
// Render the path
|
||||
|
||||
@@ -986,7 +986,6 @@ impl OverlayContext {
|
||||
self.manipulator_anchor(transform.transform_point2(point.position), false, None);
|
||||
}
|
||||
ClickTargetType::Subpath(subpath) => subpaths.push(subpath.clone()),
|
||||
ClickTargetType::CompoundPath(compound) => subpaths.extend(compound.iter().cloned()),
|
||||
});
|
||||
|
||||
if !subpaths.is_empty() {
|
||||
@@ -1040,7 +1039,7 @@ impl OverlayContext {
|
||||
}
|
||||
|
||||
let image_data = web_sys::ImageData::new_with_u8_clamped_array_and_sh(wasm_bindgen::Clamped(&data), PATTERN_WIDTH as u32, PATTERN_HEIGHT as u32).unwrap();
|
||||
pattern_context.put_image_data(&image_data, 0, 0).unwrap();
|
||||
pattern_context.put_image_data(&image_data, 0., 0.).unwrap();
|
||||
let pattern = self.render_context.create_pattern_with_offscreen_canvas(&pattern_canvas, "repeat").unwrap().unwrap();
|
||||
|
||||
self.push_path(subpaths, transform);
|
||||
|
||||
@@ -28,12 +28,6 @@ pub struct DocumentMetadata {
|
||||
pub first_element_source_ids: HashMap<NodeId, Option<NodeId>>,
|
||||
pub structure: HashMap<LayerNodeIdentifier, NodeRelations>,
|
||||
pub click_targets: HashMap<LayerNodeIdentifier, Vec<Arc<ClickTarget>>>,
|
||||
/// Source-geometry outlines for hover/selection overlays, separate from `click_targets` so
|
||||
/// nodes with an `editor:click_target` override still outline the precise geometry.
|
||||
pub outlines: HashMap<LayerNodeIdentifier, Vec<Arc<ClickTarget>>>,
|
||||
/// Per-layer text frame from item 0's `editor:text_frame` attribute (`DAffine2` mapping the (0, 0)-(1, 1) unit square onto the frame).
|
||||
/// The Text tool composes this with `transform_to_viewport(layer)` to position its drag cage.
|
||||
pub text_frames: HashMap<LayerNodeIdentifier, DAffine2>,
|
||||
pub clip_targets: HashSet<NodeId>,
|
||||
pub vector_modify: HashMap<NodeId, Vector>,
|
||||
/// Vector data keyed by layer ID, used as fallback when no Path node exists.
|
||||
@@ -110,7 +104,7 @@ impl DocumentMetadata {
|
||||
.any(|upstream| Some(upstream) == source)
|
||||
{
|
||||
use_local = false;
|
||||
info!("Local transform is invalid. Using the identity for the local transform instead.");
|
||||
info!("Local transform is invalid — using the identity for the local transform instead")
|
||||
}
|
||||
let local_transform = use_local.then(|| self.local_transforms.get(&layer.to_node()).copied()).flatten().unwrap_or_default();
|
||||
|
||||
@@ -126,7 +120,7 @@ impl DocumentMetadata {
|
||||
let local_transform = self.local_transforms.get(&layer.to_node()).copied();
|
||||
|
||||
let transform = local_transform.unwrap_or_else(|| {
|
||||
let transform_node_id = ModifyInputsContext::locate_node_in_layer_chain(&DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER), layer, network_interface);
|
||||
let transform_node_id = ModifyInputsContext::locate_node_in_layer_chain(&DefinitionIdentifier::Network("Transform".into()), layer, network_interface);
|
||||
let transform_node = transform_node_id.and_then(|id| network_interface.document_node(&id, &[]));
|
||||
transform_node.map(|node| transform_utils::get_current_transform(node.inputs.as_slice())).unwrap_or_default()
|
||||
});
|
||||
@@ -160,21 +154,9 @@ impl DocumentMetadata {
|
||||
// ===============================
|
||||
|
||||
impl DocumentMetadata {
|
||||
/// Outline targets if present, otherwise click targets. Used for bounding boxes and outline
|
||||
/// drawing so layers with an `editor:click_target` override report precise geometry bounds.
|
||||
fn visual_targets(&self, layer: LayerNodeIdentifier) -> Option<&[Arc<ClickTarget>]> {
|
||||
self.outlines.get(&layer).or_else(|| self.click_targets.get(&layer)).map(|v| v.as_slice())
|
||||
}
|
||||
|
||||
/// Whether to treat this layer as a text layer for tool UI. Checks the surfaced `editor:text_frame`
|
||||
/// metadata rather than upstream topology, so layers that strip the attribute downstream correctly drop out.
|
||||
pub fn is_text_layer(&self, layer: LayerNodeIdentifier) -> bool {
|
||||
self.text_frames.contains_key(&layer)
|
||||
}
|
||||
|
||||
/// Get the bounding box of the click target of the specified layer in the specified transform space
|
||||
pub fn bounding_box_with_transform(&self, layer: LayerNodeIdentifier, transform: DAffine2) -> Option<[DVec2; 2]> {
|
||||
self.visual_targets(layer)?
|
||||
self.click_targets(layer)?
|
||||
.iter()
|
||||
.filter_map(|click_target| click_target.bounding_box_with_transform(transform))
|
||||
.reduce(Quad::combine_bounds)
|
||||
@@ -182,14 +164,10 @@ impl DocumentMetadata {
|
||||
|
||||
/// Get the loose bounding box of the click target of the specified layer in the specified transform space
|
||||
pub fn loose_bounding_box_with_transform(&self, layer: LayerNodeIdentifier, transform: DAffine2) -> Option<[DVec2; 2]> {
|
||||
self.visual_targets(layer)?
|
||||
self.click_targets(layer)?
|
||||
.iter()
|
||||
.filter_map(|click_target| match click_target.target_type() {
|
||||
ClickTargetType::Subpath(subpath) => subpath.loose_bounding_box_with_transform(transform),
|
||||
ClickTargetType::CompoundPath(subpaths) => subpaths
|
||||
.iter()
|
||||
.filter_map(|subpath| subpath.loose_bounding_box_with_transform(transform))
|
||||
.reduce(|[a_min, a_max], [b_min, b_max]| [a_min.min(b_min), a_max.max(b_max)]),
|
||||
ClickTargetType::FreePoint(_) => click_target.bounding_box_with_transform(transform),
|
||||
})
|
||||
.reduce(Quad::combine_bounds)
|
||||
@@ -221,18 +199,6 @@ impl DocumentMetadata {
|
||||
self.bounding_box_with_transform(layer, self.transform_to_document(layer))
|
||||
}
|
||||
|
||||
/// Get the bounding box of the specified layer in document space, expanded to include the actual rendered
|
||||
/// stroke geometry when the layer is a vector with a stroke style. Falls back to the click-target-based
|
||||
/// bounds for non-vector layers (groups, raster, text, color, gradient).
|
||||
pub fn bounding_box_document_with_stroke(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
|
||||
if let Some(vector) = self.layer_vector_data.get(&layer)
|
||||
&& let Some(bounds) = vector.stroke_inclusive_bounding_box_with_transform(self.transform_to_document(layer))
|
||||
{
|
||||
return Some(bounds);
|
||||
}
|
||||
self.bounding_box_document(layer)
|
||||
}
|
||||
|
||||
/// Get the bounding box of the click target of the specified layer in viewport space
|
||||
pub fn bounding_box_viewport(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
|
||||
self.bounding_box_with_transform(layer, self.transform_to_viewport(layer))
|
||||
@@ -244,15 +210,18 @@ impl DocumentMetadata {
|
||||
}
|
||||
|
||||
pub fn layer_outline(&self, layer: LayerNodeIdentifier) -> impl Iterator<Item = &subpath::Subpath<PointId>> {
|
||||
self.visual_targets(layer).unwrap_or(&[]).iter().flat_map(|target| match target.target_type() {
|
||||
ClickTargetType::Subpath(subpath) => std::slice::from_ref(subpath),
|
||||
ClickTargetType::CompoundPath(subpaths) => subpaths.as_slice(),
|
||||
ClickTargetType::FreePoint(_) => &[],
|
||||
static EMPTY: Vec<Arc<ClickTarget>> = Vec::new();
|
||||
let click_targets = self.click_targets.get(&layer).unwrap_or(&EMPTY);
|
||||
click_targets.iter().filter_map(|target| match target.target_type() {
|
||||
ClickTargetType::Subpath(subpath) => Some(subpath),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn layer_with_free_points_outline(&self, layer: LayerNodeIdentifier) -> impl Iterator<Item = &ClickTargetType> {
|
||||
self.visual_targets(layer).unwrap_or(&[]).iter().map(|target| target.target_type())
|
||||
static EMPTY: Vec<Arc<ClickTarget>> = Vec::new();
|
||||
let click_targets = self.click_targets.get(&layer).unwrap_or(&EMPTY);
|
||||
click_targets.iter().map(|target| target.target_type())
|
||||
}
|
||||
|
||||
pub fn is_clip(&self, node: NodeId) -> bool {
|
||||
|
||||
@@ -6,8 +6,7 @@ use super::document_metadata::{DocumentMetadata, LayerNodeIdentifier, NodeRelati
|
||||
use super::misc::PTZ;
|
||||
use super::nodes::SelectedNodes;
|
||||
use crate::consts::{
|
||||
EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP, EXPORTS_TO_TOP_EDGE_PIXEL_GAP, GRID_SIZE, HALF_GRID_SIZE, IMPORTS_TO_LEFT_EDGE_PIXEL_GAP, IMPORTS_TO_TOP_EDGE_PIXEL_GAP, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH,
|
||||
STACK_VERTICAL_GAP,
|
||||
EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP, EXPORTS_TO_TOP_EDGE_PIXEL_GAP, GRID_SIZE, IMPORTS_TO_LEFT_EDGE_PIXEL_GAP, IMPORTS_TO_TOP_EDGE_PIXEL_GAP, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH, STACK_VERTICAL_GAP,
|
||||
};
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type};
|
||||
@@ -26,7 +25,7 @@ use graphene_std::ContextDependencies;
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType, FreePoint};
|
||||
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
|
||||
use graphene_std::vector::{PointId, Vector, VectorModificationType};
|
||||
use kurbo::BezPath;
|
||||
use memo_network::MemoNetwork;
|
||||
@@ -1222,34 +1221,6 @@ impl NodeNetworkInterface {
|
||||
Some(transformed.bounding_box())
|
||||
}
|
||||
|
||||
/// Calculates the document bounds in document space, expanding vector layer bounds to include the rendered
|
||||
/// stroke width. Used for export so the output canvas captures strokes that overflow the path geometry.
|
||||
pub fn document_bounds_document_space_with_stroke(&self, include_artboards: bool) -> Option<[DVec2; 2]> {
|
||||
self.document_metadata
|
||||
.all_layers()
|
||||
.filter(|layer| include_artboards || !self.is_artboard(&layer.to_node(), &[]))
|
||||
.filter_map(|layer| {
|
||||
if !self.is_artboard(&layer.to_node(), &[])
|
||||
&& let Some(artboard_node_identifier) = layer
|
||||
.ancestors(self.document_metadata())
|
||||
.find(|ancestor| *ancestor != LayerNodeIdentifier::ROOT_PARENT && self.is_artboard(&ancestor.to_node(), &[]))
|
||||
&& let Some(artboard) = self.document_node(&artboard_node_identifier.to_node(), &[])
|
||||
&& let Some(clip_input) = artboard.inputs.get(5)
|
||||
&& let NodeInput::Value { tagged_value, .. } = clip_input
|
||||
&& tagged_value.clone().deref() == &TaggedValue::Bool(true)
|
||||
{
|
||||
return Some(Quad::clip(
|
||||
self.document_metadata.bounding_box_document_with_stroke(layer).unwrap_or_default(),
|
||||
self.document_metadata.bounding_box_document(artboard_node_identifier).unwrap_or_default(),
|
||||
));
|
||||
}
|
||||
self.document_metadata.bounding_box_document_with_stroke(layer)
|
||||
})
|
||||
// Skip any layer bounds containing NaN to avoid poisoning the combined result
|
||||
.filter(|[min, max]| min.is_finite() && max.is_finite())
|
||||
.reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
/// Calculates the selected layer bounds in document space
|
||||
pub fn selected_bounds_document_space(&self, include_artboards: bool, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
let Some(selected_nodes) = self.selected_nodes_in_nested_network(network_path) else {
|
||||
@@ -1263,20 +1234,6 @@ impl NodeNetworkInterface {
|
||||
.reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
/// Calculates the selected layer bounds in document space, expanding vector layer bounds to include the
|
||||
/// rendered stroke width. Used for export so the output canvas captures strokes that overflow the path geometry.
|
||||
pub fn selected_bounds_document_space_with_stroke(&self, include_artboards: bool, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
let Some(selected_nodes) = self.selected_nodes_in_nested_network(network_path) else {
|
||||
log::error!("Could not get selected nodes in selected_bounds_document_space_with_stroke");
|
||||
return None;
|
||||
};
|
||||
selected_nodes
|
||||
.selected_layers(&self.document_metadata)
|
||||
.filter(|&layer| include_artboards || !self.is_artboard(&layer.to_node(), &[]))
|
||||
.filter_map(|layer| self.document_metadata.bounding_box_document_with_stroke(layer))
|
||||
.reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
/// Layers excluding ones that are children of other layers in the list.
|
||||
// TODO: Cache this
|
||||
pub fn shallowest_unique_layers(&self, network_path: &[NodeId]) -> impl Iterator<Item = LayerNodeIdentifier> + use<> {
|
||||
@@ -2546,7 +2503,7 @@ impl NodeNetworkInterface {
|
||||
return;
|
||||
};
|
||||
|
||||
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
|
||||
let node_top_left = node_position.as_dvec2() * 24.;
|
||||
let mut port_click_targets = Ports::new();
|
||||
let document_node_click_targets = if !node_metadata.persistent_metadata.is_layer() {
|
||||
// Create input/output click targets
|
||||
@@ -2571,10 +2528,9 @@ impl NodeNetworkInterface {
|
||||
port_click_targets.insert_node_output(output_index, node_top_left);
|
||||
}
|
||||
|
||||
let height = input_row_count.max(number_of_outputs).max(1) as u32 * GRID_SIZE;
|
||||
let width = 5 * GRID_SIZE;
|
||||
// Offset down by half a grid so the click target sits below the top connector strip.
|
||||
let node_click_target_top_left = node_top_left + DVec2::new(0., HALF_GRID_SIZE as f64);
|
||||
let height = input_row_count.max(number_of_outputs).max(1) as u32 * crate::consts::GRID_SIZE;
|
||||
let width = 5 * crate::consts::GRID_SIZE;
|
||||
let node_click_target_top_left = node_top_left + DVec2::new(0., 12.);
|
||||
let node_click_target_bottom_right = node_click_target_top_left + DVec2::new(width as f64, height as f64);
|
||||
|
||||
let radius = 3.;
|
||||
@@ -2598,90 +2554,37 @@ impl NodeNetworkInterface {
|
||||
log::error!("Could not get layer width in load_node_click_targets");
|
||||
0
|
||||
});
|
||||
let width = layer_width_cells * GRID_SIZE;
|
||||
let height = 2 * GRID_SIZE;
|
||||
let width = layer_width_cells * crate::consts::GRID_SIZE;
|
||||
let height = 2 * crate::consts::GRID_SIZE;
|
||||
let locked = self.is_locked(node_id, network_path);
|
||||
|
||||
// The layer is `2 * GRID_SIZE` tall, so its vertical center sits one grid unit below `node_top_left.y`.
|
||||
// Visibility/lock buttons fill a 1-grid-cell square (so half-extents of HALF_GRID_SIZE each side of center).
|
||||
const LAYER_VERTICAL_CENTER: f64 = GRID_SIZE as f64;
|
||||
const ICON_HALF_EXTENT: f64 = HALF_GRID_SIZE as f64;
|
||||
|
||||
// Update visibility button click target
|
||||
let visibility_offset = node_top_left + DVec2::new(width as f64, LAYER_VERTICAL_CENTER);
|
||||
let subpath = Subpath::new_rounded_rectangle(
|
||||
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + visibility_offset,
|
||||
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + visibility_offset,
|
||||
[3.; 4],
|
||||
);
|
||||
let visibility_offset = node_top_left + DVec2::new(width as f64, 24.);
|
||||
let subpath = Subpath::new_rounded_rectangle(DVec2::new(-12., -12.) + visibility_offset, DVec2::new(12., 12.) + visibility_offset, [3.; 4]);
|
||||
let visibility_click_target = ClickTarget::new_with_subpath(subpath, 0.);
|
||||
|
||||
// Update lock button click target, positioned one grid unit to the left of the visibility button (only when locked)
|
||||
let lock_click_target = if locked {
|
||||
let lock_offset = node_top_left + DVec2::new(width as f64 - GRID_SIZE as f64, LAYER_VERTICAL_CENTER);
|
||||
let subpath = Subpath::new_rounded_rectangle(
|
||||
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + lock_offset,
|
||||
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + lock_offset,
|
||||
[3.; 4],
|
||||
);
|
||||
let lock_offset = node_top_left + DVec2::new(width as f64 - GRID_SIZE as f64, 24.);
|
||||
let subpath = Subpath::new_rounded_rectangle(DVec2::new(-12., -12.) + lock_offset, DVec2::new(12., 12.) + lock_offset, [3.; 4]);
|
||||
Some(ClickTarget::new_with_subpath(subpath, 0.))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Update grip button click target, which is positioned to the left of the leftmost icon.
|
||||
// The grip is 8px wide but spans the full layer-vertical-center band.
|
||||
const GRIP_WIDTH: f64 = 8.;
|
||||
// Update grip button click target, which is positioned to the left of the leftmost icon
|
||||
let icons_width = if locked { GRID_SIZE as f64 } else { 0. };
|
||||
let grip_offset_right_edge = node_top_left + DVec2::new(width as f64 - ICON_HALF_EXTENT - icons_width, LAYER_VERTICAL_CENTER);
|
||||
let subpath = Subpath::new_rounded_rectangle(
|
||||
DVec2::new(-GRIP_WIDTH, -ICON_HALF_EXTENT) + grip_offset_right_edge,
|
||||
DVec2::new(0., ICON_HALF_EXTENT) + grip_offset_right_edge,
|
||||
[0.; 4],
|
||||
);
|
||||
let grip_offset_right_edge = node_top_left + DVec2::new(width as f64 - (GRID_SIZE as f64) / 2. - icons_width, 24.);
|
||||
let subpath = Subpath::new_rounded_rectangle(DVec2::new(-8., -12.) + grip_offset_right_edge, DVec2::new(0., 12.) + grip_offset_right_edge, [0.; 4]);
|
||||
let grip_click_target = ClickTarget::new_with_subpath(subpath, 0.);
|
||||
|
||||
// Update display-name text click target, used to detect double-click rename. Sized to the text bounds
|
||||
// (not the surrounding `.details` area) so the rest of the layer still drills into the subgraph on double-click.
|
||||
|
||||
/// `.layer` margin-left (= 12), for chain layers the negative margin-left and positive padding-left cancel out, keeping content at this same offset
|
||||
const LAYER_LEFT_MARGIN: f64 = HALF_GRID_SIZE as f64;
|
||||
/// `.thumbnail` (70px) + its 1px side margins (= 72)
|
||||
const THUMBNAIL_BLOCK_WIDTH: f64 = 3. * GRID_SIZE as f64;
|
||||
/// `.details` margin-left
|
||||
const DETAILS_LEFT_MARGIN: f64 = 8.;
|
||||
const NAME_LEFT_OFFSET: f64 = LAYER_LEFT_MARGIN + THUMBNAIL_BLOCK_WIDTH + DETAILS_LEFT_MARGIN;
|
||||
/// Distance from layer's right edge to visibility's left edge (= 12)
|
||||
const VISIBILITY_INSET_FROM_LAYER_RIGHT: f64 = HALF_GRID_SIZE as f64;
|
||||
const FONT_SIZE: f64 = 14.;
|
||||
|
||||
let display_name = self.display_name(node_id, network_path);
|
||||
let name_click_target = if display_name.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let name_left = node_top_left.x + NAME_LEFT_OFFSET;
|
||||
let icons_reserve = VISIBILITY_INSET_FROM_LAYER_RIGHT + icons_width + GRIP_WIDTH;
|
||||
let name_right_max = node_top_left.x + width as f64 - icons_reserve;
|
||||
let text_w = crate::messages::portfolio::document::overlays::utility_functions::text_width(&display_name, FONT_SIZE);
|
||||
let name_right = (name_left + text_w).min(name_right_max);
|
||||
if name_right > name_left {
|
||||
// The 1-grid-tall name strip is centered vertically in the 2-grid-tall layer.
|
||||
let name_top = node_top_left.y + HALF_GRID_SIZE as f64;
|
||||
let name_bottom = node_top_left.y + GRID_SIZE as f64 + HALF_GRID_SIZE as f64;
|
||||
let subpath = Subpath::new_rounded_rectangle(DVec2::new(name_left, name_top), DVec2::new(name_right, name_bottom), [3.; 4]);
|
||||
Some(ClickTarget::new_with_subpath(subpath, 0.))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
// Create layer click target, which is contains the layer and the chain background
|
||||
let chain_width_grid_spaces = self.chain_width(node_id, network_path);
|
||||
|
||||
let node_bottom_right = node_top_left + DVec2::new(width as f64, height as f64);
|
||||
let chain_top_left = node_top_left - DVec2::new((chain_width_grid_spaces * GRID_SIZE) as f64, 0.);
|
||||
const CORNER_RADIUS: f64 = 10.;
|
||||
let subpath = Subpath::new_rounded_rectangle(chain_top_left, node_bottom_right, [CORNER_RADIUS; 4]);
|
||||
let chain_top_left = node_top_left - DVec2::new((chain_width_grid_spaces * crate::consts::GRID_SIZE) as f64, 0.);
|
||||
let radius = 10.;
|
||||
let subpath = Subpath::new_rounded_rectangle(chain_top_left, node_bottom_right, [radius; 4]);
|
||||
let node_click_target = ClickTarget::new_with_subpath(subpath, 0.);
|
||||
|
||||
DocumentNodeClickTargets {
|
||||
@@ -2691,7 +2594,6 @@ impl NodeNetworkInterface {
|
||||
visibility_click_target,
|
||||
lock_click_target,
|
||||
grip_click_target,
|
||||
name_click_target,
|
||||
}),
|
||||
}
|
||||
};
|
||||
@@ -3030,7 +2932,6 @@ impl NodeNetworkInterface {
|
||||
LayerClickTargetTypes::Visibility => layer.visibility_click_target.intersect_point_no_stroke(point).then_some(*node_id),
|
||||
LayerClickTargetTypes::Lock => layer.lock_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)),
|
||||
LayerClickTargetTypes::Grip => layer.grip_click_target.intersect_point_no_stroke(point).then_some(*node_id),
|
||||
LayerClickTargetTypes::Name => layer.name_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)),
|
||||
}
|
||||
} else {
|
||||
None
|
||||
@@ -3191,8 +3092,8 @@ impl NodeNetworkInterface {
|
||||
let nodes = network_metadata
|
||||
.persistent_metadata
|
||||
.node_metadata
|
||||
.keys()
|
||||
.filter_map(|node_id| if self.is_layer(node_id, network_path) { Some(*node_id) } else { None })
|
||||
.iter()
|
||||
.filter_map(|(node_id, _)| if self.is_layer(node_id, network_path) { Some(*node_id) } else { None })
|
||||
.collect::<Vec<_>>();
|
||||
let layer_widths = nodes
|
||||
.iter()
|
||||
@@ -3234,39 +3135,6 @@ impl NodeNetworkInterface {
|
||||
self.document_metadata.layer_vector_data.get(&layer).map(|arc| arc.as_ref().clone())
|
||||
}
|
||||
|
||||
/// The vector geometry an upstream Path node would surface for editing.
|
||||
/// This is the result of `compute_modified_vector`, but only if a visible 'Path' node is actually upstream.
|
||||
/// Useful for tool overlays and snap target collection usages that want to match the Path tool's view
|
||||
/// (e.g. the pre-solidified centerline for a Solidify Stroke layer) and otherwise do nothing.
|
||||
pub fn upstream_path_node_vector(&self, layer: LayerNodeIdentifier) -> Option<Vector> {
|
||||
let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, self);
|
||||
graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::Network("Path".into()))?;
|
||||
self.compute_modified_vector(layer)
|
||||
}
|
||||
|
||||
/// Outline targets for the Select tool's hover/selection overlay, mirroring the Path tool's view.
|
||||
/// Returns `Some` when an upstream Path node exists so the outline matches what the Path tool edits
|
||||
/// (e.g. the pre-solidified centerline for a Solidify Stroke layer); returns `None` otherwise so the
|
||||
/// caller can fall back to the layer's recorded `outlines`/`click_targets`.
|
||||
pub fn path_aware_outline_targets(&self, layer: LayerNodeIdentifier) -> Option<Vec<ClickTargetType>> {
|
||||
let vector = self.upstream_path_node_vector(layer)?;
|
||||
|
||||
let mut targets = Vec::new();
|
||||
let subpaths: Vec<Subpath<PointId>> = vector.stroke_bezier_paths().collect();
|
||||
if !subpaths.is_empty() {
|
||||
targets.push(ClickTargetType::CompoundPath(subpaths));
|
||||
}
|
||||
|
||||
for &point_id in vector.point_domain.ids() {
|
||||
if !vector.any_connected(point_id) {
|
||||
let position = vector.point_domain.position_from_id(point_id).unwrap_or_default();
|
||||
targets.push(ClickTargetType::FreePoint(FreePoint::new(point_id, position)));
|
||||
}
|
||||
}
|
||||
|
||||
Some(targets)
|
||||
}
|
||||
|
||||
/// Loads the structure of layer nodes from a node graph.
|
||||
pub fn load_structure(&mut self) {
|
||||
self.document_metadata.structure = HashMap::from_iter([(LayerNodeIdentifier::ROOT_PARENT, NodeRelations::default())]);
|
||||
@@ -3351,8 +3219,6 @@ impl NodeNetworkInterface {
|
||||
self.document_metadata.local_transforms.retain(|node, _| nodes.contains(node));
|
||||
self.document_metadata.vector_modify.retain(|node, _| nodes.contains(node));
|
||||
self.document_metadata.click_targets.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
|
||||
self.document_metadata.outlines.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
|
||||
self.document_metadata.text_frames.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
|
||||
}
|
||||
|
||||
/// Update the cached transforms of the layers
|
||||
@@ -3361,7 +3227,7 @@ impl NodeNetworkInterface {
|
||||
self.document_metadata.local_transforms = local_transforms;
|
||||
}
|
||||
|
||||
/// Update the cached first item's source id of the layers
|
||||
/// Update the cached first instance source id of the layers
|
||||
pub fn update_first_element_source_id(&mut self, new: HashMap<NodeId, Option<NodeId>>) {
|
||||
self.document_metadata.first_element_source_ids = new;
|
||||
}
|
||||
@@ -3371,17 +3237,6 @@ impl NodeNetworkInterface {
|
||||
self.document_metadata.click_targets = new_click_targets;
|
||||
}
|
||||
|
||||
/// Update the cached source-geometry outline targets of the layers
|
||||
pub fn update_outlines(&mut self, new_outlines: HashMap<LayerNodeIdentifier, Vec<Arc<ClickTarget>>>) {
|
||||
self.document_metadata.outlines = new_outlines;
|
||||
}
|
||||
|
||||
/// Update the cached per-layer 'Text' node text frames in row-local space (as `DAffine2`
|
||||
/// mapping the unit square onto the frame).
|
||||
pub fn update_text_frames(&mut self, new_text_frames: HashMap<LayerNodeIdentifier, DAffine2>) {
|
||||
self.document_metadata.text_frames = new_text_frames;
|
||||
}
|
||||
|
||||
/// Update the cached clip targets of the layers
|
||||
pub fn update_clip_targets(&mut self, new_clip_targets: HashSet<NodeId>) {
|
||||
self.document_metadata.clip_targets = new_clip_targets;
|
||||
@@ -4659,7 +4514,32 @@ impl NodeNetworkInterface {
|
||||
return;
|
||||
}
|
||||
|
||||
node_metadata.persistent_metadata.display_name = display_name;
|
||||
node_metadata.persistent_metadata.display_name.clone_from(&display_name);
|
||||
|
||||
// Keep the alias in sync with the `ToArtboard` name input
|
||||
if self
|
||||
.reference(node_id, network_path)
|
||||
.is_some_and(|reference| reference == DefinitionIdentifier::Network("Artboard".into()))
|
||||
{
|
||||
let Some(nested_network) = self.network_mut(network_path) else {
|
||||
return;
|
||||
};
|
||||
let Some(artboard_node) = nested_network.nodes.get_mut(node_id) else {
|
||||
return;
|
||||
};
|
||||
let DocumentNodeImplementation::Network(network) = &mut artboard_node.implementation else {
|
||||
return;
|
||||
};
|
||||
// Keep this in sync with the definition
|
||||
let Some(to_artboard) = network.nodes.get_mut(&NodeId(0)) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let label_index = 1;
|
||||
let label = if !display_name.is_empty() { display_name } else { "Artboard".to_string() };
|
||||
let label_input = NodeInput::value(TaggedValue::String(label), false);
|
||||
to_artboard.inputs[label_index] = label_input;
|
||||
}
|
||||
|
||||
self.transaction_modified();
|
||||
self.try_unload_layer_width(node_id, network_path);
|
||||
@@ -5641,11 +5521,11 @@ impl NodeNetworkInterface {
|
||||
|
||||
match post_node_input {
|
||||
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Inline(_) | NodeInput::Reflection(_) => {
|
||||
// First child in the stack: wire layer output to the post_node input
|
||||
// First child in the stack — wire layer output to the post_node input
|
||||
self.set_input_for_import(&post_node, layer_output, network_path);
|
||||
}
|
||||
NodeInput::Node { .. } => {
|
||||
// Subsequent child: insert layer between post_node and its current upstream...
|
||||
// Subsequent child — insert layer between post_node and its current upstream:
|
||||
// 1. Disconnect old upstream from post_node, wire layer output to post_node
|
||||
self.set_input_for_import(&post_node, layer_output, network_path);
|
||||
// 2. Wire old upstream into layer's primary (stack) input
|
||||
@@ -6442,7 +6322,6 @@ pub struct InputPersistentMetadata {
|
||||
/// A general datastore than can store key value pairs of any types for any input
|
||||
/// Each instance of the input node needs to store its own data, since it can lose the reference to its
|
||||
/// node definition if the node signature is modified by the user. For example adding/removing/renaming an import/export of a network node.
|
||||
#[serde(serialize_with = "graphene_std::vector::serialize_hashmap_as_sorted_object")]
|
||||
pub input_data: HashMap<String, Value>,
|
||||
// An input can override a widget, which would otherwise be automatically generated from the type
|
||||
// The string is the identifier to the widget override function stored in INPUT_OVERRIDES
|
||||
@@ -6700,11 +6579,11 @@ pub enum NodeTypeTransientMetadata {
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct LayerTransientMetadata {
|
||||
// Stores the width in grid units for layer nodes from the left edge of the thumbnail (+12px padding since thumbnail ends between grid spaces) to the left end of the node
|
||||
// Stores the width in grid cell units for layer nodes from the left edge of the thumbnail (+12px padding since thumbnail ends between grid spaces) to the left end of the node
|
||||
/// This is necessary since calculating the layer width through web_sys is very slow
|
||||
pub layer_width: TransientMetadata<u32>,
|
||||
// Should not be a performance concern to calculate when needed with chain_width.
|
||||
// Stores the width in grid units for layer nodes from the left edge of the thumbnail to the end of the chain
|
||||
// Stores the width in grid cell units for layer nodes from the left edge of the thumbnail to the end of the chain
|
||||
// chain_width: u32,
|
||||
}
|
||||
|
||||
@@ -6723,10 +6602,6 @@ pub struct LayerClickTargets {
|
||||
pub lock_click_target: Option<ClickTarget>,
|
||||
/// Cache for the grip icon, which is next to the visibility button.
|
||||
pub grip_click_target: ClickTarget,
|
||||
/// Cache for the layer's display-name text bounds. Used to detect double-click rename and
|
||||
/// to skip the drill-into-subgraph behavior when the click lands on the name itself.
|
||||
/// `None` for layers whose display name is empty.
|
||||
pub name_click_target: Option<ClickTarget>,
|
||||
// TODO: Store click target for the preview button, which will appear when the node is a selected/(hovered?) layer node
|
||||
// preview_click_target: ClickTarget,
|
||||
}
|
||||
@@ -6735,7 +6610,6 @@ pub enum LayerClickTargetTypes {
|
||||
Visibility,
|
||||
Lock,
|
||||
Grip,
|
||||
Name,
|
||||
// Preview,
|
||||
}
|
||||
|
||||
|
||||
+4
-3
@@ -1,5 +1,6 @@
|
||||
use graph_craft::document::NodeNetwork;
|
||||
use std::cell::Cell;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq)]
|
||||
pub struct MemoNetwork {
|
||||
@@ -25,9 +26,9 @@ impl serde::Serialize for MemoNetwork {
|
||||
}
|
||||
}
|
||||
|
||||
impl graphene_hash::CacheHash for MemoNetwork {
|
||||
fn cache_hash<H: ::core::hash::Hasher>(&self, state: &mut H) {
|
||||
self.current_hash().cache_hash(state);
|
||||
impl Hash for MemoNetwork {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.current_hash().hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+22
-25
@@ -4,11 +4,7 @@ use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNodeImplementation, InlineRust, NodeInput};
|
||||
use graph_craft::proto::{GraphErrorType, GraphErrors};
|
||||
use graph_craft::{Type, concrete};
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::raster_types::{CPU, Raster};
|
||||
use graphene_std::uuid::NodeId;
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::{Artboard, Graphic};
|
||||
use interpreted_executor::dynamic_executor::{NodeTypes, ResolvedDocumentNodeTypesDelta};
|
||||
use interpreted_executor::node_registry::NODE_REGISTRY;
|
||||
|
||||
@@ -57,21 +53,22 @@ impl TypeSource {
|
||||
};
|
||||
match self.compiled_nested_type() {
|
||||
Some(nested_type) => match TaggedValue::from_type_or_none(nested_type) {
|
||||
TaggedValue::U32(_) | TaggedValue::U64(_) | TaggedValue::F32(_) | TaggedValue::F64(_) | TaggedValue::DVec2(_) | TaggedValue::F64Array(_) | TaggedValue::DAffine2(_) => {
|
||||
FrontendGraphDataType::Number
|
||||
}
|
||||
TaggedValue::U32(_)
|
||||
| TaggedValue::U64(_)
|
||||
| TaggedValue::F32(_)
|
||||
| TaggedValue::F64(_)
|
||||
| TaggedValue::DVec2(_)
|
||||
| TaggedValue::F64Array4(_)
|
||||
| TaggedValue::VecF64(_)
|
||||
| TaggedValue::VecDVec2(_)
|
||||
| TaggedValue::DAffine2(_) => FrontendGraphDataType::Number,
|
||||
TaggedValue::Artboard(_) => FrontendGraphDataType::Artboard,
|
||||
TaggedValue::Graphic(_) => FrontendGraphDataType::Graphic,
|
||||
TaggedValue::Raster(_) => FrontendGraphDataType::Raster,
|
||||
TaggedValue::Vector(_) => FrontendGraphDataType::Vector,
|
||||
TaggedValue::Color(_) => FrontendGraphDataType::Color,
|
||||
TaggedValue::FillGradient(_) | TaggedValue::Gradient(_) => FrontendGraphDataType::Gradient,
|
||||
TaggedValue::Gradient(_) | TaggedValue::GradientTable(_) => 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() {
|
||||
n if n == std::any::type_name::<List<Graphic>>() => FrontendGraphDataType::Graphic,
|
||||
n if n == std::any::type_name::<List<Artboard>>() => FrontendGraphDataType::Artboard,
|
||||
n if n == std::any::type_name::<List<Raster<CPU>>>() => FrontendGraphDataType::Raster,
|
||||
n if n == std::any::type_name::<List<Vector>>() => FrontendGraphDataType::Vector,
|
||||
n if n == std::any::type_name::<List<String>>() => FrontendGraphDataType::Typography,
|
||||
_ => FrontendGraphDataType::General,
|
||||
},
|
||||
_ => FrontendGraphDataType::General,
|
||||
},
|
||||
None => FrontendGraphDataType::General,
|
||||
@@ -94,8 +91,8 @@ impl TypeSource {
|
||||
/// The type to display in the tooltip label.
|
||||
pub fn resolved_type_tooltip_string(&self) -> String {
|
||||
match self {
|
||||
TypeSource::Compiled(compiled_type) => compiled_type.nested_type().to_string(),
|
||||
TypeSource::TaggedValue(value_type) => value_type.nested_type().to_string(),
|
||||
TypeSource::Compiled(compiled_type) => format!("Data Type: {}", compiled_type.nested_type()),
|
||||
TypeSource::TaggedValue(value_type) => format!("Data Type: {}", value_type.nested_type()),
|
||||
TypeSource::Unknown => "Unknown Data Type".to_string(),
|
||||
TypeSource::Invalid => "Invalid Type Combination".to_string(),
|
||||
TypeSource::Error(_) => "Error Getting Data Type".to_string(),
|
||||
@@ -245,16 +242,16 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => {
|
||||
let Some(implementations) = NODE_REGISTRY.get(proto_node_identifier) else {
|
||||
// The compiler removes the passthrough node, so it's expected to be absent from the registry
|
||||
if proto_node_identifier != &graphene_std::ops::passthrough::IDENTIFIER {
|
||||
// The compiler removes the identity node, so it's expected to be absent from the registry
|
||||
if proto_node_identifier != &graphene_std::ops::identity::IDENTIFIER {
|
||||
log::error!("Proto node `{proto_node_identifier:?}` not found in the node registry, in potential_valid_input_types");
|
||||
}
|
||||
return Vec::new();
|
||||
};
|
||||
let number_of_inputs = self.number_of_inputs(node_id, network_path);
|
||||
implementations
|
||||
.keys()
|
||||
.filter_map(|node_io| {
|
||||
.iter()
|
||||
.filter_map(|(node_io, _)| {
|
||||
// Check if this NodeIOTypes implementation is valid for the other inputs
|
||||
let valid_implementation = (0..number_of_inputs).filter(|iterator_index| iterator_index != input_index).all(|iterator_index| {
|
||||
let input_type = self.input_type_not_invalid(&InputConnector::node(*node_id, iterator_index), network_path);
|
||||
@@ -293,8 +290,8 @@ impl NodeNetworkInterface {
|
||||
let valid_output_types = self.valid_output_types(&OutputConnector::node(*node_id, 0), network_path);
|
||||
|
||||
implementations
|
||||
.keys()
|
||||
.filter_map(|node_io| {
|
||||
.iter()
|
||||
.filter_map(|(node_io, _)| {
|
||||
if !valid_output_types.iter().any(|output_type| output_type.nested_type() == node_io.return_value.nested_type()) {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -159,7 +159,7 @@ impl SelectedNodes {
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
|
||||
/// Tracks which layer occurrences are collapsed in the Layers panel. Each entry is a "tree path":
|
||||
/// Tracks which layer instances are collapsed in the Layers panel. Each entry is an "instance path":
|
||||
/// the sequence of ancestor node IDs from the root down to the collapsed layer. This allows the same
|
||||
/// layer appearing under multiple parents to have independent expand/collapse state per occurrence.
|
||||
/// layer appearing under multiple parents to have independent expand/collapse state per instance.
|
||||
pub struct CollapsedLayers(pub Vec<Vec<NodeId>>);
|
||||
@@ -54,7 +54,7 @@ impl OriginalTransforms {
|
||||
|
||||
/// Gets the transform from the most downstream transform node
|
||||
fn get_layer_transform(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<DAffine2> {
|
||||
let transform_node_id = ModifyInputsContext::locate_node_in_layer_chain(&DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER), layer, network_interface)?;
|
||||
let transform_node_id = ModifyInputsContext::locate_node_in_layer_chain(&DefinitionIdentifier::Network("Transform".into()), layer, network_interface)?;
|
||||
|
||||
let document_node = network_interface.document_network().nodes.get(&transform_node_id)?;
|
||||
Some(transform_utils::get_current_transform(&document_node.inputs))
|
||||
|
||||
@@ -6,13 +6,15 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeTemplate, OutputConnector};
|
||||
use crate::messages::prelude::DocumentMessageHandler;
|
||||
use glam::{DVec2, IVec2};
|
||||
use graph_craft::descriptor;
|
||||
use graph_craft::document::DocumentNode;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeInput, value::TaggedValue};
|
||||
use graphene_std::ProtoNodeIdentifier;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::table::Table;
|
||||
use graphene_std::text::{TextAlign, TypesettingConfig};
|
||||
use graphene_std::transform::ScaleType;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::vector::style::{PaintOrder, StrokeAlign};
|
||||
use std::collections::HashMap;
|
||||
use std::f64::consts::PI;
|
||||
@@ -28,7 +30,6 @@ const TEXT_REPLACEMENTS: &[(&str, &str)] = &[
|
||||
("graphene_core::transform::Footprint", "graphene_core::transform::Footprint"),
|
||||
("\"OptionalF64\":", "\"F64\":"),
|
||||
("\"path_bool_nodes::BooleanOperation\"", "\"vector_types::vector::misc::BooleanOperation\""),
|
||||
("\"core_types::table::Table<", "\"core_types::list::List<"),
|
||||
];
|
||||
|
||||
pub struct NodeReplacement<'a> {
|
||||
@@ -40,19 +41,13 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
// ================================
|
||||
// blending
|
||||
// ================================
|
||||
// The legacy combined "Blending" node was split into separate Blend Mode, Opacity (now also covers fill), and Clip nodes.
|
||||
// Old Blending references are remapped here to `blend_mode::IDENTIFIER` so the per-node migration in `migrate_node` can
|
||||
// detect a 5-input Blend Mode node and rewrite it as a chain (skipping any sub-node whose value is at the default and
|
||||
// not exposed/wired up).
|
||||
NodeReplacement {
|
||||
node: graphene_std::blending_nodes::blending::IDENTIFIER,
|
||||
aliases: &["graphene_core::raster::BlendingNode", "graphene_core::blending_nodes::BlendingNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::blending_nodes::blend_mode::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_core::raster::BlendModeNode",
|
||||
"graphene_core::blending_nodes::BlendModeNode",
|
||||
"graphene_core::raster::BlendingNode",
|
||||
"graphene_core::blending_nodes::BlendingNode",
|
||||
"blending_nodes::BlendingNode",
|
||||
],
|
||||
aliases: &["graphene_core::raster::BlendModeNode", "graphene_core::blending_nodes::BlendModeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::blending_nodes::opacity::IDENTIFIER,
|
||||
@@ -93,16 +88,13 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
aliases: &["graphene_core::ops::ExtractXyNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::ops::passthrough::IDENTIFIER,
|
||||
node: graphene_std::ops::identity::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_core::ops::IdentityNode",
|
||||
"graphene_core::transform::CullNode",
|
||||
"graphene_core::transform::BoundlessFootprintNode",
|
||||
"graphene_core::transform::FreezeRealTimeNode",
|
||||
"graphene_core::transform_nodes::BoundlessFootprintNode",
|
||||
"graphene_core::transform_nodes::FreezeRealTimeNode",
|
||||
"graphene_core::vector::SubpathSegmentLengthsNode",
|
||||
"core_types::vector::SubpathSegmentLengthsNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -110,13 +102,17 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
aliases: &["graphene_core::memo::MonitorNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::memo::memoize::IDENTIFIER,
|
||||
node: graphene_std::memo::memo::IDENTIFIER,
|
||||
aliases: &["graphene_core::memo::MemoNode", "graphene_core::memo::ImpureMemoNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::animation::real_time::IDENTIFIER,
|
||||
aliases: &["graphene_core::animation::RealTimeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::logic::serialize::IDENTIFIER,
|
||||
aliases: &["graphene_core::logic::SerializeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::debug::size_of::IDENTIFIER,
|
||||
aliases: &["graphene_core::ops::SizeOfNode"],
|
||||
@@ -125,6 +121,34 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::debug::some::IDENTIFIER,
|
||||
aliases: &["graphene_core::ops::SomeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::logic::string_concatenate::IDENTIFIER,
|
||||
aliases: &["graphene_core::logic::StringConcatenateNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::logic::string_length::IDENTIFIER,
|
||||
aliases: &["graphene_core::logic::StringLengthNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::logic::string_replace::IDENTIFIER,
|
||||
aliases: &["graphene_core::logic::StringReplaceNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::logic::string_slice::IDENTIFIER,
|
||||
aliases: &["graphene_core::logic::StringSliceNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::logic::string_split::IDENTIFIER,
|
||||
aliases: &["graphene_core::logic::StringSplitNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::logic::switch::IDENTIFIER,
|
||||
aliases: &["graphene_core::logic::SwitchNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::logic::to_string::IDENTIFIER,
|
||||
aliases: &["graphene_core::logic::ToStringNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::debug::unwrap_option::IDENTIFIER,
|
||||
aliases: &["graphene_core::ops::UnwrapNode", "graphene_core::debug::UnwrapNode"],
|
||||
@@ -178,6 +202,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::graphic::LegacyLayerExtendNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::graphic_nodes::source_node_id::IDENTIFIER,
|
||||
aliases: &["graphene_core::graphic::graphic::SourceNodeIdNode", "graphene_core::graphic::SourceNodeIdNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::graphic::to_graphic::IDENTIFIER,
|
||||
aliases: &[
|
||||
@@ -389,6 +417,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::math_nodes::sine_inverse::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::SineInverseNode", "graphene_core::ops::SineInverseNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::string_value::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::StringValueNode", "graphene_core::ops::StringValueNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::subtract::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::SubtractNode", "graphene_core::ops::SubtractNode"],
|
||||
@@ -522,6 +554,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::raster_nodes::adjustments::gamma_correction::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::adjustments::GammaCorrectionNode", "graphene_core::raster::adjustments::GammaCorrectionNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::generate_curves::generate_curves::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::generate_curves::GenerateCurvesNode", "graphene_core::raster::adjustments::GenerateCurvesNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::gradient_map::gradient_map::IDENTIFIER,
|
||||
aliases: &[
|
||||
@@ -549,9 +585,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::std_nodes::image::IDENTIFIER,
|
||||
node: graphene_std::raster_nodes::std_nodes::image_value::IDENTIFIER,
|
||||
aliases: &[
|
||||
"raster_nodes::std_nodes::ImageValueNode",
|
||||
"graphene_raster_nodes::std_nodes::ImageValueNode",
|
||||
"graphene_std::raster::ImageValueNode",
|
||||
"graphene_std::raster::ImageNode",
|
||||
@@ -645,46 +680,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::text::text::IDENTIFIER,
|
||||
aliases: &["graphene_core::text::text::TextNode", "graphene_core::text::TextGeneratorNode", "graphene_core::text::TextNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::text_nodes::string_value::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::StringValueNode", "graphene_core::ops::StringValueNode", "math_nodes::StringValueNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::text_nodes::string_concatenate::IDENTIFIER,
|
||||
aliases: &["graphene_core::logic::StringConcatenateNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::text_nodes::string_length::IDENTIFIER,
|
||||
aliases: &["graphene_core::logic::StringLengthNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::text_nodes::string_replace::IDENTIFIER,
|
||||
aliases: &["graphene_core::logic::StringReplaceNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::text_nodes::string_slice::IDENTIFIER,
|
||||
aliases: &["graphene_core::logic::StringSliceNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::text_nodes::string_split::IDENTIFIER,
|
||||
aliases: &["graphene_core::logic::StringSplitNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::switch::IDENTIFIER,
|
||||
aliases: &["graphene_core::logic::SwitchNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::text_nodes::to_string::IDENTIFIER,
|
||||
aliases: &["graphene_core::logic::ToStringNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::text_nodes::json::query_json::IDENTIFIER,
|
||||
aliases: &["graphene_core::logic::JsonGetNode", "graphene_std::text_nodes::JsonGetNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::text_nodes::serialize::IDENTIFIER,
|
||||
aliases: &["graphene_core::logic::SerializeNode"],
|
||||
},
|
||||
// ================================
|
||||
// transform
|
||||
// ================================
|
||||
@@ -912,8 +907,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
aliases: &["graphene_core::vector::PointsToPolylineNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::vector::scatter_points::IDENTIFIER,
|
||||
aliases: &["graphene_core::vector::PoissonDiskPointsNode", "core_types::vector::PoissonDiskPointsNode"],
|
||||
node: graphene_std::vector::poisson_disk_points::IDENTIFIER,
|
||||
aliases: &["graphene_core::vector::PoissonDiskPointsNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::vector::position_on_path::IDENTIFIER,
|
||||
@@ -951,6 +946,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::vector::stroke::IDENTIFIER,
|
||||
aliases: &["graphene_core::vector::StrokeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::vector::subpath_segment_lengths::IDENTIFIER,
|
||||
aliases: &["graphene_core::vector::SubpathSegmentLengthsNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::vector::tangent_on_path::IDENTIFIER,
|
||||
aliases: &["graphene_core::vector::TangentOnPathNode"],
|
||||
@@ -1021,16 +1020,6 @@ pub fn document_migration_reset_node_definition(document_serialized_content: &st
|
||||
return true;
|
||||
}
|
||||
|
||||
// The `source_node_id` proto node was removed in favor of `path_of_subgraph` + `write_attribute`.
|
||||
// Documents that still reference it inside their Merge or Artboard layer networks need those layer definitions
|
||||
// reset to the current default so the new internal plumbing replaces the obsolete node.
|
||||
if document_serialized_content.contains("graphic_nodes::graphic::SourceNodeIdNode")
|
||||
|| document_serialized_content.contains("graphene_core::graphic::graphic::SourceNodeIdNode")
|
||||
|| document_serialized_content.contains("graphene_core::graphic::SourceNodeIdNode")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
@@ -1063,95 +1052,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// The "Brush" wrapper network was replaced with the `brush` proto node directly. Convert old `Network("Brush")` instances to the proto node, forwarding all 3 inputs (Background, Trace, Cache) one-to-one.
|
||||
// This must run as a pre-pass before the recursive iteration below: replacing the outer Brush's network impl orphans its child paths, and the recursive iteration would log errors for those stale paths.
|
||||
let brush_layers: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter_map(|(node_id, _, path)| (document.network_interface.reference(node_id, &path) == Some(DefinitionIdentifier::Network("Brush".into()))).then_some((*node_id, path)))
|
||||
.collect();
|
||||
for (node_id, network_path) in &brush_layers {
|
||||
// Pre-load `outward_wires` so the chain-break check inside `set_input` resolves the original upstream→node wire from cache
|
||||
// rather than triggering a fresh rebuild from the (already-mutated) post-`replace_inputs` state, which would orphan wires.
|
||||
let _ = document.network_interface.outward_wires(network_path);
|
||||
let new_reference = DefinitionIdentifier::ProtoNode(graphene_std::brush::brush::brush::IDENTIFIER);
|
||||
let Some(definition) = resolve_document_node_type(&new_reference) else { continue };
|
||||
let mut node_template = definition.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
|
||||
continue;
|
||||
};
|
||||
for (index, input) in old_inputs.iter().take(3).enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, index), input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// The "Transform" wrapper network was replaced with the `transform` proto node directly. Convert old `Network("Transform")` instances to the proto node, forwarding the 5 user-facing inputs (Value, Translation, Rotation, Scale, Skew) and dropping the legacy migration sentinels (Origin Offset, Scale Appearance) at indices 5 and 6 if present.
|
||||
// Pre-pass for the same reason as the Brush migration above: replacing the outer Transform's network impl orphans its child paths.
|
||||
let transform_layers: Vec<(NodeId, Vec<NodeId>, usize)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter_map(|(node_id, node, path)| {
|
||||
(document.network_interface.reference(node_id, &path) == Some(DefinitionIdentifier::Network("Transform".into()))).then_some((*node_id, path, node.inputs.len()))
|
||||
})
|
||||
.collect();
|
||||
for (node_id, network_path, old_inputs_count) in &transform_layers {
|
||||
// Pre-load `outward_wires` so the chain-break check inside `set_input` resolves the original upstream→node wire from cache
|
||||
// rather than triggering a fresh rebuild from the (already-mutated) post-`replace_inputs` state, which would orphan wires.
|
||||
let _ = document.network_interface.outward_wires(network_path);
|
||||
let new_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
|
||||
let Some(definition) = resolve_document_node_type(&new_reference) else { continue };
|
||||
let mut node_template = definition.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
|
||||
continue;
|
||||
};
|
||||
// Forward the first 5 inputs (Value, Translation, Rotation, Scale, Skew); drop indices 5 and 6 if present.
|
||||
for (index, input) in old_inputs.iter().take(5).enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, index), input.clone(), network_path);
|
||||
}
|
||||
|
||||
// Pre-2024 documents stored Transform with 6 inputs and used radians for Rotation and `tan(radians)` for Skew. Detect that legacy
|
||||
// shape (no input at index 6) and convert the units to degrees so the values match what the new Properties panel widgets expect.
|
||||
if *old_inputs_count == 6 {
|
||||
match old_inputs.get(2) {
|
||||
Some(NodeInput::Value { tagged_value, exposed }) => {
|
||||
if let TaggedValue::F64(radians) = *tagged_value.clone().into_inner() {
|
||||
let degrees = NodeInput::value(TaggedValue::F64(radians.to_degrees()), *exposed);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 2), degrees, network_path);
|
||||
}
|
||||
}
|
||||
Some(NodeInput::Node { .. }) => {
|
||||
// Wired upstream: splice in a Multiply node by 180/π that converts radians to degrees so the upstream value
|
||||
// (which represented radians in the legacy format) reaches the now-degrees Rotation input correctly.
|
||||
if let Some(multiply_node) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::multiply::IDENTIFIER)) {
|
||||
let mut multiply_template = multiply_node.default_node_template();
|
||||
multiply_template.document_node.inputs[1] = NodeInput::value(TaggedValue::F64(180. / PI), false);
|
||||
let multiply_node_id = NodeId::new();
|
||||
if let Some(transform_position) = document.network_interface.position_from_downstream_node(node_id, network_path) {
|
||||
let multiply_position = transform_position + IVec2::new(-7, 1);
|
||||
document.network_interface.insert_node(multiply_node_id, multiply_template, network_path);
|
||||
document.network_interface.shift_absolute_node_position(&multiply_node_id, multiply_position, network_path);
|
||||
document.network_interface.insert_node_between(&multiply_node_id, &InputConnector::node(*node_id, 2), 0, network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
if let Some(NodeInput::Value { tagged_value, exposed }) = old_inputs.get(4)
|
||||
&& let TaggedValue::DVec2(old_value) = *tagged_value.clone().into_inner()
|
||||
{
|
||||
// The previous skew value stored `tan(radians)`, now it stores degrees directly.
|
||||
let new_value = DVec2::new(old_value.x.atan().to_degrees(), old_value.y.atan().to_degrees());
|
||||
let new_input = NodeInput::value(TaggedValue::DVec2(new_value), *exposed);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 4), new_input, network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Apply upgrades to each unmodified node.
|
||||
let nodes = document
|
||||
.network_interface
|
||||
@@ -1165,27 +1065,11 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
|
||||
fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId], document: &mut DocumentMessageHandler, reset_node_definitions_on_open: bool) -> Option<()> {
|
||||
// Must run before the reset block below: a node referencing a removed catalog entry would otherwise abort
|
||||
// `migrate_node` via the `?` on `resolve_document_node_type`, preventing subsequent migration blocks from running.
|
||||
migrate_removed_catalog_definitions(node_id, node, network_path, document);
|
||||
|
||||
if reset_node_definitions_on_open && let Some(reference) = document.network_interface.reference(node_id, network_path) {
|
||||
let node_definition = resolve_document_node_type(&reference)?;
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
|
||||
}
|
||||
|
||||
// Rebuild stale Merge/Artboard subgraphs that still use the removed LegacyLayerExtendNode internally
|
||||
if let DocumentNodeImplementation::Network(inner) = &node.implementation
|
||||
&& inner
|
||||
.nodes
|
||||
.values()
|
||||
.any(|n| matches!(&n.implementation, DocumentNodeImplementation::ProtoNode(id) if id.as_str().contains("LegacyLayerExtend") || id.as_str().contains("legacy_layer_extend")))
|
||||
&& let Some(reference) = document.network_interface.reference(node_id, network_path)
|
||||
&& let Some(node_definition) = resolve_document_node_type(&reference)
|
||||
{
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
|
||||
}
|
||||
|
||||
// Upgrade old nodes to use `Context` instead of `()` or `Footprint` as their call argument
|
||||
if node.call_argument == graph_craft::concrete!(()) || node.call_argument == graph_craft::concrete!(graphene_std::transform::Footprint) {
|
||||
document.network_interface.set_call_argument(node_id, network_path, graph_craft::concrete!(graphene_std::Context));
|
||||
@@ -1196,175 +1080,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
|
||||
let mut inputs_count = node.inputs.len();
|
||||
|
||||
// Split the legacy combined "Blending" node into a chain of separate Blend Mode, Opacity (now also covers fill), and Clip nodes.
|
||||
// `NODE_REPLACEMENTS` rewrites the old `Blending` proto identifier (and its older aliases) to `blend_mode::IDENTIFIER`, so a leftover
|
||||
// 5-input shape on a Blend Mode node identifies an old Blending node that still needs structural splitting. Sub-nodes whose values
|
||||
// were at the default and weren't exposed/wired up are skipped, and the existing node ID is reused for the first kept sub-node so
|
||||
// any references elsewhere in the document survive. If everything would be skipped, a no-op default Blend Mode node is left behind
|
||||
// to preserve the chain structure (the user can delete it manually).
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::blending_nodes::blend_mode::IDENTIFIER) && inputs_count == 5 {
|
||||
use graphene_std::blending::BlendMode;
|
||||
|
||||
// Snapshot the old inputs before any rewriting
|
||||
let old_inputs = node.inputs.clone();
|
||||
let content_input = old_inputs[0].clone();
|
||||
let blend_mode_input = old_inputs[1].clone();
|
||||
let opacity_input = old_inputs[2].clone();
|
||||
let fill_input = old_inputs[3].clone();
|
||||
let clip_input = old_inputs[4].clone();
|
||||
|
||||
// A sub-node is kept if its input is exposed/wired (so the user can drive it from the graph) OR if its value differs from the default
|
||||
let keep_blend_mode = blend_mode_input.is_exposed() || !matches!(blend_mode_input.as_value(), Some(TaggedValue::BlendMode(BlendMode::Normal)));
|
||||
let keep_opacity = opacity_input.is_exposed() || !matches!(opacity_input.as_value(), Some(TaggedValue::F64(v)) if (*v - 100.).abs() < f64::EPSILON);
|
||||
let keep_fill = fill_input.is_exposed() || !matches!(fill_input.as_value(), Some(TaggedValue::F64(v)) if (*v - 100.).abs() < f64::EPSILON);
|
||||
let keep_clip = clip_input.is_exposed() || !matches!(clip_input.as_value(), Some(TaggedValue::Bool(false)));
|
||||
|
||||
// Find the downstream connection so we can chain new nodes between this node and downstream
|
||||
let downstream = document
|
||||
.network_interface
|
||||
.outward_wires(network_path)
|
||||
.and_then(|wires| wires.get(&OutputConnector::node(*node_id, 0)))
|
||||
.and_then(|connections| connections.first().cloned());
|
||||
|
||||
// The position of the existing node; subsequent chain nodes are placed to the right
|
||||
let base_position = document.network_interface.position(node_id, network_path).unwrap_or_default();
|
||||
|
||||
// Decide which sub-node the existing ID becomes (the first one in the chain order: Blend Mode, Opacity, Clip)
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum SubNode {
|
||||
BlendMode,
|
||||
Opacity,
|
||||
Clip,
|
||||
}
|
||||
let first_kind = if keep_blend_mode {
|
||||
SubNode::BlendMode
|
||||
} else if keep_opacity || keep_fill {
|
||||
SubNode::Opacity
|
||||
} else if keep_clip {
|
||||
SubNode::Clip
|
||||
} else {
|
||||
// Everything was at default and not exposed: leave a no-op Blend Mode node so the chain structure is preserved
|
||||
SubNode::BlendMode
|
||||
};
|
||||
|
||||
let identifier_for = |kind: SubNode| match kind {
|
||||
SubNode::BlendMode => graphene_std::blending_nodes::blend_mode::IDENTIFIER,
|
||||
SubNode::Opacity => graphene_std::blending_nodes::opacity::IDENTIFIER,
|
||||
SubNode::Clip => graphene_std::blending_nodes::clipping_mask::IDENTIFIER,
|
||||
};
|
||||
|
||||
// Replace the existing node's implementation with the first kept sub-node's template
|
||||
let first_reference = DefinitionIdentifier::ProtoNode(identifier_for(first_kind));
|
||||
let mut first_template = resolve_document_node_type(&first_reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut first_template);
|
||||
let _ = document.network_interface.replace_inputs(node_id, network_path, &mut first_template);
|
||||
|
||||
// Wire the existing node's inputs based on its new role (input 0 is always `content`)
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), content_input, network_path);
|
||||
match first_kind {
|
||||
SubNode::BlendMode => {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), blend_mode_input.clone(), network_path);
|
||||
}
|
||||
SubNode::Opacity => {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 1), NodeInput::value(TaggedValue::Bool(keep_opacity), false), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 2), opacity_input.clone(), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 3), NodeInput::value(TaggedValue::Bool(keep_fill), false), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 4), fill_input.clone(), network_path);
|
||||
}
|
||||
SubNode::Clip => {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), clip_input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// Build the list of remaining sub-nodes to insert (after the first one), in chain order. Blend Mode is never
|
||||
// reinserted because if it was kept it would already be the `first_kind`.
|
||||
let mut remaining: Vec<SubNode> = Vec::new();
|
||||
if first_kind != SubNode::Opacity && (keep_opacity || keep_fill) {
|
||||
remaining.push(SubNode::Opacity);
|
||||
}
|
||||
if first_kind != SubNode::Clip && keep_clip {
|
||||
remaining.push(SubNode::Clip);
|
||||
}
|
||||
|
||||
// Insert each remaining sub-node into the chain between the previous node and the original downstream
|
||||
let mut chain_x_offset = 7;
|
||||
for sub in remaining {
|
||||
let identifier = identifier_for(sub);
|
||||
let new_id = NodeId::new();
|
||||
let definition = match resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier.clone())) {
|
||||
Some(definition) => definition,
|
||||
None => {
|
||||
log::error!("Could not resolve `{identifier:?}` while migrating Blending node");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let template = definition.default_node_template();
|
||||
document.network_interface.insert_node(new_id, template, network_path);
|
||||
document
|
||||
.network_interface
|
||||
.shift_absolute_node_position(&new_id, base_position + IVec2::new(chain_x_offset, 0), network_path);
|
||||
chain_x_offset += 7;
|
||||
|
||||
// Splice this node in just before the original downstream input (so each iteration appends to the chain end)
|
||||
if let Some(downstream_input) = &downstream {
|
||||
document.network_interface.insert_node_between(&new_id, downstream_input, 0, network_path);
|
||||
}
|
||||
|
||||
// Wire the parameter inputs for the inserted node
|
||||
match sub {
|
||||
SubNode::BlendMode => {
|
||||
document.network_interface.set_input(&InputConnector::node(new_id, 1), blend_mode_input.clone(), network_path);
|
||||
}
|
||||
SubNode::Opacity => {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(new_id, 1), NodeInput::value(TaggedValue::Bool(keep_opacity), false), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(new_id, 2), opacity_input.clone(), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(new_id, 3), NodeInput::value(TaggedValue::Bool(keep_fill), false), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(new_id, 4), fill_input.clone(), network_path);
|
||||
}
|
||||
SubNode::Clip => {
|
||||
document.network_interface.set_input(&InputConnector::node(new_id, 1), clip_input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inputs_count = match first_kind {
|
||||
SubNode::BlendMode => 2,
|
||||
SubNode::Opacity => 5,
|
||||
SubNode::Clip => 2,
|
||||
};
|
||||
}
|
||||
|
||||
// Upgrade old single-purpose Opacity node (content, opacity) to the new shape that also covers fill:
|
||||
// (content, has_opacity, opacity, has_fill, fill). The original opacity input is preserved with `has_opacity` enabled,
|
||||
// while `has_fill` is left disabled and the fill value defaults to 100% (no change to fill behavior).
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::blending_nodes::opacity::IDENTIFIER) && inputs_count == 2 {
|
||||
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)?;
|
||||
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 1), NodeInput::value(TaggedValue::Bool(true), false), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 2), old_inputs[1].clone(), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 3), NodeInput::value(TaggedValue::Bool(false), false), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 4), NodeInput::value(TaggedValue::F64(100.), false), network_path);
|
||||
|
||||
inputs_count = 5;
|
||||
}
|
||||
|
||||
// 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();
|
||||
@@ -1385,6 +1100,82 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 9), old_inputs[4].clone(), network_path);
|
||||
}
|
||||
|
||||
// Upgrade the old "Spline" node to the new "Spline" node
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::spline::IDENTIFIER)
|
||||
|| reference == DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::new("graphene_core::vector::generator_nodes::SplineNode"))
|
||||
|| reference == DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::new("graphene_core::vector::SplineNode"))
|
||||
|| reference == DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::new("graphene_core::vector::SplinesFromPointsNode"))
|
||||
{
|
||||
// Retrieve the proto node identifier and verify it is the old "Spline" node, otherwise skip it if this is the new "Spline" node
|
||||
let identifier = document
|
||||
.network_interface
|
||||
.implementation(node_id, network_path)
|
||||
.and_then(|implementation| implementation.get_proto_node());
|
||||
if identifier.map(|identifier| identifier.as_str()) != Some("graphene_core::vector::generator_nodes::SplineNode") {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Obtain the document node for the given node ID, extract the vector points, and create a Vector path from the list of points
|
||||
let node = document.network_interface.document_node(node_id, network_path)?;
|
||||
let Some(TaggedValue::VecDVec2(points)) = node.inputs.get(1).and_then(|tagged_value| tagged_value.as_value()) else {
|
||||
log::error!("The old Spline node's input at index 1 is not a TaggedValue::VecDVec2");
|
||||
return None;
|
||||
};
|
||||
let vector = Vector::from_subpath(Subpath::from_anchors(points.to_vec(), false));
|
||||
|
||||
// Retrieve the output connectors linked to the "Spline" node's output connector
|
||||
let Some(spline_outputs) = document.network_interface.outward_wires(network_path)?.get(&OutputConnector::node(*node_id, 0)).cloned() else {
|
||||
log::error!("Vec of InputConnector Spline node is connected to its output connector 0.");
|
||||
return None;
|
||||
};
|
||||
|
||||
// Get the node's current position in the graph
|
||||
let Some(node_position) = document.network_interface.position(node_id, network_path) else {
|
||||
log::error!("Could not get position of spline node.");
|
||||
return None;
|
||||
};
|
||||
|
||||
// Get the "Path" node definition and fill it in with the Vector path and default vector modification
|
||||
let Some(path_node_type) = resolve_network_node_type("Path") else {
|
||||
log::error!("Path node does not exist.");
|
||||
return None;
|
||||
};
|
||||
let path_node = path_node_type.node_template_input_override([
|
||||
Some(NodeInput::value(TaggedValue::Vector(Table::new_from_element(vector)), true)),
|
||||
Some(NodeInput::value(TaggedValue::VectorModification(Default::default()), false)),
|
||||
]);
|
||||
|
||||
// Get the "Spline" node definition and wire it up with the "Path" node as input
|
||||
let Some(spline_node_type) = resolve_proto_node_type(graphene_std::vector::spline::IDENTIFIER) else {
|
||||
log::error!("Spline node does not exist.");
|
||||
return None;
|
||||
};
|
||||
let spline_node = spline_node_type.node_template_input_override([Some(NodeInput::node(NodeId(1), 0))]);
|
||||
|
||||
// Create a new node group with the "Path" and "Spline" nodes and generate new node IDs for them
|
||||
let nodes = vec![(NodeId(1), path_node), (NodeId(0), spline_node)];
|
||||
let new_ids = nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect::<HashMap<_, _>>();
|
||||
let new_spline_id = *new_ids.get(&NodeId(0))?;
|
||||
let new_path_id = *new_ids.get(&NodeId(1))?;
|
||||
|
||||
// Remove the old "Spline" node from the document
|
||||
document.network_interface.delete_nodes(vec![*node_id], false, network_path);
|
||||
|
||||
// Insert the new "Path" and "Spline" nodes into the network interface with generated IDs
|
||||
document.network_interface.insert_node_group(nodes.clone(), new_ids, network_path);
|
||||
|
||||
// Reposition the new "Spline" node to match the original "Spline" node's position
|
||||
document.network_interface.shift_node(&new_spline_id, node_position, network_path);
|
||||
|
||||
// Reposition the new "Path" node with an offset relative to the original "Spline" node's position
|
||||
document.network_interface.shift_node(&new_path_id, node_position + IVec2::new(-7, 0), network_path);
|
||||
|
||||
// Redirect each output connection from the old node to the new "Spline" node's output connector
|
||||
for input_connector in spline_outputs {
|
||||
document.network_interface.set_input(&input_connector, NodeInput::node(new_spline_id, 0), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// Upgrade Text node to include line height and character spacing, which were previously hardcoded to 1, from https://github.com/GraphiteEditor/Graphite/pull/2016
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER) && inputs_count == 8 {
|
||||
let mut template: NodeTemplate = resolve_document_node_type(&reference)?.default_node_template();
|
||||
@@ -1588,7 +1379,15 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 4), old_inputs[3].clone(), network_path);
|
||||
}
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::image::IDENTIFIER) && inputs_count == 1 {
|
||||
// Upgrade artboard name being passed as hidden value input to "Create Artboard"
|
||||
if reference == DefinitionIdentifier::Network("Artboard".into()) && reset_node_definitions_on_open {
|
||||
let label = document.network_interface.display_name(node_id, network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(NodeId(0), 1), NodeInput::value(TaggedValue::String(label), false), &[*node_id]);
|
||||
}
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::image_value::IDENTIFIER) && inputs_count == 1 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
|
||||
@@ -1620,8 +1419,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
}
|
||||
|
||||
// Old shape: [background, bounds, trace, cache]. Both "bounds" (input 1) and "cache" (input 3) are dropped, and "cache" is now stored as
|
||||
// internal node state via `#[data]` on the brush node, so it is not a node input at all in the new shape.
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::brush::brush::brush::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);
|
||||
@@ -1629,18 +1426,9 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
// We have removed the second input ("bounds"), so we don't add index 1 and we shift the rest of the inputs down by one
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[2].clone(), network_path);
|
||||
}
|
||||
|
||||
// Old shape: [background, trace, cache]. The "cache" input is dropped because the brush node now stores its cache as internal `#[data]` state.
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::brush::brush::brush::IDENTIFIER) && inputs_count == 3 {
|
||||
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)?;
|
||||
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 2), old_inputs[3].clone(), network_path);
|
||||
}
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::new("graphene_core::vector::RemoveHandlesNode")) {
|
||||
@@ -1776,6 +1564,79 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.add_import(TaggedValue::U32(0), false, 1, "Loop Level", "TODO", &node_path);
|
||||
}
|
||||
|
||||
// Migrate the Transform node to use degrees instead of radians
|
||||
if reference == DefinitionIdentifier::Network("Transform".into()) && node.inputs.get(6).is_none() {
|
||||
let mut node_template = resolve_network_node_type("Transform")?.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)?;
|
||||
|
||||
// Value
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
// Translation
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
// Rotation
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 2), old_inputs[2].clone(), network_path);
|
||||
// Scale
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 3), old_inputs[3].clone(), network_path);
|
||||
// Skew
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 4), old_inputs[4].clone(), network_path);
|
||||
// Origin Offset
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 5), NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false), network_path);
|
||||
// Scale Appearance
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::Bool(true), false), network_path);
|
||||
|
||||
// Migrate rotation from radians to degrees
|
||||
match node.inputs.get(2)? {
|
||||
NodeInput::Value { tagged_value, exposed } => {
|
||||
// Read the existing Properties panel number value, which used to be in radians
|
||||
let TaggedValue::F64(radians) = *tagged_value.clone().into_inner() else { return None };
|
||||
|
||||
// Convert the radians to degrees and set it back as the new input value
|
||||
let degrees = NodeInput::value(TaggedValue::F64(radians.to_degrees()), *exposed);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 2), degrees, network_path);
|
||||
}
|
||||
NodeInput::Node { .. } => {
|
||||
// Construct a new Multiply node for converting from degrees to radians
|
||||
let Some(multiply_node) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::multiply::IDENTIFIER)) else {
|
||||
log::error!("Could not get multiply node from definition when upgrading transform");
|
||||
return None;
|
||||
};
|
||||
let mut multiply_template = multiply_node.default_node_template();
|
||||
multiply_template.document_node.inputs[1] = NodeInput::value(TaggedValue::F64(180. / PI), false);
|
||||
|
||||
// Decide on the placement position of the new Multiply node
|
||||
let multiply_node_id = NodeId::new();
|
||||
let Some(transform_position) = document.network_interface.position_from_downstream_node(node_id, network_path) else {
|
||||
log::error!("Could not get positon for transform node {node_id}");
|
||||
return None;
|
||||
};
|
||||
let multiply_position = transform_position + IVec2::new(-7, 1);
|
||||
|
||||
// Insert the new Multiply node into the network directly before it's used
|
||||
document.network_interface.insert_node(multiply_node_id, multiply_template, network_path);
|
||||
document.network_interface.shift_absolute_node_position(&multiply_node_id, multiply_position, network_path);
|
||||
document.network_interface.insert_node_between(&multiply_node_id, &InputConnector::node(*node_id, 2), 0, network_path);
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
|
||||
// Migrate skew from radians to degrees
|
||||
if let NodeInput::Value { tagged_value, exposed } = node.inputs.get(4)? {
|
||||
// Read the existing Properties panel number value, which used to be in radians
|
||||
let TaggedValue::DVec2(old_value) = *tagged_value.clone().into_inner() else { return None };
|
||||
|
||||
// The previous value stored the tangent of the displayed degrees. Now it stores the degrees, so take the arctan of it and convert to degrees.
|
||||
let new_value = DVec2::new(old_value.x.atan().to_degrees(), old_value.y.atan().to_degrees());
|
||||
let new_input = NodeInput::value(TaggedValue::DVec2(new_value), *exposed);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 4), new_input, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// Upgrade the "Animation" node to add the "Rate" input
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::animation::animation_time::IDENTIFIER) && inputs_count < 2 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
@@ -1804,20 +1665,20 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
.set_input(&InputConnector::node(*node_id, 1), NodeInput::value(TaggedValue::U32(0), false), network_path);
|
||||
}
|
||||
|
||||
// Migrate from the old source/target v1 "Morph" node to the new `List<Vector>`-based v2 "Morph" node.
|
||||
// This doesn't produce exactly equivalent results in cases involving input `List<Vector>` values with multiple items.
|
||||
// The old version would zip the source and target items, interpolating each pair together.
|
||||
// The migrated version will instead deeply flatten both merged `List`s and morph sequentially between all source vectors and all target vector elements.
|
||||
// Migrate from the old source/target v1 "Morph" node to the new vector table based v2 "Morph" node.
|
||||
// This doesn't produce exactly equivalent results in cases involving input vector tables with multiple rows.
|
||||
// The old version would zip the source and target table rows, interpoleating each pair together.
|
||||
// The migrated version will instead deeply flatten both merged tables and morph sequentially between all source vectors and all target vector elements.
|
||||
// This migration assumes most usages didn't involve multiple parallel vector elements, and instead morphed from a single source to a single target vector element.
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::morph::IDENTIFIER) && (inputs_count == 3 || inputs_count == 4) {
|
||||
// 3 inputs - old signature (#3405):
|
||||
// async fn morph(_: impl Ctx, source: List<Vector>, #[expose] target: List<Vector>, #[default(0.5)] time: Fraction) -> List<Vector> { ... }
|
||||
// async fn morph(_: impl Ctx, source: Table<Vector>, #[expose] target: Table<Vector>, #[default(0.5)] time: Fraction) -> Table<Vector> { ... }
|
||||
//
|
||||
// 4 inputs - even older signature (commit 80b8df8d4298b6669f124b929ce61bfabfc44e41):
|
||||
// async fn morph(_: impl Ctx, source: List<Vector>, #[expose] target: List<Vector>, #[default(0.5)] time: Fraction, start_index: u32) -> List<Vector> { ... }
|
||||
// async fn morph(_: impl Ctx, source: Table<Vector>, #[expose] target: Table<Vector>, #[default(0.5)] time: Fraction, #[min(0.)] start_index: IntegerCount) -> Table<Vector> { ... }
|
||||
//
|
||||
// v2 signature:
|
||||
// async fn morph<I: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: I, progression: Progression) -> List<Vector> { ... }
|
||||
// async fn morph<I: IntoGraphicTable>(_: impl Ctx, #[implementations(Table<Graphic>, Table<Vector>)] content: I, progression: Progression) -> Table<Vector> { ... }
|
||||
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
@@ -1874,7 +1735,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
return None;
|
||||
};
|
||||
|
||||
// Create Count Elements node: counts content `List` items → N
|
||||
// Create Count Elements node: counts content table rows → N
|
||||
let Some(count_elements_def) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::vector::count_elements::IDENTIFIER)) else {
|
||||
log::error!("Could not get count_elements node from definition when upgrading morph");
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
@@ -1980,7 +1841,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
|
||||
if let Some(downstream_input) = downstream {
|
||||
// Create a Transform node with translation = start
|
||||
let Some(transform_node_type) = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER) else {
|
||||
let Some(transform_node_type) = resolve_network_node_type("Transform") else {
|
||||
log::error!("Transform node definition not found during Arrow migration");
|
||||
return None;
|
||||
};
|
||||
@@ -2041,7 +1902,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
|
||||
if let Some(downstream_input) = downstream {
|
||||
// Create a Transform node with translation = start
|
||||
let Some(transform_node_type) = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER) else {
|
||||
let Some(transform_node_type) = resolve_network_node_type("Transform") else {
|
||||
log::error!("Transform node definition not found during Line migration");
|
||||
return None;
|
||||
};
|
||||
@@ -2091,30 +1952,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
.set_input(&InputConnector::node(*node_id, 3), NodeInput::value(TaggedValue::Bool(false), false), network_path);
|
||||
}
|
||||
|
||||
// SVG-import legacy Path nodes baked their geometry at non-exposed input 0; move it to input 1 (the modern slot for VectorModification).
|
||||
// For exposed input 0, any baked value is unused at runtime, so just reset it.
|
||||
if reference == DefinitionIdentifier::Network("Path".into()) {
|
||||
let input_0 = node.inputs.first()?;
|
||||
if let NodeInput::Value { tagged_value, exposed } = input_0
|
||||
&& let TaggedValue::VectorModification(modification) = &**tagged_value
|
||||
{
|
||||
let modification = modification.clone();
|
||||
let was_exposed = *exposed;
|
||||
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node(*node_id, 0),
|
||||
NodeInput::type_default(descriptor!(graphene_std::list::List<graphene_std::vector::Vector>), true),
|
||||
network_path,
|
||||
);
|
||||
|
||||
if !was_exposed {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 1), NodeInput::value(TaggedValue::VectorModification(modification), false), network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ==================================
|
||||
// PUT ALL MIGRATIONS ABOVE THIS LINE
|
||||
// ==================================
|
||||
@@ -2145,64 +1982,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Migrates document nodes whose catalog definitions have been removed.
|
||||
///
|
||||
/// This is called from `migrate_node` BEFORE its standard reset/migration logic, since that logic aborts when it can't
|
||||
/// resolve the node's `reference` against the current catalog. Each block here detects a specific decommissioned
|
||||
/// definition by its old reference name, swaps it to a still-supported implementation, and preserves the user's inputs.
|
||||
/// After this runs, the node's reference resolves cleanly so the rest of `migrate_node` proceeds normally.
|
||||
fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId], document: &mut DocumentMessageHandler) -> Option<()> {
|
||||
// Collapse the legacy "Sample Polyline" wrapper network into the standalone `sample_polyline` proto node.
|
||||
// The proto node now computes per-bezpath segment lengths inline, so the wrapper's separate `subpath_segment_lengths`
|
||||
// and `Memoize` nodes are no longer needed. The 7 user-facing inputs are positionally identical between the
|
||||
// old wrapper and the new proto node.
|
||||
if let Some(DefinitionIdentifier::Network(name)) = document.network_interface.reference(node_id, network_path)
|
||||
&& name == "Sample Polyline"
|
||||
&& node.inputs.len() == 7
|
||||
{
|
||||
let mut node_template = resolve_proto_node_type(graphene_std::vector::sample_polyline::IDENTIFIER)?.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)?;
|
||||
for (index, input) in old_inputs.iter().take(7).enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, index), input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// Collapse the legacy "Scatter Points" wrapper network into the standalone `scatter_points` proto node.
|
||||
// The wrapper's trailing `Memoize` node is now produced automatically by the `memoize` attribute on the
|
||||
// proto node, so the wrapper itself is redundant. The 3 user-facing inputs are positionally identical
|
||||
// between the old wrapper and the new proto node.
|
||||
if let Some(DefinitionIdentifier::Network(name)) = document.network_interface.reference(node_id, network_path)
|
||||
&& name == "Scatter Points"
|
||||
&& node.inputs.len() == 3
|
||||
{
|
||||
let mut node_template = resolve_proto_node_type(graphene_std::vector::scatter_points::IDENTIFIER)?.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)?;
|
||||
for (index, input) in old_inputs.iter().take(3).enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, index), input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// Collapse the legacy "Boolean Operation" wrapper network into the standalone `boolean_operation` proto node.
|
||||
// The wrapper's trailing `Memoize` node is now produced automatically by the `memoize` attribute on the
|
||||
// proto node, so the wrapper itself is redundant. The 2 user-facing inputs are positionally identical
|
||||
// between the old wrapper and the new proto node.
|
||||
if let Some(DefinitionIdentifier::Network(name)) = document.network_interface.reference(node_id, network_path)
|
||||
&& name == "Boolean Operation"
|
||||
&& node.inputs.len() == 2
|
||||
{
|
||||
let mut node_template = resolve_proto_node_type(graphene_std::path_bool_nodes::boolean_operation::IDENTIFIER)?.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)?;
|
||||
for (index, input) in old_inputs.iter().take(2).enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, index), input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
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::{AnimationExport, ExportBounds, FileType, PersistedState};
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType, PersistedState};
|
||||
use crate::messages::portfolio::document::utility_types::clipboards::Clipboard;
|
||||
use crate::messages::portfolio::utility_types::FontCatalog;
|
||||
use crate::messages::prelude::*;
|
||||
@@ -168,9 +168,6 @@ pub enum PortfolioMessage {
|
||||
SelectDocument {
|
||||
document_id: DocumentId,
|
||||
},
|
||||
RenameDocument {
|
||||
new_name: String,
|
||||
},
|
||||
SubmitDocumentExport {
|
||||
name: String,
|
||||
file_type: FileType,
|
||||
@@ -178,7 +175,6 @@ pub enum PortfolioMessage {
|
||||
bounds: ExportBounds,
|
||||
artboard_name: Option<String>,
|
||||
artboard_count: usize,
|
||||
animation: Option<AnimationExport>,
|
||||
},
|
||||
SubmitActiveGraphRender,
|
||||
SubmitGraphRender {
|
||||
@@ -196,6 +192,10 @@ pub enum PortfolioMessage {
|
||||
UpdateOpenDocumentsList,
|
||||
UpdateWorkspacePanelLayout,
|
||||
ResetWorkspaceLayout,
|
||||
ResetPanelGroupSizes {
|
||||
/// Path of child indices from the root to the split node whose children's sizes should be reset to defaults.
|
||||
split_path: Vec<usize>,
|
||||
},
|
||||
SetPanelGroupSizes {
|
||||
/// Path of child indices from the root to the split node whose children's sizes are being set.
|
||||
split_path: Vec<usize>,
|
||||
|
||||
@@ -453,13 +453,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
if let Some(layout) = state.workspace_layout {
|
||||
self.workspace_panel_layout = layout;
|
||||
responses.add(PortfolioMessage::UpdateWorkspacePanelLayout);
|
||||
|
||||
// Refill panels whose content was lost when the layout load remounted their frontend components
|
||||
for group_id in self.workspace_panel_layout.root.all_group_ids() {
|
||||
if let Some(panel_type) = self.workspace_panel_layout.panel_group(group_id).and_then(|g| g.active_panel_type()) {
|
||||
self.refresh_panel_content(panel_type, responses);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let PersistedState {
|
||||
@@ -505,7 +498,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
}
|
||||
PortfolioMessage::NewDocumentWithName { name } => {
|
||||
let mut new_document = DocumentMessageHandler::default();
|
||||
new_document.name = self.resolve_document_name(name, None);
|
||||
new_document.name = name;
|
||||
|
||||
responses.add(DocumentMessage::PTZUpdate);
|
||||
|
||||
@@ -806,26 +799,28 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
}
|
||||
});
|
||||
|
||||
let candidate_name = match (document_name, document_path, document_name_from_path) {
|
||||
(Some(name), _, None) => name,
|
||||
(_, Some(path), Some(name)) => {
|
||||
document.path = Some(path);
|
||||
name
|
||||
match (document_name, document_path, document_name_from_path) {
|
||||
(Some(name), _, None) => {
|
||||
document.name = name;
|
||||
}
|
||||
(_, _, Some(name)) => name,
|
||||
_ => String::new(),
|
||||
};
|
||||
document.name = self.resolve_document_name(candidate_name, None);
|
||||
(_, Some(path), Some(name)) => {
|
||||
document.name = name;
|
||||
document.path = Some(path);
|
||||
}
|
||||
(_, _, Some(name)) => {
|
||||
document.name = name;
|
||||
}
|
||||
_ => {
|
||||
document.name = DEFAULT_DOCUMENT_NAME.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
// Load the document into the portfolio so it opens in the editor
|
||||
self.load_document(document, document_id, responses);
|
||||
|
||||
responses.add(AppWindowMessage::Focus);
|
||||
}
|
||||
PortfolioMessage::OpenImage { name, image } => {
|
||||
// `NewDocumentWithName`'s handler routes empty/None-equivalent names through `resolve_document_name` which assigns the next available "Untitled Document {N}".
|
||||
responses.add(PortfolioMessage::NewDocumentWithName {
|
||||
name: name.clone().unwrap_or_default(),
|
||||
name: name.clone().unwrap_or(DEFAULT_DOCUMENT_NAME.into()),
|
||||
});
|
||||
|
||||
responses.add(DocumentMessage::PasteImage {
|
||||
@@ -852,7 +847,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
}
|
||||
PortfolioMessage::OpenSvg { name, svg } => {
|
||||
responses.add(PortfolioMessage::NewDocumentWithName {
|
||||
name: name.clone().unwrap_or_default(),
|
||||
name: name.clone().unwrap_or(DEFAULT_DOCUMENT_NAME.into()),
|
||||
});
|
||||
|
||||
// Parse the SVG to extract its declared canvas origin and dimensions from the viewBox attribute.
|
||||
@@ -999,10 +994,13 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
});
|
||||
|
||||
// Add default fill and stroke to the layer
|
||||
let fill = graphene_std::vector::style::Fill::solid(Color::WHITE);
|
||||
let fill_color = Color::WHITE;
|
||||
let stroke_color = Color::BLACK;
|
||||
|
||||
let fill = graphene_std::vector::style::Fill::solid(fill_color.to_gamma_srgb());
|
||||
responses.add(GraphOperationMessage::FillSet { layer, fill });
|
||||
|
||||
let stroke = graphene_std::vector::style::Stroke::new(Some(Color::BLACK), DEFAULT_STROKE_WIDTH);
|
||||
let stroke = graphene_std::vector::style::Stroke::new(Some(stroke_color.to_gamma_srgb()), DEFAULT_STROKE_WIDTH);
|
||||
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
|
||||
|
||||
// Create new point ids and add those into the existing Vector path
|
||||
@@ -1131,8 +1129,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
|
||||
responses.add(GraphOperationMessage::ResizeArtboard {
|
||||
layer: item_id,
|
||||
location: new_artboard_origin_doc.round(),
|
||||
dimensions: dimensions_doc.round(),
|
||||
location: new_artboard_origin_doc.round().as_ivec2(),
|
||||
dimensions: dimensions_doc.round().as_ivec2(),
|
||||
});
|
||||
}
|
||||
} else {
|
||||
@@ -1288,7 +1286,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-RC4").disabled(true).widget_instance()]; // TODO: After the RCs, call this "Graphite (beta) x.y.z"
|
||||
#[cfg(target_family = "wasm")]
|
||||
let widgets = vec![];
|
||||
|
||||
@@ -1336,16 +1334,13 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
Self::destroy_panel_layouts(target_active, responses);
|
||||
}
|
||||
|
||||
// Preserve the source panel's visual weight at its new location
|
||||
let source_slot_size = self.workspace_panel_layout.find_source_slot_size(&tabs);
|
||||
|
||||
// Remove the dragged tabs from their current panel groups (without pruning, so the target group survives)
|
||||
for &panel_type in &tabs {
|
||||
self.remove_panel_from_layout(panel_type);
|
||||
}
|
||||
|
||||
// Create the new panel group adjacent to the target, then prune empty groups
|
||||
let Some(new_id) = self.workspace_panel_layout.split_panel_group(target_group, direction, tabs.clone(), active_tab_index, source_slot_size) else {
|
||||
let Some(new_id) = self.workspace_panel_layout.split_panel_group(target_group, direction, tabs.clone(), active_tab_index) else {
|
||||
log::error!("Failed to insert split adjacent to panel group {target_group:?}");
|
||||
return;
|
||||
};
|
||||
@@ -1364,10 +1359,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
self.refresh_panel_content(target_active, responses);
|
||||
}
|
||||
}
|
||||
PortfolioMessage::RenameDocument { new_name } => {
|
||||
let resolved_name = self.resolve_document_name(new_name, self.active_document_id);
|
||||
responses.add(DocumentMessage::RenameDocument { new_name: resolved_name });
|
||||
}
|
||||
PortfolioMessage::SelectDocument { document_id } => {
|
||||
// Auto-save the document we are leaving
|
||||
let mut node_graph_open = false;
|
||||
@@ -1441,7 +1432,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
bounds,
|
||||
artboard_name,
|
||||
artboard_count,
|
||||
animation,
|
||||
} => {
|
||||
let document_id = self.active_document_id.expect("Tried to render non-existent document");
|
||||
let document = self.documents.get_mut(&document_id).expect("Tried to render non-existent document");
|
||||
@@ -1452,7 +1442,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
bounds,
|
||||
artboard_name,
|
||||
artboard_count,
|
||||
animation,
|
||||
..Default::default()
|
||||
};
|
||||
let result = self.executor.submit_document_export(document, document_id, export_config);
|
||||
@@ -1622,6 +1611,20 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
responses.add(PortfolioMessage::UpdateWorkspacePanelLayout);
|
||||
responses.add(MenuBarMessage::SendLayout);
|
||||
}
|
||||
PortfolioMessage::ResetPanelGroupSizes { split_path } => {
|
||||
// Walk the tree to the target split node using the path
|
||||
let mut node = &mut self.workspace_panel_layout.root;
|
||||
for &index in &split_path {
|
||||
let PanelLayoutSubdivision::Split { children } = node else { return };
|
||||
let Some(child) = children.get_mut(index) else { return };
|
||||
node = &mut child.subdivision;
|
||||
}
|
||||
|
||||
// Recalculate default sizes for this split node
|
||||
node.recalculate_default_sizes();
|
||||
|
||||
responses.add(PortfolioMessage::UpdateWorkspacePanelLayout);
|
||||
}
|
||||
PortfolioMessage::SetPanelGroupSizes { split_path, sizes } => {
|
||||
// Walk the tree to the target split node using the path
|
||||
let mut node = &mut self.workspace_panel_layout.root;
|
||||
@@ -1741,22 +1744,10 @@ impl PortfolioMessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves a proposed document name: if it's empty or only whitespace, falls back to the next
|
||||
/// available "Untitled Document {N}" via [`Self::generate_new_document_name`]. Otherwise trims surrounding
|
||||
/// whitespace and returns it. `exclude` is forwarded so a renaming document can skip its own current
|
||||
/// name when computing the fallback (preventing self-collision).
|
||||
pub fn resolve_document_name(&self, name: String, exclude: Option<DocumentId>) -> String {
|
||||
let trimmed = name.trim();
|
||||
if trimmed.is_empty() { self.generate_new_document_name(exclude) } else { trimmed.to_string() }
|
||||
}
|
||||
|
||||
/// `exclude` lets a renaming caller skip its own current name so a document can rename back to its
|
||||
/// existing slot rather than colliding with itself and getting bumped to the next number.
|
||||
pub fn generate_new_document_name(&self, exclude: Option<DocumentId>) -> String {
|
||||
pub fn generate_new_document_name(&self) -> String {
|
||||
let mut doc_title_numbers = self
|
||||
.document_ids
|
||||
.iter()
|
||||
.filter(|id| exclude != Some(**id))
|
||||
.filter_map(|id| self.document_details(*id))
|
||||
.filter_map(|doc| {
|
||||
doc.name
|
||||
@@ -1877,31 +1868,22 @@ impl PortfolioMessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the full path from the root network to the selected node that should drive the Data panel.
|
||||
/// The last element is the node itself; preceding elements identify the nested subnetwork it lives in
|
||||
/// so the Data panel can introspect nodes inside subgraphs. An empty `Vec` signals "nothing to inspect".
|
||||
pub fn node_to_inspect(&self) -> Vec<NodeId> {
|
||||
/// Get the ID of the selected node that should be used as the current source for the Data panel.
|
||||
pub fn node_to_inspect(&self) -> Option<NodeId> {
|
||||
// Skip if the Data panel is not open
|
||||
if !self.workspace_panel_layout.is_panel_visible(PanelType::Data) || self.workspace_panel_layout.focus_document {
|
||||
return Vec::new();
|
||||
return None;
|
||||
}
|
||||
|
||||
let Some(document) = self.active_document_id.and_then(|id| self.document(id)) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let network_path = document.selection_network_path();
|
||||
let Some(selected_nodes) = document.network_interface.selected_nodes_in_nested_network(network_path) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let document = self.document(self.active_document_id?)?;
|
||||
let selected_nodes = document.network_interface.selected_nodes().0;
|
||||
|
||||
// Skip if there is not exactly one selected node
|
||||
let [node_id] = selected_nodes.0.as_slice() else {
|
||||
return Vec::new();
|
||||
};
|
||||
if selected_nodes.len() != 1 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut path = network_path.to_vec();
|
||||
path.push(*node_id);
|
||||
path
|
||||
selected_nodes.first().copied()
|
||||
}
|
||||
|
||||
/// Remove a dockable panel type from whichever panel group currently contains it. Does not prune empty groups.
|
||||
@@ -1934,7 +1916,6 @@ impl PortfolioMessageHandler {
|
||||
} else {
|
||||
// Panel is not present, restore it to its default position in the layout tree
|
||||
self.workspace_panel_layout.restore_panel(panel_type);
|
||||
self.workspace_panel_layout.prune();
|
||||
self.refresh_panel_content(panel_type, responses);
|
||||
}
|
||||
|
||||
@@ -1975,12 +1956,7 @@ impl PortfolioMessageHandler {
|
||||
PanelType::Data => {
|
||||
// The Data panel's content is populated automatically as a side effect of the graph run completing, so there's nothing to do here
|
||||
}
|
||||
PanelType::Document | PanelType::Welcome => {
|
||||
// Re-send the welcome screen buttons layout to repopulate after a remount
|
||||
if self.document_ids.is_empty() {
|
||||
responses.add(PortfolioMessage::RequestWelcomeScreenButtonsLayout);
|
||||
}
|
||||
}
|
||||
PanelType::Document | PanelType::Welcome => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,6 @@ use graphene_std::Color;
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::text::{Font, FontCache};
|
||||
|
||||
/// Proportional share (0-1) for the document panel's side when splitting adjacent to non-document panels.
|
||||
const DOCUMENT_PANEL_SHARE: f64 = 0.8;
|
||||
/// Proportional share for each side when neither (or both) contain the document panel.
|
||||
const EQUAL_PANEL_SHARE: f64 = 0.5;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct CachedData {
|
||||
pub font_cache: FontCache,
|
||||
@@ -34,7 +29,6 @@ impl FontCatalog {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct FontCatalogFamily {
|
||||
/// The font family name.
|
||||
@@ -56,7 +50,6 @@ impl FontCatalogFamily {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct FontCatalogStyle {
|
||||
pub weight: u32,
|
||||
@@ -90,7 +83,7 @@ impl FontCatalogStyle {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum PanelType {
|
||||
Welcome,
|
||||
@@ -126,7 +119,7 @@ impl PanelType {
|
||||
pub struct PanelGroupId(pub u64);
|
||||
|
||||
/// Which edge of a panel group to split on when docking a dragged panel.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum DockingSplitDirection {
|
||||
Left,
|
||||
@@ -183,21 +176,6 @@ pub struct SplitChild {
|
||||
pub size: f64,
|
||||
}
|
||||
|
||||
/// Remembers where a panel was before it was removed, so it can be restored to the same location.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
struct SavedPanelPosition {
|
||||
panel_type: PanelType,
|
||||
/// The group the panel was a tab in.
|
||||
group_id: PanelGroupId,
|
||||
/// Which tab index it occupied within that group.
|
||||
tab_index: usize,
|
||||
/// The group's slot size at the time of removal (used to restore its visual weight via the sibling fallback).
|
||||
slot_size: Option<f64>,
|
||||
/// When the panel was the sole tab (so the group will be pruned), a neighboring group and
|
||||
/// whether to insert before it (`true`) or after it (`false`) to recreate the original position.
|
||||
sibling_fallback: Option<(PanelGroupId, bool)>,
|
||||
}
|
||||
|
||||
/// The complete workspace panel layout as a tree of nested rows and columns.
|
||||
/// The root subdivision is always a row (horizontal split). Direction alternates at each depth.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -208,9 +186,9 @@ pub struct WorkspacePanelLayout {
|
||||
/// Counter for generating unique panel group IDs.
|
||||
#[serde(default)]
|
||||
next_group_id: PanelGroupId,
|
||||
/// Remembers where each panel was before removal so it can be restored there.
|
||||
/// Remembers where a panel was before being removed (panel type, group ID, and tab index), so it can be restored there.
|
||||
#[serde(default)]
|
||||
saved_positions: Vec<SavedPanelPosition>,
|
||||
saved_positions: Vec<(PanelType, PanelGroupId, usize)>,
|
||||
/// Whether Focus Document mode is active, hiding all non-document panels.
|
||||
#[serde(default)]
|
||||
pub focus_document: bool,
|
||||
@@ -266,119 +244,54 @@ impl WorkspacePanelLayout {
|
||||
/// The direction determines where the new group goes relative to the target.
|
||||
/// Left/Right creates a horizontal (row) split, Top/Bottom creates a vertical (column) split.
|
||||
/// Returns the ID of the newly created panel group, or `None` if insertion failed.
|
||||
///
|
||||
/// `source_slot_size` overrides the new panel's size (for moves where the old slot will be pruned).
|
||||
/// If `None`, target's slot is split in the default ratio.
|
||||
pub fn split_panel_group(
|
||||
&mut self,
|
||||
target_group_id: PanelGroupId,
|
||||
direction: DockingSplitDirection,
|
||||
tabs: Vec<PanelType>,
|
||||
active_tab_index: usize,
|
||||
source_slot_size: Option<f64>,
|
||||
) -> Option<PanelGroupId> {
|
||||
pub fn split_panel_group(&mut self, target_group_id: PanelGroupId, direction: DockingSplitDirection, tabs: Vec<PanelType>, active_tab_index: usize) -> Option<PanelGroupId> {
|
||||
let new_id = self.next_id();
|
||||
let new_group = SplitChild {
|
||||
subdivision: PanelLayoutSubdivision::PanelGroup {
|
||||
id: new_id,
|
||||
state: PanelGroupState { tabs, active_tab_index },
|
||||
},
|
||||
size: source_slot_size.unwrap_or(EQUAL_PANEL_SHARE),
|
||||
size: 50.,
|
||||
};
|
||||
|
||||
let insert_before = matches!(direction, DockingSplitDirection::Left | DockingSplitDirection::Top);
|
||||
let needs_horizontal = matches!(direction, DockingSplitDirection::Left | DockingSplitDirection::Right);
|
||||
|
||||
self.root
|
||||
.insert_split_adjacent(target_group_id, new_group, insert_before, needs_horizontal, 0, source_slot_size)
|
||||
.then_some(new_id)
|
||||
}
|
||||
|
||||
/// Find the slot size of the panel group whose entire content is exactly the given tabs.
|
||||
/// Returns `None` if the tabs span multiple groups or don't fill their group exactly.
|
||||
pub fn find_source_slot_size(&self, tabs: &[PanelType]) -> Option<f64> {
|
||||
if tabs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let group_id = self.find_panel(tabs[0])?;
|
||||
if !tabs.iter().all(|&t| self.find_panel(t) == Some(group_id)) {
|
||||
return None;
|
||||
}
|
||||
let group = self.panel_group(group_id)?;
|
||||
if group.tabs.len() != tabs.len() {
|
||||
return None;
|
||||
}
|
||||
self.root.find_slot_size_by_group_id(group_id)
|
||||
self.root.insert_split_adjacent(target_group_id, new_group, insert_before, needs_horizontal, 0).then_some(new_id)
|
||||
}
|
||||
|
||||
/// Recalculate the default sizes for all splits in the tree based on document panel proximity.
|
||||
pub fn recalculate_default_sizes(&mut self) {
|
||||
self.root.recalculate_default_sizes_recursive();
|
||||
self.root.recalculate_default_sizes();
|
||||
}
|
||||
|
||||
/// Remember where a panel was before removal so it can be restored there later.
|
||||
/// Saves the group ID and tab index. If the panel is the sole tab (so the group will be pruned),
|
||||
/// also saves a sibling group as a fallback for adjacency-based restoration.
|
||||
/// Remember which panel group and tab index a panel was in before removal, so it can be restored there later.
|
||||
pub fn save_panel_position(&mut self, panel_type: PanelType) {
|
||||
let Some(group_id) = self.find_panel(panel_type) else { return };
|
||||
let tab_index = self.panel_group(group_id).and_then(|g| g.tabs.iter().position(|&t| t == panel_type)).unwrap_or(0);
|
||||
let is_sole_tab = self.panel_group(group_id).is_some_and(|g| g.tabs.len() == 1);
|
||||
if let Some(group_id) = self.find_panel(panel_type) {
|
||||
let tab_index = self.panel_group(group_id).and_then(|g| g.tabs.iter().position(|&t| t == panel_type)).unwrap_or(0);
|
||||
|
||||
// When it's the sole tab, the group will be pruned, so save a sibling and slot size as fallback
|
||||
let sibling_fallback = if is_sole_tab { self.root.find_sibling_group(group_id) } else { None };
|
||||
let slot_size = if is_sole_tab { self.root.find_slot_size_by_group_id(group_id) } else { None };
|
||||
|
||||
self.saved_positions.retain(|s| s.panel_type != panel_type);
|
||||
self.saved_positions.push(SavedPanelPosition {
|
||||
panel_type,
|
||||
group_id,
|
||||
tab_index,
|
||||
slot_size,
|
||||
sibling_fallback,
|
||||
});
|
||||
// Replace any existing saved position for this panel type
|
||||
self.saved_positions.retain(|(pt, _, _)| *pt != panel_type);
|
||||
self.saved_positions.push((panel_type, group_id, tab_index));
|
||||
}
|
||||
}
|
||||
|
||||
/// Restore a panel to its previous position if available, otherwise to its default position.
|
||||
/// If the panel was previously in a group that still exists, it's added back as a tab at its original index.
|
||||
/// Otherwise, it's placed at its default structural position in the tree.
|
||||
pub fn restore_panel(&mut self, panel_type: PanelType) {
|
||||
let saved = self.saved_positions.iter().find(|s| s.panel_type == panel_type).copied();
|
||||
self.saved_positions.retain(|s| s.panel_type != panel_type);
|
||||
|
||||
let Some(saved) = saved else {
|
||||
self.restore_panel_to_default_position(panel_type);
|
||||
return;
|
||||
};
|
||||
|
||||
// Primary: restore as a tab in the original group if it still exists
|
||||
if let Some(group) = self.panel_group_mut(saved.group_id) {
|
||||
let insert_index = saved.tab_index.min(group.tabs.len());
|
||||
// Try to restore to the previously saved group and tab position
|
||||
let saved = self.saved_positions.iter().find(|(pt, _, _)| *pt == panel_type).copied();
|
||||
if let Some((_, saved_group_id, saved_tab_index)) = saved
|
||||
&& let Some(group) = self.panel_group_mut(saved_group_id)
|
||||
{
|
||||
let insert_index = saved_tab_index.min(group.tabs.len());
|
||||
group.tabs.insert(insert_index, panel_type);
|
||||
group.active_tab_index = insert_index;
|
||||
self.saved_positions.retain(|(pt, _, _)| *pt != panel_type);
|
||||
return;
|
||||
}
|
||||
|
||||
// Fallback: the original group was pruned, but a sibling in the same parent split survives
|
||||
if let Some((sibling_id, before_sibling)) = saved.sibling_fallback
|
||||
&& self.root.contains_group(sibling_id)
|
||||
{
|
||||
let new_id = self.next_id();
|
||||
let new_subdivision = PanelLayoutSubdivision::PanelGroup {
|
||||
id: new_id,
|
||||
state: PanelGroupState {
|
||||
tabs: vec![panel_type],
|
||||
active_tab_index: 0,
|
||||
},
|
||||
};
|
||||
|
||||
let new_group = SplitChild {
|
||||
subdivision: new_subdivision,
|
||||
size: saved.slot_size.unwrap_or_else(|| {
|
||||
let sibling_contains_document = self.root.find_subtree_containing_group(sibling_id).is_some_and(|s| s.contains_document());
|
||||
if sibling_contains_document { 1. - DOCUMENT_PANEL_SHARE } else { EQUAL_PANEL_SHARE }
|
||||
}),
|
||||
};
|
||||
self.root.insert_adjacent_to_group(sibling_id, new_group, before_sibling);
|
||||
return;
|
||||
}
|
||||
self.saved_positions.retain(|(pt, _, _)| *pt != panel_type);
|
||||
|
||||
self.restore_panel_to_default_position(panel_type);
|
||||
}
|
||||
@@ -397,7 +310,12 @@ impl WorkspacePanelLayout {
|
||||
active_tab_index: 0,
|
||||
},
|
||||
},
|
||||
size: EQUAL_PANEL_SHARE,
|
||||
size: match panel_type {
|
||||
PanelType::Data => 30.,
|
||||
PanelType::Properties => 45.,
|
||||
PanelType::Layers => 55.,
|
||||
_ => 50.,
|
||||
},
|
||||
};
|
||||
|
||||
// Determine which root child column to insert into and at which position
|
||||
@@ -412,10 +330,7 @@ impl WorkspacePanelLayout {
|
||||
if !matches!(&self.root, PanelLayoutSubdivision::Split { .. }) {
|
||||
let old_root = std::mem::replace(&mut self.root, PanelLayoutSubdivision::Split { children: vec![] });
|
||||
if let PanelLayoutSubdivision::Split { children } = &mut self.root {
|
||||
children.push(SplitChild {
|
||||
subdivision: old_root,
|
||||
size: DOCUMENT_PANEL_SHARE,
|
||||
});
|
||||
children.push(SplitChild { subdivision: old_root, size: 80. });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -425,7 +340,7 @@ impl WorkspacePanelLayout {
|
||||
while root_children.len() <= root_child_index {
|
||||
root_children.push(SplitChild {
|
||||
subdivision: PanelLayoutSubdivision::Split { children: vec![] },
|
||||
size: (1. - DOCUMENT_PANEL_SHARE),
|
||||
size: 20.,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -436,7 +351,7 @@ impl WorkspacePanelLayout {
|
||||
if let PanelLayoutSubdivision::Split { children } = target {
|
||||
children.push(SplitChild {
|
||||
subdivision: old_subdivision,
|
||||
size: EQUAL_PANEL_SHARE,
|
||||
size: 50.,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -448,12 +363,6 @@ impl WorkspacePanelLayout {
|
||||
children.insert(0, new_group);
|
||||
}
|
||||
}
|
||||
|
||||
// Recalculate sizes within the target column to get the correct document-aware ratio
|
||||
let PanelLayoutSubdivision::Split { children: root_children } = &mut self.root else { return };
|
||||
if let Some(target) = root_children.get_mut(root_child_index) {
|
||||
target.subdivision.recalculate_default_sizes();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -477,10 +386,10 @@ impl Default for WorkspacePanelLayout {
|
||||
active_tab_index: 0,
|
||||
},
|
||||
},
|
||||
size: 1.,
|
||||
size: 100.,
|
||||
}],
|
||||
},
|
||||
size: DOCUMENT_PANEL_SHARE,
|
||||
size: 80.,
|
||||
},
|
||||
SplitChild {
|
||||
subdivision: PanelLayoutSubdivision::Split {
|
||||
@@ -493,7 +402,7 @@ impl Default for WorkspacePanelLayout {
|
||||
active_tab_index: 0,
|
||||
},
|
||||
},
|
||||
size: EQUAL_PANEL_SHARE,
|
||||
size: 50.,
|
||||
},
|
||||
SplitChild {
|
||||
subdivision: PanelLayoutSubdivision::PanelGroup {
|
||||
@@ -503,11 +412,11 @@ impl Default for WorkspacePanelLayout {
|
||||
active_tab_index: 0,
|
||||
},
|
||||
},
|
||||
size: EQUAL_PANEL_SHARE,
|
||||
size: 50.,
|
||||
},
|
||||
],
|
||||
},
|
||||
size: (1. - DOCUMENT_PANEL_SHARE),
|
||||
size: 20.,
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -518,15 +427,6 @@ impl Default for WorkspacePanelLayout {
|
||||
}
|
||||
}
|
||||
|
||||
/// The share of the slot that should go to the old side when splitting it with a new side.
|
||||
fn document_split_share(old_side: &PanelLayoutSubdivision, new_side: &PanelLayoutSubdivision) -> f64 {
|
||||
match (old_side.contains_document(), new_side.contains_document()) {
|
||||
(true, false) => DOCUMENT_PANEL_SHARE,
|
||||
(false, true) => 1. - DOCUMENT_PANEL_SHARE,
|
||||
_ => EQUAL_PANEL_SHARE,
|
||||
}
|
||||
}
|
||||
|
||||
impl PanelLayoutSubdivision {
|
||||
/// Find the panel group state for a given ID.
|
||||
pub fn find_group(&self, target_id: PanelGroupId) -> Option<&PanelGroupState> {
|
||||
@@ -563,10 +463,9 @@ impl PanelLayoutSubdivision {
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove empty groups/splits and flatten single-child `Split`-in-`Split` nesting (which docking sequences can create).
|
||||
///
|
||||
/// Flattening preserves depth parity (and therefore direction). `PanelGroup`-only single-child splits are left
|
||||
/// alone since collapsing would change the panel's depth and alter future wrap orientation.
|
||||
/// Remove empty panel groups and collapse unnecessary nesting.
|
||||
/// Does NOT collapse single-child splits into their child, as that would change subdivision depths
|
||||
/// and break the direction-by-depth alternation system.
|
||||
pub fn prune(&mut self) {
|
||||
let PanelLayoutSubdivision::Split { children } = self else { return };
|
||||
|
||||
@@ -578,54 +477,6 @@ impl PanelLayoutSubdivision {
|
||||
|
||||
// Remove empty splits (splits that lost all their children after pruning)
|
||||
children.retain(|child| !matches!(&child.subdivision, PanelLayoutSubdivision::Split { children } if children.is_empty()));
|
||||
|
||||
// Flatten single-child `Split`-in-`Split` nesting, rescaling sizes to preserve visual proportions
|
||||
let mut i = 0;
|
||||
while i < children.len() {
|
||||
// Must be a `Split`...
|
||||
let PanelLayoutSubdivision::Split { children: outer } = &children[i].subdivision else {
|
||||
i += 1;
|
||||
continue;
|
||||
};
|
||||
// ...with exactly one child...
|
||||
let [only_child] = outer.as_slice() else {
|
||||
i += 1;
|
||||
continue;
|
||||
};
|
||||
// ...that is itself a `Split`
|
||||
let PanelLayoutSubdivision::Split { .. } = &only_child.subdivision else {
|
||||
i += 1;
|
||||
continue;
|
||||
};
|
||||
|
||||
// Remove the redundant wrapper
|
||||
let removed = children.remove(i);
|
||||
let outer_size = removed.size;
|
||||
|
||||
// Extract the inner grandchildren
|
||||
let PanelLayoutSubdivision::Split { children: mut outer_children } = removed.subdivision else {
|
||||
continue;
|
||||
};
|
||||
let Some(inner_split) = outer_children.pop() else { continue };
|
||||
let PanelLayoutSubdivision::Split { children: inner_children } = inner_split.subdivision else {
|
||||
continue;
|
||||
};
|
||||
|
||||
// Splice grandchildren in at the same position, scaling their sizes to fill the removed slot
|
||||
let inner_total: f64 = inner_children.iter().map(|c| c.size).sum();
|
||||
for (offset, mut grandchild) in inner_children.into_iter().enumerate() {
|
||||
grandchild.size = if inner_total > 0. { grandchild.size / inner_total * outer_size } else { outer_size };
|
||||
children.insert(i + offset, grandchild);
|
||||
}
|
||||
}
|
||||
|
||||
// Renormalize to sum=1 since dock/prune cycles can compound shrinkage
|
||||
let total: f64 = children.iter().map(|c| c.size).sum();
|
||||
if total > 0. && (total - 1.).abs() > 0.001 {
|
||||
for child in children.iter_mut() {
|
||||
child.size /= total;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove all non-document/non-welcome tabs from panel groups, leaving only document-related panels.
|
||||
@@ -641,80 +492,6 @@ impl PanelLayoutSubdivision {
|
||||
}
|
||||
}
|
||||
|
||||
/// Find the nearest sibling panel group for the given group within the same parent split.
|
||||
/// Returns the sibling's ID and whether the target was before it (`true`) or after it (`false`).
|
||||
/// Prefers the immediately previous sibling (with before=false meaning "insert after it"), falling
|
||||
/// back to the next sibling (with before=true) so all positions in a 3-child split are distinguishable.
|
||||
pub fn find_sibling_group(&self, target_id: PanelGroupId) -> Option<(PanelGroupId, bool)> {
|
||||
let PanelLayoutSubdivision::Split { children } = self else { return None };
|
||||
|
||||
let target_index = children
|
||||
.iter()
|
||||
.position(|child| matches!(&child.subdivision, PanelLayoutSubdivision::PanelGroup { id, .. } if *id == target_id));
|
||||
|
||||
if let Some(index) = target_index {
|
||||
let previous = (0..index).rev().find_map(|i| Self::group_id_of(&children[i]).map(|id| (id, false)));
|
||||
let next = ((index + 1)..children.len()).find_map(|i| Self::group_id_of(&children[i]).map(|id| (id, true)));
|
||||
return previous.or(next);
|
||||
}
|
||||
|
||||
children.iter().find_map(|child| child.subdivision.find_sibling_group(target_id))
|
||||
}
|
||||
|
||||
/// Get a panel group ID from a child, either directly or the first one in a subtree.
|
||||
fn group_id_of(child: &SplitChild) -> Option<PanelGroupId> {
|
||||
match &child.subdivision {
|
||||
PanelLayoutSubdivision::PanelGroup { id, .. } => Some(*id),
|
||||
sub => sub.first_group_id(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the first panel group ID found in this subtree.
|
||||
fn first_group_id(&self) -> Option<PanelGroupId> {
|
||||
match self {
|
||||
PanelLayoutSubdivision::PanelGroup { id, .. } => Some(*id),
|
||||
PanelLayoutSubdivision::Split { children } => children.iter().find_map(|child| child.subdivision.first_group_id()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Insert a new split child immediately before or after the given group in its parent split,
|
||||
/// scaling existing siblings down proportionally to make room for the new child's size.
|
||||
/// Returns whether the insertion was performed.
|
||||
pub fn insert_adjacent_to_group(&mut self, sibling_id: PanelGroupId, new_child: SplitChild, before_sibling: bool) -> bool {
|
||||
let PanelLayoutSubdivision::Split { children } = self else { return false };
|
||||
|
||||
let sibling_index = children
|
||||
.iter()
|
||||
.position(|child| matches!(&child.subdivision, PanelLayoutSubdivision::PanelGroup { id, .. } if *id == sibling_id));
|
||||
if let Some(index) = sibling_index {
|
||||
// Shrink existing siblings proportionally to make room
|
||||
let old_total: f64 = children.iter().map(|c| c.size).sum();
|
||||
let scale = if old_total > 0. { (old_total - new_child.size).max(0.) / old_total } else { 1. };
|
||||
for child in children.iter_mut() {
|
||||
child.size *= scale;
|
||||
}
|
||||
|
||||
let insert_at = if before_sibling { index } else { index + 1 };
|
||||
children.insert(insert_at, new_child);
|
||||
return true;
|
||||
}
|
||||
|
||||
children
|
||||
.iter_mut()
|
||||
.any(|child| child.subdivision.insert_adjacent_to_group(sibling_id, new_child.clone(), before_sibling))
|
||||
}
|
||||
|
||||
/// Find the `SplitChild` subtree that contains the panel group with the given ID.
|
||||
pub fn find_subtree_containing_group(&self, target_id: PanelGroupId) -> Option<&PanelLayoutSubdivision> {
|
||||
let PanelLayoutSubdivision::Split { children } = self else { return None };
|
||||
for child in children {
|
||||
if child.subdivision.contains_group(target_id) {
|
||||
return Some(&child.subdivision);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Check if this subtree contains a panel group with the given ID.
|
||||
pub fn contains_group(&self, target_id: PanelGroupId) -> bool {
|
||||
match self {
|
||||
@@ -726,9 +503,7 @@ impl PanelLayoutSubdivision {
|
||||
/// Inserts a new split child adjacent to a target panel group and returns whether the insertion was successful.
|
||||
/// Recurses to the deepest split closest to the target that matches the requested split direction.
|
||||
/// If the target is a direct child of a mismatched-direction split, this wraps it in a new sub-split.
|
||||
///
|
||||
/// `source_slot_size` preserves the moved panel's visual weight. If `None`, uses the default split ratio.
|
||||
pub fn insert_split_adjacent(&mut self, target_id: PanelGroupId, new_child: SplitChild, insert_before: bool, needs_horizontal: bool, depth: usize, source_slot_size: Option<f64>) -> bool {
|
||||
pub fn insert_split_adjacent(&mut self, target_id: PanelGroupId, new_child: SplitChild, insert_before: bool, needs_horizontal: bool, depth: usize) -> bool {
|
||||
let PanelLayoutSubdivision::Split { children } = self else { return false };
|
||||
|
||||
let is_horizontal = depth.is_multiple_of(2);
|
||||
@@ -742,35 +517,18 @@ impl PanelLayoutSubdivision {
|
||||
// If the target is a direct child: we can certainly insert the new split, either as a sibling (if direction matches) or wrapping the target in a new split (if direction is mismatched)
|
||||
let target_is_direct_child = matches!(&children[containing_index].subdivision, PanelLayoutSubdivision::PanelGroup { id, .. } if *id == target_id);
|
||||
if target_is_direct_child {
|
||||
// Direction matches: insert as sibling, sizing based on whether target will be pruned, source size hint, or default ratio
|
||||
// Direction matches and target is right here: insert as a sibling
|
||||
if direction_matches {
|
||||
let mut new_child = new_child;
|
||||
let target_will_be_pruned = matches!(&children[containing_index].subdivision, PanelLayoutSubdivision::PanelGroup { state, .. } if state.tabs.is_empty());
|
||||
if target_will_be_pruned {
|
||||
new_child.size = children[containing_index].size;
|
||||
} else if let Some(hint) = source_slot_size {
|
||||
new_child.size = hint;
|
||||
} else {
|
||||
let target_share = document_split_share(&children[containing_index].subdivision, &new_child.subdivision);
|
||||
let total = children[containing_index].size;
|
||||
children[containing_index].size = total * target_share;
|
||||
new_child.size = total * (1. - target_share);
|
||||
}
|
||||
|
||||
let insert_index = if insert_before { containing_index } else { containing_index + 1 };
|
||||
children.insert(insert_index, new_child);
|
||||
}
|
||||
// Direction mismatch: wrap target in a sub-split at depth+1, sharing the slot in the default ratio
|
||||
// Direction mismatch: wrap the target in a new sub-split (at depth+1, which has the opposite direction of this and thus is the requested direction)
|
||||
else {
|
||||
let old_child_subdivision = std::mem::replace(&mut children[containing_index].subdivision, PanelLayoutSubdivision::Split { children: vec![] });
|
||||
|
||||
let old_share = document_split_share(&old_child_subdivision, &new_child.subdivision);
|
||||
let old_child = SplitChild {
|
||||
subdivision: old_child_subdivision,
|
||||
size: old_share,
|
||||
size: 50.,
|
||||
};
|
||||
let mut new_child = new_child;
|
||||
new_child.size = 1. - old_share;
|
||||
|
||||
if let PanelLayoutSubdivision::Split { children: sub_children } = &mut children[containing_index].subdivision {
|
||||
if insert_before {
|
||||
@@ -789,25 +547,7 @@ impl PanelLayoutSubdivision {
|
||||
// The target is deeper, so recurse into the containing child's subtree and return its insertion outcome
|
||||
children[containing_index]
|
||||
.subdivision
|
||||
.insert_split_adjacent(target_id, new_child.clone(), insert_before, needs_horizontal, depth + 1, source_slot_size)
|
||||
}
|
||||
|
||||
/// Find the size of the `SplitChild` slot whose subdivision is the panel group with the given ID, if it exists.
|
||||
pub fn find_slot_size_by_group_id(&self, group_id: PanelGroupId) -> Option<f64> {
|
||||
let PanelLayoutSubdivision::Split { children } = self else { return None };
|
||||
for child in children {
|
||||
if let PanelLayoutSubdivision::PanelGroup { id, .. } = &child.subdivision
|
||||
&& *id == group_id
|
||||
{
|
||||
return Some(child.size);
|
||||
}
|
||||
}
|
||||
for child in children {
|
||||
if let Some(size) = child.subdivision.find_slot_size_by_group_id(group_id) {
|
||||
return Some(size);
|
||||
}
|
||||
}
|
||||
None
|
||||
.insert_split_adjacent(target_id, new_child.clone(), insert_before, needs_horizontal, depth + 1)
|
||||
}
|
||||
|
||||
/// Check if this subtree contains the document panel.
|
||||
@@ -818,46 +558,39 @@ impl PanelLayoutSubdivision {
|
||||
}
|
||||
}
|
||||
|
||||
/// Recalculate the default sizes for this subdivision's direct children based on proximity to the document panel.
|
||||
/// Recalculate the default sizes for this subdivision's children based on proximity to the document panel.
|
||||
/// Splits directly surrounding the document panel use 80-20 weighting.
|
||||
/// All other splits use equal division.
|
||||
/// Does not recurse into descendants: use [`Self::recalculate_default_sizes_recursive`] for that.
|
||||
pub fn recalculate_default_sizes(&mut self) {
|
||||
let PanelLayoutSubdivision::Split { children } = self else { return };
|
||||
|
||||
let child_count = children.len();
|
||||
if child_count == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if any child directly contains (or is) the document panel
|
||||
let document_child_index = children.iter().position(|child| child.subdivision.contains_document());
|
||||
|
||||
if let Some(document_index) = document_child_index {
|
||||
// This split directly surrounds the document panel
|
||||
let non_document_count = child_count - 1;
|
||||
let document_share = if non_document_count > 0 { DOCUMENT_PANEL_SHARE } else { 1. };
|
||||
let other_share = if non_document_count > 0 { (1. - DOCUMENT_PANEL_SHARE) / non_document_count as f64 } else { 0. };
|
||||
|
||||
for (i, child) in children.iter_mut().enumerate() {
|
||||
child.size = if i == document_index { document_share } else { other_share };
|
||||
}
|
||||
} else {
|
||||
// This split doesn't directly contain the document, use equal division
|
||||
let equal_share = 1. / child_count as f64;
|
||||
for child in children.iter_mut() {
|
||||
child.size = equal_share;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Recalculate the default sizes for this subdivision and all its descendant splits.
|
||||
pub fn recalculate_default_sizes_recursive(&mut self) {
|
||||
self.recalculate_default_sizes();
|
||||
|
||||
if let PanelLayoutSubdivision::Split { children } = self {
|
||||
let child_count = children.len();
|
||||
if child_count == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if any child directly contains (or is) the document panel
|
||||
let document_child_index = children.iter().position(|child| child.subdivision.contains_document());
|
||||
|
||||
if let Some(document_index) = document_child_index {
|
||||
// This split directly surrounds the document panel, so use 80-20 weighting
|
||||
let non_document_count = child_count - 1;
|
||||
let document_share = if non_document_count > 0 { 80. } else { 100. };
|
||||
let other_share = if non_document_count > 0 { 20. / non_document_count as f64 } else { 0. };
|
||||
|
||||
for (i, child) in children.iter_mut().enumerate() {
|
||||
child.size = if i == document_index { document_share } else { other_share };
|
||||
}
|
||||
} else {
|
||||
// This split doesn't directly contain the document, use equal division
|
||||
let equal_share = 100. / child_count as f64;
|
||||
for child in children.iter_mut() {
|
||||
child.size = equal_share;
|
||||
}
|
||||
}
|
||||
|
||||
// Recurse into children
|
||||
for child in children.iter_mut() {
|
||||
child.subdivision.recalculate_default_sizes_recursive();
|
||||
child.subdivision.recalculate_default_sizes();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ pub use crate::messages::app_window::{AppWindowMessage, AppWindowMessageDiscrimi
|
||||
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::color_picker::{ColorPickerMessage, ColorPickerMessageDiscriminant, ColorPickerMessageHandler};
|
||||
pub use crate::messages::debug::{DebugMessage, DebugMessageDiscriminant, DebugMessageHandler};
|
||||
pub use crate::messages::defer::{DeferMessage, DeferMessageDiscriminant, DeferMessageHandler};
|
||||
pub use crate::messages::dialog::export_dialog::{ExportDialogMessage, ExportDialogMessageContext, ExportDialogMessageDiscriminant, ExportDialogMessageHandler};
|
||||
|
||||
@@ -1,76 +1,74 @@
|
||||
use crate::consts::DEFAULT_STROKE_WIDTH;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::TransactionStatus;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::utility_types::DocumentToolData;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::vector::style::{FillChoice, FillChoiceUI, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ToolColorType {
|
||||
Primary,
|
||||
Secondary,
|
||||
Custom,
|
||||
}
|
||||
|
||||
/// Color selector widgets seen in [`LayoutTarget::ToolOptions`] bar.
|
||||
pub struct ToolColorOptions {
|
||||
/// The fill/stroke value shown in the swatch. `None` = mixed across selected layers.
|
||||
pub fill_choice: Option<FillChoice>,
|
||||
/// The checkbox state. `None` = mixed across selected layers.
|
||||
pub enabled: Option<bool>,
|
||||
/// When set, `fill_choice` is a working-color fallback (vs. a layer-derived saved color) and is refreshed live by `WorkingColorChanged`.
|
||||
pub tracks_working_color: bool,
|
||||
pub custom_color: Option<Color>,
|
||||
pub primary_working_color: Option<Color>,
|
||||
pub secondary_working_color: Option<Color>,
|
||||
pub color_type: ToolColorType,
|
||||
}
|
||||
|
||||
impl Default for ToolColorOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
fill_choice: Some(FillChoice::Solid(Color::BLACK)),
|
||||
enabled: Some(true),
|
||||
tracks_working_color: true,
|
||||
color_type: ToolColorType::Primary,
|
||||
custom_color: Some(Color::BLACK),
|
||||
primary_working_color: Some(Color::BLACK),
|
||||
secondary_working_color: Some(Color::WHITE),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolColorOptions {
|
||||
pub fn new_enabled() -> Self {
|
||||
pub fn new_primary() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn new_disabled() -> Self {
|
||||
pub fn new_secondary() -> Self {
|
||||
Self {
|
||||
fill_choice: Some(FillChoice::None),
|
||||
enabled: Some(false),
|
||||
tracks_working_color: true,
|
||||
color_type: ToolColorType::Secondary,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// True when the slot is actively applied, i.e. `enabled` is `Some(true)`.
|
||||
/// `None` (mixed) and `Some(false)` both count as not actively applied.
|
||||
pub fn is_active(&self) -> bool {
|
||||
self.enabled == Some(true)
|
||||
pub fn new_none() -> Self {
|
||||
Self {
|
||||
color_type: ToolColorType::Custom,
|
||||
custom_color: None,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The active solid color, suitable for storing in a working color or downstream rendering input.
|
||||
pub fn active_color(&self) -> Option<Color> {
|
||||
if !self.is_active() {
|
||||
return None;
|
||||
match self.color_type {
|
||||
ToolColorType::Custom => self.custom_color,
|
||||
ToolColorType::Primary => self.primary_working_color,
|
||||
ToolColorType::Secondary => self.secondary_working_color,
|
||||
}
|
||||
self.fill_choice.as_ref()?.as_solid()
|
||||
}
|
||||
|
||||
pub fn apply_fill(&self, layer: LayerNodeIdentifier, responses: &mut VecDeque<Message>) {
|
||||
if !self.is_active() {
|
||||
return;
|
||||
}
|
||||
if let Some(FillChoice::Solid(color)) = &self.fill_choice {
|
||||
let fill = graphene_std::vector::style::Fill::Solid(*color);
|
||||
if let Some(color) = self.active_color() {
|
||||
let fill = graphene_std::vector::style::Fill::solid(color.to_gamma_srgb());
|
||||
responses.add(GraphOperationMessage::FillSet { layer, fill });
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_stroke(&self, weight: f64, layer: LayerNodeIdentifier, responses: &mut VecDeque<Message>) {
|
||||
if !self.is_active() {
|
||||
return;
|
||||
}
|
||||
if let Some(FillChoice::Solid(color)) = &self.fill_choice {
|
||||
let stroke = graphene_std::vector::style::Stroke::new(Some(*color), weight);
|
||||
if let Some(color) = self.active_color() {
|
||||
let stroke = graphene_std::vector::style::Stroke::new(Some(color.to_gamma_srgb()), weight);
|
||||
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
|
||||
}
|
||||
}
|
||||
@@ -78,523 +76,49 @@ impl ToolColorOptions {
|
||||
pub fn create_widgets(
|
||||
&self,
|
||||
label_text: impl Into<String>,
|
||||
checkbox_callback: impl Fn(&CheckboxInput) -> Message + 'static + Send + Sync,
|
||||
color_allow_none: bool,
|
||||
reset_callback: impl Fn(&IconButton) -> Message + 'static + Send + Sync,
|
||||
radio_callback: fn(ToolColorType) -> WidgetCallback<()>,
|
||||
color_callback: impl Fn(&ColorInput) -> Message + 'static + Send + Sync,
|
||||
) -> Vec<WidgetInstance> {
|
||||
let checkbox_id = CheckboxId::new();
|
||||
// In the mixed state (`fill_choice` is `None`) the dash overlay covers the swatch, so the underlying widget value just drives the picker's initial position.
|
||||
// `FillChoice::None` gives it a neutral starting point.
|
||||
let mixed_color = self.fill_choice.is_none();
|
||||
// Convert the internal linear-light `FillChoice` to the JS-boundary `FillChoiceUI` (with `SRGBA8` colors) for the widget value.
|
||||
let widget_value = FillChoiceUI::from(self.fill_choice.as_ref().unwrap_or(&FillChoice::None));
|
||||
let mixed_enabled = self.enabled.is_none();
|
||||
// In the mixed-enabled state the underlying `checked` value is hidden behind the indeterminate dash.
|
||||
// The frontend's click handler sends `true` when the user resolves the mixed state by clicking.
|
||||
let checked = self.enabled.unwrap_or(false);
|
||||
let mut widgets = vec![TextLabel::new(label_text).widget_instance()];
|
||||
|
||||
vec![
|
||||
CheckboxInput::new(checked).mixed(mixed_enabled).on_update(checkbox_callback).for_label(checkbox_id).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
TextLabel::new(label_text).for_checkbox(checkbox_id).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
ColorInput::new(widget_value)
|
||||
.mixed(mixed_color)
|
||||
.min_width(48)
|
||||
.max_width(48)
|
||||
.narrow(true)
|
||||
.on_update(color_callback)
|
||||
.widget_instance(),
|
||||
if !color_allow_none {
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
} else {
|
||||
let reset = IconButton::new("CloseX", 12)
|
||||
.disabled(self.custom_color.is_none() && self.color_type == ToolColorType::Custom)
|
||||
.tooltip_label("Clear Color")
|
||||
.on_update(reset_callback);
|
||||
|
||||
widgets.push(Separator::new(SeparatorStyle::Related).widget_instance());
|
||||
widgets.push(reset.widget_instance());
|
||||
widgets.push(Separator::new(SeparatorStyle::Related).widget_instance());
|
||||
};
|
||||
|
||||
let entries = vec![
|
||||
("WorkingColorsPrimary", "Primary Working Color", ToolColorType::Primary),
|
||||
("WorkingColorsSecondary", "Secondary Working Color", ToolColorType::Secondary),
|
||||
("CustomColor", "Custom Color", ToolColorType::Custom),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared per-tool state for drawing tools that produce a stroked-and-filled shape (Shape, Pen, Freehand, Spline).
|
||||
pub struct DrawingToolState {
|
||||
/// The current stroke weight. `None` = mixed across selected layers.
|
||||
pub line_weight: Option<f64>,
|
||||
/// Persistent default weight, updated when the user edits the weight while no layer is selected.
|
||||
pub default_line_weight: f64,
|
||||
/// Stroke alignment from the selection. `None` = mixed.
|
||||
pub stroke_align: Option<StrokeAlign>,
|
||||
/// Stroke cap from the selection. `None` = mixed.
|
||||
pub stroke_cap: Option<StrokeCap>,
|
||||
/// Stroke join from the selection. `None` = mixed.
|
||||
pub stroke_join: Option<StrokeJoin>,
|
||||
/// Stroke miter limit from the selection. `None` = mixed.
|
||||
pub miter_limit: Option<f64>,
|
||||
/// Paint order from the selection. `None` = mixed.
|
||||
pub paint_order: Option<PaintOrder>,
|
||||
/// Dash lengths from the selection. `None` = mixed.
|
||||
pub dash_lengths: Option<Vec<f64>>,
|
||||
/// Dash offset from the selection. `None` = mixed.
|
||||
pub dash_offset: Option<f64>,
|
||||
/// Set of layers we last synced from, used to detect real selection changes vs. internal node toggles.
|
||||
pub last_synced_selection: Vec<LayerNodeIdentifier>,
|
||||
/// The fill swatch's color, checkbox, and mixed state.
|
||||
pub fill: ToolColorOptions,
|
||||
/// The stroke swatch's color, checkbox, and mixed state.
|
||||
pub stroke: ToolColorOptions,
|
||||
/// When false (default), fill follows the secondary working color and stroke follows the primary; when true, the routing is reversed.
|
||||
/// Persisted per-tool. The Shape tool additionally persists it for each shape mode via its options.
|
||||
pub colors_swapped: bool,
|
||||
}
|
||||
|
||||
impl DrawingToolState {
|
||||
pub fn new(fill_enabled: bool) -> Self {
|
||||
Self {
|
||||
line_weight: Some(DEFAULT_STROKE_WIDTH),
|
||||
default_line_weight: DEFAULT_STROKE_WIDTH,
|
||||
stroke_align: Some(StrokeAlign::default()),
|
||||
stroke_cap: Some(StrokeCap::default()),
|
||||
stroke_join: Some(StrokeJoin::default()),
|
||||
miter_limit: Some(4.),
|
||||
paint_order: Some(PaintOrder::default()),
|
||||
dash_lengths: Some(Vec::new()),
|
||||
dash_offset: Some(0.),
|
||||
last_synced_selection: Vec::new(),
|
||||
fill: if fill_enabled { ToolColorOptions::new_enabled() } else { ToolColorOptions::new_disabled() },
|
||||
stroke: ToolColorOptions::new_enabled(),
|
||||
colors_swapped: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The line weight to apply, falling back to the persistent default when [`Self::line_weight`] is `None` (mixed).
|
||||
pub fn effective_line_weight(&self) -> f64 {
|
||||
self.line_weight.unwrap_or(self.default_line_weight)
|
||||
}
|
||||
|
||||
/// Dash lengths to apply, falling back to empty when [`Self::dash_lengths`] is `None` (mixed).
|
||||
pub fn effective_dash_lengths(&self) -> Vec<f64> {
|
||||
self.dash_lengths.clone().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Applies a stroke to a freshly created `layer` using the tool's currently selected color, weight, and stroke options (align, cap, join, etc.).
|
||||
/// Used by the drawing tools at shape-creation time so new shapes inherit the popover's options instead of defaulting to the `Stroke` struct's defaults.
|
||||
pub fn apply_stroke_to_new_layer(&self, layer: LayerNodeIdentifier, responses: &mut VecDeque<Message>) {
|
||||
if !self.stroke.is_active() {
|
||||
return;
|
||||
}
|
||||
let Some(FillChoice::Solid(color)) = &self.stroke.fill_choice else { return };
|
||||
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(),
|
||||
join: self.stroke_join.unwrap_or_default(),
|
||||
join_miter_limit: self.miter_limit.unwrap_or(4.),
|
||||
paint_order: self.paint_order.unwrap_or_default(),
|
||||
dash_lengths: self.effective_dash_lengths(),
|
||||
dash_offset: self.dash_offset.unwrap_or(0.),
|
||||
transform: glam::DAffine2::IDENTITY,
|
||||
};
|
||||
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a `FillChoice::Solid` from a color.
|
||||
pub fn solid(color: Color) -> FillChoice {
|
||||
FillChoice::Solid(color)
|
||||
}
|
||||
|
||||
/// The fill working color (the source for the fill swatch when nothing is selected).
|
||||
/// Defaults to secondary, swapped to primary when the per-tool [`DrawingToolState::colors_swapped`] flag is set.
|
||||
pub fn fill_working_color(global: &DocumentToolData, colors_swapped: bool) -> Color {
|
||||
if colors_swapped { global.primary_color } else { global.secondary_color }
|
||||
}
|
||||
|
||||
/// The stroke working color (the source for the stroke swatch when nothing is selected).
|
||||
/// Defaults to primary, swapped to secondary when the per-tool [`DrawingToolState::colors_swapped`] flag is set.
|
||||
pub fn stroke_working_color(global: &DocumentToolData, colors_swapped: bool) -> Color {
|
||||
if colors_swapped { global.secondary_color } else { global.primary_color }
|
||||
}
|
||||
|
||||
/// Syncs fill and stroke from the selection (or working colors when empty). With `selection_changed = false`, preserves display values
|
||||
/// for inactive states instead of resetting them. Returns `true` if anything changed.
|
||||
pub fn sync_color_options(
|
||||
drawing: &mut DrawingToolState,
|
||||
natural_fill_enabled: bool,
|
||||
natural_stroke_enabled: bool,
|
||||
global: &DocumentToolData,
|
||||
document: &DocumentMessageHandler,
|
||||
selection_changed: bool,
|
||||
) -> bool {
|
||||
let fill_fallback = solid(fill_working_color(global, drawing.colors_swapped));
|
||||
let stroke_fallback = solid(stroke_working_color(global, drawing.colors_swapped));
|
||||
|
||||
let mut changed = false;
|
||||
|
||||
// FILL
|
||||
|
||||
let new_fill = if let Some(state) = graph_modification_utils::selected_fill_state(document) {
|
||||
let active = state.enabled == Some(true);
|
||||
let (display_choice, tracks_working) = match &state.fill_choice {
|
||||
Some(choice) if active => (Some(choice.clone()), false),
|
||||
Some(_) if selection_changed => (Some(fill_fallback.clone()), true),
|
||||
Some(_) => (drawing.fill.fill_choice.clone(), drawing.fill.tracks_working_color),
|
||||
None => (None, true),
|
||||
};
|
||||
(state.enabled, display_choice, tracks_working)
|
||||
} else {
|
||||
// On a real deselect, revert to the working color; otherwise preserve the displayed value.
|
||||
let display_choice = if selection_changed { Some(fill_fallback) } else { drawing.fill.fill_choice.clone() };
|
||||
let tracks_working = if selection_changed { true } else { drawing.fill.tracks_working_color };
|
||||
(Some(natural_fill_enabled), display_choice, tracks_working)
|
||||
};
|
||||
if drawing.fill.enabled != new_fill.0 || drawing.fill.fill_choice != new_fill.1 || drawing.fill.tracks_working_color != new_fill.2 {
|
||||
drawing.fill.enabled = new_fill.0;
|
||||
drawing.fill.fill_choice = new_fill.1;
|
||||
drawing.fill.tracks_working_color = new_fill.2;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
// STROKE
|
||||
|
||||
let new_stroke = if let Some(state) = graph_modification_utils::selected_stroke_state(document) {
|
||||
let active = state.enabled == Some(true);
|
||||
let (display_choice, tracks_working) = match state.optional_color {
|
||||
Some(color) if active => (Some(color.map_or(FillChoice::None, FillChoice::Solid)), false),
|
||||
Some(_) if selection_changed => (Some(stroke_fallback.clone()), true),
|
||||
Some(_) => (drawing.stroke.fill_choice.clone(), drawing.stroke.tracks_working_color),
|
||||
None => (None, true),
|
||||
};
|
||||
(state.enabled, display_choice, tracks_working)
|
||||
} else {
|
||||
let display_choice = if selection_changed { Some(stroke_fallback) } else { drawing.stroke.fill_choice.clone() };
|
||||
let tracks_working = if selection_changed { true } else { drawing.stroke.tracks_working_color };
|
||||
(Some(natural_stroke_enabled), display_choice, tracks_working)
|
||||
};
|
||||
if drawing.stroke.enabled != new_stroke.0 || drawing.stroke.fill_choice != new_stroke.1 || drawing.stroke.tracks_working_color != new_stroke.2 {
|
||||
drawing.stroke.enabled = new_stroke.0;
|
||||
drawing.stroke.fill_choice = new_stroke.1;
|
||||
drawing.stroke.tracks_working_color = new_stroke.2;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
changed
|
||||
}
|
||||
|
||||
/// Full SelectionChanged update for a drawing tool: syncs fill/stroke colors and the stroke weight. Returns `true` if the layout needs refreshing.
|
||||
pub fn sync_drawing_state(drawing: &mut DrawingToolState, natural_fill_enabled: bool, natural_stroke_enabled: bool, global: &DocumentToolData, document: &DocumentMessageHandler) -> bool {
|
||||
let selection_changed = selection_changed_since_last_sync(&mut drawing.last_synced_selection, document);
|
||||
let mut needs_refresh = sync_color_options(drawing, natural_fill_enabled, natural_stroke_enabled, global, document, selection_changed);
|
||||
|
||||
let new_line_weight = match compute_weight_sync(document) {
|
||||
WeightSyncOutcome::Set(weight) => Some(weight),
|
||||
WeightSyncOutcome::Mixed => None,
|
||||
// On a real selection change, revert to the default; otherwise preserve.
|
||||
WeightSyncOutcome::NoStrokes | WeightSyncOutcome::NoSelection => {
|
||||
if selection_changed {
|
||||
Some(drawing.default_line_weight)
|
||||
} else {
|
||||
drawing.line_weight
|
||||
}
|
||||
}
|
||||
};
|
||||
if drawing.line_weight != new_line_weight {
|
||||
drawing.line_weight = new_line_weight;
|
||||
needs_refresh = true;
|
||||
}
|
||||
|
||||
needs_refresh |= sync_stroke_options(drawing, document);
|
||||
|
||||
needs_refresh
|
||||
}
|
||||
|
||||
/// Reads the stroke proto-node inputs (align, cap, join, miter limit, paint order, dash lengths, dash offset) across the selection and updates
|
||||
/// the matching fields on `drawing`. Each field becomes `None` (mixed) when selected strokes disagree. With no selection, fields are left as-is.
|
||||
fn sync_stroke_options(drawing: &mut DrawingToolState, document: &DocumentMessageHandler) -> bool {
|
||||
let strokes: Vec<_> = document
|
||||
.network_interface
|
||||
.selected_nodes()
|
||||
.selected_layers_except_artboards(&document.network_interface)
|
||||
.filter_map(|layer| graph_modification_utils::get_stroke_options(layer, &document.network_interface))
|
||||
.into_iter()
|
||||
.map(|(icon, label, color_type)| {
|
||||
let mut entry = RadioEntryData::new(format!("{color_type:?}")).tooltip_label(label).icon(icon);
|
||||
entry.on_update = radio_callback(color_type);
|
||||
entry
|
||||
})
|
||||
.collect();
|
||||
if strokes.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let radio = RadioInput::new(entries).selected_index(Some(self.color_type.clone() as u32)).widget_instance();
|
||||
widgets.push(radio);
|
||||
widgets.push(Separator::new(SeparatorStyle::Related).widget_instance());
|
||||
|
||||
fn unanimous<T: PartialEq + Clone>(values: impl IntoIterator<Item = T>) -> Option<T> {
|
||||
let mut iter = values.into_iter();
|
||||
let first = iter.next()?;
|
||||
iter.all(|v| v == first).then_some(first)
|
||||
}
|
||||
|
||||
let new_align = unanimous(strokes.iter().map(|s| s.align));
|
||||
let new_cap = unanimous(strokes.iter().map(|s| s.cap));
|
||||
let new_join = unanimous(strokes.iter().map(|s| s.join));
|
||||
let new_miter = unanimous(strokes.iter().map(|s| s.miter_limit));
|
||||
let new_paint_order = unanimous(strokes.iter().map(|s| s.paint_order));
|
||||
let new_dash_lengths = unanimous(strokes.iter().map(|s| &s.dash_lengths)).cloned();
|
||||
let new_dash_offset = unanimous(strokes.iter().map(|s| s.dash_offset));
|
||||
|
||||
let mut changed = false;
|
||||
|
||||
if drawing.stroke_align != new_align {
|
||||
drawing.stroke_align = new_align;
|
||||
changed = true;
|
||||
}
|
||||
if drawing.stroke_cap != new_cap {
|
||||
drawing.stroke_cap = new_cap;
|
||||
changed = true;
|
||||
}
|
||||
if drawing.stroke_join != new_join {
|
||||
drawing.stroke_join = new_join;
|
||||
changed = true;
|
||||
}
|
||||
if drawing.miter_limit != new_miter {
|
||||
drawing.miter_limit = new_miter;
|
||||
changed = true;
|
||||
}
|
||||
if drawing.paint_order != new_paint_order {
|
||||
drawing.paint_order = new_paint_order;
|
||||
changed = true;
|
||||
}
|
||||
if drawing.dash_lengths != new_dash_lengths {
|
||||
drawing.dash_lengths = new_dash_lengths;
|
||||
changed = true;
|
||||
}
|
||||
if drawing.dash_offset != new_dash_offset {
|
||||
drawing.dash_offset = new_dash_offset;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
changed
|
||||
}
|
||||
|
||||
/// Same as [`sync_color_options`] but for tools that only have a fill option (e.g., text). The fill follows the given working color when nothing is selected.
|
||||
pub fn sync_fill_only(fill: &mut ToolColorOptions, natural_fill_enabled: bool, fill_color: Color, document: &DocumentMessageHandler, selection_changed: bool) -> bool {
|
||||
let fill_fallback = solid(fill_color);
|
||||
|
||||
let new_fill = if let Some(state) = graph_modification_utils::selected_fill_state(document) {
|
||||
let active = state.enabled == Some(true);
|
||||
let (display_choice, tracks_working_color) = match &state.fill_choice {
|
||||
Some(choice) if active => (Some(choice.clone()), false),
|
||||
Some(_) if selection_changed => (Some(fill_fallback.clone()), true),
|
||||
Some(_) => (fill.fill_choice.clone(), fill.tracks_working_color),
|
||||
None => (None, true),
|
||||
let fill_choice = match self.active_color() {
|
||||
Some(color) => FillChoice::Solid(color.to_gamma_srgb()),
|
||||
None => FillChoice::None,
|
||||
};
|
||||
(state.enabled, display_choice, tracks_working_color)
|
||||
} else {
|
||||
let display_choice = if selection_changed { Some(fill_fallback) } else { fill.fill_choice.clone() };
|
||||
let tracks_working = if selection_changed { true } else { fill.tracks_working_color };
|
||||
(Some(natural_fill_enabled), display_choice, tracks_working)
|
||||
};
|
||||
let color_button = ColorInput::new(fill_choice).allow_none(color_allow_none).on_update(color_callback);
|
||||
widgets.push(color_button.widget_instance());
|
||||
|
||||
if fill.enabled != new_fill.0 || fill.fill_choice != new_fill.1 || fill.tracks_working_color != new_fill.2 {
|
||||
fill.enabled = new_fill.0;
|
||||
fill.fill_choice = new_fill.1;
|
||||
fill.tracks_working_color = new_fill.2;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
widgets
|
||||
}
|
||||
}
|
||||
|
||||
/// True if at least one (non-artboard) layer is currently selected.
|
||||
pub fn has_selection(document: &DocumentMessageHandler) -> bool {
|
||||
document
|
||||
.network_interface
|
||||
.selected_nodes()
|
||||
.selected_layers_except_artboards(&document.network_interface)
|
||||
.next()
|
||||
.is_some()
|
||||
}
|
||||
|
||||
/// Applies a user-picked fill (gradient or solid). With a selection, writes to the layers; with none, pushes a solid to the swap-routed working color slot.
|
||||
pub fn apply_fill_color_pick(drawing: &mut DrawingToolState, fill_choice: FillChoice, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
apply_fill_only_color_pick(&mut drawing.fill, fill_choice, drawing.colors_swapped, document, responses);
|
||||
}
|
||||
|
||||
/// Single-slot variant of [`apply_fill_color_pick`] (e.g. for text). `slot_is_primary` says which working color this slot binds to.
|
||||
pub fn apply_fill_only_color_pick(fill: &mut ToolColorOptions, fill_choice: FillChoice, slot_is_primary: bool, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
fill.fill_choice = Some(fill_choice.clone());
|
||||
fill.enabled = Some(true);
|
||||
fill.tracks_working_color = false;
|
||||
if has_selection(document) {
|
||||
if document.network_interface.transaction_status() == TransactionStatus::Finished {
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
}
|
||||
graph_modification_utils::set_fill_for_selected_layers(fill_choice, document, responses);
|
||||
} else if let FillChoice::Solid(color) = fill_choice {
|
||||
responses.add(ToolMessage::SelectWorkingColor { color, primary: slot_is_primary });
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies a user-picked stroke color. With a selection, writes to the layers; with none, pushes to the swap-routed working color slot.
|
||||
pub fn apply_stroke_color_pick(drawing: &mut DrawingToolState, color: Option<Color>, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.stroke.fill_choice = Some(color.map_or(FillChoice::None, FillChoice::Solid));
|
||||
drawing.stroke.enabled = Some(true);
|
||||
drawing.stroke.tracks_working_color = false;
|
||||
if has_selection(document) {
|
||||
if document.network_interface.transaction_status() == TransactionStatus::Finished {
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
}
|
||||
graph_modification_utils::set_stroke_color_for_selected_layers(color, drawing.effective_line_weight(), document, responses);
|
||||
} else if let Some(color) = color {
|
||||
responses.add(ToolMessage::SelectWorkingColor {
|
||||
color,
|
||||
primary: !drawing.colors_swapped,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Toggles the fill checkbox: re-applies the preserved color when enabled, removes the fill node when disabled.
|
||||
pub fn apply_fill_enabled(drawing: &mut DrawingToolState, enabled: bool, global: &DocumentToolData, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
apply_fill_only_enabled(&mut drawing.fill, enabled, fill_working_color(global, drawing.colors_swapped), document, responses);
|
||||
}
|
||||
|
||||
/// Single-slot variant of [`apply_fill_enabled`]. `working_color` is the fallback used when re-ticking or unticking from a mixed state.
|
||||
pub fn apply_fill_only_enabled(fill: &mut ToolColorOptions, enabled: bool, working_color: Color, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
fill.enabled = Some(enabled);
|
||||
if has_selection(document) {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
}
|
||||
if enabled {
|
||||
// Mixed re-tick has no per-layer color to restore; fall back to the working color and keep tracking it.
|
||||
let fill_choice = fill.fill_choice.clone().unwrap_or_else(|| {
|
||||
fill.tracks_working_color = true;
|
||||
solid(working_color)
|
||||
});
|
||||
fill.fill_choice = Some(fill_choice.clone());
|
||||
graph_modification_utils::set_fill_for_selected_layers(fill_choice, document, responses);
|
||||
} else {
|
||||
// Unticking from mixed: capture the working color as the saved value so the swatch keeps following the link.
|
||||
if fill.fill_choice.is_none() {
|
||||
fill.fill_choice = Some(solid(working_color));
|
||||
fill.tracks_working_color = true;
|
||||
}
|
||||
graph_modification_utils::remove_fill_for_selected_layers(document, responses);
|
||||
}
|
||||
}
|
||||
|
||||
/// Toggles the stroke checkbox: mirrors [`apply_fill_enabled`].
|
||||
pub fn apply_stroke_enabled(drawing: &mut DrawingToolState, enabled: bool, global: &DocumentToolData, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.stroke.enabled = Some(enabled);
|
||||
if has_selection(document) {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
}
|
||||
if enabled {
|
||||
let stroke_choice = drawing.stroke.fill_choice.clone().unwrap_or_else(|| {
|
||||
drawing.stroke.tracks_working_color = true;
|
||||
solid(stroke_working_color(global, drawing.colors_swapped))
|
||||
});
|
||||
drawing.stroke.fill_choice = Some(stroke_choice.clone());
|
||||
graph_modification_utils::set_stroke_color_for_selected_layers(stroke_choice.as_solid(), drawing.effective_line_weight(), document, responses);
|
||||
} else {
|
||||
if drawing.stroke.fill_choice.is_none() {
|
||||
drawing.stroke.fill_choice = Some(solid(stroke_working_color(global, drawing.colors_swapped)));
|
||||
drawing.stroke.tracks_working_color = true;
|
||||
}
|
||||
graph_modification_utils::remove_stroke_for_selected_layers(document, responses);
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies a user-edited stroke weight to the selection, also persisting it as the no-selection default.
|
||||
pub fn apply_line_weight(drawing: &mut DrawingToolState, line_weight: f64, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.line_weight = Some(line_weight);
|
||||
if !has_selection(document) {
|
||||
drawing.default_line_weight = line_weight;
|
||||
}
|
||||
graph_modification_utils::set_stroke_weight_for_selected_layers(line_weight, document, responses);
|
||||
}
|
||||
|
||||
/// Propagates working colors to the tool's swatches. With no selection both slots refresh; with a selection, only slots tracking the working color.
|
||||
pub fn apply_working_colors(drawing: &mut DrawingToolState, global: &DocumentToolData, document: &DocumentMessageHandler) {
|
||||
refresh_slot_working_color(&mut drawing.fill, fill_working_color(global, drawing.colors_swapped), document);
|
||||
refresh_slot_working_color(&mut drawing.stroke, stroke_working_color(global, drawing.colors_swapped), document);
|
||||
}
|
||||
|
||||
/// Refreshes a single swatch from the given working color, subject to the rules in [`apply_working_colors`].
|
||||
pub fn refresh_slot_working_color(slot: &mut ToolColorOptions, working_color: Color, document: &DocumentMessageHandler) {
|
||||
if slot.fill_choice.is_some() && (!has_selection(document) || slot.tracks_working_color) {
|
||||
slot.fill_choice = Some(solid(working_color));
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets the tool's swatches to the working colors. Called on tool deactivation and shape-mode changes.
|
||||
pub fn reset_colors_on_deactivation(drawing: &mut DrawingToolState, global: &DocumentToolData) {
|
||||
drawing.fill.fill_choice = Some(solid(fill_working_color(global, drawing.colors_swapped)));
|
||||
drawing.stroke.fill_choice = Some(solid(stroke_working_color(global, drawing.colors_swapped)));
|
||||
drawing.fill.tracks_working_color = true;
|
||||
drawing.stroke.tracks_working_color = true;
|
||||
}
|
||||
|
||||
/// Handles the "Swap Fill/Stroke" button. Stroke can only hold a solid color, so a gradient fill collapses to `None` when moved.
|
||||
pub fn swap_fill_and_stroke(drawing: &mut DrawingToolState, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.colors_swapped = !drawing.colors_swapped;
|
||||
|
||||
if has_selection(document) {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
}
|
||||
|
||||
// The new fill takes the old stroke's value as-is; the new stroke takes the old fill (with any gradient collapsed to `None`,
|
||||
// since stroke can only hold a solid color). `None` (mixed) on either side propagates as `None` to the other.
|
||||
let new_fill = drawing.stroke.fill_choice.clone();
|
||||
let new_stroke = drawing.fill.fill_choice.as_ref().map(|c| c.as_solid().map_or(FillChoice::None, FillChoice::Solid));
|
||||
let (new_fill_tracks, new_stroke_tracks) = (drawing.stroke.tracks_working_color, drawing.fill.tracks_working_color);
|
||||
|
||||
drawing.fill.fill_choice = new_fill.clone();
|
||||
drawing.stroke.fill_choice = new_stroke.clone();
|
||||
drawing.fill.tracks_working_color = new_fill_tracks;
|
||||
drawing.stroke.tracks_working_color = new_stroke_tracks;
|
||||
|
||||
if has_selection(document) {
|
||||
// Apply to layers only when we have a concrete value (`None` means mixed, no single value to broadcast).
|
||||
if drawing.fill.is_active()
|
||||
&& let Some(choice) = new_fill
|
||||
{
|
||||
graph_modification_utils::set_fill_for_selected_layers(choice, document, responses);
|
||||
}
|
||||
if drawing.stroke.is_active()
|
||||
&& let Some(choice) = new_stroke
|
||||
{
|
||||
graph_modification_utils::set_stroke_color_for_selected_layers(choice.as_solid(), drawing.effective_line_weight(), document, responses);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates the cache and returns `true` if the current selection differs from the last-synced one. Cache stays sorted to keep comparisons cheap.
|
||||
pub fn selection_changed_since_last_sync(last_synced: &mut Vec<LayerNodeIdentifier>, document: &DocumentMessageHandler) -> bool {
|
||||
let mut current: Vec<LayerNodeIdentifier> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
|
||||
|
||||
current.sort();
|
||||
|
||||
let changed = current != *last_synced;
|
||||
*last_synced = current;
|
||||
changed
|
||||
}
|
||||
|
||||
/// How the weight widget should update from inspecting selected layers' strokes.
|
||||
pub enum WeightSyncOutcome {
|
||||
/// All strokes share this weight.
|
||||
Set(f64),
|
||||
/// Stroke weights differ (or some layers lack a stroke): show the mixed dash.
|
||||
Mixed,
|
||||
/// Selection has no strokes: reset to the tool's default on a real selection change, otherwise preserve.
|
||||
NoStrokes,
|
||||
/// No selection: preserve the current value.
|
||||
NoSelection,
|
||||
}
|
||||
|
||||
/// Inspects the selection and returns how the weight widget should update.
|
||||
pub fn compute_weight_sync(document: &DocumentMessageHandler) -> WeightSyncOutcome {
|
||||
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
|
||||
|
||||
if layers.is_empty() {
|
||||
return WeightSyncOutcome::NoSelection;
|
||||
}
|
||||
|
||||
let stroke_weights: Vec<f64> = layers.iter().filter_map(|l| graph_modification_utils::get_stroke_width(*l, &document.network_interface)).collect();
|
||||
|
||||
if stroke_weights.is_empty() {
|
||||
return WeightSyncOutcome::NoStrokes;
|
||||
}
|
||||
|
||||
if stroke_weights.len() != layers.len() {
|
||||
return WeightSyncOutcome::Mixed;
|
||||
}
|
||||
|
||||
let first = stroke_weights[0];
|
||||
let all_same = stroke_weights.iter().all(|&w| (w - first).abs() < f64::EPSILON * 100.);
|
||||
if all_same { WeightSyncOutcome::Set(first) } else { WeightSyncOutcome::Mixed }
|
||||
}
|
||||
@@ -9,14 +9,14 @@ use graph_craft::document::{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;
|
||||
use graphene_std::raster_types::{CPU, GPU, Image, Raster};
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::table::Table;
|
||||
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::{Fill, Gradient};
|
||||
use graphene_std::vector::{PointId, SegmentId, VectorModificationType};
|
||||
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.
|
||||
@@ -147,7 +147,7 @@ pub fn merge_layers(document: &DocumentMessageHandler, first_layer: LayerNodeIde
|
||||
|
||||
// Add a transform node to ensure correct tooling modifications
|
||||
let transform_node_id = NodeId::new();
|
||||
let transform_node = document_node_definitions::resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
|
||||
let transform_node = document_node_definitions::resolve_network_node_type("Transform")
|
||||
.expect("Failed to create transform node")
|
||||
.default_node_template();
|
||||
responses.add(NodeGraphMessage::InsertNode {
|
||||
@@ -218,9 +218,14 @@ pub fn new_vector_layer(subpaths: Vec<Subpath<PointId>>, id: NodeId, parent: Lay
|
||||
}
|
||||
|
||||
/// Create a new bitmap layer.
|
||||
pub fn new_image_layer(image: Image<Color>, id: NodeId, parent: LayerNodeIdentifier, responses: &mut VecDeque<Message>) -> LayerNodeIdentifier {
|
||||
pub fn new_image_layer(image_frame: Table<Raster<CPU>>, id: NodeId, parent: LayerNodeIdentifier, responses: &mut VecDeque<Message>) -> LayerNodeIdentifier {
|
||||
let insert_index = 0;
|
||||
responses.add(GraphOperationMessage::NewBitmapLayer { id, image, parent, insert_index });
|
||||
responses.add(GraphOperationMessage::NewBitmapLayer {
|
||||
id,
|
||||
image_frame,
|
||||
parent,
|
||||
insert_index,
|
||||
});
|
||||
LayerNodeIdentifier::new_unchecked(id)
|
||||
}
|
||||
|
||||
@@ -251,9 +256,7 @@ pub fn new_custom(id: NodeId, nodes: Vec<(NodeId, NodeTemplate)>, parent: LayerN
|
||||
pub fn get_origin(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<DVec2> {
|
||||
use graphene_std::transform_nodes::transform::*;
|
||||
|
||||
if let TaggedValue::DVec2(origin) =
|
||||
NodeGraphLayer::new(layer, network_interface).find_input(&DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER), TranslationInput::INDEX)?
|
||||
{
|
||||
if let TaggedValue::DVec2(origin) = NodeGraphLayer::new(layer, network_interface).find_input(&DefinitionIdentifier::Network("Transform".into()), TranslationInput::INDEX)? {
|
||||
Some(*origin)
|
||||
} else {
|
||||
None
|
||||
@@ -282,81 +285,36 @@ pub fn get_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkI
|
||||
Some(gradient.clone())
|
||||
}
|
||||
|
||||
/// Get the gradient stops of a layer, if any.
|
||||
pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<GradientStops> {
|
||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_value::IDENTIFIER))?;
|
||||
let TaggedValue::Gradient(stops) = inputs.get(graphene_std::math_nodes::gradient_value::GradientInput::INDEX)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
Some(stops.clone())
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub fn gradient_space_transform(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> glam::DAffine2 {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
|
||||
let metadata = network_interface.document_metadata();
|
||||
let is_gradient_list = is_layer_fed_by_node_of_name(layer, network_interface, &DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_value::IDENTIFIER));
|
||||
if is_gradient_list {
|
||||
return metadata
|
||||
.upstream_footprints
|
||||
.get(&layer.to_node())
|
||||
.map(|footprint| footprint.transform)
|
||||
.unwrap_or(metadata.document_to_viewport);
|
||||
}
|
||||
let multiplied = metadata.transform_to_viewport(layer);
|
||||
let bounds = metadata.nonzero_bounding_box(layer);
|
||||
let bound_transform = glam::DAffine2::from_scale_angle_translation(bounds[1] - bounds[0], 0., bounds[0]);
|
||||
multiplied * bound_transform
|
||||
}
|
||||
|
||||
/// 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);
|
||||
if (viewport_end.x - viewport_start.x).abs() > f64::EPSILON * 1e6 {
|
||||
viewport_end.x > viewport_start.x
|
||||
} else {
|
||||
(viewport_start.x + viewport_start.y) < (viewport_end.x + viewport_end.y)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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::Fill(Fill::Solid(color)) = inputs.get(fill_index)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
Some(color)
|
||||
Some(color.to_linear_srgb())
|
||||
}
|
||||
|
||||
/// Get the current blend mode of a layer from the closest upstream "Blend Mode" node.
|
||||
/// Get the current blend mode of a layer from the closest "Blending" node.
|
||||
pub fn get_blend_mode(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<BlendMode> {
|
||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::blending_nodes::blend_mode::IDENTIFIER))?;
|
||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::blending_nodes::blending::IDENTIFIER))?;
|
||||
let TaggedValue::BlendMode(blend_mode) = inputs.get(1)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
Some(*blend_mode)
|
||||
}
|
||||
|
||||
/// Get the current opacity of a layer from the closest upstream "Opacity" node, only when the node's `has_opacity` checkbox is enabled.
|
||||
/// Get the current opacity of a layer from the closest "Blending" node.
|
||||
/// This may differ from the actual opacity contained within the data type reaching this layer, because that actual opacity may be:
|
||||
/// - Multiplied with additional Opacity nodes earlier in the chain
|
||||
/// - Multiplied with additional opacity nodes earlier in the chain
|
||||
/// - Set by an Opacity node with an exposed input value driven by another node
|
||||
/// - Already factored into the pixel alpha channel of an image
|
||||
/// - The default value of 100% if no Opacity node has its checkbox enabled (this function returns `None` in that case)
|
||||
/// - The default value of 100% if no Opacity node is present, but this function returns None in that case
|
||||
///
|
||||
/// With those limitations in mind, the intention of this function is to show just the value already present in an upstream Opacity node so that value can be directly edited.
|
||||
pub fn get_opacity(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<f64> {
|
||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::blending_nodes::opacity::IDENTIFIER))?;
|
||||
let TaggedValue::Bool(true) = inputs.get(1)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::blending_nodes::blending::IDENTIFIER))?;
|
||||
let TaggedValue::F64(opacity) = inputs.get(2)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
@@ -364,20 +322,16 @@ pub fn get_opacity(layer: LayerNodeIdentifier, network_interface: &NodeNetworkIn
|
||||
}
|
||||
|
||||
pub fn get_clip_mode(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<bool> {
|
||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::blending_nodes::clipping_mask::IDENTIFIER))?;
|
||||
let TaggedValue::Bool(clip) = inputs.get(1)?.as_value()? else {
|
||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::blending_nodes::blending::IDENTIFIER))?;
|
||||
let TaggedValue::Bool(clip) = inputs.get(4)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
Some(*clip)
|
||||
}
|
||||
|
||||
/// Get the current fill of a layer from the closest upstream "Opacity" node, only when the node's `has_fill` checkbox is enabled.
|
||||
pub fn get_fill(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<f64> {
|
||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::blending_nodes::opacity::IDENTIFIER))?;
|
||||
let TaggedValue::Bool(true) = inputs.get(3)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
let TaggedValue::F64(fill) = inputs.get(4)?.as_value()? else {
|
||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::blending_nodes::blending::IDENTIFIER))?;
|
||||
let TaggedValue::F64(fill) = inputs.get(3)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
Some(*fill)
|
||||
@@ -468,7 +422,7 @@ pub fn get_text(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInter
|
||||
let Some(&TaggedValue::TextAlign(align)) = inputs[graphene_std::text::text::AlignInput::INDEX].as_value() else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::Bool(per_glyph_items)) = inputs[graphene_std::text::text::SeparateGlyphsInput::INDEX].as_value() else {
|
||||
let Some(&TaggedValue::Bool(per_glyph_instances)) = inputs[graphene_std::text::text::SeparateGlyphElementsInput::INDEX].as_value() else {
|
||||
return None;
|
||||
};
|
||||
|
||||
@@ -481,7 +435,7 @@ pub fn get_text(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInter
|
||||
tilt,
|
||||
align,
|
||||
};
|
||||
Some((text, font, typesetting, per_glyph_items))
|
||||
Some((text, font, typesetting, per_glyph_instances))
|
||||
}
|
||||
|
||||
pub fn get_stroke_width(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<f64> {
|
||||
@@ -493,306 +447,6 @@ pub fn get_stroke_width(layer: LayerNodeIdentifier, network_interface: &NodeNetw
|
||||
}
|
||||
}
|
||||
|
||||
/// Subset of Stroke node inputs read for the control bar's stroke options popover.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct StrokeOptionsState {
|
||||
pub align: StrokeAlign,
|
||||
pub cap: StrokeCap,
|
||||
pub join: StrokeJoin,
|
||||
pub miter_limit: f64,
|
||||
pub paint_order: PaintOrder,
|
||||
pub dash_lengths: Vec<f64>,
|
||||
pub dash_offset: f64,
|
||||
}
|
||||
|
||||
/// Reads the non-color stroke option inputs from a layer's Stroke proto node. Returns `None` when the layer has no Stroke node.
|
||||
/// Inputs that aren't a static value (e.g. wired to another node) fall back to per-field defaults so the layer still participates in the sync.
|
||||
pub fn get_stroke_options(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<StrokeOptionsState> {
|
||||
let stroke = &DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
|
||||
let layer_view = NodeGraphLayer::new(layer, network_interface);
|
||||
layer_view.upstream_node_id_from_name(stroke)?;
|
||||
let read = |index: usize| layer_view.find_input(stroke, index);
|
||||
|
||||
let align = match read(graphene_std::vector::stroke::AlignInput::INDEX) {
|
||||
Some(TaggedValue::StrokeAlign(value)) => *value,
|
||||
_ => StrokeAlign::default(),
|
||||
};
|
||||
let cap = match read(graphene_std::vector::stroke::CapInput::INDEX) {
|
||||
Some(TaggedValue::StrokeCap(value)) => *value,
|
||||
_ => StrokeCap::default(),
|
||||
};
|
||||
let join = match read(graphene_std::vector::stroke::JoinInput::INDEX) {
|
||||
Some(TaggedValue::StrokeJoin(value)) => *value,
|
||||
_ => StrokeJoin::default(),
|
||||
};
|
||||
let miter_limit = match read(graphene_std::vector::stroke::MiterLimitInput::INDEX) {
|
||||
Some(TaggedValue::F64(value)) => *value,
|
||||
_ => 4.,
|
||||
};
|
||||
let paint_order = match read(graphene_std::vector::stroke::PaintOrderInput::INDEX) {
|
||||
Some(TaggedValue::PaintOrder(value)) => *value,
|
||||
_ => PaintOrder::default(),
|
||||
};
|
||||
let dash_lengths = match read(graphene_std::vector::stroke::DashLengthsInput::<List<f64>>::INDEX) {
|
||||
Some(TaggedValue::F64Array(value)) => value.clone(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let dash_offset = match read(graphene_std::vector::stroke::DashOffsetInput::INDEX) {
|
||||
Some(TaggedValue::F64(value)) => *value,
|
||||
_ => 0.,
|
||||
};
|
||||
|
||||
Some(StrokeOptionsState {
|
||||
align,
|
||||
cap,
|
||||
join,
|
||||
miter_limit,
|
||||
paint_order,
|
||||
dash_lengths,
|
||||
dash_offset,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the node ID of a layer's upstream Stroke proto node, if one exists.
|
||||
pub fn get_stroke_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
|
||||
NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER))
|
||||
}
|
||||
|
||||
/// Stroke weight of the first selected non-artboard layer, used by tool control bars to mirror the selection's weight.
|
||||
/// Returns `Some(0.)` if the layer has no Stroke node so the widget reads "0 px", and `None` only when no layer is selected.
|
||||
pub fn first_selected_stroke_weight(document: &DocumentMessageHandler) -> Option<f64> {
|
||||
document
|
||||
.network_interface
|
||||
.selected_nodes()
|
||||
.selected_layers_except_artboards(&document.network_interface)
|
||||
.next()
|
||||
.map(|layer| get_stroke_width(layer, &document.network_interface).unwrap_or(0.))
|
||||
}
|
||||
|
||||
/// Writes the weight back to every selected non-artboard layer's stroke. Layers with an existing stroke just have their
|
||||
/// `WeightInput` updated; layers without one get a fresh stroke node added (defaulting to a black stroke with the new
|
||||
/// weight) only when the new weight is nonzero, so changing back to 0 doesn't keep adding empty strokes.
|
||||
pub fn set_stroke_weight_for_selected_layers(weight: f64, 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 {
|
||||
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
|
||||
let input_index = graphene_std::vector::stroke::WeightInput::INDEX;
|
||||
let value = TaggedValue::F64(weight);
|
||||
responses.add(NodeGraphMessage::SetInputValue { node_id, input_index, value });
|
||||
} else if weight > 0. {
|
||||
let stroke = graphene_std::vector::style::Stroke::default().with_weight(weight);
|
||||
responses.add(GraphOperationMessage::StrokeSet { layer, 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 }
|
||||
}
|
||||
|
||||
/// 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 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 }
|
||||
}
|
||||
|
||||
/// Aggregated fill state across all selected non-artboard layers.
|
||||
pub struct SelectedFillState {
|
||||
/// `None` means mixed values between selected layers.
|
||||
pub enabled: Option<bool>,
|
||||
/// `None` means mixed values between selected layers.
|
||||
pub fill_choice: Option<FillChoice>,
|
||||
}
|
||||
|
||||
/// Aggregated stroke state across all selected non-artboard layers.
|
||||
pub struct SelectedStrokeState {
|
||||
/// `None` means mixed values between selected layers.
|
||||
pub enabled: Option<bool>,
|
||||
/// `None` means mixed values between selected layers.
|
||||
pub optional_color: Option<Option<Color>>,
|
||||
}
|
||||
|
||||
/// Reads the fill state across all selected non-artboard layers, including whether their enabled states or colors differ.
|
||||
/// "Enabled" tracks node attachment: a layer counts as enabled whenever a Fill node is attached, even when that fill's value is [`FillChoice::None`].
|
||||
/// Unticked means there is no Fill node. Returns `None` only when no layer is selected.
|
||||
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() {
|
||||
return (false, FillChoice::None);
|
||||
}
|
||||
let fill_choice = get_fill_value(layer, &document.network_interface).map_or(FillChoice::None, FillChoice::from);
|
||||
(true, fill_choice)
|
||||
});
|
||||
|
||||
let (initial_enabled, initial_choice) = per_layer.next()?;
|
||||
let mut enabled_mixed = false;
|
||||
let mut color_mixed = false;
|
||||
let mut comparison_enabled = initial_enabled;
|
||||
let mut comparison_choice = initial_choice;
|
||||
for (enabled, fill_choice) in per_layer {
|
||||
if enabled != initial_enabled {
|
||||
enabled_mixed = true;
|
||||
}
|
||||
if enabled {
|
||||
if comparison_enabled {
|
||||
if fill_choice != comparison_choice {
|
||||
color_mixed = true;
|
||||
}
|
||||
} else {
|
||||
comparison_enabled = true;
|
||||
comparison_choice = fill_choice;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(SelectedFillState {
|
||||
enabled: (!enabled_mixed).then_some(initial_enabled),
|
||||
fill_choice: (!color_mixed).then_some(comparison_choice),
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads the stroke state across all selected non-artboard layers, including whether their enabled states or colors differ.
|
||||
/// "Enabled" tracks node attachment: a layer counts as enabled whenever a Stroke node is attached, even when that stroke's color is `None`.
|
||||
/// Unticked means there is no Stroke node. Returns `None` only when no layer is selected.
|
||||
pub fn selected_stroke_state(document: &DocumentMessageHandler) -> Option<SelectedStrokeState> {
|
||||
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_stroke_id(layer, &document.network_interface).is_none() {
|
||||
return (false, None);
|
||||
}
|
||||
let color = get_stroke_color(layer, &document.network_interface).flatten();
|
||||
(true, color)
|
||||
});
|
||||
|
||||
let (initial_enabled, initial_color) = per_layer.next()?;
|
||||
let mut enabled_mixed = false;
|
||||
let mut color_mixed = false;
|
||||
let mut comparison_enabled = initial_enabled;
|
||||
let mut comparison_color = initial_color;
|
||||
for (enabled, color) in per_layer {
|
||||
if enabled != initial_enabled {
|
||||
enabled_mixed = true;
|
||||
}
|
||||
if enabled {
|
||||
if comparison_enabled {
|
||||
if color != comparison_color {
|
||||
color_mixed = true;
|
||||
}
|
||||
} else {
|
||||
comparison_enabled = true;
|
||||
comparison_color = color;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(SelectedStrokeState {
|
||||
enabled: (!enabled_mixed).then_some(initial_enabled),
|
||||
optional_color: (!color_mixed).then_some(comparison_color),
|
||||
})
|
||||
}
|
||||
|
||||
/// Sets the fill on all selected non-artboard layers, preserving gradient transform data when the layer already has a gradient fill.
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the stroke color on all selected non-artboard layers. Layers without an existing Stroke node get one created using
|
||||
/// the provided `weight`, so picking any color (including `None`) from an unticked stroke control bar entry both attaches
|
||||
/// the Stroke node and applies the chosen color.
|
||||
pub fn set_stroke_color_for_selected_layers(color: Option<Color>, weight: f64, 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 {
|
||||
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
|
||||
let input_index = graphene_std::vector::stroke::ColorInput::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 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the Fill node from all selected non-artboard layers.
|
||||
pub fn remove_fill_for_selected_layers(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 {
|
||||
if let Some(node_id) = get_fill_id(layer, &document.network_interface) {
|
||||
responses.add(NodeGraphMessage::DeleteNodes {
|
||||
node_ids: vec![node_id],
|
||||
delete_children: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
|
||||
/// Removes the Stroke node from all selected non-artboard layers.
|
||||
pub fn remove_stroke_for_selected_layers(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 {
|
||||
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
|
||||
responses.add(NodeGraphMessage::DeleteNodes {
|
||||
node_ids: vec![node_id],
|
||||
delete_children: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
|
||||
/// Reads a specific input from the matching proto node on the first selected non-artboard layer that has one.
|
||||
/// Used by tool control bars to mirror per-shape parameters (sides, arc type, turns, etc.) from the selection
|
||||
/// into the control bar's input widget state without each call site re-implementing the layer iteration.
|
||||
pub fn first_selected_proto_node_input(document: &DocumentMessageHandler, identifier: graph_craft::ProtoNodeIdentifier, input_index: usize) -> Option<&TaggedValue> {
|
||||
let identifier = DefinitionIdentifier::ProtoNode(identifier);
|
||||
document
|
||||
.network_interface
|
||||
.selected_nodes()
|
||||
.selected_layers_except_artboards(&document.network_interface)
|
||||
.find_map(|layer| NodeGraphLayer::new(layer, &document.network_interface).find_input(&identifier, input_index))
|
||||
}
|
||||
|
||||
/// Writes a value to a specific input on the matching proto node of every selected non-artboard layer that has one.
|
||||
/// Used by tool control bars to push per-shape parameter changes back onto all selected layers of that shape.
|
||||
pub fn set_proto_node_input_for_selected_layers(
|
||||
document: &DocumentMessageHandler,
|
||||
identifier: graph_craft::ProtoNodeIdentifier,
|
||||
input_index: usize,
|
||||
value: TaggedValue,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) {
|
||||
let identifier = DefinitionIdentifier::ProtoNode(identifier);
|
||||
|
||||
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
|
||||
|
||||
for layer in layers {
|
||||
let Some(node_id) = NodeGraphLayer::new(layer, &document.network_interface).upstream_node_id_from_name(&identifier) else {
|
||||
continue;
|
||||
};
|
||||
responses.add(NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index,
|
||||
value: value.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks if a specified layer uses an upstream node matching the given name.
|
||||
pub fn is_layer_fed_by_node_of_name(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface, identifier: &DefinitionIdentifier) -> bool {
|
||||
NodeGraphLayer::new(layer, network_interface).find_node_inputs(identifier).is_some()
|
||||
@@ -819,10 +473,9 @@ impl<'a> NodeGraphLayer<'a> {
|
||||
self.network_interface.upstream_flow_back_from_nodes(vec![self.layer_node], &[], FlowType::HorizontalFlow)
|
||||
}
|
||||
|
||||
/// Node id of a node if it exists in this specific layer's primary flow, stopping at the next layer upstream so a group doesn't incorrectly match its children's nodes.
|
||||
/// Node id of a node if it exists in the layer's primary flow
|
||||
pub fn upstream_node_id_from_name(&self, identifier: &DefinitionIdentifier) -> Option<NodeId> {
|
||||
self.horizontal_layer_flow()
|
||||
.take_while(|&node_id| node_id == self.layer_node || !self.network_interface.is_layer(&node_id, &[]))
|
||||
.find(|node_id| self.network_interface.reference(node_id, &[]).is_some_and(|reference| reference == *identifier))
|
||||
}
|
||||
|
||||
@@ -868,6 +521,6 @@ impl<'a> NodeGraphLayer<'a> {
|
||||
pub fn is_raster_layer(layer: LayerNodeIdentifier, network_interface: &mut NodeNetworkInterface) -> bool {
|
||||
let layer_input_type = network_interface.input_type(&InputConnector::node(layer.to_node(), 1), &[]);
|
||||
|
||||
layer_input_type.compiled_nested_type() == Some(&concrete!(List<Raster<CPU>>)) || layer_input_type.compiled_nested_type() == Some(&concrete!(List<Raster<GPU>>))
|
||||
layer_input_type.compiled_nested_type() == Some(&concrete!(Table<Raster<CPU>>)) || layer_input_type.compiled_nested_type() == Some(&concrete!(Table<Raster<GPU>>))
|
||||
}
|
||||
}
|
||||
Loaded 100 of 313 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user