mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
141
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5faf5e67f2 | ||
|
|
1d3d32c169 | ||
|
|
21d2994059 | ||
|
|
d5f0140f26 | ||
|
|
c4a978009a | ||
|
|
256dd26b99 | ||
|
|
06e2a049de | ||
|
|
79df7cfa87 | ||
|
|
16c7544d96 | ||
|
|
a56746c6bf | ||
|
|
456a7c868d | ||
|
|
1c9c19a697 | ||
|
|
696b625a3e | ||
|
|
4d5dce976e | ||
|
|
629a1f4b4c | ||
|
|
f6def3b911 | ||
|
|
98daa75c26 | ||
|
|
a28b9437aa | ||
|
|
6b3e4757de | ||
|
|
cb21e5960b | ||
|
|
d97fe835b5 | ||
|
|
9d876ab27d | ||
|
|
dff8ac5511 | ||
|
|
0834bff2da | ||
|
|
525e49f7e9 | ||
|
|
1596469e92 | ||
|
|
9512f7df41 | ||
|
|
24c857ddc7 | ||
|
|
2ae35a67e7 | ||
|
|
c0a8241f50 | ||
|
|
1c2ac19b16 | ||
|
|
8ae8c47fe1 | ||
|
|
023cf1bedd | ||
|
|
d106bedecd | ||
|
|
ecf94258fa | ||
|
|
22a6e0d767 | ||
|
|
9565d43481 | ||
|
|
05f6138b65 | ||
|
|
39a7c45ccd | ||
|
|
269a217cf9 | ||
|
|
5becf132e7 | ||
|
|
644e9cf91e | ||
|
|
9db91a1ac4 | ||
|
|
e59612c4ce | ||
|
|
62203cb171 | ||
|
|
21e5e06b0b | ||
|
|
b27b4c6be7 | ||
|
|
ebdb835890 | ||
|
|
de2ae29edd | ||
|
|
325e9aff06 | ||
|
|
ab7f59ca61 | ||
|
|
a0d5f418d9 | ||
|
|
9943af5248 | ||
|
|
485bac89e5 | ||
|
|
eeb1f85e25 | ||
|
|
42f4c1396b | ||
|
|
eddd742f9b | ||
|
|
0acfd3e178 | ||
|
|
29f6e686ee | ||
|
|
7cd5531730 | ||
|
|
83d03ad67d | ||
|
|
4c1974c200 | ||
|
|
4474de4662 | ||
|
|
86134c26b4 | ||
|
|
4b2430290c | ||
|
|
e686ee9f42 | ||
|
|
8cadafa063 | ||
|
|
f52009b402 | ||
|
|
ba63c26c62 | ||
|
|
0847d7b0ab | ||
|
|
5774ec215d | ||
|
|
f6c73d1c20 | ||
|
|
b6ac217b70 | ||
|
|
d44b0cd308 | ||
|
|
b152f46380 | ||
|
|
fc7348d08a | ||
|
|
6b11b47753 | ||
|
|
84fb901b5a | ||
|
|
b396d17211 | ||
|
|
cf150b5cff | ||
|
|
df8c2125d9 | ||
|
|
e0368435b9 | ||
|
|
3eba762135 | ||
|
|
881784ba66 | ||
|
|
afc2c9178e | ||
|
|
76938eb69a | ||
|
|
324b9e664c | ||
|
|
824d1162eb | ||
|
|
3d84e63ef9 | ||
|
|
7bb01c9651 | ||
|
|
c9c76df40c | ||
|
|
c32c808d5b | ||
|
|
6c0af72053 | ||
|
|
328c4f272b | ||
|
|
a59fed9d1c | ||
|
|
1444c333ab | ||
|
|
f42d12da9e | ||
|
|
fcf9396a71 | ||
|
|
e2117d9a02 | ||
|
|
d3f36a95cf | ||
|
|
c2e1208d82 | ||
|
|
6c5e3c97f8 | ||
|
|
2a2a60883d | ||
|
|
60f16d72a5 | ||
|
|
79d778a535 | ||
|
|
da45ab2f87 | ||
|
|
661e8bc569 | ||
|
|
b100892bfa | ||
|
|
b099e2faca | ||
|
|
39656d4c73 | ||
|
|
0eb440db14 | ||
|
|
211111a01f | ||
|
|
1d0337285a | ||
|
|
848ff5fd52 | ||
|
|
19aaeb374b | ||
|
|
bf269d7693 | ||
|
|
a99b2806ff | ||
|
|
e0212ca4b9 | ||
|
|
55463fe0aa | ||
|
|
4360359d60 | ||
|
|
7077e877f9 | ||
|
|
b52bf7b7d4 | ||
|
|
55115d89d5 | ||
|
|
5edb00bd9a | ||
|
|
ab822afae4 | ||
|
|
1a06d3ea80 | ||
|
|
87bd3d41df | ||
|
|
662691f32a | ||
|
|
1543d974ac | ||
|
|
79bf1ab688 | ||
|
|
211b9113a1 | ||
|
|
d41883a942 | ||
|
|
86e41a110a | ||
|
|
203910a92f | ||
|
|
a3ea6ab0af | ||
|
|
e2a142333f | ||
|
|
71ff4c937f | ||
|
|
50a618ad12 | ||
|
|
6388a32ac5 | ||
|
|
865e9713ad | ||
|
|
e529f74495 |
No files matched your search
@@ -1,2 +1,2 @@
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/8ae15dc9c51a3855475d8cab1d0f29d9d9bc622c.tar.gz
|
||||
c19abe4ac848f3c835e43dc065c59e20e60233ae023ea0a064c5fed442be2d3d
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/0d004aa61e6b48d316e8e5db6d59ccc4788f192d.tar.gz
|
||||
772d64518be43c99977ba56f69e574531c56e83d2df2f42ab066f77f74b0dd1f
|
||||
@@ -1,3 +1,7 @@
|
||||
[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
|
||||
@@ -9,6 +13,9 @@ 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]00",
|
||||
"onCreateCommand": "cargo install cargo-watch wasm-pack cargo-about && cargo install -f [email protected]21",
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
// NOTE: Keep this in sync with `.vscode/extensions.json`
|
||||
|
||||
+55
-22
@@ -20,9 +20,6 @@ on:
|
||||
linux:
|
||||
description: "Linux"
|
||||
type: boolean
|
||||
push_to_nix_cache:
|
||||
description: "Linux: push to Nix cache"
|
||||
type: boolean
|
||||
debug:
|
||||
description: "Debug build"
|
||||
type: boolean
|
||||
@@ -36,8 +33,6 @@ on:
|
||||
type: boolean
|
||||
linux:
|
||||
type: boolean
|
||||
push_to_nix_cache:
|
||||
type: boolean
|
||||
debug:
|
||||
type: boolean
|
||||
checkout_repo:
|
||||
@@ -158,22 +153,38 @@ 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 }}"
|
||||
ENVIRONMENT="graphite-dev (Preview)"
|
||||
AUTO_INACTIVE="false"
|
||||
TRANSIENT_ENVIRONMENT="true"
|
||||
fi
|
||||
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":[]}
|
||||
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
|
||||
}
|
||||
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" \
|
||||
@@ -193,9 +204,19 @@ 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 |"
|
||||
| $CF_URL |
|
||||
|
||||
Wasm: **$WASM_SIZE** — JS: **$JS_SIZE** — CSS: **$CSS_SIZE** — Fonts: **$FONT_SIZE** — Images: **$IMAGE_SIZE** — All Assets: **$ALL_SIZE**"
|
||||
|
||||
if [ "${{ github.ref }}" = "refs/tags/latest-stable" ]; then
|
||||
# Push tag: skip commenting (commit was already commented on master merge)
|
||||
@@ -262,7 +283,7 @@ jobs:
|
||||
pull-requests: write
|
||||
|
||||
env:
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.100"
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.121"
|
||||
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
@@ -453,7 +474,7 @@ jobs:
|
||||
pull-requests: write
|
||||
|
||||
env:
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.100"
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.121"
|
||||
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
@@ -639,23 +660,35 @@ jobs:
|
||||
|
||||
- name: ❄ Install Nix
|
||||
uses: DeterminateSystems/nix-installer-action@main
|
||||
with:
|
||||
extra-conf: |
|
||||
extra-substituters = https://graphite.cachix.org https://graphite-dev.cachix.org
|
||||
extra-trusted-public-keys = graphite.cachix.org-1:B7Il1yMpkquN/dXM+5GRmz+4Xmu2aaCS1GcWNfFhsOo= graphite-dev.cachix.org-1:RppXYpiV1qO2TYKTkXXGHsAEQDOB5G51b3VlrN9QmbI=
|
||||
|
||||
- name: 🗑 Free disk space
|
||||
run: sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache
|
||||
|
||||
- name: 📦 Build Nix package
|
||||
run: nix build .#graphite${{ inputs.debug && '-dev' || '' }} --no-link --print-out-paths
|
||||
run: nix build .#graphite${{ inputs.debug && '-dev' || '' }} --no-link --print-out-paths --print-build-logs
|
||||
|
||||
- name: 📤 Push to Nix cache
|
||||
if: (github.event_name == 'push' || inputs.push_to_nix_cache) && !inputs.debug
|
||||
env:
|
||||
NIX_CACHE_AUTH_TOKEN: ${{ secrets.NIX_CACHE_AUTH_TOKEN }}
|
||||
NIX_CACHE_AUTH_TOKEN: ${{ (!inputs.debug && github.ref == 'refs/heads/master') && secrets.NIX_CACHE_AUTH_TOKEN || secrets.NIX_CACHE_AUTH_TOKEN_DEV }}
|
||||
NIX_CACHE_NAME: ${{ (!inputs.debug && github.ref == 'refs/heads/master') && 'graphite' || 'graphite-dev' }}
|
||||
run: |
|
||||
nix run nixpkgs#cachix -- authtoken $NIX_CACHE_AUTH_TOKEN
|
||||
nix build --no-link --print-out-paths | nix run nixpkgs#cachix -- push graphite
|
||||
nix build .#graphite${{ inputs.debug && '-dev' || '' }} --no-link --print-out-paths | nix run nixpkgs#cachix -- push $NIX_CACHE_NAME
|
||||
|
||||
- name: 📤 Push Dependencies to dev Nix cache
|
||||
env:
|
||||
NIX_CACHE_AUTH_TOKEN: ${{ secrets.NIX_CACHE_AUTH_TOKEN_DEV }}
|
||||
NIX_CACHE_NAME: graphite-dev
|
||||
run: |
|
||||
nix run nixpkgs#cachix -- authtoken $NIX_CACHE_AUTH_TOKEN
|
||||
nix build .#graphite${{ inputs.debug && '-dev' || '' }}.deps --no-link --print-out-paths | nix run nixpkgs#cachix -- push $NIX_CACHE_NAME
|
||||
|
||||
- name: 🏗 Build Linux bundle
|
||||
run: nix build .#graphite${{ inputs.debug && '-dev' || '' }}-bundle.tar.xz && cp ./result ./graphite-linux-bundle.tar.xz
|
||||
run: nix build .#graphite-bundle${{ inputs.debug && '-dev' || '' }}.tar.xz && cp ./result ./graphite-linux-bundle.tar.xz
|
||||
|
||||
- name: 📦 Upload Linux bundle
|
||||
uses: actions/upload-artifact@v6
|
||||
@@ -693,7 +726,7 @@ jobs:
|
||||
|
||||
- name: 🏗 Build Flatpak
|
||||
run: |
|
||||
nix build .#graphite${{ inputs.debug && '-dev' || '' }}-flatpak-manifest
|
||||
nix build .#graphite-flatpak-manifest${{ inputs.debug && '-dev' || '' }}
|
||||
|
||||
rm -rf .flatpak
|
||||
mkdir -p .flatpak
|
||||
|
||||
@@ -57,7 +57,8 @@ jobs:
|
||||
|
||||
- name: 🧪 Run Rust tests
|
||||
env:
|
||||
RUSTFLAGS: -Dwarnings
|
||||
# `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml`
|
||||
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
|
||||
run: mold -run cargo test --all-features
|
||||
|
||||
# Rust format check on GitHub runner
|
||||
|
||||
@@ -22,27 +22,14 @@ 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: 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: Install gungraun-runner and valgrind
|
||||
uses: gungraun/setup-gungraun@v1
|
||||
|
||||
- name: Checkout master branch
|
||||
run: |
|
||||
@@ -66,21 +53,21 @@ jobs:
|
||||
id: cache-benchmark-baselines
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: target/iai
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-benchmark-baselines-master-${{ steps.master-sha.outputs.sha }}
|
||||
path: target/gungraun
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-gungraun-benchmark-baselines-master-${{ steps.master-sha.outputs.sha }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-benchmark-baselines-master-
|
||||
${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-gungraun-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_iai -- --save-baseline=master
|
||||
cargo bench --bench compile_demo_art_gungraun -- --save-baseline=master
|
||||
|
||||
# Runtime benchmarks
|
||||
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
|
||||
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
|
||||
|
||||
- name: Checkout PR branch
|
||||
run: git checkout ${{ github.event.pull_request.head.sha }}
|
||||
@@ -88,12 +75,12 @@ jobs:
|
||||
- name: Run PR benchmarks
|
||||
run: |
|
||||
# Compile benchmarks
|
||||
cargo bench --bench compile_demo_art_iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/compile_output.json
|
||||
cargo bench --bench compile_demo_art_gungraun -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/compile_output.json
|
||||
|
||||
# Runtime benchmarks
|
||||
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
|
||||
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
|
||||
|
||||
- name: Make old comments collapsed by default
|
||||
# Only run if we have write permissions (not a fork)
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
name: "Nix Housekeeping"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
workflow_dispatch: {}
|
||||
|
||||
jobs:
|
||||
cache-dev-shell:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
repository: ${{ inputs.checkout_repo || github.repository }}
|
||||
ref: ${{ inputs.checkout_ref || '' }}
|
||||
|
||||
- name: ❄ Install Nix
|
||||
uses: DeterminateSystems/nix-installer-action@main
|
||||
with:
|
||||
extra-conf: |
|
||||
extra-substituters = https://graphite.cachix.org https://graphite-dev.cachix.org
|
||||
extra-trusted-public-keys = graphite.cachix.org-1:B7Il1yMpkquN/dXM+5GRmz+4Xmu2aaCS1GcWNfFhsOo= graphite-dev.cachix.org-1:RppXYpiV1qO2TYKTkXXGHsAEQDOB5G51b3VlrN9QmbI=
|
||||
|
||||
- name: 🔎 Check whether development shell is already in binary cache
|
||||
id: cache-check
|
||||
run: |
|
||||
out_path="$(nix eval --raw .#devShells.x86_64-linux.default.outPath)"
|
||||
if nix path-info --store https://graphite-dev.cachix.org "$out_path" &>/dev/null; then
|
||||
echo "cached=true" >> "$GITHUB_OUTPUT"
|
||||
echo "Development shell is already cached at $out_path"
|
||||
else
|
||||
echo "cached=false" >> "$GITHUB_OUTPUT"
|
||||
echo "Development shell is not cached"
|
||||
fi
|
||||
|
||||
- name: 📦 Build Nix development shell
|
||||
if: steps.cache-check.outputs.cached == 'false'
|
||||
run: nix build .#devShells.x86_64-linux.default --no-link --print-out-paths
|
||||
|
||||
- name: 📤 Push Nix development shell to binary cache
|
||||
if: steps.cache-check.outputs.cached == 'false'
|
||||
env:
|
||||
NIX_CACHE_AUTH_TOKEN: ${{ secrets.NIX_CACHE_AUTH_TOKEN_DEV }}
|
||||
run: |
|
||||
nix run nixpkgs#cachix -- authtoken $NIX_CACHE_AUTH_TOKEN
|
||||
nix build .#devShells.x86_64-linux.default --no-link --print-out-paths | nix run nixpkgs#cachix -- push graphite-dev
|
||||
@@ -17,9 +17,10 @@ jobs:
|
||||
|
||||
- name: ❄ Install Nix
|
||||
uses: DeterminateSystems/nix-installer-action@main
|
||||
|
||||
- name: 💾 Set up Nix cache
|
||||
uses: DeterminateSystems/magic-nix-cache-action@main
|
||||
with:
|
||||
extra-conf: |
|
||||
extra-substituters = https://graphite.cachix.org https://graphite-dev.cachix.org
|
||||
extra-trusted-public-keys = graphite.cachix.org-1:B7Il1yMpkquN/dXM+5GRmz+4Xmu2aaCS1GcWNfFhsOo= graphite-dev.cachix.org-1:RppXYpiV1qO2TYKTkXXGHsAEQDOB5G51b3VlrN9QmbI=
|
||||
|
||||
- name: 🏗 Build graphene raster nodes shaders
|
||||
run: nix build .#graphite-raster-nodes-shaders && cp result raster_nodes_shaders_entrypoint.wgsl
|
||||
@@ -34,3 +35,11 @@ jobs:
|
||||
raster_nodes_shaders_entrypoint.wgsl \
|
||||
"${{ github.sha }} raster_nodes_shaders_entrypoint.wgsl" \
|
||||
${{ secrets.ARTIFACTS_REPO_TOKEN }}
|
||||
|
||||
- name: 📤 Push shaders to dev Nix cache
|
||||
env:
|
||||
NIX_CACHE_AUTH_TOKEN: ${{ secrets.NIX_CACHE_AUTH_TOKEN_DEV }}
|
||||
NIX_CACHE_NAME: graphite-dev
|
||||
run: |
|
||||
nix run nixpkgs#cachix -- authtoken $NIX_CACHE_AUTH_TOKEN
|
||||
nix build .#graphite-raster-nodes-shaders --no-link --print-out-paths | nix run nixpkgs#cachix -- push $NIX_CACHE_NAME
|
||||
@@ -12,3 +12,4 @@ flamegraph.svg
|
||||
.idea/
|
||||
.direnv
|
||||
.DS_Store
|
||||
.nvim.lua
|
||||
+3
-7
@@ -31,7 +31,6 @@ let
|
||||
|
||||
deps = {
|
||||
crane = lib.call ./deps/crane.nix;
|
||||
cef = lib.call ./deps/cef.nix;
|
||||
rustGPU = lib.call ./deps/rust-gpu.nix;
|
||||
};
|
||||
|
||||
@@ -60,15 +59,12 @@ in
|
||||
graphite-raster-nodes-shaders = lib.call ./pkgs/graphite-raster-nodes-shaders.nix;
|
||||
graphite-branding = lib.call ./pkgs/graphite-branding.nix;
|
||||
graphite-bundle = (lib.call ./pkgs/graphite-bundle.nix) { };
|
||||
graphite-dev-bundle = (lib.call ./pkgs/graphite-bundle.nix) { graphite = graphite-dev; };
|
||||
graphite-bundle-dev = (lib.call ./pkgs/graphite-bundle.nix) { graphite = graphite-dev; };
|
||||
graphite-flatpak-manifest = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { };
|
||||
graphite-dev-flatpak-manifest = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { graphite-bundle = graphite-dev-bundle; };
|
||||
graphite-flatpak-manifest-dev = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { graphite-bundle = graphite-bundle-dev; };
|
||||
graphite-cef = lib.call ./pkgs/graphite-cef.nix;
|
||||
|
||||
# TODO: graphene-cli = lib.call ./pkgs/graphene-cli.nix;
|
||||
|
||||
tools = {
|
||||
third-party-licenses = lib.call ./pkgs/tools/third-party-licenses.nix;
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
{ pkgs, ... }:
|
||||
|
||||
let
|
||||
cefPath = pkgs.cef-binary.overrideAttrs (finalAttrs: {
|
||||
postInstall = ''
|
||||
rm -r $out/* $out/.* || true
|
||||
strip ./Release/*.so*
|
||||
mv ./Release/* $out/
|
||||
find "./Resources/locales" -maxdepth 1 -type f ! -name 'en-US.pak' -delete
|
||||
mv ./Resources/* $out/
|
||||
mv ./include $out/
|
||||
|
||||
cat ./CREDITS.html | ${pkgs.xz}/bin/xz -9 -e -c > $out/CREDITS.html.xz
|
||||
|
||||
echo '${
|
||||
builtins.toJSON {
|
||||
type = "minimal";
|
||||
name = builtins.baseNameOf finalAttrs.src.url;
|
||||
sha1 = "";
|
||||
}
|
||||
}' > $out/archive.json
|
||||
'';
|
||||
});
|
||||
in
|
||||
{
|
||||
env.CEF_PATH = cefPath;
|
||||
}
|
||||
+25
-2
@@ -1,5 +1,28 @@
|
||||
{ pkgs, inputs, ... }:
|
||||
{
|
||||
pkgs,
|
||||
inputs,
|
||||
...
|
||||
}:
|
||||
|
||||
{
|
||||
lib = inputs.crane.mkLib pkgs;
|
||||
lib = (inputs.crane.mkLib pkgs) // {
|
||||
vendorCargoDepsFlatten =
|
||||
src:
|
||||
pkgs.stdenvNoCC.mkDerivation (finalAttrs: {
|
||||
name = "graphite-cargo-vendored";
|
||||
inherit src;
|
||||
|
||||
installPhase = ''
|
||||
cp -rL --no-preserve=mode "$src" "$out"
|
||||
chmod -R u+w "$out"
|
||||
find "$out" -type f -print0 | xargs -r -0 sed -i "s|$src|$out|g"
|
||||
'';
|
||||
|
||||
disallowedReferences = [ finalAttrs.src ];
|
||||
|
||||
dontUnpack = true;
|
||||
dontConfigure = true;
|
||||
dontBuild = true;
|
||||
});
|
||||
};
|
||||
}
|
||||
+14
-17
@@ -1,16 +1,15 @@
|
||||
{ pkgs, ... }:
|
||||
|
||||
let
|
||||
extensions = [
|
||||
"rust-src"
|
||||
"rust-analyzer"
|
||||
"clippy"
|
||||
"cargo"
|
||||
"rustc-dev"
|
||||
"llvm-tools"
|
||||
];
|
||||
toolchain = pkgs.rust-bin.nightly."2025-06-23".default.override {
|
||||
inherit extensions;
|
||||
toolchain = pkgs.rust-bin.nightly."2026-04-11".default.override {
|
||||
extensions = [
|
||||
"rust-src"
|
||||
"rust-analyzer"
|
||||
"clippy"
|
||||
"cargo"
|
||||
"rustc-dev"
|
||||
"llvm-tools"
|
||||
];
|
||||
};
|
||||
cargo = pkgs.writeShellScriptBin "cargo" ''
|
||||
#!${pkgs.lib.getExe pkgs.bash}
|
||||
@@ -32,14 +31,12 @@ let
|
||||
}).buildRustPackage
|
||||
(finalAttrs: {
|
||||
pname = "rustc_codegen_spirv";
|
||||
version = "0-unstable-2025-08-04";
|
||||
src = pkgs.fetchFromGitHub {
|
||||
owner = "Firestar99";
|
||||
repo = "rust-gpu-new";
|
||||
rev = "c12f216121820580731440ee79ebc7403d6ea04f";
|
||||
hash = "sha256-rG1cZvOV0vYb1dETOzzbJ0asYdE039UZImobXZfKIno=";
|
||||
version = "0.10.0-alpha.1";
|
||||
src = pkgs.fetchCrate {
|
||||
inherit (finalAttrs) pname version;
|
||||
sha256 = "sha256-zJEpExkPgYzwo7fR4ge4GxJNj7H5yo4bJ4eTOw36+7c=";
|
||||
};
|
||||
cargoHash = "sha256-AEigcEc5wiBd3zLqWN/2HSbkfOVFneAqNvg9HsouZf4=";
|
||||
cargoHash = "sha256-J1rtbfGqrL2NJ7Bu2pYfDwCdUmnECB/kzxrpYluA0kY=";
|
||||
cargoBuildFlags = [
|
||||
"-p"
|
||||
"rustc_codegen_spirv"
|
||||
|
||||
+10
-8
@@ -1,4 +1,10 @@
|
||||
{ pkgs, deps, ... }:
|
||||
{
|
||||
pkgs,
|
||||
deps,
|
||||
self,
|
||||
system,
|
||||
...
|
||||
}:
|
||||
|
||||
let
|
||||
libs = [
|
||||
@@ -22,9 +28,8 @@ pkgs.mkShell (
|
||||
|
||||
pkgs.lld
|
||||
pkgs.nodejs
|
||||
pkgs.nodePackages.npm
|
||||
pkgs.binaryen
|
||||
pkgs.wasm-bindgen-cli_0_2_100
|
||||
pkgs.wasm-bindgen-cli_0_2_121
|
||||
pkgs.wasm-pack
|
||||
pkgs.cargo-about
|
||||
|
||||
@@ -52,13 +57,10 @@ pkgs.mkShell (
|
||||
pkgs.graphviz
|
||||
];
|
||||
|
||||
LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libs}:${deps.cef.env.CEF_PATH}";
|
||||
CEF_PATH = self.packages.${system}.graphite-cef;
|
||||
LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libs}:${self.packages.${system}.graphite-cef}";
|
||||
XDG_DATA_DIRS = "${pkgs.gsettings-desktop-schemas}/share/gsettings-schemas/${pkgs.gsettings-desktop-schemas.name}:${pkgs.gtk3}/share/gsettings-schemas/${pkgs.gtk3.name}:$XDG_DATA_DIRS";
|
||||
|
||||
shellHook = ''
|
||||
alias cargo='mold --run cargo'
|
||||
'';
|
||||
}
|
||||
// deps.cef.env
|
||||
// deps.rustGPU.env
|
||||
)
|
||||
@@ -1,5 +1,6 @@
|
||||
{
|
||||
pkgs,
|
||||
deps,
|
||||
self,
|
||||
system,
|
||||
...
|
||||
@@ -33,7 +34,7 @@ let
|
||||
cp -r ${graphite}/share out/share
|
||||
mkdir -p out/lib/cef
|
||||
mkdir -p ./cef
|
||||
tar -xvf ${pkgs.cef-binary.src} -C ./cef --strip-components=1
|
||||
tar -xvf ${self.packages.${system}.graphite-cef.src} -C ./cef --strip-components=1
|
||||
cp -r ./cef/Release/* out/lib/cef/
|
||||
cp -r ./cef/Resources/* out/lib/cef/
|
||||
find "out/lib/cef/locales" -type f ! -name 'en-US*' -delete
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
{ 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=";
|
||||
};
|
||||
|
||||
selectSystem =
|
||||
attrs:
|
||||
attrs.${pkgs.stdenv.hostPlatform.system}
|
||||
or (throw "Unsupported system ${pkgs.stdenv.hostPlatform.system}");
|
||||
|
||||
src = pkgs.fetchurl {
|
||||
url = "https://cef-builds.spotifycdn.com/cef_binary_${version}_${
|
||||
selectSystem {
|
||||
aarch64-linux = "linuxarm64";
|
||||
x86_64-linux = "linux64";
|
||||
}
|
||||
}_minimal.tar.bz2";
|
||||
hash = selectSystem hashes;
|
||||
};
|
||||
in
|
||||
pkgs.cef-binary.overrideAttrs (finalAttrs: {
|
||||
version = builtins.head (builtins.split "\\+" version);
|
||||
inherit src;
|
||||
postInstall = ''
|
||||
rm -r $out/* $out/.* || true
|
||||
strip ./Release/*.so*
|
||||
mv ./Release/* $out/
|
||||
find "./Resources/locales" -maxdepth 1 -type f ! -name 'en-US.pak' -delete
|
||||
mv ./Resources/* $out/
|
||||
mv ./include $out/
|
||||
|
||||
cat ./CREDITS.html | ${pkgs.xz}/bin/xz -9 -e -c > $out/CREDITS.html.xz
|
||||
|
||||
echo '${
|
||||
builtins.toJSON {
|
||||
type = "minimal";
|
||||
name = builtins.baseNameOf finalAttrs.src.url;
|
||||
sha1 = "";
|
||||
}
|
||||
}' > $out/archive.json
|
||||
'';
|
||||
})
|
||||
@@ -1,16 +1,16 @@
|
||||
{ info, deps, ... }:
|
||||
{
|
||||
info,
|
||||
deps,
|
||||
self,
|
||||
system,
|
||||
...
|
||||
}:
|
||||
|
||||
(deps.crane.lib.overrideToolchain (_: deps.rustGPU.toolchain)).buildPackage {
|
||||
pname = "raster-nodes-shaders";
|
||||
pname = "graphite-raster-nodes-shaders";
|
||||
inherit (info) version src;
|
||||
|
||||
cargoVendorDir = deps.crane.lib.vendorMultipleCargoDeps {
|
||||
inherit (deps.crane.lib.findCargoFiles (deps.crane.lib.cleanCargoSource info.src)) cargoConfigs;
|
||||
cargoLockList = [
|
||||
"${info.src}/Cargo.lock"
|
||||
"${deps.rustGPU.toolchain.availableComponents.rust-src}/lib/rustlib/src/rust/library/Cargo.lock"
|
||||
];
|
||||
};
|
||||
inherit (self.packages.${system}.graphite) cargoVendorDir cargoArtifacts;
|
||||
|
||||
strictDeps = true;
|
||||
|
||||
|
||||
+80
-91
@@ -14,125 +14,107 @@
|
||||
|
||||
let
|
||||
branding = self.packages.${system}.graphite-branding;
|
||||
cargoVendorDir = deps.crane.lib.vendorCargoDeps { inherit (info) src; };
|
||||
resourcesCommon = {
|
||||
pname = "${info.pname}-resources";
|
||||
inherit (info) version src;
|
||||
inherit cargoVendorDir;
|
||||
strictDeps = true;
|
||||
nativeBuildInputs = [
|
||||
pkgs.pkg-config
|
||||
pkgs.lld
|
||||
pkgs.nodejs
|
||||
pkgs.nodePackages.npm
|
||||
pkgs.binaryen
|
||||
pkgs.wasm-bindgen-cli_0_2_100
|
||||
pkgs.wasm-pack
|
||||
pkgs.cargo-about
|
||||
];
|
||||
buildInputs = [ pkgs.openssl ];
|
||||
env.CARGO_PROFILE = if dev then "dev" else "release";
|
||||
cargoExtraArgs = "--target wasm32-unknown-unknown -p graphite-wasm-wrapper --no-default-features --features native";
|
||||
doCheck = false;
|
||||
};
|
||||
resources = deps.crane.lib.buildPackage (
|
||||
resourcesCommon
|
||||
// {
|
||||
cargoArtifacts = deps.crane.lib.buildDepsOnly resourcesCommon;
|
||||
|
||||
npmDeps = pkgs.importNpmLock {
|
||||
npmRoot = "${info.src}/frontend";
|
||||
};
|
||||
|
||||
npmRoot = "frontend";
|
||||
npmConfigScript = "setup";
|
||||
makeCacheWritable = true;
|
||||
|
||||
nativeBuildInputs = [
|
||||
pkgs.importNpmLock.npmConfigHook
|
||||
pkgs.removeReferencesTo
|
||||
]
|
||||
++ resourcesCommon.nativeBuildInputs;
|
||||
|
||||
prePatch = ''
|
||||
mkdir branding
|
||||
cp -r ${branding}/* branding
|
||||
cp ${info.src}/.branding branding/.branding
|
||||
'';
|
||||
|
||||
buildPhase = ''
|
||||
export HOME="$TMPDIR"
|
||||
|
||||
pushd frontend
|
||||
npm run native:build-${if dev then "dev" else "production"}
|
||||
popd
|
||||
'';
|
||||
|
||||
installPhase = ''
|
||||
mkdir -p $out
|
||||
cp -r frontend/dist/* $out/
|
||||
'';
|
||||
|
||||
postFixup = ''
|
||||
find "$out" -type f -exec remove-references-to -t "${cargoVendorDir}" '{}' +
|
||||
'';
|
||||
}
|
||||
);
|
||||
libs = [
|
||||
pkgs.wayland
|
||||
pkgs.vulkan-loader
|
||||
pkgs.libGL
|
||||
pkgs.openssl
|
||||
pkgs.libraw
|
||||
|
||||
# X11 Support
|
||||
pkgs.libxkbcommon
|
||||
pkgs.libXcursor
|
||||
pkgs.libxcb
|
||||
pkgs.libX11
|
||||
];
|
||||
|
||||
common = {
|
||||
inherit (info) pname version src;
|
||||
inherit cargoVendorDir;
|
||||
strictDeps = true;
|
||||
cargoVendorDir = deps.crane.lib.vendorCargoDepsFlatten (
|
||||
deps.crane.lib.vendorMultipleCargoDeps {
|
||||
inherit (deps.crane.lib.findCargoFiles (deps.crane.lib.cleanCargoSource info.src)) cargoConfigs;
|
||||
cargoLockList = [
|
||||
"${info.src}/Cargo.lock"
|
||||
"${deps.rustGPU.toolchain.availableComponents.rust-src}/lib/rustlib/src/rust/library/Cargo.lock"
|
||||
];
|
||||
}
|
||||
);
|
||||
buildInputs = libs;
|
||||
nativeBuildInputs = [
|
||||
pkgs.pkg-config
|
||||
pkgs.cargo-about
|
||||
pkgs.removeReferencesTo
|
||||
];
|
||||
env = deps.cef.env // {
|
||||
CARGO_PROFILE = if dev then "dev" else "release";
|
||||
};
|
||||
cargoExtraArgs = "-p graphite-desktop";
|
||||
strictDeps = true;
|
||||
doCheck = false;
|
||||
};
|
||||
|
||||
cargoArtifacts = deps.crane.lib.buildDepsOnly (
|
||||
common
|
||||
// {
|
||||
nativeBuildInputs = [
|
||||
pkgs.pkg-config
|
||||
pkgs.lld
|
||||
];
|
||||
env.CEF_PATH = self.packages.${system}.graphite-cef;
|
||||
buildPhase =
|
||||
let
|
||||
profile = if dev then "dev" else "release";
|
||||
in
|
||||
''
|
||||
cargo check --profile ${profile} --locked -p graphite-desktop-platform-linux
|
||||
cargo build --profile ${profile} --locked -p graphite-desktop-platform-linux
|
||||
|
||||
cargo check --profile ${profile} --target wasm32-unknown-unknown --locked -p graphite-wasm-wrapper --no-default-features --features native
|
||||
cargo build --profile ${profile} --target wasm32-unknown-unknown --locked -p graphite-wasm-wrapper --no-default-features --features native
|
||||
|
||||
cargo check --locked -p third-party-licenses --features desktop
|
||||
cargo build --locked -p third-party-licenses --features desktop
|
||||
|
||||
cargo check --profile ${profile} --locked -p graphite-desktop-bundle
|
||||
cargo build --profile ${profile} --locked -p graphite-desktop-bundle
|
||||
'';
|
||||
}
|
||||
);
|
||||
in
|
||||
|
||||
deps.crane.lib.buildPackage (
|
||||
common
|
||||
// {
|
||||
cargoArtifacts = deps.crane.lib.buildDepsOnly common;
|
||||
inherit cargoArtifacts;
|
||||
|
||||
env = common.env // {
|
||||
RASTER_NODES_SHADER_PATH = self.packages.${system}.graphite-raster-nodes-shaders;
|
||||
EMBEDDED_RESOURCES = resources;
|
||||
GRAPHITE_GIT_COMMIT_HASH = self.rev or "unknown";
|
||||
GRAPHITE_GIT_COMMIT_DATE = self.lastModified or "unknown";
|
||||
};
|
||||
buildInputs = libs;
|
||||
nativeBuildInputs = [
|
||||
pkgs.pkg-config
|
||||
pkgs.lld
|
||||
pkgs.nodejs
|
||||
pkgs.binaryen
|
||||
pkgs.wasm-bindgen-cli_0_2_121
|
||||
pkgs.wasm-pack
|
||||
pkgs.cargo-about
|
||||
pkgs.removeReferencesTo
|
||||
pkgs.importNpmLock.npmConfigHook
|
||||
];
|
||||
|
||||
npmDeps = pkgs.importNpmLock {
|
||||
npmRoot = "${info.src}/frontend";
|
||||
};
|
||||
npmRoot = "frontend";
|
||||
nativeBuildInputs = [
|
||||
pkgs.importNpmLock.npmConfigHook
|
||||
pkgs.nodePackages.npm
|
||||
]
|
||||
++ common.nativeBuildInputs;
|
||||
npmConfigScript = "setup";
|
||||
makeCacheWritable = true;
|
||||
|
||||
env = {
|
||||
RASTER_NODES_SHADER_PATH = self.packages.${system}.graphite-raster-nodes-shaders;
|
||||
GRAPHITE_GIT_COMMIT_HASH = self.rev or "unknown";
|
||||
GRAPHITE_GIT_COMMIT_DATE = self.lastModified or "unknown";
|
||||
CEF_PATH = self.packages.${system}.graphite-cef;
|
||||
};
|
||||
|
||||
postPatch = ''
|
||||
mkdir branding
|
||||
cp -r ${branding}/* branding
|
||||
cp ${info.src}/.branding branding/.branding
|
||||
'';
|
||||
|
||||
preBuild = ''
|
||||
${lib.getExe self.packages.${system}.tools.third-party-licenses}
|
||||
# Prevent `package-installer.js` from trying to update npm dependencies
|
||||
touch -r frontend/package-lock.json -d '+1 year' frontend/node_modules/.install-timestamp
|
||||
|
||||
export HOME="$TMPDIR"
|
||||
''
|
||||
+ (
|
||||
if self ? rev then
|
||||
@@ -143,6 +125,10 @@ deps.crane.lib.buildPackage (
|
||||
""
|
||||
);
|
||||
|
||||
buildPhaseCargoCommand = "cargo run build desktop${if dev then " debug" else ""}";
|
||||
|
||||
doNotPostBuildInstallCargoBinaries = true;
|
||||
|
||||
installPhase = ''
|
||||
mkdir -p $out/bin
|
||||
cp target/${if dev then "debug" else "release"}/graphite $out/bin/graphite
|
||||
@@ -161,12 +147,15 @@ deps.crane.lib.buildPackage (
|
||||
'';
|
||||
|
||||
postFixup = ''
|
||||
remove-references-to -t "${cargoVendorDir}" $out/bin/graphite
|
||||
remove-references-to -t "${common.cargoVendorDir}" $out/bin/graphite
|
||||
|
||||
patchelf \
|
||||
--set-rpath "${pkgs.lib.makeLibraryPath libs}:${deps.cef.env.CEF_PATH}" \
|
||||
--set-rpath "${pkgs.lib.makeLibraryPath libs}:${self.packages.${system}.graphite-cef}" \
|
||||
--add-needed libGL.so \
|
||||
--add-needed libEGL.so \
|
||||
$out/bin/graphite
|
||||
'';
|
||||
|
||||
passthru.deps = cargoArtifacts;
|
||||
}
|
||||
)
|
||||
@@ -1,31 +0,0 @@
|
||||
{
|
||||
info,
|
||||
deps,
|
||||
pkgs,
|
||||
...
|
||||
}:
|
||||
|
||||
let
|
||||
cargoVendorDir = deps.crane.lib.vendorCargoDeps { inherit (info) src; };
|
||||
common = {
|
||||
pname = "third-party-licenses";
|
||||
inherit (info) version src;
|
||||
inherit cargoVendorDir;
|
||||
nativeBuildInputs = [ pkgs.pkg-config ];
|
||||
buildInputs = [ pkgs.openssl ];
|
||||
strictDeps = true;
|
||||
env = deps.cef.env // {
|
||||
CARGO_PROFILE = "dev";
|
||||
};
|
||||
cargoExtraArgs = "-p third-party-licenses --features desktop";
|
||||
doCheck = false;
|
||||
};
|
||||
in
|
||||
deps.crane.lib.buildPackage (
|
||||
common
|
||||
// {
|
||||
inherit cargoVendorDir;
|
||||
cargoArtifacts = deps.crane.lib.buildDepsOnly common;
|
||||
meta.mainProgram = "third-party-licenses";
|
||||
}
|
||||
)
|
||||
Vendored
+2
-1
@@ -70,5 +70,6 @@
|
||||
"*.graphite": "json"
|
||||
},
|
||||
"editor.renderWhitespace": "boundary",
|
||||
"editor.minimap.markSectionHeaderRegex": "// ===+\\n\\s*//\\s*(?<label>[^\\n]{1,18})[^\\n]*(\\n\\s*//[^\\n]*)*\\n\\s*// ===+"
|
||||
"editor.minimap.markSectionHeaderRegex": "// ===+\\n\\s*//\\s*(?<label>[^\\n]{1,18})[^\\n]*(\\n\\s*//[^\\n]*)*\\n\\s*// ===+",
|
||||
"git.addAICoAuthor": "off"
|
||||
}
|
||||
Generated
+689
-1046
File diff suppressed because it is too large.
Load diff
+27
-18
@@ -11,6 +11,7 @@ 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",
|
||||
@@ -63,6 +64,7 @@ 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" }
|
||||
@@ -89,6 +91,8 @@ interpreted-executor = { path = "node-graph/interpreted-executor" }
|
||||
node-macro = { path = "node-graph/node-macro" }
|
||||
wgpu-executor = { path = "node-graph/libraries/wgpu-executor" }
|
||||
graphite-proc-macros = { path = "proc-macros" }
|
||||
graphite-editor = { path = "editor" }
|
||||
graphene-canvas-utils = { path = "node-graph/libraries/canvas-utils" }
|
||||
|
||||
# Workspace dependencies
|
||||
rustc-hash = "2.0"
|
||||
@@ -104,6 +108,9 @@ 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"
|
||||
@@ -113,17 +120,17 @@ quote = "1.0"
|
||||
chrono = "0.4"
|
||||
ron = "0.12"
|
||||
fastnoise-lite = "1.1"
|
||||
wgpu = { version = "27.0", features = [
|
||||
wgpu = { version = "29.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.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 = "=0.2.121" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned across CI workflows, devcontainer, Nix, and the `cargo-run` tool. We pin this version because wasm-bindgen upgrades may break various things.
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "=0.3.77"
|
||||
web-sys = { version = "=0.3.77", features = [
|
||||
js-sys = "=0.3.98"
|
||||
web-sys = { version = "=0.3.98", features = [
|
||||
"Document",
|
||||
"DomRect",
|
||||
"Element",
|
||||
@@ -147,17 +154,18 @@ 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.7"
|
||||
vello_encoding = "0.7"
|
||||
vello = "0.9"
|
||||
vello_encoding = "0.9"
|
||||
resvg = "0.47"
|
||||
usvg = "0.47"
|
||||
parley = "0.6"
|
||||
skrifa = "0.40"
|
||||
parley = { version = "0.9", default-features = false, features = ["std"] }
|
||||
skrifa = "0.42"
|
||||
polycool = "0.4"
|
||||
color = "0.3"
|
||||
# Linebender ecosystem (END)
|
||||
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
|
||||
rand_chacha = "0.9"
|
||||
glam = { version = "0.29", default-features = false, features = [
|
||||
glam = { version = "0.32.1", default-features = false, features = [
|
||||
"nostd-libm",
|
||||
"scalar-math",
|
||||
"bytemuck",
|
||||
@@ -191,26 +199,27 @@ 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"] }
|
||||
iai-callgrind = { version = "0.16" }
|
||||
gungraun = { version = "0.18" }
|
||||
ndarray = "0.16"
|
||||
strum = { version = "0.27", features = ["derive"] }
|
||||
dirs = "6.0"
|
||||
cef = "142"
|
||||
cef-dll-sys = "142"
|
||||
cef = "148"
|
||||
cef-dll-sys = "148"
|
||||
include_dir = "0.7"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
tracing = "0.1"
|
||||
rfd = "0.15"
|
||||
rfd = "0.17"
|
||||
open = "5.3"
|
||||
spin = "0.10"
|
||||
clap = "4.5"
|
||||
spirv-std = { git = "https://github.com/Firestar99/rust-gpu-new", rev = "c12f216121820580731440ee79ebc7403d6ea04f", features = ["bytemuck"] }
|
||||
cargo-gpu = { git = "https://github.com/Firestar99/cargo-gpu", rev = "3952a22d16edbd38689f3a876e417899f21e1fe7", default-features = false }
|
||||
spirv-std = { version = "0.10.0-alpha.1", features = ["bytemuck"] }
|
||||
cargo-gpu-install = { version = "0.10.0-alpha.1", default-features = false }
|
||||
qrcodegen = "1.8"
|
||||
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
|
||||
scraper = "0.25"
|
||||
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"))'] }
|
||||
@@ -236,6 +245,6 @@ debug = true
|
||||
[patch.crates-io]
|
||||
# Force cargo to use only one version of the dpi crate (vendoring breaks without this)
|
||||
dpi = { git = "https://github.com/rust-windowing/winit.git" }
|
||||
download-cef = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite" }
|
||||
vello = { git = "https://github.com/Keavon/vello.git", branch = "0.7.0-fix-images-rendering-blurry" }
|
||||
vello_encoding = { git = "https://github.com/Keavon/vello.git", branch = "0.7.0-fix-images-rendering-blurry" }
|
||||
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,4 +1,5 @@
|
||||
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":[[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
|
||||
{"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
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"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
|
||||
{"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
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"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
|
||||
{"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
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"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
|
||||
{"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
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"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":[[11731553664207576737,{"inputs":[{"Node":{"node_id":757876048866560520,"output_index":0}},{"Value":{"tagged_value":{"F64":48.900000000000006},"exposed":false}},{"Node":{"node_id":7828034197076821310,"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::JitterPointsNode"}},"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":""}}],[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":""}}],[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_node_id":[null]}},"exposed":false}},{"Value":{"tagged_valueLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.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
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"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
|
||||
{"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
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"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
|
||||
{"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
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"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
|
||||
{"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
|
||||
@@ -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 `iai-callgrind`
|
||||
"RUSTSEC-2025-0141", # Unmaintained `bincode`, pulled in by dev dependency `gungraun`
|
||||
]
|
||||
# Threshold for security vulnerabilities, any vulnerability with a CVSS score
|
||||
# lower than the range specified will be ignored. Note that ignored advisories
|
||||
@@ -63,6 +63,7 @@ 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,6 +48,7 @@ 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,6 +13,9 @@ 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)?;
|
||||
@@ -73,7 +76,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: ICONS_FILE_NAME.to_string(),
|
||||
cf_bundle_icon_file: if is_helper { None } else { Some(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(),
|
||||
@@ -85,6 +88,8 @@ 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");
|
||||
@@ -92,6 +97,47 @@ 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")]
|
||||
@@ -103,7 +149,8 @@ struct InfoPlist {
|
||||
#[serde(rename = "CFBundleExecutable")]
|
||||
cf_bundle_executable: String,
|
||||
#[serde(rename = "CFBundleIconFile")]
|
||||
cf_bundle_icon_file: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
cf_bundle_icon_file: Option<String>,
|
||||
#[serde(rename = "CFBundleInfoDictionaryVersion")]
|
||||
cf_bundle_info_dictionary_version: String,
|
||||
#[serde(rename = "CFBundlePackageType")]
|
||||
@@ -123,7 +170,53 @@ 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,
|
||||
}
|
||||
+78
-84
@@ -2,6 +2,7 @@ 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};
|
||||
@@ -14,10 +15,9 @@ 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::PersistentData;
|
||||
use crate::persist;
|
||||
use crate::preferences;
|
||||
use crate::render::{RenderError, RenderState};
|
||||
use crate::window::Window;
|
||||
@@ -45,10 +45,8 @@ pub(crate) struct App {
|
||||
start_render_sender: SyncSender<()>,
|
||||
web_communication_initialized: bool,
|
||||
web_communication_startup_buffer: Vec<Vec<u8>>,
|
||||
persistent_data: PersistentData,
|
||||
#[cfg_attr(not(target_os = "macos"), expect(unused))]
|
||||
preferences: Preferences,
|
||||
cli: Cli,
|
||||
launch_documents: Option<Vec<PathBuf>>,
|
||||
startup_time: Option<Instant>,
|
||||
exiting: Arc<AtomicBool>,
|
||||
exit_reason: ExitReason,
|
||||
@@ -59,6 +57,7 @@ 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>,
|
||||
@@ -66,7 +65,7 @@ impl App {
|
||||
app_event_receiver: Receiver<AppEvent>,
|
||||
app_event_scheduler: AppEventScheduler,
|
||||
preferences: Preferences,
|
||||
cli: Cli,
|
||||
launch_documents: Vec<PathBuf>,
|
||||
) -> Self {
|
||||
let ctrlc_app_event_scheduler = app_event_scheduler.clone();
|
||||
ctrlc::set_handler(move || {
|
||||
@@ -92,9 +91,6 @@ impl App {
|
||||
}
|
||||
});
|
||||
|
||||
let mut persistent_data = PersistentData::default();
|
||||
persistent_data.load_from_disk();
|
||||
|
||||
let desktop_wrapper = DesktopWrapper::new(rand::rng().random());
|
||||
|
||||
Self {
|
||||
@@ -118,9 +114,8 @@ impl App {
|
||||
start_render_sender,
|
||||
web_communication_initialized: false,
|
||||
web_communication_startup_buffer: Vec::new(),
|
||||
persistent_data,
|
||||
preferences,
|
||||
cli,
|
||||
launch_documents: Some(launch_documents),
|
||||
startup_time: None,
|
||||
exiting,
|
||||
exit_reason: ExitReason::Shutdown,
|
||||
@@ -202,7 +197,7 @@ impl App {
|
||||
};
|
||||
self.send_or_queue_web_message(bytes);
|
||||
}
|
||||
DesktopFrontendMessage::OpenFileDialog { title, filters, context } => {
|
||||
DesktopFrontendMessage::OpenFileDialog { title, filters, multiple, context } => {
|
||||
let app_event_scheduler = self.app_event_scheduler.clone();
|
||||
let _ = thread::spawn(move || {
|
||||
let mut dialog = AsyncFileDialog::new().set_title(title);
|
||||
@@ -210,13 +205,21 @@ impl App {
|
||||
dialog = dialog.add_filter(filter.name, &filter.extensions);
|
||||
}
|
||||
|
||||
let show_dialog = async move { dialog.pick_file().await.map(|f| f.path().to_path_buf()) };
|
||||
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()
|
||||
};
|
||||
|
||||
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));
|
||||
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),
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -246,6 +249,12 @@ 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);
|
||||
}
|
||||
@@ -284,17 +293,24 @@ impl App {
|
||||
window.request_redraw();
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::PersistenceWriteDocument { id, document } => {
|
||||
self.persistent_data.write_document(id, document);
|
||||
DesktopFrontendMessage::PersistenceWriteState { state } => {
|
||||
persist::write_state(state);
|
||||
}
|
||||
DesktopFrontendMessage::PersistenceReadState => {
|
||||
responses.push(DesktopWrapperMessage::LoadPersistedState { state: persist::read_state() });
|
||||
}
|
||||
DesktopFrontendMessage::PersistenceReadDocument { id } => {
|
||||
if let Some(document) = persist::read_document_content(&id) {
|
||||
responses.push(DesktopWrapperMessage::LoadDocumentContent { id, document });
|
||||
} else {
|
||||
tracing::error!("Failed to read document content for {id:?}");
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::PersistenceWriteDocument { id, document_serialized_content } => {
|
||||
persist::write_document_content(id, document_serialized_content);
|
||||
}
|
||||
DesktopFrontendMessage::PersistenceDeleteDocument { id } => {
|
||||
self.persistent_data.delete_document(&id);
|
||||
}
|
||||
DesktopFrontendMessage::PersistenceUpdateCurrentDocument { id } => {
|
||||
self.persistent_data.set_current_document(id);
|
||||
}
|
||||
DesktopFrontendMessage::PersistenceUpdateDocumentsList { ids } => {
|
||||
self.persistent_data.set_document_order(ids);
|
||||
persist::delete_document(&id);
|
||||
}
|
||||
DesktopFrontendMessage::PersistenceWritePreferences { preferences } => {
|
||||
preferences::write(preferences);
|
||||
@@ -304,58 +320,12 @@ impl App {
|
||||
let message = DesktopWrapperMessage::LoadPreferences { preferences };
|
||||
responses.push(message);
|
||||
}
|
||||
DesktopFrontendMessage::PersistenceLoadCurrentDocument => {
|
||||
if let Some((id, document)) = self.persistent_data.current_document() {
|
||||
let message = DesktopWrapperMessage::LoadDocument {
|
||||
id,
|
||||
document,
|
||||
to_front: false,
|
||||
select_after_open: true,
|
||||
};
|
||||
responses.push(message);
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::PersistenceLoadRemainingDocuments => {
|
||||
for (id, document) in self.persistent_data.documents_before_current().into_iter().rev() {
|
||||
let message = DesktopWrapperMessage::LoadDocument {
|
||||
id,
|
||||
document,
|
||||
to_front: true,
|
||||
select_after_open: false,
|
||||
};
|
||||
responses.push(message);
|
||||
}
|
||||
for (id, document) in self.persistent_data.documents_after_current() {
|
||||
let message = DesktopWrapperMessage::LoadDocument {
|
||||
id,
|
||||
document,
|
||||
to_front: false,
|
||||
select_after_open: false,
|
||||
};
|
||||
responses.push(message);
|
||||
}
|
||||
if let Some(id) = self.persistent_data.current_document_id() {
|
||||
let message = DesktopWrapperMessage::SelectDocument { id };
|
||||
responses.push(message);
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::OpenLaunchDocuments => {
|
||||
if self.cli.files.is_empty() {
|
||||
let Some(launch_documents) = std::mem::take(&mut self.launch_documents) else {
|
||||
tracing::error!("OpenLaunchDocuments should only be sent once");
|
||||
return;
|
||||
}
|
||||
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());
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
self.app_event_scheduler.schedule(AppEvent::OpenFiles(launch_documents));
|
||||
}
|
||||
DesktopFrontendMessage::UpdateMenu { entries } => {
|
||||
if let Some(window) = &self.window {
|
||||
@@ -403,6 +373,11 @@ 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();
|
||||
@@ -508,6 +483,29 @@ 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 });
|
||||
@@ -590,20 +588,16 @@ impl ApplicationHandler for App {
|
||||
Err(RenderError::OutdatedUITextureError) => {
|
||||
self.cef_context.notify_view_info_changed();
|
||||
}
|
||||
Err(RenderError::SurfaceError(wgpu::SurfaceError::Lost)) => {
|
||||
Err(RenderError::SurfaceLost) => {
|
||||
tracing::warn!("lost surface");
|
||||
}
|
||||
Err(RenderError::SurfaceError(wgpu::SurfaceError::OutOfMemory)) => {
|
||||
tracing::error!("GPU out of memory");
|
||||
self.exit(None);
|
||||
}
|
||||
Err(RenderError::SurfaceError(e)) => tracing::error!("Render error: {:?}", e),
|
||||
Err(other) => tracing::error!("Render error: {:?}", other),
|
||||
}
|
||||
let _ = self.start_render_sender.try_send(());
|
||||
}
|
||||
|
||||
if !self.cef_init_successful
|
||||
&& !self.cli.disable_ui_acceleration
|
||||
&& !self.preferences.disable_ui_acceleration
|
||||
&& self.web_communication_initialized
|
||||
&& let Some(startup_time) = self.startup_time
|
||||
&& startup_time.elapsed() > Duration::from_secs(3)
|
||||
|
||||
@@ -27,7 +27,6 @@ use crate::wrapper::{WgpuContext, deserialize_editor_message};
|
||||
|
||||
mod consts;
|
||||
mod context;
|
||||
mod dirs;
|
||||
mod input;
|
||||
mod internal;
|
||||
mod ipc;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use graphite_desktop_wrapper::DOUBLE_CLICK_MILLISECONDS;
|
||||
use std::time::Duration;
|
||||
|
||||
pub(crate) const RESOURCE_SCHEME: &str = "resources";
|
||||
@@ -18,5 +19,5 @@ pub(crate) const SCROLL_SPEED_Y: f32 = 1.0;
|
||||
|
||||
pub(crate) const PINCH_ZOOM_SPEED: f64 = 300.0;
|
||||
|
||||
pub(crate) const MULTICLICK_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
pub(crate) const MULTICLICK_TIMEOUT: Duration = Duration::from_millis(DOUBLE_CLICK_MILLISECONDS);
|
||||
pub(crate) const MULTICLICK_ALLOWED_TRAVEL: usize = 4;
|
||||
@@ -4,15 +4,15 @@ use cef::{
|
||||
App, BrowserSettings, CefString, Client, DictionaryValue, ImplCommandLine, ImplRequestContext, LogSeverity, RequestContextSettings, SchemeHandlerFactory, Settings, WindowInfo, api_hash,
|
||||
browser_host_create_browser_sync, execute_process,
|
||||
};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::Path;
|
||||
|
||||
use super::CefContext;
|
||||
use super::singlethreaded::SingleThreadedCefContext;
|
||||
use crate::cef::CefEventHandler;
|
||||
use crate::cef::consts::{RESOURCE_DOMAIN, RESOURCE_SCHEME};
|
||||
use crate::cef::dirs::{create_instance_dir, delete_instance_dirs};
|
||||
use crate::cef::input::InputState;
|
||||
use crate::cef::internal::{BrowserProcessAppImpl, BrowserProcessClientImpl, RenderProcessAppImpl, SchemeHandlerFactoryImpl};
|
||||
use crate::dirs::TempDir;
|
||||
|
||||
pub(crate) struct CefContextBuilder<H: CefEventHandler> {
|
||||
pub(crate) args: Args,
|
||||
@@ -24,14 +24,13 @@ unsafe impl<H: CefEventHandler> Send for CefContextBuilder<H> {}
|
||||
|
||||
impl<H: CefEventHandler> CefContextBuilder<H> {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self::new_inner(false)
|
||||
Self::new_impl(false)
|
||||
}
|
||||
|
||||
pub(crate) fn new_helper() -> Self {
|
||||
Self::new_inner(true)
|
||||
Self::new_impl(true)
|
||||
}
|
||||
|
||||
fn new_inner(helper: bool) -> Self {
|
||||
fn new_impl(helper: bool) -> Self {
|
||||
#[cfg(target_os = "macos")]
|
||||
let _loader = {
|
||||
let loader = cef::library_loader::LibraryLoader::new(&std::env::current_exe().unwrap(), helper);
|
||||
@@ -42,12 +41,8 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
|
||||
let _ = helper;
|
||||
|
||||
let _ = api_hash(CEF_API_VERSION_LAST, 0);
|
||||
|
||||
let args = Args::new();
|
||||
let cmd = args.as_cmd_line().unwrap();
|
||||
let switch = CefString::from("type");
|
||||
let is_sub_process = cmd.has_switch(Some(&switch)) == 1;
|
||||
|
||||
let is_sub_process = args.as_cmd_line().unwrap().has_switch(Some(&"type".into())) == 1;
|
||||
Self {
|
||||
args,
|
||||
is_sub_process,
|
||||
@@ -61,8 +56,7 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
|
||||
|
||||
pub(crate) fn execute_sub_process(&self) -> SetupError {
|
||||
let cmd = self.args.as_cmd_line().unwrap();
|
||||
let switch = CefString::from("type");
|
||||
let process_type = CefString::from(&cmd.switch_value(Some(&switch)));
|
||||
let process_type = CefString::from(&cmd.switch_value(Some(&"type".into())));
|
||||
let mut app = RenderProcessAppImpl::<H>::app();
|
||||
let ret = execute_process(Some(self.args.as_main_args()), Some(&mut app), std::ptr::null_mut());
|
||||
if ret >= 0 {
|
||||
@@ -72,105 +66,96 @@ 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: CefString::from(""),
|
||||
disable_signal_handlers: 1,
|
||||
log_severity,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) fn initialize(self, event_handler: H, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
|
||||
delete_instance_dirs();
|
||||
let instance_dir = create_instance_dir();
|
||||
|
||||
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: CefString::from(app_root.to_str().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)
|
||||
};
|
||||
|
||||
self.initialize_inner(&event_handler, settings)?;
|
||||
|
||||
create_browser(event_handler, instance_dir, disable_gpu_acceleration)
|
||||
pub(crate) fn create(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)
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub(crate) fn initialize(self, event_handler: H, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
|
||||
delete_instance_dirs();
|
||||
let instance_dir = create_instance_dir();
|
||||
|
||||
let settings = Settings {
|
||||
multi_threaded_message_loop: 1,
|
||||
#[cfg(target_os = "linux")]
|
||||
no_sandbox: 1,
|
||||
..Self::common_settings(&instance_dir)
|
||||
};
|
||||
|
||||
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);
|
||||
}
|
||||
pub(crate) fn create(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),
|
||||
});
|
||||
|
||||
Ok(super::multithreaded::MultiThreadedCefContextProxy)
|
||||
}
|
||||
|
||||
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());
|
||||
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());
|
||||
if result != 1 {
|
||||
let cef_exit_code = cef::get_exit_code() as u32;
|
||||
return Err(InitError::InitializationFailureCode(cef_exit_code));
|
||||
return Err(InitError::InitializationFailureCode(cef::get_exit_code() as u32));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: PathBuf, disable_gpu_acceleration: bool) -> Result<SingleThreadedCefContext, InitError> {
|
||||
let mut client = Client::new(BrowserProcessClientImpl::new(&event_handler));
|
||||
|
||||
fn accelerated_paint(disable_gpu_acceleration: bool) -> bool {
|
||||
#[cfg(feature = "accelerated_paint")]
|
||||
let use_accelerated_paint = if disable_gpu_acceleration {
|
||||
{
|
||||
!disable_gpu_acceleration && crate::cef::platform::should_enable_hardware_acceleration()
|
||||
}
|
||||
#[cfg(not(feature = "accelerated_paint"))]
|
||||
{
|
||||
let _ = disable_gpu_acceleration;
|
||||
false
|
||||
} else {
|
||||
crate::cef::platform::should_enable_hardware_acceleration()
|
||||
}
|
||||
}
|
||||
|
||||
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> {
|
||||
let mut client = Client::new(BrowserProcessClientImpl::new(&event_handler));
|
||||
|
||||
let window_info = WindowInfo {
|
||||
windowless_rendering_enabled: 1,
|
||||
#[cfg(feature = "accelerated_paint")]
|
||||
shared_texture_enabled: use_accelerated_paint as i32,
|
||||
shared_texture_enabled: accelerated_paint as i32,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
@@ -183,7 +168,7 @@ fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: PathBuf, d
|
||||
let Some(mut incognito_request_context) = cef::request_context_create_context(
|
||||
Some(&RequestContextSettings {
|
||||
persist_session_cookies: 0,
|
||||
cache_path: CefString::from(""),
|
||||
cache_path: "".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
Option::<&mut cef::RequestContextHandler>::None,
|
||||
@@ -193,30 +178,27 @@ fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: PathBuf, d
|
||||
|
||||
let mut scheme_handler_factory = SchemeHandlerFactory::new(SchemeHandlerFactoryImpl::new(event_handler.duplicate()));
|
||||
incognito_request_context.clear_scheme_handler_factories();
|
||||
incognito_request_context.register_scheme_handler_factory(Some(&CefString::from(RESOURCE_SCHEME)), Some(&CefString::from(RESOURCE_DOMAIN)), Some(&mut scheme_handler_factory));
|
||||
incognito_request_context.register_scheme_handler_factory(Some(&RESOURCE_SCHEME.into()), Some(&RESOURCE_DOMAIN.into()), Some(&mut scheme_handler_factory));
|
||||
|
||||
let url = CefString::from(format!("{RESOURCE_SCHEME}://{RESOURCE_DOMAIN}/").as_str());
|
||||
|
||||
let browser = browser_host_create_browser_sync(
|
||||
let url = format!("{RESOURCE_SCHEME}://{RESOURCE_DOMAIN}/");
|
||||
browser_host_create_browser_sync(
|
||||
Some(&window_info),
|
||||
Some(&mut client),
|
||||
Some(&url),
|
||||
Some(&url.as_str().into()),
|
||||
Some(&settings),
|
||||
Option::<&mut DictionaryValue>::None,
|
||||
Some(&mut incognito_request_context),
|
||||
);
|
||||
|
||||
if let Some(browser) = browser {
|
||||
Ok(SingleThreadedCefContext {
|
||||
event_handler: Box::new(event_handler),
|
||||
browser,
|
||||
input_state: InputState::default(),
|
||||
instance_dir,
|
||||
})
|
||||
} else {
|
||||
)
|
||||
.map(|browser| SingleThreadedCefContext {
|
||||
event_handler: Box::new(event_handler),
|
||||
browser,
|
||||
input_state: InputState::default(),
|
||||
_instance_dir: instance_dir,
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
tracing::error!("Failed to create browser");
|
||||
Err(InitError::BrowserCreationFailed)
|
||||
}
|
||||
InitError::BrowserCreationFailed
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
|
||||
@@ -54,7 +54,12 @@ impl CefContext for MultiThreadedCefContextProxy {
|
||||
impl Drop for MultiThreadedCefContextProxy {
|
||||
fn drop(&mut self) {
|
||||
// Force dropping underlying context on the UI thread
|
||||
run_on_ui_thread(move || drop(CONTEXT.take()));
|
||||
let (sync_drop_tx, sync_drop_rx) = std::sync::mpsc::channel();
|
||||
run_on_ui_thread(move || {
|
||||
drop(CONTEXT.take());
|
||||
let _ = sync_drop_tx.send(());
|
||||
});
|
||||
let _ = sync_drop_rx.recv();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ use winit::event::WindowEvent;
|
||||
use crate::cef::input::InputState;
|
||||
use crate::cef::ipc::{MessageType, SendMessage};
|
||||
use crate::cef::{CefEventHandler, input};
|
||||
use crate::dirs::TempDir;
|
||||
|
||||
use super::CefContext;
|
||||
|
||||
@@ -11,7 +12,7 @@ pub(super) struct SingleThreadedCefContext {
|
||||
pub(super) event_handler: Box<dyn CefEventHandler>,
|
||||
pub(super) browser: Browser,
|
||||
pub(super) input_state: InputState,
|
||||
pub(super) instance_dir: std::path::PathBuf,
|
||||
pub(super) _instance_dir: TempDir,
|
||||
}
|
||||
|
||||
impl CefContext for SingleThreadedCefContext {
|
||||
@@ -46,19 +47,6 @@ impl Drop for SingleThreadedCefContext {
|
||||
// CEF wants us to close the browser before shutting down, otherwise it may run longer that necessary.
|
||||
self.browser.host().unwrap().close_browser(1);
|
||||
cef::shutdown();
|
||||
|
||||
// Sometimes some CEF processes still linger at this point and hold file handles to the cache directory.
|
||||
// To mitigate this, we try to remove the directory multiple times with some delay.
|
||||
// TODO: find a better solution if possible.
|
||||
for _ in 0..30 {
|
||||
match std::fs::remove_dir_all(&self.instance_dir) {
|
||||
Ok(_) => break,
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to remove CEF cache directory, retrying...: {e}");
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,7 +56,6 @@ impl SendMessage for SingleThreadedCefContext {
|
||||
tracing::error!("Main frame is not available, cannot send message");
|
||||
return;
|
||||
};
|
||||
|
||||
frame.send_message(message_type, message);
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::dirs::{app_data_dir, ensure_dir_exists};
|
||||
|
||||
static CEF_DIR_NAME: &str = "browser";
|
||||
|
||||
pub(crate) fn delete_instance_dirs() {
|
||||
let cef_dir = app_data_dir().join(CEF_DIR_NAME);
|
||||
if let Ok(entries) = std::fs::read_dir(&cef_dir) {
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn create_instance_dir() -> PathBuf {
|
||||
let instance_id: String = (0..32).map(|_| format!("{:x}", rand::random::<u8>() % 16)).collect();
|
||||
let path = app_data_dir().join(CEF_DIR_NAME).join(instance_id);
|
||||
ensure_dir_exists(&path);
|
||||
path
|
||||
}
|
||||
@@ -6,7 +6,7 @@ mod keymap;
|
||||
use keymap::{ToCharRepresentation, ToNativeKeycode, ToVKBits};
|
||||
|
||||
mod state;
|
||||
pub(crate) use state::{CefModifiers, ClickCount, InputState};
|
||||
pub(crate) use state::{CefModifiers, InputState};
|
||||
|
||||
use super::consts::{PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
|
||||
|
||||
@@ -36,11 +36,7 @@ pub(crate) fn handle_window_event(browser: &Browser, input_state: &mut InputStat
|
||||
}
|
||||
};
|
||||
|
||||
let click_count = input_state.mouse_input(mouse_button, state);
|
||||
if matches!(click_count, ClickCount::Ignore) {
|
||||
return;
|
||||
}
|
||||
let cef_click_count = click_count.into();
|
||||
let cef_click_count = input_state.mouse_input(mouse_button, state).into();
|
||||
let cef_mouse_up = match state {
|
||||
ElementState::Pressed => 0,
|
||||
ElementState::Released => 1,
|
||||
|
||||
@@ -173,10 +173,6 @@ impl ClickTracker {
|
||||
}
|
||||
}
|
||||
|
||||
if matches!(state, ElementState::Released) && record.down_count != record.up_count {
|
||||
return ClickCount::Ignore;
|
||||
}
|
||||
|
||||
count
|
||||
}
|
||||
}
|
||||
@@ -187,7 +183,6 @@ pub(crate) enum ClickCount {
|
||||
Single,
|
||||
Double,
|
||||
Triple,
|
||||
Ignore,
|
||||
}
|
||||
impl From<ClickCount> for i32 {
|
||||
fn from(count: ClickCount) -> i32 {
|
||||
@@ -195,7 +190,6 @@ impl From<ClickCount> for i32 {
|
||||
ClickCount::Single => 1,
|
||||
ClickCount::Double => 2,
|
||||
ClickCount::Triple => 3,
|
||||
ClickCount::Ignore => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
#[cfg(target_os = "linux")]
|
||||
use std::env;
|
||||
|
||||
use cef::rc::{Rc, RcImpl};
|
||||
use cef::sys::{_cef_app_t, cef_base_ref_counted_t};
|
||||
use cef::{BrowserProcessHandler, CefString, ImplApp, ImplCommandLine, SchemeRegistrar, WrapApp};
|
||||
@@ -12,12 +9,14 @@ 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) -> Self {
|
||||
pub(crate) fn new(event_handler: H, accelerated_paint: bool) -> Self {
|
||||
Self {
|
||||
object: std::ptr::null_mut(),
|
||||
event_handler,
|
||||
accelerated_paint,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,81 +32,75 @@ impl<H: CefEventHandler> ImplApp for BrowserProcessAppImpl<H> {
|
||||
|
||||
fn on_before_command_line_processing(&self, _process_type: Option<&cef::CefString>, command_line: Option<&mut cef::CommandLine>) {
|
||||
if let Some(cmd) = command_line {
|
||||
cmd.append_switch_with_value(Some(&CefString::from("renderer-process-limit")), Some(&CefString::from("1")));
|
||||
cmd.append_switch_with_value(Some(&CefString::from("password-store")), Some(&CefString::from("basic")));
|
||||
cmd.append_switch_with_value(Some(&CefString::from("disk-cache-size")), Some(&CefString::from("0")));
|
||||
cmd.append_switch(Some(&CefString::from("incognito")));
|
||||
cmd.append_switch(Some(&CefString::from("no-first-run")));
|
||||
cmd.append_switch(Some(&CefString::from("no-default-browser-check")));
|
||||
cmd.append_switch(Some(&CefString::from("disable-component-update")));
|
||||
cmd.append_switch(Some(&CefString::from("disable-geolocation")));
|
||||
cmd.append_switch(Some(&CefString::from("disable-notifications")));
|
||||
cmd.append_switch(Some(&CefString::from("disable-audio-input")));
|
||||
cmd.append_switch(Some(&CefString::from("disable-audio-output")));
|
||||
cmd.append_switch(Some(&CefString::from("disable-sync")));
|
||||
cmd.append_switch(Some(&CefString::from("disable-file-system")));
|
||||
cmd.append_switch(Some(&CefString::from("disable-local-storage")));
|
||||
cmd.append_switch(Some(&CefString::from("disable-background-networking")));
|
||||
cmd.append_switch(Some(&CefString::from("disable-default-apps")));
|
||||
cmd.append_switch(Some(&CefString::from("disable-breakpad")));
|
||||
cmd.append_switch_with_value(Some(&CefString::from("disable-blink-features")), Some(&CefString::from("WebBluetooth,WebUSB,Serial")));
|
||||
cmd.append_switch_with_value(Some(&"renderer-process-limit".into()), Some(&"1".into()));
|
||||
cmd.append_switch_with_value(Some(&"password-store".into()), Some(&"basic".into()));
|
||||
cmd.append_switch_with_value(Some(&"disk-cache-size".into()), Some(&"0".into()));
|
||||
cmd.append_switch(Some(&"no-sandbox".into()));
|
||||
cmd.append_switch(Some(&"no-first-run".into()));
|
||||
cmd.append_switch(Some(&"noerrdialogs".into()));
|
||||
cmd.append_switch(Some(&"no-default-browser-check".into()));
|
||||
cmd.append_switch(Some(&"mute-audio".into()));
|
||||
cmd.append_switch(Some(&"use-fake-device-for-media-stream".into()));
|
||||
cmd.append_switch(Some(&"incognito".into()));
|
||||
cmd.append_switch(Some(&"disable-sync".into()));
|
||||
cmd.append_switch(Some(&"disable-file-system".into()));
|
||||
cmd.append_switch(Some(&"disable-component-update".into()));
|
||||
cmd.append_switch(Some(&"disable-geolocation".into()));
|
||||
cmd.append_switch(Some(&"disable-notifications".into()));
|
||||
cmd.append_switch(Some(&"disable-background-networking".into()));
|
||||
cmd.append_switch(Some(&"disable-default-apps".into()));
|
||||
cmd.append_switch(Some(&"disable-breakpad".into()));
|
||||
cmd.append_switch_with_value(Some(&"disable-blink-features".into()), Some(&"WebBluetooth,WebUSB,Serial".into()));
|
||||
|
||||
let extra_disabled_features = ["OptimizationHints", "OnDeviceModelService", "TranslateUI"];
|
||||
let disabled_features_switch = Some(&CefString::from("disable-features"));
|
||||
let disabled_features: String = CefString::from(&cmd.switch_value(disabled_features_switch))
|
||||
let disabled_features_switch = Some(&"disable-features".into());
|
||||
let mut disabled_features: Vec<String> = CefString::from(&cmd.switch_value(disabled_features_switch))
|
||||
.to_string()
|
||||
.split(',')
|
||||
.chain(extra_disabled_features)
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
cmd.append_switch_with_value(disabled_features_switch, Some(&CefString::from(disabled_features.as_str())));
|
||||
.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()));
|
||||
|
||||
#[cfg(not(feature = "accelerated_paint"))]
|
||||
{
|
||||
// Disable GPU acceleration when accelerated_paint feature is not enabled
|
||||
cmd.append_switch(Some(&CefString::from("disable-gpu")));
|
||||
cmd.append_switch(Some(&CefString::from("disable-gpu-compositing")));
|
||||
}
|
||||
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(feature = "accelerated_paint")]
|
||||
{
|
||||
// Enable GPU acceleration switches for better performance
|
||||
cmd.append_switch(Some(&CefString::from("enable-gpu-rasterization")));
|
||||
cmd.append_switch(Some(&CefString::from("enable-accelerated-2d-canvas")));
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
cmd.append_switch_with_value(Some(&"use-angle".into()), Some(&"gl-egl".into()));
|
||||
|
||||
#[cfg(all(feature = "accelerated_paint", target_os = "linux"))]
|
||||
{
|
||||
// Use Vulkan for accelerated painting
|
||||
cmd.append_switch_with_value(Some(&CefString::from("use-angle")), Some(&CefString::from("vulkan")));
|
||||
}
|
||||
|
||||
// Tell CEF to use Wayland if available
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let use_wayland = env::var("WAYLAND_DISPLAY")
|
||||
.ok()
|
||||
.filter(|var| !var.is_empty())
|
||||
.or_else(|| env::var("WAYLAND_SOCKET").ok())
|
||||
.filter(|var| !var.is_empty())
|
||||
.is_some();
|
||||
if use_wayland {
|
||||
cmd.append_switch_with_value(Some(&CefString::from("ozone-platform")), Some(&CefString::from("wayland")));
|
||||
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 {
|
||||
cmd.append_switch(Some(&"disable-gpu".into()));
|
||||
cmd.append_switch(Some(&"disable-gpu-compositing".into()));
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
// Hide user prompt asking for keychain access
|
||||
cmd.append_switch(Some(&CefString::from("use-mock-keychain")));
|
||||
cmd.append_switch(Some(&"use-mock-keychain".into()));
|
||||
}
|
||||
|
||||
// Enable browser debugging via environment variable
|
||||
if let Some(env) = std::env::var("GRAPHITE_BROWSER_DEBUG_PORT").ok()
|
||||
&& let Some(port) = env.parse::<u16>().ok()
|
||||
{
|
||||
cmd.append_switch_with_value(Some(&CefString::from("remote-debugging-port")), Some(&CefString::from(port.to_string().as_str())));
|
||||
cmd.append_switch_with_value(Some(&CefString::from("remote-allow-origins")), Some(&CefString::from("*")));
|
||||
cmd.append_switch_with_value(Some(&"remote-debugging-port".into()), Some(&port.to_string().as_str().into()));
|
||||
cmd.append_switch_with_value(Some(&"remote-allow-origins".into()), Some(&"*".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -126,6 +119,7 @@ impl<H: CefEventHandler> Clone for BrowserProcessAppImpl<H> {
|
||||
Self {
|
||||
object: self.object,
|
||||
event_handler: self.event_handler.duplicate(),
|
||||
accelerated_paint: self.accelerated_paint,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use cef::rc::{ConvertReturnValue, Rc, RcImpl};
|
||||
use cef::sys::{_cef_render_process_handler_t, cef_base_ref_counted_t, cef_render_process_handler_t, cef_v8_propertyattribute_t, cef_v8_value_create_array_buffer_with_copy};
|
||||
use cef::{CefString, ImplFrame, ImplRenderProcessHandler, ImplV8Context, ImplV8Value, V8Handler, V8Propertyattribute, V8Value, WrapRenderProcessHandler, v8_value_create_function};
|
||||
use cef::{ImplFrame, ImplRenderProcessHandler, ImplV8Context, ImplV8Value, V8Handler, V8Propertyattribute, V8Value, WrapRenderProcessHandler, v8_value_create_function};
|
||||
|
||||
use crate::cef::ipc::{MessageType, UnpackMessage, UnpackedMessage};
|
||||
|
||||
@@ -52,14 +52,10 @@ impl ImplRenderProcessHandler for RenderProcessHandlerImpl {
|
||||
|
||||
let function_call = format!("window.{function_name}(window.{property_name})");
|
||||
|
||||
global.set_value_bykey(
|
||||
Some(&CefString::from(property_name)),
|
||||
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(&CefString::from(function_name))).is_some() {
|
||||
frame.execute_java_script(Some(&CefString::from(function_call.as_str())), None, 0);
|
||||
if global.value_bykey(Some(&function_name.into())).is_some() {
|
||||
frame.execute_java_script(Some(&function_call.as_str().into()), None, 0);
|
||||
}
|
||||
|
||||
if context.exit() == 0 {
|
||||
@@ -78,7 +74,7 @@ impl ImplRenderProcessHandler for RenderProcessHandlerImpl {
|
||||
fn on_context_created(&self, _browser: Option<&mut cef::Browser>, _frame: Option<&mut cef::Frame>, context: Option<&mut cef::V8Context>) {
|
||||
let register_js_function = |context: &mut cef::V8Context, name: &'static str| {
|
||||
let mut v8_handler = V8Handler::new(RenderProcessV8HandlerImpl::new());
|
||||
let Some(mut function) = v8_value_create_function(Some(&CefString::from(name)), Some(&mut v8_handler)) else {
|
||||
let Some(mut function) = v8_value_create_function(Some(&name.into()), Some(&mut v8_handler)) else {
|
||||
tracing::error!("Failed to create V8 function {name}");
|
||||
return;
|
||||
};
|
||||
@@ -87,7 +83,7 @@ impl ImplRenderProcessHandler for RenderProcessHandlerImpl {
|
||||
tracing::error!("Global object is not available in V8 context");
|
||||
return;
|
||||
};
|
||||
global.set_value_bykey(Some(&CefString::from(name)), Some(&mut function), V8Propertyattribute::default());
|
||||
global.set_value_bykey(Some(&name.into()), Some(&mut function), V8Propertyattribute::default());
|
||||
};
|
||||
|
||||
let Some(context) = context else {
|
||||
|
||||
@@ -46,15 +46,14 @@ impl ImplResourceHandler for ResourceHandlerImpl {
|
||||
if let Some(response) = response {
|
||||
if self.reader.is_some() {
|
||||
if let Some(mimetype) = &self.mimetype {
|
||||
let cef_mime = CefString::from(mimetype.as_str());
|
||||
response.set_mime_type(Some(&cef_mime));
|
||||
response.set_mime_type(Some(&mimetype.as_str().into()));
|
||||
} else {
|
||||
response.set_mime_type(None);
|
||||
}
|
||||
response.set_status(200);
|
||||
} else {
|
||||
response.set_status(404);
|
||||
response.set_mime_type(Some(&CefString::from("text/plain")));
|
||||
response.set_mime_type(Some(&"text/plain".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ impl<H: CefEventHandler> SchemeHandlerFactoryImpl<H> {
|
||||
scheme_options |= cef_scheme_options_t::CEF_SCHEME_OPTION_FETCH_ENABLED as i32;
|
||||
scheme_options |= cef_scheme_options_t::CEF_SCHEME_OPTION_SECURE as i32;
|
||||
scheme_options |= cef_scheme_options_t::CEF_SCHEME_OPTION_CORS_ENABLED as i32;
|
||||
registrar.add_custom_scheme(Some(&CefString::from(RESOURCE_SCHEME)), scheme_options);
|
||||
registrar.add_custom_scheme(Some(&RESOURCE_SCHEME.into()), scheme_options);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use cef::{CefString, Frame, ImplBinaryValue, ImplFrame, ImplListValue, ImplProcessMessage, ImplV8Context, ProcessId, V8Context, sys::cef_process_id_t};
|
||||
use cef::{Frame, ImplBinaryValue, ImplFrame, ImplListValue, ImplProcessMessage, ImplV8Context, ProcessId, V8Context, sys::cef_process_id_t};
|
||||
|
||||
pub(crate) enum MessageType {
|
||||
Initialized,
|
||||
@@ -67,7 +67,7 @@ impl SendMessage for Frame {
|
||||
fn send_message(&self, message_type: MessageType, message: &[u8]) {
|
||||
let MessageInfo { name, target } = message_type.into();
|
||||
|
||||
let Some(mut process_message) = cef::process_message_create(Some(&CefString::from(name.as_str()))) else {
|
||||
let Some(mut process_message) = cef::process_message_create(Some(&name.as_str().into())) else {
|
||||
tracing::error!("Failed to create process message: {}", name);
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -7,6 +7,7 @@ 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";
|
||||
|
||||
+75
-3
@@ -1,11 +1,31 @@
|
||||
use std::fs::create_dir_all;
|
||||
use std::path::PathBuf;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::consts::{APP_DIRECTORY_NAME, APP_DOCUMENTS_DIRECTORY_NAME};
|
||||
|
||||
pub(crate) fn ensure_dir_exists(path: &PathBuf) {
|
||||
if !path.exists() {
|
||||
create_dir_all(path).unwrap_or_else(|_| panic!("Failed to create directory at {path:?}"));
|
||||
fs::create_dir_all(path).unwrap_or_else(|_| panic!("Failed to create directory at {path:?}"));
|
||||
}
|
||||
}
|
||||
|
||||
fn clear_dir(path: &PathBuf) {
|
||||
let Ok(entries) = fs::read_dir(path) else {
|
||||
tracing::error!("Failed to read directory at {path:?}");
|
||||
return;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let entry_path = entry.path();
|
||||
if entry_path.is_dir() {
|
||||
if let Err(e) = fs::remove_dir_all(&entry_path) {
|
||||
tracing::error!("Failed to remove directory at {:?}: {}", entry_path, e);
|
||||
}
|
||||
} else if entry_path.is_file() {
|
||||
if let Err(e) = fs::remove_file(&entry_path) {
|
||||
tracing::error!("Failed to remove file at {:?}: {}", entry_path, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,8 +35,60 @@ pub(crate) fn app_data_dir() -> PathBuf {
|
||||
path
|
||||
}
|
||||
|
||||
fn app_tmp_dir() -> PathBuf {
|
||||
let path = std::env::temp_dir().join(APP_DIRECTORY_NAME);
|
||||
ensure_dir_exists(&path);
|
||||
path
|
||||
}
|
||||
|
||||
pub(crate) fn app_tmp_dir_cleanup() {
|
||||
clear_dir(&app_tmp_dir());
|
||||
}
|
||||
|
||||
pub(crate) fn app_autosave_documents_dir() -> PathBuf {
|
||||
let path = app_data_dir().join(APP_DOCUMENTS_DIRECTORY_NAME);
|
||||
ensure_dir_exists(&path);
|
||||
path
|
||||
}
|
||||
|
||||
/// Temporary directory that is automatically deleted when dropped.
|
||||
pub struct TempDir {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TempDir {
|
||||
pub fn new() -> io::Result<Self> {
|
||||
Self::new_with_parent(app_tmp_dir())
|
||||
}
|
||||
|
||||
pub fn new_with_parent(parent: impl AsRef<Path>) -> io::Result<Self> {
|
||||
let random_suffix = format!("{:032x}", rand::random::<u128>());
|
||||
let name = format!("{}_{}", std::process::id(), random_suffix);
|
||||
let path = parent.as_ref().join(name);
|
||||
fs::create_dir_all(&path)?;
|
||||
Ok(Self { path })
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let result = fs::remove_dir_all(&self.path);
|
||||
if let Err(e) = result {
|
||||
tracing::error!("Failed to remove temporary directory at {:?}: {}", self.path, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<Path> for TempDir {
|
||||
fn as_ref(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory
|
||||
pub(crate) fn delete_old_cef_browser_directory() {
|
||||
let old_browser_dir = crate::dirs::app_data_dir().join("browser");
|
||||
if old_browser_dir.is_dir() {
|
||||
let _ = std::fs::remove_dir_all(&old_browser_dir);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ pub(crate) enum AppEvent {
|
||||
DesktopWrapperMessage(DesktopWrapperMessage),
|
||||
NodeGraphExecutionResult(NodeGraphExecutionResult),
|
||||
Exit,
|
||||
OpenFiles(Vec<std::path::PathBuf>),
|
||||
#[cfg(target_os = "macos")]
|
||||
MenuEvent {
|
||||
id: String,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::wrapper::{WgpuContext, WgpuContextBuilder, WgpuFeatures};
|
||||
|
||||
pub(super) async fn create_wgpu_context() -> WgpuContext {
|
||||
let wgpu_context_builder = WgpuContextBuilder::new().with_features(WgpuFeatures::PUSH_CONSTANTS);
|
||||
let wgpu_context_builder = WgpuContextBuilder::new().with_features(WgpuFeatures::IMMEDIATES);
|
||||
|
||||
// TODO: add a cli flag to list adapters and exit instead of always printing
|
||||
println!("\nAvailable WGPU adapters:\n{}", wgpu_context_builder.available_adapters_fmt().await);
|
||||
|
||||
+22
-6
@@ -19,6 +19,7 @@ mod gpu_context;
|
||||
mod persist;
|
||||
mod preferences;
|
||||
mod render;
|
||||
mod socket;
|
||||
mod window;
|
||||
|
||||
pub(crate) mod consts;
|
||||
@@ -58,11 +59,22 @@ pub fn start() {
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::error!("Another instance is already running, Exiting.");
|
||||
std::process::exit(1);
|
||||
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;
|
||||
}
|
||||
};
|
||||
|
||||
let prefs = preferences::read();
|
||||
dirs::app_tmp_dir_cleanup();
|
||||
|
||||
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory
|
||||
dirs::delete_old_cef_browser_directory();
|
||||
|
||||
let mut prefs = preferences::read();
|
||||
|
||||
// Must be called before event loop initialization or native window integrations will break
|
||||
App::init();
|
||||
@@ -73,15 +85,19 @@ 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();
|
||||
|
||||
let disable_ui_acceleration = prefs.disable_ui_acceleration || cli.disable_ui_acceleration;
|
||||
if disable_ui_acceleration {
|
||||
if cli.disable_ui_acceleration {
|
||||
prefs.disable_ui_acceleration = true;
|
||||
}
|
||||
if prefs.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.initialize(cef_handler, disable_ui_acceleration) {
|
||||
let cef_context = match cef_context_builder.create(cef_handler, prefs.disable_ui_acceleration) {
|
||||
Ok(context) => {
|
||||
tracing::info!("CEF initialized successfully");
|
||||
context
|
||||
@@ -97,7 +113,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);
|
||||
let app = App::new(Box::new(cef_context), cef_view_info_sender, wgpu_context, app_event_receiver, app_event_scheduler, prefs, cli.files);
|
||||
|
||||
let exit_reason = app.run(event_loop);
|
||||
|
||||
|
||||
+73
-173
@@ -1,192 +1,92 @@
|
||||
use crate::wrapper::messages::{Document, DocumentId};
|
||||
use crate::wrapper::messages::{DocumentId, PersistedState};
|
||||
|
||||
#[derive(Default, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) struct PersistentData {
|
||||
documents: DocumentStore,
|
||||
current_document: Option<DocumentId>,
|
||||
#[serde(skip)]
|
||||
document_order: Option<Vec<DocumentId>>,
|
||||
pub(crate) fn read_state() -> PersistedState {
|
||||
let path = state_file_path();
|
||||
let data = match std::fs::read_to_string(&path) {
|
||||
Ok(d) => d,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
tracing::info!("No persistent data file found at {path:?}, starting fresh");
|
||||
return PersistedState::default();
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to read persistent data from disk: {e}");
|
||||
return PersistedState::default();
|
||||
}
|
||||
};
|
||||
let loaded = match ron::from_str(&data) {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to deserialize persistent data: {e}");
|
||||
return PersistedState::default();
|
||||
}
|
||||
};
|
||||
|
||||
garbage_collect_document_files(&loaded);
|
||||
loaded
|
||||
}
|
||||
|
||||
impl PersistentData {
|
||||
pub(crate) fn write_document(&mut self, id: DocumentId, document: Document) {
|
||||
self.documents.write(id, document);
|
||||
if let Some(order) = &self.document_order {
|
||||
self.documents.force_order(order);
|
||||
pub(crate) fn write_state(state: PersistedState) {
|
||||
let state: &PersistedState = &state;
|
||||
let data = match ron::ser::to_string_pretty(state, Default::default()) {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to serialize persistent data: {e}");
|
||||
return;
|
||||
}
|
||||
self.flush();
|
||||
};
|
||||
if let Err(e) = std::fs::write(state_file_path(), data) {
|
||||
tracing::error!("Failed to write persistent data to disk: {e}");
|
||||
}
|
||||
garbage_collect_document_files(state);
|
||||
}
|
||||
|
||||
pub(crate) fn delete_document(&mut self, id: &DocumentId) {
|
||||
if Some(*id) == self.current_document {
|
||||
self.current_document = None;
|
||||
}
|
||||
self.documents.delete(id);
|
||||
self.flush();
|
||||
}
|
||||
|
||||
pub(crate) fn current_document_id(&self) -> Option<DocumentId> {
|
||||
match self.current_document {
|
||||
Some(id) => Some(id),
|
||||
None => Some(*self.documents.document_ids().first()?),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn current_document(&self) -> Option<(DocumentId, Document)> {
|
||||
let current_id = self.current_document_id()?;
|
||||
Some((current_id, self.documents.read(¤t_id)?))
|
||||
}
|
||||
|
||||
pub(crate) fn documents_before_current(&self) -> Vec<(DocumentId, Document)> {
|
||||
let Some(current_id) = self.current_document_id() else {
|
||||
return Vec::new();
|
||||
};
|
||||
self.documents
|
||||
.document_ids()
|
||||
.into_iter()
|
||||
.take_while(|id| *id != current_id)
|
||||
.filter_map(|id| Some((id, self.documents.read(&id)?)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn documents_after_current(&self) -> Vec<(DocumentId, Document)> {
|
||||
let Some(current_id) = self.current_document_id() else {
|
||||
return Vec::new();
|
||||
};
|
||||
self.documents
|
||||
.document_ids()
|
||||
.into_iter()
|
||||
.skip_while(|id| *id != current_id)
|
||||
.skip(1)
|
||||
.filter_map(|id| Some((id, self.documents.read(&id)?)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn set_current_document(&mut self, id: DocumentId) {
|
||||
self.current_document = Some(id);
|
||||
self.flush();
|
||||
}
|
||||
|
||||
pub(crate) fn set_document_order(&mut self, order: Vec<DocumentId>) {
|
||||
self.document_order = Some(order);
|
||||
self.flush();
|
||||
}
|
||||
|
||||
fn flush(&self) {
|
||||
let data = match ron::ser::to_string_pretty(self, Default::default()) {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to serialize persistent data: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Err(e) = std::fs::write(Self::state_file_path(), data) {
|
||||
tracing::error!("Failed to write persistent data to disk: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn load_from_disk(&mut self) {
|
||||
let path = Self::state_file_path();
|
||||
let data = match std::fs::read_to_string(&path) {
|
||||
Ok(d) => d,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
tracing::info!("No persistent data file found at {path:?}, starting fresh");
|
||||
return;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to read persistent data from disk: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let loaded = match ron::from_str(&data) {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to deserialize persistent data: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
*self = loaded;
|
||||
}
|
||||
|
||||
fn state_file_path() -> std::path::PathBuf {
|
||||
let mut path = crate::dirs::app_data_dir();
|
||||
path.push(crate::consts::APP_STATE_FILE_NAME);
|
||||
path
|
||||
pub(crate) fn write_document_content(id: DocumentId, document_content: String) {
|
||||
if let Err(e) = std::fs::write(document_content_path(&id), document_content) {
|
||||
tracing::error!("Failed to write document {id:?} to disk: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, serde::Serialize, serde::Deserialize)]
|
||||
struct DocumentStore(Vec<DocumentInfo>);
|
||||
impl DocumentStore {
|
||||
fn write(&mut self, id: DocumentId, document: Document) {
|
||||
let meta = DocumentInfo::new(id, &document);
|
||||
if let Some(existing) = self.0.iter_mut().find(|meta| meta.id == id) {
|
||||
*existing = meta;
|
||||
} else {
|
||||
self.0.push(meta);
|
||||
}
|
||||
if let Err(e) = std::fs::write(Self::document_path(&id), document.content) {
|
||||
tracing::error!("Failed to write document {id:?} to disk: {e}");
|
||||
}
|
||||
}
|
||||
pub(crate) fn read_document_content(id: &DocumentId) -> Option<String> {
|
||||
std::fs::read_to_string(document_content_path(id)).ok()
|
||||
}
|
||||
|
||||
fn delete(&mut self, id: &DocumentId) {
|
||||
self.0.retain(|meta| meta.id != *id);
|
||||
if let Err(e) = std::fs::remove_file(Self::document_path(id)) {
|
||||
tracing::error!("Failed to delete document {id:?} from disk: {e}");
|
||||
pub(crate) fn delete_document(id: &DocumentId) {
|
||||
if let Err(e) = std::fs::remove_file(document_content_path(id)) {
|
||||
tracing::error!("Failed to delete document {id:?} from disk: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
fn garbage_collect_document_files(state: &PersistedState) {
|
||||
let valid_paths: std::collections::HashSet<_> = state.documents.iter().map(|doc| document_content_path(&doc.id)).collect();
|
||||
|
||||
let directory = crate::dirs::app_autosave_documents_dir();
|
||||
let entries = match std::fs::read_dir(&directory) {
|
||||
Ok(entries) => entries,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to read autosave documents directory: {e}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
fn read(&self, id: &DocumentId) -> Option<Document> {
|
||||
let meta = self.0.iter().find(|meta| meta.id == *id)?;
|
||||
let content = std::fs::read_to_string(Self::document_path(id)).ok()?;
|
||||
Some(Document {
|
||||
content,
|
||||
name: meta.name.clone(),
|
||||
path: meta.path.clone(),
|
||||
is_saved: meta.is_saved,
|
||||
})
|
||||
}
|
||||
|
||||
fn force_order(&mut self, desired_order: &Vec<DocumentId>) {
|
||||
let mut ordered_prefix_len = 0;
|
||||
for id in desired_order {
|
||||
if let Some(offset) = self.0[ordered_prefix_len..].iter().position(|meta| meta.id == *id) {
|
||||
let found_index = ordered_prefix_len + offset;
|
||||
if found_index != ordered_prefix_len {
|
||||
self.0[ordered_prefix_len..=found_index].rotate_right(1);
|
||||
}
|
||||
ordered_prefix_len += 1;
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_file() && !valid_paths.contains(&path) {
|
||||
if let Err(e) = std::fs::remove_file(&path) {
|
||||
tracing::error!("Failed to remove orphaned document file {path:?}: {e}");
|
||||
}
|
||||
}
|
||||
self.0.truncate(ordered_prefix_len);
|
||||
}
|
||||
|
||||
fn document_ids(&self) -> Vec<DocumentId> {
|
||||
self.0.iter().map(|meta| meta.id).collect()
|
||||
}
|
||||
|
||||
fn document_path(id: &DocumentId) -> std::path::PathBuf {
|
||||
let mut path = crate::dirs::app_autosave_documents_dir();
|
||||
path.push(format!("{:x}.{}", id.0, graphite_desktop_wrapper::FILE_EXTENSION));
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
struct DocumentInfo {
|
||||
id: DocumentId,
|
||||
name: String,
|
||||
path: Option<std::path::PathBuf>,
|
||||
is_saved: bool,
|
||||
fn state_file_path() -> std::path::PathBuf {
|
||||
let mut path = crate::dirs::app_data_dir();
|
||||
path.push(crate::consts::APP_STATE_FILE_NAME);
|
||||
path
|
||||
}
|
||||
impl DocumentInfo {
|
||||
fn new(id: DocumentId, Document { name, path, is_saved, .. }: &Document) -> Self {
|
||||
Self {
|
||||
id,
|
||||
name: name.clone(),
|
||||
path: path.clone(),
|
||||
is_saved: *is_saved,
|
||||
}
|
||||
}
|
||||
|
||||
fn document_content_path(id: &DocumentId) -> std::path::PathBuf {
|
||||
let mut path = crate::dirs::app_autosave_documents_dir();
|
||||
path.push(format!("{:x}.{}", id.0, graphite_desktop_wrapper::FILE_EXTENSION));
|
||||
path
|
||||
}
|
||||
@@ -26,14 +26,14 @@ fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
|
||||
// FRAGMENT SHADER
|
||||
// ===============
|
||||
|
||||
struct Constants {
|
||||
struct Immediates {
|
||||
viewport_scale: vec2<f32>,
|
||||
viewport_offset: vec2<f32>,
|
||||
ui_scale: vec2<f32>,
|
||||
background_color: vec4<f32>,
|
||||
};
|
||||
|
||||
var<push_constant> constants: Constants;
|
||||
var<immediate> immediates: Immediates;
|
||||
|
||||
@group(0) @binding(0)
|
||||
var t_viewport: texture_2d<f32>;
|
||||
@@ -46,10 +46,10 @@ var s_diffuse: sampler;
|
||||
|
||||
@fragment
|
||||
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
let ui_coordinate = in.tex_coords * constants.ui_scale;
|
||||
let ui_coordinate = in.tex_coords * immediates.ui_scale;
|
||||
if (ui_coordinate.x < 0.0 || ui_coordinate.x > 1.0 ||
|
||||
ui_coordinate.y < 0.0 || ui_coordinate.y > 1.0) {
|
||||
return srgb_to_linear(constants.background_color);
|
||||
return srgb_to_linear(immediates.background_color);
|
||||
}
|
||||
|
||||
let ui_linear = srgb_to_linear(textureSample(t_ui, s_diffuse, ui_coordinate));
|
||||
@@ -60,19 +60,19 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
// UI texture is premultiplied, we need to unpremultiply before blending
|
||||
let ui_srgb = linear_to_srgb(unpremultiply(ui_linear));
|
||||
|
||||
let viewport_coordinate = (in.tex_coords - constants.viewport_offset) * constants.viewport_scale;
|
||||
let viewport_coordinate = (in.tex_coords - immediates.viewport_offset) * immediates.viewport_scale;
|
||||
if (viewport_coordinate.x < 0.0 || viewport_coordinate.x > 1.0 ||
|
||||
viewport_coordinate.y < 0.0 || viewport_coordinate.y > 1.0) {
|
||||
return srgb_to_linear(constants.background_color);
|
||||
return srgb_to_linear(immediates.background_color);
|
||||
}
|
||||
|
||||
let overlay_srgb = textureSample(t_overlays, s_diffuse, viewport_coordinate);
|
||||
var viewport_srgb = textureSample(t_viewport, s_diffuse, viewport_coordinate);
|
||||
|
||||
if (viewport_srgb.a < 0.001) {
|
||||
viewport_srgb = constants.background_color;
|
||||
viewport_srgb = immediates.background_color;
|
||||
} else if (viewport_srgb.a < 0.999) {
|
||||
viewport_srgb = blend(viewport_srgb, constants.background_color);
|
||||
viewport_srgb = blend(viewport_srgb, immediates.background_color);
|
||||
}
|
||||
|
||||
if (overlay_srgb.a < 0.001) {
|
||||
|
||||
+42
-26
@@ -1,8 +1,7 @@
|
||||
use std::borrow::Cow;
|
||||
use wgpu::PresentMode;
|
||||
|
||||
use crate::window::Window;
|
||||
use crate::wrapper::{TargetTexture, WgpuContext, WgpuExecutor};
|
||||
use crate::wrapper::{WgpuContext, WgpuExecutor};
|
||||
|
||||
#[derive(derivative::Derivative)]
|
||||
#[derivative(Debug)]
|
||||
@@ -19,7 +18,7 @@ pub(crate) struct RenderState {
|
||||
viewport_scale: [f32; 2],
|
||||
viewport_offset: [f32; 2],
|
||||
viewport_texture: Option<std::sync::Arc<wgpu::Texture>>,
|
||||
overlays_texture: Option<TargetTexture>,
|
||||
overlays_texture: Option<std::sync::Arc<wgpu::Texture>>,
|
||||
ui_texture: Option<wgpu::Texture>,
|
||||
bind_group: Option<wgpu::BindGroup>,
|
||||
#[derivative(Debug = "ignore")]
|
||||
@@ -73,7 +72,7 @@ impl RenderState {
|
||||
address_mode_w: wgpu::AddressMode::ClampToEdge,
|
||||
mag_filter: wgpu::FilterMode::Linear,
|
||||
min_filter: wgpu::FilterMode::Nearest,
|
||||
mipmap_filter: wgpu::FilterMode::Nearest,
|
||||
mipmap_filter: wgpu::MipmapFilterMode::Nearest,
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
@@ -121,11 +120,8 @@ impl RenderState {
|
||||
|
||||
let render_pipeline_layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Render Pipeline Layout"),
|
||||
bind_group_layouts: &[&texture_bind_group_layout],
|
||||
push_constant_ranges: &[wgpu::PushConstantRange {
|
||||
stages: wgpu::ShaderStages::FRAGMENT,
|
||||
range: 0..size_of::<Constants>() as u32,
|
||||
}],
|
||||
bind_group_layouts: &[Some(&texture_bind_group_layout)],
|
||||
immediate_size: size_of::<Immediates>() as u32,
|
||||
});
|
||||
|
||||
let render_pipeline = context.device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
@@ -162,7 +158,7 @@ impl RenderState {
|
||||
mask: !0,
|
||||
alpha_to_coverage_enabled: false,
|
||||
},
|
||||
multiview: None,
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
|
||||
@@ -236,11 +232,17 @@ 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_to_target_texture(&scene, size, &Default::default(), None, &mut self.overlays_texture));
|
||||
if let Err(e) = result {
|
||||
tracing::error!("Error rendering overlays: {:?}", e);
|
||||
return;
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
self.update_bindgroup();
|
||||
}
|
||||
|
||||
@@ -260,7 +262,17 @@ impl RenderState {
|
||||
self.render_overlays(scene);
|
||||
}
|
||||
|
||||
let output = self.surface.get_current_texture().map_err(RenderError::SurfaceError)?;
|
||||
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 view = output.texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
@@ -281,13 +293,13 @@ impl RenderState {
|
||||
depth_stencil_attachment: None,
|
||||
occlusion_query_set: None,
|
||||
timestamp_writes: None,
|
||||
multiview_mask: None,
|
||||
});
|
||||
|
||||
render_pass.set_pipeline(&self.render_pipeline);
|
||||
render_pass.set_push_constants(
|
||||
wgpu::ShaderStages::FRAGMENT,
|
||||
render_pass.set_immediates(
|
||||
0,
|
||||
bytemuck::bytes_of(&Constants {
|
||||
bytemuck::bytes_of(&Immediates {
|
||||
viewport_scale: self.viewport_scale,
|
||||
viewport_offset: self.viewport_offset,
|
||||
ui_scale: ui_scale.unwrap_or([1., 1.]),
|
||||
@@ -306,6 +318,10 @@ 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);
|
||||
}
|
||||
@@ -317,11 +333,7 @@ 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()
|
||||
.map(|target| Cow::Borrowed(target.view()))
|
||||
.unwrap_or_else(|| Cow::Owned(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 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 {
|
||||
@@ -333,7 +345,7 @@ impl RenderState {
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::TextureView(overlays_texture_view.as_ref()),
|
||||
resource: wgpu::BindingResource::TextureView(&overlays_texture_view),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
@@ -351,14 +363,18 @@ impl RenderState {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum RenderError {
|
||||
OutdatedUITextureError,
|
||||
SurfaceError(wgpu::SurfaceError),
|
||||
SurfaceLost,
|
||||
SurfaceOutdated,
|
||||
SurfaceTimeout,
|
||||
SurfaceValidation,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
struct Constants {
|
||||
struct Immediates {
|
||||
viewport_scale: [f32; 2],
|
||||
viewport_offset: [f32; 2],
|
||||
ui_scale: [f32; 2],
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
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,6 +140,11 @@ 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,6 +1,75 @@
|
||||
use objc2::{ClassType, define_class, msg_send};
|
||||
use objc2_app_kit::{NSApplication, NSEvent, NSEventType, NSResponder};
|
||||
use objc2_foundation::NSObject;
|
||||
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);
|
||||
}
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super(NSApplication, NSResponder, NSObject))]
|
||||
@@ -20,22 +89,31 @@ define_class!(
|
||||
}
|
||||
);
|
||||
|
||||
fn instance() -> objc2::rc::Retained<NSApplication> {
|
||||
unsafe { msg_send![GraphiteApplication::class(), sharedApplication] }
|
||||
}
|
||||
define_class!(
|
||||
#[unsafe(super(NSObject))]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[name = "GraphiteApplicationDelegate"]
|
||||
struct GraphiteApplicationDelegate;
|
||||
|
||||
pub(super) fn init() {
|
||||
let _ = instance();
|
||||
}
|
||||
unsafe impl NSObjectProtocol for GraphiteApplicationDelegate {}
|
||||
|
||||
pub(super) fn hide() {
|
||||
instance().hide(None);
|
||||
}
|
||||
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_others() {
|
||||
instance().hideOtherApplications(None);
|
||||
}
|
||||
|
||||
pub(super) fn show_all() {
|
||||
instance().unhideAllApplications(None);
|
||||
}
|
||||
dispatch_event(AppEvent::OpenFiles(paths));
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -72,7 +72,7 @@ impl NativeWindowHandle {
|
||||
|
||||
// Subclass the main window.
|
||||
// https://learn.microsoft.com/windows/win32/api/winuser/nf-winuser-setwindowlongptra
|
||||
let prev_window_message_handler = unsafe { SetWindowLongPtrW(main, GWLP_WNDPROC, main_window_handle_message as isize) };
|
||||
let prev_window_message_handler = unsafe { SetWindowLongPtrW(main, GWLP_WNDPROC, main_window_handle_message as *const () as isize) };
|
||||
if prev_window_message_handler == 0 {
|
||||
let _ = unsafe { DestroyWindow(helper) };
|
||||
panic!("SetWindowLongPtrW failed");
|
||||
|
||||
@@ -13,9 +13,7 @@ gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
graphite-editor = { path = "../../editor", features = [
|
||||
"gpu",
|
||||
] }
|
||||
graphite-editor = { workspace = true }
|
||||
graphene-std = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
wgpu-executor = { workspace = true }
|
||||
|
||||
@@ -31,6 +31,20 @@ 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 };
|
||||
@@ -49,26 +63,12 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
||||
let message = FrontendMessage::UpdateFullscreen { fullscreen };
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
DesktopWrapperMessage::LoadDocument {
|
||||
id,
|
||||
document,
|
||||
to_front,
|
||||
select_after_open,
|
||||
} => {
|
||||
let message = PortfolioMessage::OpenDocumentFileWithId {
|
||||
document_id: id,
|
||||
document_name: Some(document.name),
|
||||
document_path: document.path,
|
||||
document_serialized_content: document.content,
|
||||
document_is_auto_saved: true,
|
||||
document_is_saved: document.is_saved,
|
||||
to_front,
|
||||
select_after_open,
|
||||
};
|
||||
DesktopWrapperMessage::LoadDocumentContent { id, document } => {
|
||||
let message = PersistentStateMessage::LoadDocument { document_id: id, document };
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
DesktopWrapperMessage::SelectDocument { id } => {
|
||||
let message = PortfolioMessage::SelectDocument { document_id: id };
|
||||
DesktopWrapperMessage::LoadPersistedState { state } => {
|
||||
let message = PersistentStateMessage::LoadState { state };
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
DesktopWrapperMessage::LoadPreferences { preferences } => {
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
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;
|
||||
|
||||
use super::DesktopWrapperMessageDispatcher;
|
||||
use super::messages::{DesktopFrontendMessage, Document, FileFilter, OpenFileDialogContext, SaveFileDialogContext};
|
||||
use super::messages::{DesktopFrontendMessage, FileFilter, OpenFileDialogContext, SaveFileDialogContext};
|
||||
|
||||
pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: FrontendMessage) -> Option<FrontendMessage> {
|
||||
match message {
|
||||
@@ -14,6 +15,7 @@ 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,
|
||||
});
|
||||
}
|
||||
@@ -21,6 +23,7 @@ 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,
|
||||
});
|
||||
}
|
||||
@@ -57,6 +60,61 @@ 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));
|
||||
}
|
||||
@@ -67,39 +125,23 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
dispatcher.respond(DesktopFrontendMessage::UpdateUIScale { scale });
|
||||
return Some(FrontendMessage::UpdateUIScale { scale });
|
||||
}
|
||||
FrontendMessage::TriggerPersistenceWriteDocument { document_id, document, details } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteDocument {
|
||||
id: document_id,
|
||||
document: Document {
|
||||
name: details.name,
|
||||
path: details.path,
|
||||
content: document,
|
||||
is_saved: details.is_saved,
|
||||
},
|
||||
});
|
||||
FrontendMessage::TriggerPersistenceReadState => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PersistenceReadState);
|
||||
}
|
||||
FrontendMessage::TriggerPersistenceRemoveDocument { document_id } => {
|
||||
FrontendMessage::TriggerPersistenceWriteState { state } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteState { state });
|
||||
}
|
||||
FrontendMessage::TriggerPersistenceReadDocument { document_id } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PersistenceReadDocument { id: document_id });
|
||||
}
|
||||
FrontendMessage::TriggerPersistenceDeleteDocument { document_id } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PersistenceDeleteDocument { id: document_id });
|
||||
}
|
||||
FrontendMessage::UpdateActiveDocument { document_id } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PersistenceUpdateCurrentDocument { id: document_id });
|
||||
|
||||
// Forward this to update the UI
|
||||
return Some(FrontendMessage::UpdateActiveDocument { document_id });
|
||||
}
|
||||
FrontendMessage::UpdateOpenDocumentsList { open_documents } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PersistenceUpdateDocumentsList {
|
||||
ids: open_documents.iter().map(|document| document.id).collect(),
|
||||
FrontendMessage::TriggerPersistenceWriteDocument { document_id, document } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteDocument {
|
||||
id: document_id,
|
||||
document_serialized_content: document,
|
||||
});
|
||||
|
||||
// Forward this to update the UI
|
||||
return Some(FrontendMessage::UpdateOpenDocumentsList { open_documents });
|
||||
}
|
||||
FrontendMessage::TriggerLoadFirstAutoSaveDocument => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PersistenceLoadCurrentDocument);
|
||||
}
|
||||
FrontendMessage::TriggerLoadRestAutoSaveDocuments => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PersistenceLoadRemainingDocuments);
|
||||
}
|
||||
FrontendMessage::TriggerOpenLaunchDocuments => {
|
||||
dispatcher.respond(DesktopFrontendMessage::OpenLaunchDocuments);
|
||||
@@ -153,6 +195,9 @@ 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);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
use graph_craft::wasm_application_io::WasmApplicationIo;
|
||||
use graph_craft::application_io::PlatformApplicationIo;
|
||||
use graphite_editor::application::{Editor, Environment, Host, Platform};
|
||||
use graphite_editor::messages::prelude::{FrontendMessage, Message};
|
||||
use message_dispatcher::DesktopWrapperMessageDispatcher;
|
||||
use messages::{DesktopFrontendMessage, DesktopWrapperMessage};
|
||||
|
||||
pub use graphite_editor::consts::FILE_EXTENSION;
|
||||
pub use wgpu_executor::TargetTexture;
|
||||
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
|
||||
pub use wgpu_executor::WgpuContext;
|
||||
pub use wgpu_executor::WgpuContextBuilder;
|
||||
pub use wgpu_executor::WgpuExecutor;
|
||||
@@ -38,7 +37,7 @@ impl DesktopWrapper {
|
||||
}
|
||||
|
||||
pub fn init(&self, wgpu_context: WgpuContext) {
|
||||
let application_io = WasmApplicationIo::new_with_context(wgpu_context);
|
||||
let application_io = PlatformApplicationIo::new_with_context(wgpu_context);
|
||||
futures::executor::block_on(graphite_editor::node_graph_executor::replace_application_io(application_io));
|
||||
}
|
||||
|
||||
@@ -51,7 +50,7 @@ impl DesktopWrapper {
|
||||
pub async fn execute_node_graph() -> NodeGraphExecutionResult {
|
||||
let result = graphite_editor::node_graph_executor::run_node_graph().await;
|
||||
match result {
|
||||
(true, texture) => NodeGraphExecutionResult::HasRun(texture.map(|t| t.texture)),
|
||||
(true, texture) => NodeGraphExecutionResult::HasRun(texture.map(Into::into)),
|
||||
(false, _) => NodeGraphExecutionResult::NotRun,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ use std::path::PathBuf;
|
||||
|
||||
pub(crate) use graphite_editor::messages::prelude::Message as EditorMessage;
|
||||
|
||||
pub use graphite_editor::messages::frontend::utility_types::{DocumentInfo, PersistedState};
|
||||
pub use graphite_editor::messages::input_mapper::utility_types::input_keyboard::{Key, ModifierKeys};
|
||||
pub use graphite_editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState as MouseState, EditorPosition as Position, MouseKeys};
|
||||
pub use graphite_editor::messages::prelude::DocumentId;
|
||||
@@ -15,6 +16,7 @@ pub enum DesktopFrontendMessage {
|
||||
OpenFileDialog {
|
||||
title: String,
|
||||
filters: Vec<FileFilter>,
|
||||
multiple: bool,
|
||||
context: OpenFileDialogContext,
|
||||
},
|
||||
SaveFileDialog {
|
||||
@@ -41,23 +43,22 @@ pub enum DesktopFrontendMessage {
|
||||
UpdateOverlays(vello::Scene),
|
||||
PersistenceWriteDocument {
|
||||
id: DocumentId,
|
||||
document: Document,
|
||||
document_serialized_content: String,
|
||||
},
|
||||
PersistenceDeleteDocument {
|
||||
id: DocumentId,
|
||||
},
|
||||
PersistenceUpdateCurrentDocument {
|
||||
id: DocumentId,
|
||||
},
|
||||
PersistenceLoadCurrentDocument,
|
||||
PersistenceLoadRemainingDocuments,
|
||||
PersistenceUpdateDocumentsList {
|
||||
ids: Vec<DocumentId>,
|
||||
},
|
||||
PersistenceWritePreferences {
|
||||
preferences: Preferences,
|
||||
},
|
||||
PersistenceLoadPreferences,
|
||||
PersistenceWriteState {
|
||||
state: PersistedState,
|
||||
},
|
||||
PersistenceReadState,
|
||||
PersistenceReadDocument {
|
||||
id: DocumentId,
|
||||
},
|
||||
UpdateMenu {
|
||||
entries: Vec<MenuItem>,
|
||||
},
|
||||
@@ -71,6 +72,7 @@ pub enum DesktopFrontendMessage {
|
||||
WindowMaximize,
|
||||
WindowFullscreen,
|
||||
WindowDrag,
|
||||
WindowFocus,
|
||||
WindowHide,
|
||||
WindowHideOthers,
|
||||
WindowShowAll,
|
||||
@@ -81,63 +83,20 @@ pub enum DesktopFrontendMessage {
|
||||
pub enum DesktopWrapperMessage {
|
||||
FromWeb(Box<EditorMessage>),
|
||||
Input(InputMessage),
|
||||
FileDialogResult {
|
||||
path: PathBuf,
|
||||
content: Vec<u8>,
|
||||
context: OpenFileDialogContext,
|
||||
},
|
||||
SaveFileDialogResult {
|
||||
path: PathBuf,
|
||||
context: SaveFileDialogContext,
|
||||
},
|
||||
OpenFile {
|
||||
path: PathBuf,
|
||||
content: Vec<u8>,
|
||||
},
|
||||
ImportFile {
|
||||
path: PathBuf,
|
||||
content: Vec<u8>,
|
||||
},
|
||||
FileDialogResult { path: PathBuf, content: Vec<u8>, context: OpenFileDialogContext },
|
||||
SaveFileDialogResult { path: PathBuf, context: SaveFileDialogContext },
|
||||
OpenFile { path: PathBuf, content: Vec<u8> },
|
||||
ImportFile { path: PathBuf, content: Vec<u8> },
|
||||
PollNodeGraphEvaluation,
|
||||
UpdateMaximized {
|
||||
maximized: bool,
|
||||
},
|
||||
UpdateFullscreen {
|
||||
fullscreen: bool,
|
||||
},
|
||||
LoadDocument {
|
||||
id: DocumentId,
|
||||
document: Document,
|
||||
to_front: bool,
|
||||
select_after_open: bool,
|
||||
},
|
||||
SelectDocument {
|
||||
id: DocumentId,
|
||||
},
|
||||
LoadPreferences {
|
||||
preferences: Preferences,
|
||||
},
|
||||
MenuEvent {
|
||||
id: String,
|
||||
},
|
||||
ClipboardReadResult {
|
||||
content: Option<String>,
|
||||
},
|
||||
PointerLockMove {
|
||||
x: f64,
|
||||
y: f64,
|
||||
},
|
||||
LoadThirdPartyLicenses {
|
||||
text: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, serde::Serialize, serde::Deserialize, Debug)]
|
||||
pub struct Document {
|
||||
pub content: String,
|
||||
pub name: String,
|
||||
pub path: Option<PathBuf>,
|
||||
pub is_saved: bool,
|
||||
UpdateMaximized { maximized: bool },
|
||||
UpdateFullscreen { fullscreen: bool },
|
||||
LoadDocumentContent { id: DocumentId, document: String },
|
||||
LoadPersistedState { state: PersistedState },
|
||||
LoadPreferences { preferences: Preferences },
|
||||
MenuEvent { id: String },
|
||||
ClipboardReadResult { content: Option<String> },
|
||||
PointerLockMove { x: f64, y: f64 },
|
||||
LoadThirdPartyLicenses { text: String },
|
||||
}
|
||||
|
||||
pub struct FileFilter {
|
||||
@@ -145,14 +104,28 @@ 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> },
|
||||
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,
|
||||
},
|
||||
}
|
||||
|
||||
pub enum MenuItem {
|
||||
|
||||
+5
-3
@@ -11,14 +11,15 @@ repository = "https://github.com/GraphiteEditor/Graphite"
|
||||
license = "Apache-2.0"
|
||||
|
||||
[features]
|
||||
default = ["wasm", "gpu"]
|
||||
wasm = ["wasm-bindgen", "graphene-std/wasm"]
|
||||
gpu = ["interpreted-executor/gpu", "wgpu-executor"]
|
||||
default = ["gpu"]
|
||||
wasm = ["graphene-std/wasm", "interpreted-executor/wasm", "dep:wasm-bindgen"]
|
||||
gpu = ["interpreted-executor/gpu", "dep:wgpu-executor"]
|
||||
|
||||
[dependencies]
|
||||
# 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 }
|
||||
@@ -45,6 +46,7 @@ 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,5 +1,6 @@
|
||||
// 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;
|
||||
@@ -186,3 +187,6 @@ pub const DOUBLE_CLICK_MILLISECONDS: u64 = 500;
|
||||
pub const UI_SCALE_DEFAULT: f64 = 1.;
|
||||
pub const UI_SCALE_MIN: f64 = 0.5;
|
||||
pub const UI_SCALE_MAX: f64 = 3.;
|
||||
|
||||
// ACTIONS
|
||||
pub const BLEND_COUNT_PER_LAYER: usize = 10;
|
||||
@@ -2,6 +2,7 @@ use crate::messages::debug::utility_types::MessageLoggingVerbosity;
|
||||
use crate::messages::defer::DeferMessageContext;
|
||||
use crate::messages::dialog::DialogMessageContext;
|
||||
use crate::messages::layout::layout_message_handler::LayoutMessageContext;
|
||||
use crate::messages::portfolio::utility_types::PanelType;
|
||||
use crate::messages::preferences::preferences_message_handler::PreferencesMessageContext;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::utility_functions::make_path_editable_is_allowed;
|
||||
@@ -20,6 +21,7 @@ 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,
|
||||
@@ -163,6 +165,7 @@ 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, ());
|
||||
}
|
||||
@@ -233,10 +236,11 @@ impl Dispatcher {
|
||||
Message::MenuBar(message) => {
|
||||
let menu_bar_message_handler = &mut self.message_handlers.menu_bar_message_handler;
|
||||
|
||||
menu_bar_message_handler.focus_document = self.message_handlers.portfolio_message_handler.focus_document;
|
||||
menu_bar_message_handler.data_panel_open = self.message_handlers.portfolio_message_handler.data_panel_open;
|
||||
menu_bar_message_handler.layers_panel_open = self.message_handlers.portfolio_message_handler.layers_panel_open;
|
||||
menu_bar_message_handler.properties_panel_open = self.message_handlers.portfolio_message_handler.properties_panel_open;
|
||||
menu_bar_message_handler.focus_document = self.message_handlers.portfolio_message_handler.workspace_panel_layout.focus_document;
|
||||
let layout = &self.message_handlers.portfolio_message_handler.workspace_panel_layout;
|
||||
menu_bar_message_handler.data_panel_open = layout.is_panel_present(PanelType::Data);
|
||||
menu_bar_message_handler.layers_panel_open = layout.is_panel_present(PanelType::Layers);
|
||||
menu_bar_message_handler.properties_panel_open = layout.is_panel_present(PanelType::Properties);
|
||||
menu_bar_message_handler.message_logging_verbosity = self.message_handlers.debug_message_handler.message_logging_verbosity;
|
||||
menu_bar_message_handler.reset_node_definitions_on_open = self.message_handlers.portfolio_message_handler.reset_node_definitions_on_open;
|
||||
|
||||
@@ -293,7 +297,7 @@ impl Dispatcher {
|
||||
document_id,
|
||||
document,
|
||||
input: &self.message_handlers.input_preprocessor_message_handler,
|
||||
persistent_data: &self.message_handlers.portfolio_message_handler.persistent_data,
|
||||
cached_data: &self.message_handlers.portfolio_message_handler.cached_data,
|
||||
node_graph: &self.message_handlers.portfolio_message_handler.executor,
|
||||
preferences: &self.message_handlers.preferences_message_handler,
|
||||
viewport: &self.message_handlers.viewport_message_handler,
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
// 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,6 +11,7 @@ pub enum AppWindowMessage {
|
||||
Maximize,
|
||||
Fullscreen,
|
||||
Drag,
|
||||
Focus,
|
||||
Hide,
|
||||
HideOthers,
|
||||
ShowAll,
|
||||
|
||||
@@ -36,6 +36,10 @@ 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);
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
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,
|
||||
}
|
||||
@@ -0,0 +1,664 @@
|
||||
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()
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
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(),
|
||||
name: portfolio.generate_new_document_name(None),
|
||||
infinite: false,
|
||||
dimensions: glam::UVec2::new(1920, 1080),
|
||||
};
|
||||
|
||||
@@ -6,8 +6,11 @@ use crate::messages::prelude::*;
|
||||
pub enum ExportDialogMessage {
|
||||
FileType { file_type: FileType },
|
||||
ScaleFactor { factor: f64 },
|
||||
TransparentBackground { transparent: bool },
|
||||
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::{ExportBounds, FileType};
|
||||
use crate::messages::frontend::utility_types::{AnimationExport, ExportBounds, FileType};
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::prelude::*;
|
||||
@@ -14,9 +14,12 @@ pub struct ExportDialogMessageHandler {
|
||||
pub file_type: FileType,
|
||||
pub scale_factor: f64,
|
||||
pub bounds: ExportBounds,
|
||||
pub transparent_background: bool,
|
||||
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 {
|
||||
@@ -25,13 +28,34 @@ impl Default for ExportDialogMessageHandler {
|
||||
file_type: Default::default(),
|
||||
scale_factor: 1.,
|
||||
bounds: Default::default(),
|
||||
transparent_background: false,
|
||||
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) {
|
||||
@@ -40,22 +64,49 @@ impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for Exp
|
||||
match message {
|
||||
ExportDialogMessage::FileType { file_type } => self.file_type = file_type,
|
||||
ExportDialogMessage::ScaleFactor { factor } => self.scale_factor = factor,
|
||||
ExportDialogMessage::TransparentBackground { transparent } => self.transparent_background = transparent,
|
||||
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 => {
|
||||
let artboard_name = match self.bounds {
|
||||
// Fall back to "All Artwork" if "Selection" was chosen but nothing is currently selected
|
||||
let bounds = if !self.has_selection && self.bounds == ExportBounds::Selection {
|
||||
ExportBounds::AllArtwork
|
||||
} else {
|
||||
self.bounds
|
||||
};
|
||||
|
||||
let artboard_name = match bounds {
|
||||
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,
|
||||
scale_factor: self.scale_factor,
|
||||
bounds: self.bounds,
|
||||
transparent_background: self.file_type != FileType::Jpg && self.transparent_background,
|
||||
bounds,
|
||||
artboard_name,
|
||||
artboard_count: self.artboards.len(),
|
||||
animation,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -127,6 +178,7 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
||||
let artboards = self.artboards.iter().map(|(&layer, name)| (ExportBounds::Artboard(layer), name.to_string(), false)).collect();
|
||||
let choices = [standard_bounds, artboards];
|
||||
|
||||
// Fall back to "All Artwork" if "Selection" was chosen but nothing is currently selected
|
||||
let current_bounds = if !self.has_selection && self.bounds == ExportBounds::Selection {
|
||||
ExportBounds::AllArtwork
|
||||
} else {
|
||||
@@ -159,22 +211,74 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
||||
DropdownInput::new(entries).selected_index(Some(index as u32)).widget_instance(),
|
||||
];
|
||||
|
||||
let checkbox_id = CheckboxId::new();
|
||||
let transparent_background = vec![
|
||||
TextLabel::new("Transparency").table_align(true).min_width(100).for_checkbox(checkbox_id).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.transparent_background)
|
||||
.disabled(self.file_type == FileType::Jpg)
|
||||
.on_update(move |value: &CheckboxInput| ExportDialogMessage::TransparentBackground { transparent: value.checked }.into())
|
||||
.for_label(checkbox_id)
|
||||
CheckboxInput::new(self.animated)
|
||||
.on_update(|checkbox_input: &CheckboxInput| ExportDialogMessage::Animated { animated: checkbox_input.checked }.into())
|
||||
.for_label(animation_checkbox_id)
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
Layout(vec![
|
||||
let mut layout_groups = vec![
|
||||
LayoutGroup::row(export_type),
|
||||
LayoutGroup::row(resolution),
|
||||
LayoutGroup::row(export_area),
|
||||
LayoutGroup::row(transparent_background),
|
||||
])
|
||||
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)
|
||||
}
|
||||
}
|
||||
+37
-15
@@ -1,7 +1,9 @@
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::prelude::*;
|
||||
use glam::{IVec2, UVec2};
|
||||
use glam::UVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
|
||||
/// A dialog to allow users to set some initial options about a new document.
|
||||
#[derive(Debug, Clone, Default, ExtractField)]
|
||||
@@ -22,26 +24,46 @@ impl MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHa
|
||||
NewDocumentDialogMessage::Submit => {
|
||||
responses.add(PortfolioMessage::NewDocumentWithName { name: self.name.clone() });
|
||||
|
||||
let create_artboard = !self.infinite && self.dimensions.x > 0 && self.dimensions.y > 0;
|
||||
if create_artboard {
|
||||
if self.infinite {
|
||||
// Infinite canvas: add a locked white background layer
|
||||
let node_id = NodeId::new();
|
||||
responses.add(GraphOperationMessage::NewColorFillLayer {
|
||||
node_id,
|
||||
color: Color::WHITE,
|
||||
parent: LayerNodeIdentifier::ROOT_PARENT,
|
||||
insert_index: 0,
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetDisplayNameImpl {
|
||||
node_id,
|
||||
network_path: Vec::new(),
|
||||
alias: "Background".to_string(),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetLocked {
|
||||
node_id,
|
||||
network_path: Vec::new(),
|
||||
locked: true,
|
||||
});
|
||||
} else if self.dimensions.x > 0 && self.dimensions.y > 0 {
|
||||
// Finite canvas: create an artboard with the specified dimensions
|
||||
responses.add(GraphOperationMessage::NewArtboard {
|
||||
id: NodeId::new(),
|
||||
artboard: graphene_std::Artboard::new(IVec2::ZERO, self.dimensions.as_ivec2()),
|
||||
location: glam::DVec2::ZERO,
|
||||
dimensions: self.dimensions.as_dvec2(),
|
||||
background: Color::WHITE,
|
||||
clip: true,
|
||||
});
|
||||
responses.add(NavigationMessage::CanvasPan { delta: self.dimensions.as_dvec2() });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
|
||||
responses.add(ViewportMessage::RepropagateUpdate);
|
||||
|
||||
responses.add(DeferMessage::AfterNavigationReady {
|
||||
messages: vec![
|
||||
DocumentMessage::ZoomCanvasToFitAll.into(),
|
||||
DocumentMessage::DeselectAllLayers.into(),
|
||||
PortfolioMessage::AutoSaveActiveDocument.into(),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(ViewportMessage::RepropagateUpdate);
|
||||
|
||||
responses.add(DocumentMessage::DeselectAllLayers);
|
||||
|
||||
responses.add(DeferMessage::AfterNavigationReady {
|
||||
messages: vec![DocumentMessage::ZoomCanvasToFitAll.into(), PortfolioMessage::AutoSaveActiveDocument.into()],
|
||||
});
|
||||
|
||||
responses.add(DocumentMessage::MarkAsSaved);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::IconName;
|
||||
use super::utility_types::{DocumentDetails, MouseCursorIcon, OpenDocument};
|
||||
use super::utility_types::{MouseCursorIcon, PersistedState};
|
||||
use crate::messages::app_window::app_window_message_handler::AppWindowPlatform;
|
||||
use crate::messages::frontend::utility_types::EyedropperPreviewImage;
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, ExportAnimationFrame, 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::{
|
||||
@@ -9,12 +9,14 @@ use crate::messages::portfolio::document::node_graph::utility_types::{
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
|
||||
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
|
||||
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::raster::color::Color;
|
||||
use graphene_std::text::{Font, TextAlign};
|
||||
use graphene_std::text::Font;
|
||||
use graphene_std::vector::style::FillChoiceUI;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
@@ -49,7 +51,9 @@ pub enum FrontendMessage {
|
||||
max_width: Option<f64>,
|
||||
#[serde(rename = "maxHeight")]
|
||||
max_height: Option<f64>,
|
||||
align: TextAlign,
|
||||
align: String,
|
||||
#[serde(rename = "alignLast")]
|
||||
align_last: String,
|
||||
},
|
||||
DisplayEditableTextboxUpdateFontData {
|
||||
#[serde(rename = "fontData")]
|
||||
@@ -103,6 +107,23 @@ 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,
|
||||
@@ -112,7 +133,15 @@ pub enum FrontendMessage {
|
||||
font: Font,
|
||||
url: String,
|
||||
},
|
||||
TriggerPersistenceRemoveDocument {
|
||||
TriggerPersistenceReadState,
|
||||
TriggerPersistenceReadDocument {
|
||||
#[serde(rename = "documentId")]
|
||||
document_id: DocumentId,
|
||||
},
|
||||
TriggerPersistenceWriteState {
|
||||
state: PersistedState,
|
||||
},
|
||||
TriggerPersistenceDeleteDocument {
|
||||
#[serde(rename = "documentId")]
|
||||
document_id: DocumentId,
|
||||
},
|
||||
@@ -120,23 +149,21 @@ pub enum FrontendMessage {
|
||||
#[serde(rename = "documentId")]
|
||||
document_id: DocumentId,
|
||||
document: String,
|
||||
details: DocumentDetails,
|
||||
},
|
||||
TriggerLoadFirstAutoSaveDocument,
|
||||
TriggerLoadRestAutoSaveDocuments,
|
||||
TriggerOpenLaunchDocuments,
|
||||
TriggerLoadPreferences,
|
||||
TriggerOpen,
|
||||
TriggerImport,
|
||||
TriggerSavePreferences {
|
||||
#[tsify(type = "unknown")]
|
||||
#[cfg_attr(feature = "wasm", tsify(type = "unknown"))]
|
||||
preferences: PreferencesMessageHandler,
|
||||
},
|
||||
TriggerSaveActiveDocument {
|
||||
#[serde(rename = "documentId")]
|
||||
document_id: DocumentId,
|
||||
},
|
||||
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,
|
||||
},
|
||||
@@ -157,9 +184,17 @@ pub enum FrontendMessage {
|
||||
document_id: DocumentId,
|
||||
},
|
||||
UpdateGradientStopColorPickerPosition {
|
||||
color: Color, // TODO: Color (without `none`) -> Color (with `none`)
|
||||
color: SRGBA8, // 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>>,
|
||||
@@ -194,14 +229,9 @@ pub enum FrontendMessage {
|
||||
UpdateGraphViewOverlay {
|
||||
open: bool,
|
||||
},
|
||||
UpdateDataPanelState {
|
||||
open: bool,
|
||||
},
|
||||
UpdatePropertiesPanelState {
|
||||
open: bool,
|
||||
},
|
||||
UpdateLayersPanelState {
|
||||
open: bool,
|
||||
UpdateWorkspacePanelLayout {
|
||||
#[serde(rename = "panelLayout")]
|
||||
panel_layout: WorkspacePanelLayout,
|
||||
},
|
||||
UpdateLayout {
|
||||
#[serde(rename = "layoutTarget")]
|
||||
@@ -228,7 +258,7 @@ pub enum FrontendMessage {
|
||||
svg: String,
|
||||
},
|
||||
UpdateImageData {
|
||||
image_data: Vec<(u64, Image<Color>)>,
|
||||
image_data: Vec<(u64, Image<SRGBA8>)>,
|
||||
},
|
||||
UpdateDocumentLayerDetails {
|
||||
data: LayerPanelEntry,
|
||||
@@ -242,6 +272,10 @@ 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),
|
||||
@@ -291,7 +325,7 @@ pub enum FrontendMessage {
|
||||
},
|
||||
UpdateOpenDocumentsList {
|
||||
#[serde(rename = "openDocuments")]
|
||||
open_documents: Vec<OpenDocument>,
|
||||
open_documents: Vec<DocumentInfo>,
|
||||
},
|
||||
UpdateWirePathInProgress {
|
||||
#[serde(rename = "wirePath")]
|
||||
@@ -345,6 +379,8 @@ 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,
|
||||
|
||||
@@ -1,24 +1,26 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::utility_types::WorkspacePanelLayout;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(PartialEq, Eq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct OpenDocument {
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct DocumentInfo {
|
||||
pub id: DocumentId,
|
||||
pub details: DocumentDetails,
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub path: Option<PathBuf>,
|
||||
pub is_saved: bool,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(PartialEq, Eq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct DocumentDetails {
|
||||
pub name: String,
|
||||
pub path: Option<PathBuf>,
|
||||
#[serde(rename = "isSaved")]
|
||||
pub is_saved: bool,
|
||||
#[serde(rename = "isAutoSaved")]
|
||||
pub is_auto_saved: bool,
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints, from_wasm_abi))]
|
||||
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PersistedState {
|
||||
pub documents: Vec<DocumentInfo>,
|
||||
pub current_document: Option<DocumentId>,
|
||||
#[serde(default)]
|
||||
pub workspace_layout: Option<WorkspacePanelLayout>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -57,6 +59,14 @@ 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))]
|
||||
@@ -68,6 +78,56 @@ 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 {
|
||||
|
||||
@@ -357,6 +357,8 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
entry!(KeyDown(KeyS); modifiers=[Accel, Shift], action_dispatch=DocumentMessage::SaveDocumentAs),
|
||||
entry!(KeyDown(KeyD); modifiers=[Accel], canonical, action_dispatch=DocumentMessage::DuplicateSelectedLayers),
|
||||
entry!(KeyDown(KeyJ); modifiers=[Accel], action_dispatch=DocumentMessage::DuplicateSelectedLayers),
|
||||
entry!(KeyDown(KeyB); modifiers=[Accel, Alt], action_dispatch=DocumentMessage::BlendSelectedLayers),
|
||||
entry!(KeyDown(KeyM); modifiers=[Accel, Alt], action_dispatch=DocumentMessage::MorphSelectedLayers), // Might get eaten by the GeForce Experience overlay for some Windows users
|
||||
entry!(KeyDown(KeyG); modifiers=[Accel], action_dispatch=DocumentMessage::GroupSelectedLayers { group_folder_type: GroupFolderType::Layer }),
|
||||
entry!(KeyDown(KeyG); modifiers=[Accel, Shift], action_dispatch=DocumentMessage::UngroupSelectedLayers),
|
||||
entry!(KeyDown(KeyN); modifiers=[Accel, Shift], action_dispatch=DocumentMessage::CreateEmptyFolder),
|
||||
|
||||
@@ -139,7 +139,8 @@ impl FrameTimeInfo {
|
||||
}
|
||||
|
||||
pub fn advance_timestamp(&mut self, next_timestamp: Duration) {
|
||||
debug_assert!(next_timestamp >= self.timestamp);
|
||||
// Guard against non-monotonic timestamps from the browser (Keavon observed this once in Chrome)
|
||||
let next_timestamp = next_timestamp.max(self.timestamp);
|
||||
|
||||
self.prev_timestamp = Some(self.timestamp);
|
||||
self.timestamp = next_timestamp;
|
||||
|
||||
@@ -26,4 +26,8 @@ pub enum LayoutMessage {
|
||||
widget_id: WidgetId,
|
||||
value: serde_json::Value,
|
||||
},
|
||||
WidgetValueDragDrop {
|
||||
layout_target: LayoutTarget,
|
||||
widget_id: WidgetId,
|
||||
},
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
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::vector::style::FillChoice;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::vector::style::FillChoiceUI;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -61,6 +62,19 @@ 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,22 +116,22 @@ impl LayoutMessageHandler {
|
||||
}
|
||||
LayoutGroup::Table(WidgetTable { rows, .. }) => {
|
||||
for (row_index, row) in rows.iter().enumerate() {
|
||||
for (cell_index, cell) in row.iter().enumerate() {
|
||||
for (value_index, value) in row.iter().enumerate() {
|
||||
// Return if this is the correct ID
|
||||
if cell.widget_id == widget_id {
|
||||
if value.widget_id == widget_id {
|
||||
widget_path.push(row_index);
|
||||
widget_path.push(cell_index);
|
||||
return Some((cell, widget_path));
|
||||
widget_path.push(value_index);
|
||||
return Some((value, widget_path));
|
||||
}
|
||||
|
||||
if let Widget::PopoverButton(popover) = &*cell.widget {
|
||||
if let Widget::PopoverButton(popover) = &*value.widget {
|
||||
stack.extend(
|
||||
popover
|
||||
.popover_layout
|
||||
.0
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(child, val)| ([widget_path.as_slice(), &[row_index, cell_index, child]].concat(), val)),
|
||||
.map(|(child, val)| ([widget_path.as_slice(), &[row_index, value_index, child]].concat(), val)),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -167,31 +181,38 @@ 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) = serde_json::from_value::<FillChoice>(value) else {
|
||||
warn!("ColorInput update was not able to be parsed as FillChoice: {color_button:?}");
|
||||
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:?}");
|
||||
return;
|
||||
};
|
||||
color_button.value = fill_choice;
|
||||
color_button.value = fill_choice_ui;
|
||||
(color_button.on_update.callback)(color_button)
|
||||
}
|
||||
};
|
||||
|
||||
responses.add(callback_message);
|
||||
}
|
||||
Widget::CurveInput(curve_input) => {
|
||||
Widget::ColorPresetsInput(color_presets_input) => {
|
||||
let callback_message = match action {
|
||||
WidgetValueAction::Commit => (curve_input.on_commit.callback)(&()),
|
||||
WidgetValueAction::Commit => (color_presets_input.on_commit.callback)(&()),
|
||||
WidgetValueAction::Update => {
|
||||
let Some(curve) = serde_json::from_value(value).ok() else {
|
||||
error!("CurveInput event data could not be deserialized");
|
||||
let Ok(update) = serde_json::from_value::<ColorPresetsInputUpdate>(value) else {
|
||||
warn!("ColorPresetsInput update was not able to be parsed as ColorPresetsInputUpdate");
|
||||
return;
|
||||
};
|
||||
curve_input.value = curve;
|
||||
(curve_input.on_update.callback)(curve_input)
|
||||
(color_presets_input.on_update.callback)(&update)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -226,6 +247,25 @@ 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)(&()),
|
||||
@@ -383,6 +423,23 @@ 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(_) => {}
|
||||
};
|
||||
}
|
||||
@@ -395,14 +452,17 @@ impl LayoutMessageHandler {
|
||||
responses: &mut VecDeque<Message>,
|
||||
action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>,
|
||||
) {
|
||||
// Step 1: Collect CheckboxId mappings from new layout
|
||||
// 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);
|
||||
|
||||
// Step 2: Replace all IDs in new layout with deterministic ones
|
||||
// Replace all IDs in new layout with deterministic ones
|
||||
new_layout.replace_widget_ids(layout_target, &mut Vec::new(), &checkbox_map);
|
||||
|
||||
// Step 3: Diff with deterministic IDs
|
||||
// Populate computed display fields on widgets that need derived values
|
||||
populate_computed_display_fields(&mut new_layout);
|
||||
|
||||
// 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);
|
||||
@@ -440,3 +500,27 @@ 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))]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
#[derive(PartialEq, Clone, Debug, Hash, Eq, Copy, serde::Serialize, serde::Deserialize)]
|
||||
#[repr(u8)]
|
||||
pub enum LayoutTarget {
|
||||
@@ -44,7 +44,11 @@ macro_rules! define_layout_target {
|
||||
};
|
||||
}
|
||||
define_layout_target!(
|
||||
/// The spreadsheet panel allows for the visualisation of data in the graph.
|
||||
/// 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.
|
||||
DataPanel,
|
||||
/// Contains the action buttons at the bottom of the dialog. Must be shown with the `FrontendMessage::DisplayDialog` message.
|
||||
DialogButtons,
|
||||
@@ -424,7 +428,6 @@ 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,
|
||||
@@ -443,7 +446,11 @@ impl LayoutGroup {
|
||||
| Widget::ShortcutLabel(_)
|
||||
| Widget::WorkingColorsInput(_)
|
||||
| Widget::NodeCatalog(_)
|
||||
| Widget::ParameterExposeButton(_) => continue,
|
||||
| Widget::ParameterExposeButton(_)
|
||||
| Widget::ColorComparisonInput(_)
|
||||
| Widget::ColorPresetsInput(_)
|
||||
| Widget::SpectrumInput(_)
|
||||
| Widget::VisualColorPickersInput(_) => continue,
|
||||
};
|
||||
if val.is_empty() {
|
||||
val.clone_from(&description);
|
||||
@@ -661,6 +668,7 @@ 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() {
|
||||
@@ -758,8 +766,9 @@ impl<T> Default for WidgetCallback<T> {
|
||||
pub enum Widget {
|
||||
BreadcrumbTrailButtons(BreadcrumbTrailButtons),
|
||||
CheckboxInput(CheckboxInput),
|
||||
ColorComparisonInput(ColorComparisonInput),
|
||||
ColorInput(ColorInput),
|
||||
CurveInput(CurveInput),
|
||||
ColorPresetsInput(ColorPresetsInput),
|
||||
DropdownInput(DropdownInput),
|
||||
IconButton(IconButton),
|
||||
IconLabel(IconLabel),
|
||||
@@ -773,10 +782,12 @@ pub enum Widget {
|
||||
PopoverButton(PopoverButton),
|
||||
RadioInput(RadioInput),
|
||||
Separator(Separator),
|
||||
SpectrumInput(SpectrumInput),
|
||||
TextAreaInput(TextAreaInput),
|
||||
TextButton(TextButton),
|
||||
TextInput(TextInput),
|
||||
TextLabel(TextLabel),
|
||||
VisualColorPickersInput(VisualColorPickersInput),
|
||||
WorkingColorsInput(WorkingColorsInput),
|
||||
}
|
||||
|
||||
@@ -785,7 +796,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>,
|
||||
@@ -826,7 +837,6 @@ impl DiffUpdate {
|
||||
Widget::ShortcutLabel(widget) => widget.shortcut.as_mut(),
|
||||
Widget::IconLabel(_)
|
||||
| Widget::ImageLabel(_)
|
||||
| Widget::CurveInput(_)
|
||||
| Widget::NodeCatalog(_)
|
||||
| Widget::ReferencePointInput(_)
|
||||
| Widget::RadioInput(_)
|
||||
@@ -834,7 +844,11 @@ impl DiffUpdate {
|
||||
| Widget::TextAreaInput(_)
|
||||
| Widget::TextInput(_)
|
||||
| Widget::TextLabel(_)
|
||||
| Widget::WorkingColorsInput(_) => None,
|
||||
| Widget::WorkingColorsInput(_)
|
||||
| Widget::ColorComparisonInput(_)
|
||||
| Widget::ColorPresetsInput(_)
|
||||
| Widget::SpectrumInput(_)
|
||||
| Widget::VisualColorPickersInput(_) => 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::FillChoice;
|
||||
use graphene_std::vector::style::FillChoiceUI;
|
||||
use graphite_proc_macros::WidgetBuilder;
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -39,6 +39,9 @@ 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))]
|
||||
@@ -187,9 +190,13 @@ pub struct ImageButton {
|
||||
#[derivative(Debug, PartialEq, Default)]
|
||||
pub struct ColorInput {
|
||||
// Content
|
||||
/// WARNING: The colors are gamma, not linear!
|
||||
#[widget_builder(constructor)]
|
||||
pub value: FillChoice,
|
||||
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>,
|
||||
#[serde(rename = "allowNone")]
|
||||
#[derivative(Default(value = "true"))]
|
||||
pub allow_none: bool,
|
||||
@@ -197,6 +204,13 @@ 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,8 +4,9 @@ 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::raster::curve::Curve;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::transform::ReferencePoint;
|
||||
use graphene_std::vector::style::{FillChoiceUI, GradientStopsUI};
|
||||
use graphite_proc_macros::WidgetBuilder;
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -20,6 +21,7 @@ pub struct CheckboxInput {
|
||||
#[serde(rename = "forLabel")]
|
||||
pub for_label: CheckboxId,
|
||||
pub disabled: bool,
|
||||
pub mixed: bool,
|
||||
|
||||
// Tooltips
|
||||
#[serde(rename = "tooltipLabel")]
|
||||
@@ -348,9 +350,9 @@ pub struct RadioEntryData {
|
||||
pub struct WorkingColorsInput {
|
||||
// Content
|
||||
#[widget_builder(constructor)]
|
||||
pub primary: Color,
|
||||
pub primary: SRGBA8,
|
||||
#[widget_builder(constructor)]
|
||||
pub secondary: Color,
|
||||
pub secondary: SRGBA8,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -362,6 +364,7 @@ pub struct TextAreaInput {
|
||||
pub value: String,
|
||||
pub label: Option<String>,
|
||||
pub disabled: bool,
|
||||
pub monospace: bool,
|
||||
|
||||
// Tooltips
|
||||
#[serde(rename = "tooltipLabel")]
|
||||
@@ -418,31 +421,237 @@ 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, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder)]
|
||||
#[derivative(Debug, PartialEq, Default)]
|
||||
pub struct CurveInput {
|
||||
#[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)]
|
||||
pub value: Curve,
|
||||
#[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,
|
||||
|
||||
// Tooltips
|
||||
#[serde(rename = "tooltipLabel")]
|
||||
pub tooltip_label: String,
|
||||
#[serde(rename = "tooltipDescription")]
|
||||
pub tooltip_description: String,
|
||||
#[serde(rename = "tooltipShortcut")]
|
||||
pub tooltip_shortcut: Option<ActionShortcut>,
|
||||
// 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<CurveInput>,
|
||||
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)]
|
||||
#[derivative(Debug, PartialEq, Default)]
|
||||
pub struct SpectrumInput {
|
||||
// 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,
|
||||
|
||||
// Callbacks
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_update: WidgetCallback<SpectrumInputUpdate>,
|
||||
#[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,6 +72,8 @@ 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,
|
||||
|
||||
|
||||
@@ -495,6 +495,18 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
})
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
]]),
|
||||
MenuListEntry::new("Blend")
|
||||
.label("Blend")
|
||||
.icon("InterpolationBlend")
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::BlendSelectedLayers))
|
||||
.on_commit(|_| DocumentMessage::BlendSelectedLayers.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
MenuListEntry::new("Morph")
|
||||
.label("Morph")
|
||||
.icon("InterpolationMorph")
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::MorphSelectedLayers))
|
||||
.on_commit(|_| DocumentMessage::MorphSelectedLayers.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Make Path Editable")
|
||||
@@ -502,6 +514,11 @@ 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(),
|
||||
@@ -635,6 +652,12 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::ToggleFocusDocument))
|
||||
.on_commit(|_| PortfolioMessage::ToggleFocusDocument.into()),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Reset Workspace")
|
||||
.label("Reset Workspace")
|
||||
.icon("Reset")
|
||||
.on_commit(|_| PortfolioMessage::ResetWorkspaceLayout.into()),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Properties")
|
||||
.label("Properties")
|
||||
|
||||
@@ -14,6 +14,8 @@ pub enum Message {
|
||||
#[child]
|
||||
Clipboard(ClipboardMessage),
|
||||
#[child]
|
||||
ColorPicker(ColorPickerMessage),
|
||||
#[child]
|
||||
Debug(DebugMessage),
|
||||
#[child]
|
||||
Defer(DeferMessage),
|
||||
|
||||
@@ -4,6 +4,7 @@ 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,9 +10,12 @@ 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 {
|
||||
index: usize,
|
||||
step: PathStep,
|
||||
},
|
||||
TruncateElementPath {
|
||||
len: usize,
|
||||
@@ -23,6 +26,14 @@ 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
@@ -84,6 +84,10 @@ pub enum DocumentMessage {
|
||||
GridVisibility {
|
||||
visible: bool,
|
||||
},
|
||||
BlendSelectedLayers,
|
||||
MorphSelectedLayers,
|
||||
ExpandFillStrokeOnSelectedLayers,
|
||||
ExpandFillStrokeOnSelectedLayersNoTransaction,
|
||||
GroupSelectedLayers {
|
||||
group_folder_type: GroupFolderType,
|
||||
},
|
||||
@@ -197,7 +201,7 @@ pub enum DocumentMessage {
|
||||
undo_count: usize,
|
||||
},
|
||||
ToggleLayerExpansion {
|
||||
id: NodeId,
|
||||
tree_path: Vec<NodeId>,
|
||||
recursive: bool,
|
||||
},
|
||||
ToggleSelectedVisibility,
|
||||
@@ -213,6 +217,12 @@ 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>,
|
||||
},
|
||||
|
||||
@@ -5,12 +5,13 @@ use super::utility_types::network_interface::{self, NodeNetworkInterface, Transa
|
||||
use super::utility_types::nodes::{CollapsedLayers, LayerStructureEntry, SelectedNodes};
|
||||
use crate::application::{GRAPHITE_GIT_COMMIT_HASH, generate_uuid};
|
||||
use crate::consts::{
|
||||
ASYMPTOTIC_EFFECT, COLOR_OVERLAY_GRAY, DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH, SCALE_EFFECT, SCROLLBAR_SPACING, VIEWPORT_ROTATE_SNAP_INTERVAL,
|
||||
ASYMPTOTIC_EFFECT, BLEND_COUNT_PER_LAYER, COLOR_OVERLAY_GRAY, DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH, SCALE_EFFECT, SCROLLBAR_SPACING,
|
||||
VIEWPORT_ROTATE_SNAP_INTERVAL,
|
||||
};
|
||||
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::TransformIn;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::{ModifyInputsContext, 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;
|
||||
@@ -19,29 +20,29 @@ 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};
|
||||
use crate::messages::portfolio::utility_types::{PanelType, PersistentData};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate, OutputConnector};
|
||||
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};
|
||||
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, IVec2};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::descriptor;
|
||||
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::RenderMode;
|
||||
use graphene_std::vector::style::{Fill, RenderMode};
|
||||
use kurbo::{Affine, BezPath, Line, PathSeg};
|
||||
use std::collections::HashSet;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
@@ -50,7 +51,7 @@ use std::time::Duration;
|
||||
pub struct DocumentMessageContext<'a> {
|
||||
pub document_id: DocumentId,
|
||||
pub ipp: &'a InputPreprocessorMessageHandler,
|
||||
pub persistent_data: &'a PersistentData,
|
||||
pub cached_data: &'a CachedData,
|
||||
pub executor: &'a mut NodeGraphExecutor,
|
||||
pub current_tool: &'a ToolType,
|
||||
pub preferences: &'a PreferencesMessageHandler,
|
||||
@@ -84,8 +85,8 @@ 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,
|
||||
/// List of the [`LayerNodeIdentifier`]s that are currently collapsed by the user in the Layers panel.
|
||||
/// Collapsed means that the expansion arrow isn't set to show the children of these layers.
|
||||
/// Tracks which layer occurrences are collapsed in the Layers panel, keyed by tree 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.
|
||||
/// We save this to provide a hint about which version of the editor was used to create the document.
|
||||
@@ -191,7 +192,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
let DocumentMessageContext {
|
||||
document_id,
|
||||
ipp,
|
||||
persistent_data,
|
||||
cached_data,
|
||||
executor,
|
||||
viewport,
|
||||
current_tool,
|
||||
@@ -229,7 +230,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
selection_network_path: &self.selection_network_path,
|
||||
document_name: self.name.as_str(),
|
||||
executor,
|
||||
persistent_data,
|
||||
cached_data,
|
||||
properties_panel_open,
|
||||
};
|
||||
self.properties_panel_message_handler.process_message(message, responses, context);
|
||||
@@ -317,7 +318,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
DocumentMessage::ClearLayersPanel => {
|
||||
// Send an empty layer list
|
||||
if layers_panel_open {
|
||||
let layer_structure = Self::default().build_layer_structure(LayerNodeIdentifier::ROOT_PARENT);
|
||||
let layer_structure = Self::default().build_layer_structure();
|
||||
responses.add(FrontendMessage::UpdateDocumentLayerStructure { layer_structure });
|
||||
}
|
||||
|
||||
@@ -380,7 +381,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
DocumentMessage::DocumentStructureChanged => {
|
||||
if layers_panel_open {
|
||||
self.network_interface.load_structure();
|
||||
let layer_structure = self.build_layer_structure(LayerNodeIdentifier::ROOT_PARENT);
|
||||
let layer_structure = self.build_layer_structure();
|
||||
|
||||
self.update_layers_panel_control_bar_widgets(layers_panel_open, responses);
|
||||
self.update_layers_panel_bottom_bar_widgets(layers_panel_open, responses);
|
||||
@@ -624,6 +625,30 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.snapping_state.grid_snapping = visible;
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
}
|
||||
DocumentMessage::BlendSelectedLayers => {
|
||||
self.handle_group_selected_layers(GroupFolderType::Blend, responses);
|
||||
}
|
||||
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);
|
||||
}
|
||||
@@ -688,11 +713,12 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
|
||||
let layer = graph_modification_utils::new_image_layer(Table::new_from_element(Raster::new_cpu(image)), layer_node_id, layer_parent, responses);
|
||||
let layer = graph_modification_utils::new_image_layer(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,
|
||||
});
|
||||
@@ -750,6 +776,7 @@ 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,
|
||||
});
|
||||
@@ -776,7 +803,15 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
responses.add(EventMessage::SelectionChanged);
|
||||
}
|
||||
DocumentMessage::RenameDocument { new_name } => {
|
||||
self.name = new_name.clone();
|
||||
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.path = None;
|
||||
self.set_save_state(false);
|
||||
@@ -822,11 +857,31 @@ 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 => {
|
||||
@@ -1013,8 +1068,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
}
|
||||
}
|
||||
DocumentMessage::SetActivePanel { active_panel: panel } => {
|
||||
match panel {
|
||||
DocumentMessage::SetActivePanel { active_panel } => {
|
||||
match active_panel {
|
||||
PanelType::Document => {
|
||||
if self.graph_view_overlay_open {
|
||||
self.selection_network_path.clone_from(&self.breadcrumb_network_path);
|
||||
@@ -1167,25 +1222,27 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
}
|
||||
DocumentMessage::ToggleLayerExpansion { id, recursive } => {
|
||||
let layer = LayerNodeIdentifier::new(id, &self.network_interface);
|
||||
let metadata = self.metadata();
|
||||
|
||||
let is_collapsed = self.collapsed.0.contains(&layer);
|
||||
DocumentMessage::ToggleLayerExpansion { tree_path, recursive } => {
|
||||
let is_collapsed = self.collapsed.0.contains(&tree_path);
|
||||
|
||||
if is_collapsed {
|
||||
if recursive {
|
||||
let children: HashSet<_> = layer.descendants(metadata).collect();
|
||||
self.collapsed.0.retain(|collapsed_layer| !children.contains(collapsed_layer) && collapsed_layer != &layer);
|
||||
// Remove this path and all descendant paths (paths that start with this one)
|
||||
self.collapsed.0.retain(|path| !path.starts_with(&tree_path));
|
||||
} else {
|
||||
self.collapsed.0.retain(|collapsed_layer| collapsed_layer != &layer);
|
||||
self.collapsed.0.retain(|path| *path != tree_path);
|
||||
}
|
||||
} else {
|
||||
if recursive {
|
||||
let children_to_add: Vec<_> = layer.descendants(metadata).filter(|child| !self.collapsed.0.contains(child)).collect();
|
||||
self.collapsed.0.extend(children_to_add);
|
||||
// Collapse all expanded descendant occurrences by collecting their tree paths from the structure tree
|
||||
let descendant_paths = self.collect_descendant_tree_paths(&tree_path);
|
||||
for path in descendant_paths {
|
||||
if !self.collapsed.0.contains(&path) {
|
||||
self.collapsed.0.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.collapsed.0.push(layer);
|
||||
self.collapsed.0.push(tree_path);
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
@@ -1232,6 +1289,32 @@ 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);
|
||||
}
|
||||
@@ -1378,11 +1461,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, dimensions, DVec2::ZERO)
|
||||
(origin.as_dvec2(), dimensions.as_dvec2(), 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 { IVec2::ZERO } else { bounds[0].round().as_ivec2() };
|
||||
(location, (bounds[1] - bounds[0]).round().as_ivec2(), -bounds[0].round())
|
||||
let location = if place_artboard_at_origin { DVec2::ZERO } else { bounds[0].round() };
|
||||
(location, (bounds[1] - bounds[0]).round(), -bounds[0].round())
|
||||
};
|
||||
|
||||
// Create an artboard and set its dimensions to the bounding box size and location
|
||||
@@ -1390,8 +1473,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
let node_layer_id = LayerNodeIdentifier::new_unchecked(node_id);
|
||||
let new_artboard_node = document_node_definitions::resolve_network_node_type("Artboard")
|
||||
.expect("Failed to create artboard node")
|
||||
// Enable clipping by default (input index 5) so imported content is masked to the artboard bounds
|
||||
.node_template_input_override([None, None, None, None, None, Some(NodeInput::value(TaggedValue::Bool(true), false))]);
|
||||
.default_node_template();
|
||||
responses.add(NodeGraphMessage::InsertNode {
|
||||
node_id,
|
||||
node_template: Box::new(new_artboard_node),
|
||||
@@ -1482,6 +1564,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
DeleteSelectedLayers,
|
||||
DuplicateSelectedLayers,
|
||||
GroupSelectedLayers,
|
||||
BlendSelectedLayers,
|
||||
MorphSelectedLayers,
|
||||
SelectedLayersLower,
|
||||
SelectedLayersLowerToBack,
|
||||
SelectedLayersRaise,
|
||||
@@ -1584,6 +1668,11 @@ 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);
|
||||
@@ -1677,6 +1766,12 @@ 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
|
||||
@@ -1740,22 +1835,218 @@ impl DocumentMessageHandler {
|
||||
Ok(document_message_handler)
|
||||
}
|
||||
|
||||
/// Recursively builds the layer structure tree for a folder.
|
||||
fn build_layer_structure(&self, folder: LayerNodeIdentifier) -> Vec<LayerStructureEntry> {
|
||||
folder
|
||||
.children(self.metadata())
|
||||
.map(|layer_node| {
|
||||
let children = if layer_node.has_children(self.metadata()) && !self.collapsed.0.contains(&layer_node) {
|
||||
self.build_layer_structure(layer_node)
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
LayerStructureEntry {
|
||||
layer_id: layer_node.to_node(),
|
||||
children,
|
||||
/// Builds the layer structure tree by traversing the node graph directly.
|
||||
/// Unlike the canonical `structure` field of [`DocumentMetadata`] (which stores single-parent relationships), this allows
|
||||
/// the same layer to appear under multiple parents when the graph feeds the same child content into separate parent layers.
|
||||
fn build_layer_structure(&self) -> Vec<LayerStructureEntry> {
|
||||
let network = &self.network_interface;
|
||||
|
||||
let Some(root_node) = network.root_node(&[]) else { return Vec::new() };
|
||||
let Some(first_root_layer_id) = network
|
||||
.upstream_flow_back_from_nodes(vec![root_node.node_id], &[], FlowType::PrimaryFlow)
|
||||
.find(|node_id| network.is_layer(node_id, &[]))
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
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 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));
|
||||
|
||||
// Layers in the primary flow (input[0] chain) from the first root layer are root-level siblings
|
||||
let mut root_ancestors = HashSet::new();
|
||||
root_ancestors.insert(first_root_layer_id);
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
/// 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);
|
||||
|
||||
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 children = if children_present && !collapsed {
|
||||
self.collect_layer_children(layer_id, &child_ancestors, selected_layers, &tree_path)
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
// Compute whether any descendant is selected (checking expanded children and, if collapsed, via graph traversal)
|
||||
let descendant_selected = if !children.is_empty() {
|
||||
children.iter().any(|child| child.descendant_selected || selected_layers.contains(&child.layer_id))
|
||||
} else if children_present {
|
||||
// Layer is collapsed but has children, so check via graph traversal
|
||||
self.has_selected_descendant_in_graph(layer_id, &child_ancestors, selected_layers)
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
LayerStructureEntry {
|
||||
layer_id,
|
||||
children,
|
||||
children_present,
|
||||
descendant_selected,
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks whether a layer has any child layers reachable via horizontal flow in the graph.
|
||||
fn has_layer_children_in_graph(&self, layer_id: NodeId, child_ancestors: &HashSet<NodeId>) -> bool {
|
||||
let network = &self.network_interface;
|
||||
|
||||
network
|
||||
.upstream_flow_back_from_nodes(vec![layer_id], &[], FlowType::HorizontalFlow)
|
||||
.skip(1)
|
||||
.any(|id| network.is_layer(&id, &[]) && !child_ancestors.contains(&id))
|
||||
}
|
||||
|
||||
/// Checks whether any descendant layer in the graph (via horizontal + primary flow) is selected.
|
||||
/// Used when a layer is collapsed to determine if the ancestor-of-selected indicator should show.
|
||||
fn has_selected_descendant_in_graph(&self, layer_id: NodeId, ancestors: &HashSet<NodeId>, selected_layers: &HashSet<NodeId>) -> bool {
|
||||
let network = &self.network_interface;
|
||||
|
||||
// Find child layers via horizontal flow
|
||||
let mut stack: Vec<NodeId> = network
|
||||
.upstream_flow_back_from_nodes(vec![layer_id], &[], FlowType::HorizontalFlow)
|
||||
.skip(1)
|
||||
.filter(|node_id| network.is_layer(node_id, &[]) && !ancestors.contains(node_id))
|
||||
.collect();
|
||||
|
||||
let mut visited = ancestors.clone();
|
||||
|
||||
// Iteratively explore all descendant layers via a depth-first traversal
|
||||
while let Some(current_id) = stack.pop() {
|
||||
// Skip already-visited layers to avoid infinite loops from graph cycles
|
||||
if !visited.insert(current_id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Found a selected descendant, the ancestor indicator should be shown
|
||||
if selected_layers.contains(¤t_id) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check this layer's children via horizontal flow
|
||||
for node_id in network.upstream_flow_back_from_nodes(vec![current_id], &[], FlowType::HorizontalFlow).skip(1) {
|
||||
if network.is_layer(&node_id, &[]) && !visited.contains(&node_id) {
|
||||
stack.push(node_id);
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// Check stacked siblings via primary flow
|
||||
for node_id in network.upstream_flow_back_from_nodes(vec![current_id], &[], FlowType::PrimaryFlow).skip(1) {
|
||||
if network.is_layer(&node_id, &[]) && !visited.contains(&node_id) {
|
||||
stack.push(node_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
/// Collects the child entries for a given layer by traversing its horizontal and primary flows.
|
||||
/// 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> {
|
||||
let network = &self.network_interface;
|
||||
|
||||
// Find the first nested layer via horizontal flow (content inside this layer)
|
||||
let Some(nested_id) = network
|
||||
.upstream_flow_back_from_nodes(vec![layer_id], &[], FlowType::HorizontalFlow)
|
||||
.skip(1)
|
||||
.find(|id| network.is_layer(id, &[]))
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
// Cycle detected, this layer is already an ancestor in the current branch
|
||||
if ancestors.contains(&nested_id) {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
// 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)];
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
/// Collects tree paths for all descendant layers of the given tree 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() };
|
||||
let network = &self.network_interface;
|
||||
|
||||
let mut paths = Vec::new();
|
||||
let mut stack: Vec<(NodeId, Vec<NodeId>)> = Vec::new();
|
||||
|
||||
// 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();
|
||||
child_path.push(node_id);
|
||||
stack.push((node_id, child_path));
|
||||
}
|
||||
}
|
||||
|
||||
let mut visited = HashSet::new();
|
||||
|
||||
// Depth-first traversal collecting all unique descendant tree 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
|
||||
paths.push(current_path.clone());
|
||||
|
||||
// Add nested content layers found via horizontal flow
|
||||
for node_id in network.upstream_flow_back_from_nodes(vec![current_id], &[], FlowType::HorizontalFlow).skip(1) {
|
||||
if network.is_layer(&node_id, &[]) {
|
||||
let mut child_path = current_path.clone();
|
||||
child_path.push(node_id);
|
||||
stack.push((node_id, child_path));
|
||||
}
|
||||
}
|
||||
|
||||
// Add stacked sibling layers found via primary flow
|
||||
for node_id in network.upstream_flow_back_from_nodes(vec![current_id], &[], FlowType::PrimaryFlow).skip(1) {
|
||||
if network.is_layer(&node_id, &[]) {
|
||||
// Siblings share the same parent path (everything up to the last element of current_path)
|
||||
let mut sibling_path = current_path[..current_path.len() - 1].to_vec();
|
||||
sibling_path.push(node_id);
|
||||
stack.push((node_id, sibling_path));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
paths
|
||||
}
|
||||
|
||||
pub fn undo_with_history(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
@@ -1939,7 +2230,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::Network("Boolean Operation".into()))
|
||||
.is_some_and(|reference| reference == DefinitionIdentifier::ProtoNode(graphene_std::path_bool_nodes::boolean_operation::IDENTIFIER))
|
||||
})
|
||||
});
|
||||
|
||||
@@ -1961,6 +2252,57 @@ impl DocumentMessageHandler {
|
||||
});
|
||||
}
|
||||
}
|
||||
GroupFolderType::Blend | GroupFolderType::Morph => {
|
||||
let control_path_id = NodeId(generate_uuid());
|
||||
let all_layers_to_group = network_interface.shallowest_unique_layers_sorted(&[]);
|
||||
let blend_count = matches!(group_folder_type, GroupFolderType::Blend).then(|| all_layers_to_group.len() * BLEND_COUNT_PER_LAYER);
|
||||
|
||||
responses.add(GraphOperationMessage::NewInterpolationLayer {
|
||||
id: folder_id,
|
||||
control_path_id,
|
||||
parent,
|
||||
insert_index,
|
||||
blend_count,
|
||||
});
|
||||
|
||||
let new_group_folder = LayerNodeIdentifier::new_unchecked(folder_id);
|
||||
|
||||
// Move selected layers into the group as children
|
||||
for layer_to_group in all_layers_to_group.into_iter().rev() {
|
||||
responses.add(NodeGraphMessage::MoveLayerToStack {
|
||||
layer: layer_to_group,
|
||||
parent: new_group_folder,
|
||||
insert_index: 0,
|
||||
});
|
||||
}
|
||||
|
||||
// Connect the child stack to the control path layer as a co-parent
|
||||
responses.add(GraphOperationMessage::ConnectInterpolationControlPathToChildren {
|
||||
interpolation_layer_id: folder_id,
|
||||
control_path_id,
|
||||
});
|
||||
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![folder_id] });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(DocumentMessage::DocumentStructureChanged);
|
||||
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
|
||||
.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
|
||||
};
|
||||
responses.add(DocumentMessage::ToggleLayerExpansion { tree_path, recursive: false });
|
||||
|
||||
return folder_id;
|
||||
}
|
||||
}
|
||||
|
||||
let new_group_folder = LayerNodeIdentifier::new_unchecked(folder_id);
|
||||
@@ -2026,6 +2368,86 @@ 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>) {
|
||||
@@ -2103,7 +2525,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 vector table row.
|
||||
// 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: 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();
|
||||
@@ -2866,17 +3288,23 @@ 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(),
|
||||
];
|
||||
@@ -3021,7 +3449,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::Artboard(Default::default()), -1, "", &[]);
|
||||
network_interface.add_export(TaggedValue::TypeDefault(descriptor!(graphene_std::list::List<graphene_std::Artboard>)), -1, "", &[]);
|
||||
network_interface
|
||||
}
|
||||
|
||||
@@ -3221,6 +3649,16 @@ impl Iterator for ClickXRayIter<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Deserializes `CollapsedLayers` with backwards compatibility for the old format
|
||||
/// (flat list of layer node IDs) by consuming the entire value first, then attempting
|
||||
/// to interpret it as the new format. Falls back to an empty default for old documents.
|
||||
fn deserialize_collapsed_layers<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<CollapsedLayers, D::Error> {
|
||||
use serde::Deserialize;
|
||||
// Buffer the entire value to avoid leaving the deserializer in a bad state on type mismatch
|
||||
let value = serde_json::Value::deserialize(deserializer)?;
|
||||
Ok(serde_json::from_value(value).unwrap_or_default())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod document_message_handler_tests {
|
||||
use super::*;
|
||||
|
||||
@@ -2,18 +2,16 @@ 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, IVec2};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Artboard;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::brush::brush_stroke::BrushStroke;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster_types::{CPU, Raster};
|
||||
use graphene_std::raster_types::Image;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::table::Table;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::PointId;
|
||||
use graphene_std::vector::VectorModificationType;
|
||||
use graphene_std::vector::style::{Fill, Stroke};
|
||||
use graphene_std::vector::style::{Fill, GradientSpreadMethod, GradientType, Stroke};
|
||||
use graphene_std::vector::{GradientStops, PointId, VectorModificationType};
|
||||
|
||||
#[impl_message(Message, DocumentMessage, GraphOperation)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
@@ -26,6 +24,23 @@ 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,
|
||||
@@ -66,14 +81,28 @@ pub enum GraphOperationMessage {
|
||||
},
|
||||
NewArtboard {
|
||||
id: NodeId,
|
||||
artboard: Artboard,
|
||||
location: DVec2,
|
||||
dimensions: DVec2,
|
||||
background: Color,
|
||||
clip: bool,
|
||||
},
|
||||
NewBitmapLayer {
|
||||
id: NodeId,
|
||||
image_frame: Table<Raster<CPU>>,
|
||||
image: Image<Color>,
|
||||
parent: LayerNodeIdentifier,
|
||||
insert_index: usize,
|
||||
},
|
||||
NewInterpolationLayer {
|
||||
id: NodeId,
|
||||
control_path_id: NodeId,
|
||||
parent: LayerNodeIdentifier,
|
||||
insert_index: usize,
|
||||
blend_count: Option<usize>,
|
||||
},
|
||||
ConnectInterpolationControlPathToChildren {
|
||||
interpolation_layer_id: NodeId,
|
||||
control_path_id: NodeId,
|
||||
},
|
||||
NewBooleanOperationLayer {
|
||||
id: NodeId,
|
||||
operation: graphene_std::vector::misc::BooleanOperation,
|
||||
@@ -86,6 +115,12 @@ pub enum GraphOperationMessage {
|
||||
parent: LayerNodeIdentifier,
|
||||
insert_index: usize,
|
||||
},
|
||||
NewColorFillLayer {
|
||||
node_id: NodeId,
|
||||
color: Color,
|
||||
parent: LayerNodeIdentifier,
|
||||
insert_index: usize,
|
||||
},
|
||||
NewVectorLayer {
|
||||
id: NodeId,
|
||||
subpaths: Vec<Subpath<PointId>>,
|
||||
@@ -102,8 +137,8 @@ pub enum GraphOperationMessage {
|
||||
},
|
||||
ResizeArtboard {
|
||||
layer: LayerNodeIdentifier,
|
||||
location: IVec2,
|
||||
dimensions: IVec2,
|
||||
location: DVec2,
|
||||
dimensions: DVec2,
|
||||
},
|
||||
RemoveArtboards,
|
||||
NewSvg {
|
||||
|
||||
+148
-24
@@ -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::document::value::TaggedValue;
|
||||
use graph_craft::descriptor;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_std::Color;
|
||||
use graphene_std::list::List;
|
||||
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, GradientStop, GradientStops, GradientType, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
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,7 +42,27 @@ 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.blending_fill_set(fill);
|
||||
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);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::OpacitySet { layer, opacity } => {
|
||||
@@ -108,11 +128,16 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
|
||||
network_interface.force_set_upstream_to_chain(&first_chain_node, &[]);
|
||||
}
|
||||
GraphOperationMessage::NewArtboard { id, artboard } => {
|
||||
GraphOperationMessage::NewArtboard {
|
||||
id,
|
||||
location,
|
||||
dimensions,
|
||||
background,
|
||||
clip,
|
||||
} => {
|
||||
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
|
||||
|
||||
let artboard_location = artboard.location;
|
||||
let artboard_layer = modify_inputs.create_artboard(id, artboard);
|
||||
let artboard_layer = modify_inputs.create_artboard(id, location, dimensions, background, clip);
|
||||
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
|
||||
@@ -138,14 +163,14 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
// Apply a translation to prevent the content from shifting
|
||||
responses.add(GraphOperationMessage::TransformChange {
|
||||
layer,
|
||||
transform: DAffine2::from_translation(-artboard_location.as_dvec2()),
|
||||
transform: DAffine2::from_translation(-location),
|
||||
transform_in: TransformIn::Local,
|
||||
skip_rerender: true,
|
||||
});
|
||||
}
|
||||
|
||||
// Set the bottom input of the artboard back to artboard
|
||||
let bottom_input = NodeInput::value(TaggedValue::Artboard(Table::new()), true);
|
||||
let bottom_input = NodeInput::type_default(descriptor!(List<Artboard>), 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.
|
||||
@@ -153,24 +178,92 @@ 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::value(TaggedValue::Artboard(Table::new()), true);
|
||||
let bottom_input = NodeInput::type_default(descriptor!(List<Artboard>), 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 {
|
||||
GraphOperationMessage::NewBitmapLayer { id, image, 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);
|
||||
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
GraphOperationMessage::NewInterpolationLayer {
|
||||
id,
|
||||
image_frame,
|
||||
control_path_id,
|
||||
parent,
|
||||
insert_index,
|
||||
blend_count,
|
||||
} => {
|
||||
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
|
||||
let layer = modify_inputs.create_layer(id);
|
||||
modify_inputs.insert_image_data(image_frame, layer);
|
||||
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
|
||||
// Insert the main chain node (Blend or Morph) depending on whether a blend count is provided
|
||||
let (chain_node_id, layer_alias, path_alias) = if let Some(count) = blend_count {
|
||||
(modify_inputs.insert_blend_data(layer, count as f64), "Blend", "Blend Path")
|
||||
} else {
|
||||
(modify_inputs.insert_morph_data(layer), "Morph", "Morph Path")
|
||||
};
|
||||
|
||||
// Create the control path layer (Path → Auto-Tangents → Origins to Polyline)
|
||||
let control_path_layer = modify_inputs.create_layer(control_path_id);
|
||||
let path_node_id = modify_inputs.insert_control_path_data(control_path_layer);
|
||||
|
||||
network_interface.move_layer_to_stack(control_path_layer, parent, insert_index, &[]);
|
||||
network_interface.move_layer_to_stack(layer, parent, insert_index + 1, &[]);
|
||||
|
||||
// Connect the Path node's output to the chain node's path parameter input (input 4 for both Morph and Blend).
|
||||
// Done after move_layer_to_stack so chain nodes have correct positions when converted to absolute.
|
||||
network_interface.set_input(&InputConnector::node(chain_node_id, 4), NodeInput::node(path_node_id, 0), &[]);
|
||||
|
||||
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(),
|
||||
});
|
||||
}
|
||||
GraphOperationMessage::ConnectInterpolationControlPathToChildren {
|
||||
interpolation_layer_id,
|
||||
control_path_id,
|
||||
} => {
|
||||
// Find the chain node (Blend or Morph, first in chain of the layer)
|
||||
let Some(OutputConnector::Node { node_id: chain_node, .. }) = network_interface.upstream_output_connector(&InputConnector::node(interpolation_layer_id, 1), &[]) else {
|
||||
log::error!("Could not find chain node for layer {interpolation_layer_id}");
|
||||
return;
|
||||
};
|
||||
|
||||
// Get what feeds into the chain node's primary input (the children stack)
|
||||
let Some(OutputConnector::Node { node_id: children_id, output_index }) = network_interface.upstream_output_connector(&InputConnector::node(chain_node, 0), &[]) else {
|
||||
log::error!("Could not find children stack feeding chain node {chain_node}");
|
||||
return;
|
||||
};
|
||||
|
||||
// Find the deepest node in the control path layer's chain (Origins to Polyline)
|
||||
let mut deepest_chain_node = None;
|
||||
let mut current_connector = InputConnector::node(control_path_id, 1);
|
||||
while let Some(OutputConnector::Node { node_id, .. }) = network_interface.upstream_output_connector(¤t_connector, &[]) {
|
||||
deepest_chain_node = Some(node_id);
|
||||
current_connector = InputConnector::node(node_id, 0);
|
||||
}
|
||||
|
||||
// Connect children to the deepest chain node's input 0 (or the layer's input 1 if no chain)
|
||||
let target_connector = match deepest_chain_node {
|
||||
Some(node_id) => InputConnector::node(node_id, 0),
|
||||
None => InputConnector::node(control_path_id, 1),
|
||||
};
|
||||
network_interface.set_input(&target_connector, NodeInput::node(children_id, output_index), &[]);
|
||||
|
||||
// Shift the child stack (topmost child only, the rest follow) down 3 and left 10
|
||||
network_interface.shift_node(&children_id, IVec2::new(-10, 3), &[]);
|
||||
}
|
||||
GraphOperationMessage::NewBooleanOperationLayer { id, operation, parent, insert_index } => {
|
||||
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
|
||||
@@ -179,6 +272,7 @@ 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);
|
||||
@@ -203,6 +297,13 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
responses.add(NodeGraphMessage::MoveLayerToStack { layer, parent, insert_index });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
GraphOperationMessage::NewColorFillLayer { node_id, color, parent, insert_index } => {
|
||||
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
|
||||
let layer = modify_inputs.create_layer(node_id);
|
||||
modify_inputs.insert_color_value(color, layer);
|
||||
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
GraphOperationMessage::NewVectorLayer { id, subpaths, parent, insert_index } => {
|
||||
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
|
||||
let layer = modify_inputs.create_layer(id);
|
||||
@@ -222,7 +323,6 @@ 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 } => {
|
||||
@@ -270,6 +370,7 @@ 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,
|
||||
});
|
||||
@@ -384,7 +485,8 @@ struct ArtboardInfo {
|
||||
}
|
||||
|
||||
fn usvg_color(c: usvg::Color, a: f32) -> Color {
|
||||
Color::from_rgbaf32_unchecked(c.red as f32 / 255., c.green as f32 / 255., c.blue as f32 / 255., a)
|
||||
// `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)
|
||||
}
|
||||
|
||||
fn usvg_transform(c: usvg::Transform) -> DAffine2 {
|
||||
@@ -590,7 +692,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_network_node_id("Transform", false) {
|
||||
if has_transform && let Some(transform_node_id) = modify_inputs.existing_proto_node_id(graphene_std::transform_nodes::transform::IDENTIFIER, false) {
|
||||
transform_utils::update_transform(modify_inputs.network_interface, &transform_node_id, node_transform);
|
||||
}
|
||||
|
||||
@@ -640,10 +742,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), &[]);
|
||||
@@ -687,6 +789,14 @@ fn apply_usvg_stroke(stroke: &usvg::Stroke, modify_inputs: &mut ModifyInputsCont
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_spread_method(spread_method: usvg::SpreadMethod) -> GradientSpreadMethod {
|
||||
match spread_method {
|
||||
usvg::SpreadMethod::Pad => GradientSpreadMethod::Pad,
|
||||
usvg::SpreadMethod::Reflect => GradientSpreadMethod::Reflect,
|
||||
usvg::SpreadMethod::Repeat => GradientSpreadMethod::Repeat,
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, bounds_transform: DAffine2, graphite_gradient_stops: &HashMap<String, GradientStops>) {
|
||||
modify_inputs.fill_set(match &fill.paint() {
|
||||
usvg::Paint::Color(color) => Fill::solid(usvg_color(*color, fill.opacity().get())),
|
||||
@@ -709,8 +819,15 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, b
|
||||
GradientStops::new(stops)
|
||||
}
|
||||
};
|
||||
let spread_method = convert_spread_method(linear.spread_method());
|
||||
|
||||
Fill::Gradient(Gradient { start, end, gradient_type, stops })
|
||||
Fill::Gradient(Gradient {
|
||||
start,
|
||||
end,
|
||||
gradient_type,
|
||||
stops,
|
||||
spread_method,
|
||||
})
|
||||
}
|
||||
usvg::Paint::RadialGradient(radial) => {
|
||||
let gradient_transform = usvg_transform(radial.transform());
|
||||
@@ -732,8 +849,15 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, b
|
||||
GradientStops::new(stops)
|
||||
}
|
||||
};
|
||||
let spread_method = convert_spread_method(radial.spread_method());
|
||||
|
||||
Fill::Gradient(Gradient { start, end, gradient_type, stops })
|
||||
Fill::Gradient(Gradient {
|
||||
start,
|
||||
end,
|
||||
gradient_type,
|
||||
stops,
|
||||
spread_method,
|
||||
})
|
||||
}
|
||||
usvg::Paint::Pattern(_) => {
|
||||
warn!("SVG patterns are not currently supported");
|
||||
|
||||
@@ -3,44 +3,21 @@ use glam::{DAffine2, DVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::transform::Transform;
|
||||
use graphene_std::vector::PointId;
|
||||
|
||||
/// Convert an affine transform into the tuple `(scale, angle, translation, shear)` assuming `shear.y = 0`.
|
||||
pub fn compute_scale_angle_translation_shear(transform: DAffine2) -> (DVec2, f64, DVec2, DVec2) {
|
||||
let x_axis = transform.matrix2.x_axis;
|
||||
let y_axis = transform.matrix2.y_axis;
|
||||
|
||||
// Assuming there is no vertical shear
|
||||
let angle = x_axis.y.atan2(x_axis.x);
|
||||
let (sin, cos) = angle.sin_cos();
|
||||
let scale_x = if cos.abs() > 1e-10 { x_axis.x / cos } else { x_axis.y / sin };
|
||||
|
||||
let mut shear_x = (sin * y_axis.y + cos * y_axis.x) / (sin * sin * scale_x + cos * cos * scale_x);
|
||||
if !shear_x.is_finite() {
|
||||
shear_x = 0.;
|
||||
}
|
||||
let scale_y = if cos.abs() > 1e-10 {
|
||||
(y_axis.y - scale_x * sin * shear_x) / cos
|
||||
} else {
|
||||
(scale_x * cos * shear_x - y_axis.x) / sin
|
||||
};
|
||||
let translation = transform.translation;
|
||||
let scale = DVec2::new(scale_x, scale_y);
|
||||
let shear = DVec2::new(shear_x, 0.);
|
||||
(scale, angle, translation, shear)
|
||||
}
|
||||
|
||||
/// Update the inputs of the transform node to match a new transform
|
||||
pub fn update_transform(network_interface: &mut NodeNetworkInterface, node_id: &NodeId, transform: DAffine2) {
|
||||
let (scale, rotation, translation, shear) = compute_scale_angle_translation_shear(transform);
|
||||
let (rotation, scale, skew) = transform.decompose_rotation_scale_skew();
|
||||
let translation = transform.translation;
|
||||
|
||||
let rotation = rotation.to_degrees();
|
||||
let shear = DVec2::new(shear.x.atan().to_degrees(), shear.y.atan().to_degrees());
|
||||
let skew = DVec2::new(skew.atan().to_degrees(), 0.);
|
||||
|
||||
network_interface.set_input(&InputConnector::node(*node_id, 1), NodeInput::value(TaggedValue::DVec2(translation), false), &[]);
|
||||
network_interface.set_input(&InputConnector::node(*node_id, 2), NodeInput::value(TaggedValue::F64(rotation), false), &[]);
|
||||
network_interface.set_input(&InputConnector::node(*node_id, 3), NodeInput::value(TaggedValue::DVec2(scale), false), &[]);
|
||||
network_interface.set_input(&InputConnector::node(*node_id, 4), NodeInput::value(TaggedValue::DVec2(shear), false), &[]);
|
||||
network_interface.set_input(&InputConnector::node(*node_id, 4), NodeInput::value(TaggedValue::DVec2(skew), false), &[]);
|
||||
}
|
||||
|
||||
// TODO: This should be extracted from the graph at the location of the transform node.
|
||||
@@ -81,12 +58,12 @@ pub fn get_current_transform(inputs: &[NodeInput]) -> DAffine2 {
|
||||
};
|
||||
let rotation = if let Some(&TaggedValue::F64(rotation)) = inputs[2].as_value() { rotation } else { 0. };
|
||||
let scale = if let Some(&TaggedValue::DVec2(scale)) = inputs[3].as_value() { scale } else { DVec2::ONE };
|
||||
let shear = if let Some(&TaggedValue::DVec2(shear)) = inputs[4].as_value() { shear } else { DVec2::ZERO };
|
||||
let skew = if let Some(&TaggedValue::DVec2(skew)) = inputs[4].as_value() { skew } else { DVec2::ZERO };
|
||||
|
||||
let rotation = rotation.to_radians();
|
||||
let shear = DVec2::new(shear.x.to_radians().tan(), shear.y.to_radians().tan());
|
||||
let skew = DVec2::new(skew.x.to_radians().tan(), skew.y.to_radians().tan());
|
||||
|
||||
DAffine2::from_scale_angle_translation(scale, rotation, translation) * DAffine2::from_cols_array(&[1., shear.y, shear.x, 1., 0., 0.])
|
||||
DAffine2::from_scale_angle_translation(scale, rotation, translation) * DAffine2::from_cols_array(&[1., skew.y, skew.x, 1., 0., 0.])
|
||||
}
|
||||
|
||||
/// Extract the current normalized pivot from the layer
|
||||
@@ -135,8 +112,8 @@ mod tests {
|
||||
/// ```
|
||||
#[test]
|
||||
fn derive_transform() {
|
||||
for shear_x in -10..=10 {
|
||||
let shear_x = (shear_x as f64) / 2.;
|
||||
for skew_x in -10..=10 {
|
||||
let skew_x = (skew_x as f64) / 2.;
|
||||
for angle in (0..=360).step_by(15) {
|
||||
let angle = (angle as f64).to_radians();
|
||||
for scale_x in 1..10 {
|
||||
@@ -144,22 +121,23 @@ mod tests {
|
||||
for scale_y in 1..10 {
|
||||
let scale_y = (scale_y as f64) / 5.;
|
||||
|
||||
let shear = DVec2::new(shear_x, 0.);
|
||||
let skew = DVec2::new(skew_x, 0.);
|
||||
let scale = DVec2::new(scale_x, scale_y);
|
||||
let translate = DVec2::new(5666., 644.);
|
||||
|
||||
let original_transform = DAffine2::from_cols(
|
||||
DVec2::new(scale.x * angle.cos() - scale.y * angle.sin() * shear.y, scale.x * angle.sin() + scale.y * angle.cos() * shear.y),
|
||||
DVec2::new(scale.x * angle.cos() * shear.x - scale.y * angle.sin(), scale.x * angle.sin() * shear.x + scale.y * angle.cos()),
|
||||
DVec2::new(scale.x * angle.cos() - scale.y * angle.sin() * skew.y, scale.x * angle.sin() + scale.y * angle.cos() * skew.y),
|
||||
DVec2::new(scale.x * angle.cos() * skew.x - scale.y * angle.sin(), scale.x * angle.sin() * skew.x + scale.y * angle.cos()),
|
||||
translate,
|
||||
);
|
||||
|
||||
let (new_scale, new_angle, new_translation, new_shear) = compute_scale_angle_translation_shear(original_transform);
|
||||
let new_transform = DAffine2::from_scale_angle_translation(new_scale, new_angle, new_translation) * DAffine2::from_cols_array(&[1., new_shear.y, new_shear.x, 1., 0., 0.]);
|
||||
let (new_angle, new_scale, new_skew) = original_transform.decompose_rotation_scale_skew();
|
||||
let new_translation = original_transform.translation;
|
||||
let new_transform = DAffine2::from_scale_angle_translation(new_scale, new_angle, new_translation) * DAffine2::from_cols_array(&[1., 0., new_skew, 1., 0., 0.]);
|
||||
|
||||
assert!(
|
||||
new_transform.abs_diff_eq(original_transform, 1e-10),
|
||||
"original_transform {original_transform} new_transform {new_transform} / scale {scale} new_scale {new_scale} / angle {angle} new_angle {new_angle} / shear {shear} / new_shear {new_shear}",
|
||||
"original_transform {original_transform} new_transform {new_transform} / scale {scale} new_scale {new_scale} / angle {angle} new_angle {new_angle} / skew {skew} / new_skew {new_skew}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,21 +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, IVec2};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graph_craft::{ProtoNodeIdentifier, concrete};
|
||||
use graphene_std::Artboard;
|
||||
use graph_craft::{ProtoNodeIdentifier, concrete, descriptor};
|
||||
use graphene_std::brush::brush_stroke::BrushStroke;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster_types::{CPU, Raster};
|
||||
use graphene_std::raster_types::Image;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::table::Table;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::vector::style::{Fill, Stroke};
|
||||
use graphene_std::vector::{PointId, VectorModificationType};
|
||||
use graphene_std::{Graphic, NodeInputDecleration};
|
||||
use graphene_std::vector::style::{Fill, GradientSpreadMethod, GradientType, Stroke};
|
||||
use graphene_std::vector::{GradientStops, PointId, Vector, VectorModification, VectorModificationType};
|
||||
use graphene_std::{Artboard, Color, Graphic, NodeInputDecleration};
|
||||
|
||||
#[derive(PartialEq, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum TransformIn {
|
||||
@@ -131,43 +129,100 @@ 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, artboard: Artboard) -> LayerNodeIdentifier {
|
||||
/// 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 {
|
||||
let artboard_node_template = resolve_network_node_type("Artboard").expect("Node").node_template_input_override([
|
||||
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)),
|
||||
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)),
|
||||
]);
|
||||
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_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 = 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_id = NodeId::new();
|
||||
self.network_interface.insert_node(boolean_id, boolean, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&boolean_id, layer, &[], self.import);
|
||||
}
|
||||
|
||||
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_id = NodeId::new();
|
||||
self.network_interface.insert_node(blend_id, blend, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&blend_id, layer, &[], self.import);
|
||||
|
||||
blend_id
|
||||
}
|
||||
|
||||
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))]);
|
||||
|
||||
let morph_id = NodeId::new();
|
||||
self.network_interface.insert_node(morph_id, morph, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&morph_id, layer, &[], self.import);
|
||||
|
||||
morph_id
|
||||
}
|
||||
|
||||
/// Returns the Path node ID (the node closest to the layer's merge node in the chain).
|
||||
pub fn insert_control_path_data(&mut self, layer: LayerNodeIdentifier) -> NodeId {
|
||||
// Add Origins to Polyline node first (will be pushed deepest in the chain)
|
||||
let origins_to_polyline = resolve_network_node_type("Origins to Polyline")
|
||||
.expect("Origins to Polyline node does not exist")
|
||||
.default_node_template();
|
||||
let origins_to_polyline_id = NodeId::new();
|
||||
self.network_interface.insert_node(origins_to_polyline_id, origins_to_polyline, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&origins_to_polyline_id, layer, &[], self.import);
|
||||
|
||||
// Add Auto-Tangents node (between Origins to Polyline and Path), with spread=1 and preserve_existing=false
|
||||
let auto_tangents = resolve_proto_node_type(graphene_std::vector::auto_tangents::IDENTIFIER)
|
||||
.expect("Auto-Tangents node does not exist")
|
||||
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(1.), false)), Some(NodeInput::value(TaggedValue::Bool(false), false))]);
|
||||
let auto_tangents_id = NodeId::new();
|
||||
self.network_interface.insert_node(auto_tangents_id, auto_tangents, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&auto_tangents_id, layer, &[], self.import);
|
||||
|
||||
// Add Path node to chain start (closest to the Merge node)
|
||||
let path = resolve_network_node_type("Path").expect("Path node does not exist").default_node_template();
|
||||
let path_id = NodeId::new();
|
||||
self.network_interface.insert_node(path_id, path, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&path_id, layer, &[], self.import);
|
||||
|
||||
path_id
|
||||
}
|
||||
|
||||
pub fn insert_vector(&mut self, subpaths: Vec<Subpath<PointId>>, layer: LayerNodeIdentifier, include_transform: bool, include_fill: bool, include_stroke: bool) {
|
||||
let vector = Table::new_from_element(Vector::from_subpaths(subpaths, true));
|
||||
// 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 shape = resolve_network_node_type("Path")
|
||||
.expect("Path node does not exist")
|
||||
.node_template_input_override([Some(NodeInput::value(TaggedValue::Vector(vector), false))]);
|
||||
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::VectorModification(modification), 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_network_node_type("Transform").expect("Transform node does not exist").default_node_template();
|
||||
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
|
||||
.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);
|
||||
@@ -209,9 +264,8 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.tilt), false)),
|
||||
Some(NodeInput::value(TaggedValue::TextAlign(typesetting.align), false)),
|
||||
]);
|
||||
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")
|
||||
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
|
||||
.expect("Transform 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")
|
||||
@@ -225,23 +279,31 @@ 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);
|
||||
}
|
||||
|
||||
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))]);
|
||||
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))]);
|
||||
|
||||
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))]);
|
||||
|
||||
let image_id = NodeId::new();
|
||||
self.network_interface.insert_node(image_id, image, &[]);
|
||||
self.network_interface.insert_node(image_id, image_node, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&image_id, layer, &[], self.import);
|
||||
|
||||
let transform_id = NodeId::new();
|
||||
@@ -321,10 +383,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 table data by utilizing the reference (index or ID?) for each row.
|
||||
// TODO: Allow the 'Path' node to operate on `List` data by utilizing the reference (index or ID?) for each item.
|
||||
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!(Table<Graphic>)) {
|
||||
if layer_input_type.compiled_nested_type() == Some(&concrete!(List<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;
|
||||
@@ -351,15 +413,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(Table::new()), false), true);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(None), false), true);
|
||||
}
|
||||
Fill::Solid(color) => {
|
||||
let input_connector = InputConnector::node(fill_node_id, backup_color_index);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(Table::new_from_element(*color)), false), true);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(Some(*color)), false), true);
|
||||
}
|
||||
Fill::Gradient(gradient) => {
|
||||
let input_connector = InputConnector::node(fill_node_id, backup_gradient_index);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Gradient(gradient.clone()), false), true);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::FillGradient(gradient.clone()), false), true);
|
||||
}
|
||||
}
|
||||
let input_connector = InputConnector::node(fill_node_id, fill_index);
|
||||
@@ -367,35 +429,160 @@ 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::blending::IDENTIFIER, true) else {
|
||||
let Some(blend_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::blend_mode::IDENTIFIER, true) else {
|
||||
return;
|
||||
};
|
||||
let input_connector = InputConnector::node(blend_node_id, 1);
|
||||
let input_connector = InputConnector::node(blend_node_id, graphene_std::blending_nodes::blend_mode::BlendModeInput::INDEX);
|
||||
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(blend_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::blending::IDENTIFIER, true) else {
|
||||
let Some(opacity_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::opacity::IDENTIFIER, true) else {
|
||||
return;
|
||||
};
|
||||
let input_connector = InputConnector::node(blend_node_id, 2);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(opacity * 100.), false), false);
|
||||
// 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,
|
||||
);
|
||||
}
|
||||
|
||||
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 {
|
||||
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 {
|
||||
return;
|
||||
};
|
||||
let input_connector = InputConnector::node(blend_node_id, 3);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(fill * 100.), false), false);
|
||||
// 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);
|
||||
}
|
||||
|
||||
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::blending::IDENTIFIER, true) else {
|
||||
let Some(clip_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::clipping_mask::IDENTIFIER, true) else {
|
||||
return;
|
||||
};
|
||||
let input_connector = InputConnector::node(clip_node_id, 4);
|
||||
let input_connector = InputConnector::node(clip_node_id, graphene_std::blending_nodes::clipping_mask::ClipInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Bool(clip), false), false);
|
||||
}
|
||||
|
||||
@@ -404,10 +591,8 @@ 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);
|
||||
@@ -420,8 +605,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::<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::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::DashOffsetInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.dash_offset), false), true);
|
||||
}
|
||||
@@ -431,7 +616,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_network_node_id("Transform", false)
|
||||
.existing_proto_node_id(graphene_std::transform_nodes::transform::IDENTIFIER, 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))
|
||||
@@ -455,17 +640,32 @@ 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_network_node_id("Transform", false);
|
||||
let transform_node_id = self.existing_proto_node_id(graphene_std::transform_nodes::transform::IDENTIFIER, false);
|
||||
|
||||
// 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(),
|
||||
// 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
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
@@ -480,7 +680,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
// Create the Transform node
|
||||
self.existing_network_node_id("Transform", true)
|
||||
self.existing_proto_node_id(graphene_std::transform_nodes::transform::IDENTIFIER, true)
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
@@ -505,13 +705,13 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
pub fn brush_modify(&mut self, strokes: Vec<BrushStroke>) {
|
||||
let Some(brush_node_id) = self.existing_network_node_id("Brush", true) else {
|
||||
let Some(brush_node_id) = self.existing_proto_node_id(graphene_std::brush::brush::brush::IDENTIFIER, 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: IVec2, dimensions: IVec2) {
|
||||
pub fn resize_artboard(&mut self, location: DVec2, dimensions: DVec2) {
|
||||
let Some(artboard_node_id) = self.existing_network_node_id("Artboard", true) else {
|
||||
return;
|
||||
};
|
||||
@@ -519,19 +719,19 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
let mut dimensions = dimensions;
|
||||
let mut location = location;
|
||||
|
||||
if dimensions.x < 0 {
|
||||
dimensions.x *= -1;
|
||||
if dimensions.x < 0. {
|
||||
dimensions.x = -dimensions.x;
|
||||
location.x -= dimensions.x;
|
||||
}
|
||||
if dimensions.y < 0 {
|
||||
dimensions.y *= -1;
|
||||
if dimensions.y < 0. {
|
||||
dimensions.y = -dimensions.y;
|
||||
location.y -= dimensions.y;
|
||||
}
|
||||
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);
|
||||
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);
|
||||
}
|
||||
|
||||
/// 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);
|
||||
@@ -540,3 +740,29 @@ 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)
|
||||
}
|
||||
Loaded 100 of 401 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user