mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
43c780c5c0 | ||
|
|
3c04c2bb8b | ||
|
|
e0d3c21429 | ||
|
|
96b18d2552 | ||
|
|
7afa1ced37 | ||
|
|
adee7fc46f | ||
|
|
9e2a274453 | ||
|
|
97f44e8915 |
No files matched your search
@@ -1,2 +1,2 @@
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/0d004aa61e6b48d316e8e5db6d59ccc4788f192d.tar.gz
|
||||
772d64518be43c99977ba56f69e574531c56e83d2df2f42ab066f77f74b0dd1f
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/1509880500e32cb21235343ba865adcf0579133f.tar.gz
|
||||
89b4c58aee186b0c1610a8778bd199c9bdaf1191b4006e6b007dc40a402f4aa7
|
||||
@@ -1,7 +1,3 @@
|
||||
[build]
|
||||
# Keep `--cfg=web_sys_unstable_apis` here so the wasm wrapper crates build with the same web-sys API signatures (e.g. `put_image_data`/`get_image_data` taking `i32` rather than `f64`) on both native test builds and the wasm target. Cargo applies `[build]` rustflags only when no target-specific rustflags table matches, so the wasm-specific list below must continue to include this cfg.
|
||||
rustflags = ["--cfg=web_sys_unstable_apis"]
|
||||
|
||||
[target.wasm32-unknown-unknown]
|
||||
rustflags = [
|
||||
# Currently disabled because of https://github.com/GraphiteEditor/Graphite/issues/1262
|
||||
@@ -13,9 +9,6 @@ rustflags = [
|
||||
"-C",
|
||||
"link-arg=--max-memory=4294967296",
|
||||
"--cfg=web_sys_unstable_apis",
|
||||
# TODO: Remove this and find a better way to stay within the 25MB limit of cloudflare pages
|
||||
"-C",
|
||||
"opt-level=s",
|
||||
]
|
||||
|
||||
[env]
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
},
|
||||
"ghcr.io/devcontainers/features/node:1": {}
|
||||
},
|
||||
"onCreateCommand": "cargo install cargo-watch wasm-pack cargo-about && cargo install -f [email protected]21",
|
||||
"onCreateCommand": "cargo install cargo-watch wasm-pack cargo-about && cargo install -f [email protected]00",
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
// NOTE: Keep this in sync with `.vscode/extensions.json`
|
||||
|
||||
+13
-39
@@ -123,7 +123,7 @@ jobs:
|
||||
DELAY=15
|
||||
for ATTEMPT in $(seq 1 $MAX_ATTEMPTS); do
|
||||
echo "Attempt $ATTEMPT of $MAX_ATTEMPTS..."
|
||||
npx wrangler@3 pages deploy "frontend/dist" --project-name="${{ steps.production-env.outputs.cf_project || 'graphite-dev' }}" --branch="master" --commit-dirty=true 2>&1 | tee /tmp/wrangler_output
|
||||
npx wrangler@3 pages deploy "frontend/dist" --project-name="${{ steps.production-env.outputs.cf_project || 'graphite-dev' }}" --commit-dirty=true 2>&1 | tee /tmp/wrangler_output
|
||||
if [ ${PIPESTATUS[0]} -eq 0 ]; then
|
||||
URL=$(grep -oP 'https://[^\s]+\.pages\.dev' /tmp/wrangler_output | head -1)
|
||||
echo "url=$URL" >> "$GITHUB_OUTPUT"
|
||||
@@ -153,38 +153,22 @@ jobs:
|
||||
if [ "${{ github.ref }}" = "refs/tags/latest-stable" ]; then
|
||||
REF="latest-stable"
|
||||
ENVIRONMENT="graphite-editor (Production)"
|
||||
AUTO_INACTIVE="true"
|
||||
TRANSIENT_ENVIRONMENT="false"
|
||||
elif [ "${{ github.event_name }}" = "push" ]; then
|
||||
REF="master"
|
||||
ENVIRONMENT="graphite-dev (Production)"
|
||||
AUTO_INACTIVE="true"
|
||||
TRANSIENT_ENVIRONMENT="false"
|
||||
else
|
||||
REF="${{ inputs.checkout_ref || github.head_ref || github.ref_name }}"
|
||||
REF="$(git rev-parse HEAD)"
|
||||
ENVIRONMENT="graphite-dev (Preview)"
|
||||
AUTO_INACTIVE="false"
|
||||
TRANSIENT_ENVIRONMENT="true"
|
||||
fi
|
||||
create_deployment() {
|
||||
gh api \
|
||||
-X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
repos/${{ github.repository }}/deployments \
|
||||
--input - \
|
||||
--jq '.id' <<EOF
|
||||
{
|
||||
"ref": "$1",
|
||||
"environment": "$ENVIRONMENT",
|
||||
"auto_merge": false,
|
||||
"required_contexts": [],
|
||||
"auto_inactive": $AUTO_INACTIVE,
|
||||
"transient_environment": $TRANSIENT_ENVIRONMENT
|
||||
}
|
||||
DEPLOY_ID=$(gh api \
|
||||
-X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
repos/${{ github.repository }}/deployments \
|
||||
--input - \
|
||||
--jq '.id' <<EOF
|
||||
{"ref":"$REF","environment":"$ENVIRONMENT","auto_merge":false,"required_contexts":[]}
|
||||
EOF
|
||||
}
|
||||
# Try branch name first (needed for GitHub's PR "View deployment" button), fall back to commit SHA if the branch was deleted
|
||||
DEPLOY_ID=$(create_deployment "$REF" 2>/dev/null) || DEPLOY_ID=$(create_deployment "$(git rev-parse HEAD)")
|
||||
)
|
||||
gh api \
|
||||
-X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
@@ -204,19 +188,9 @@ jobs:
|
||||
exit 0
|
||||
fi
|
||||
|
||||
size_of() { find frontend/dist/assets "$@" -printf '%s\n' | awk '{s+=$1} END {printf "%.2f MB", s/1048576}'; }
|
||||
WASM_SIZE=$(size_of -name '*.wasm')
|
||||
JS_SIZE=$(size_of -name '*.js')
|
||||
CSS_SIZE=$(size_of -name '*.css')
|
||||
FONT_SIZE=$(size_of \( -name '*.woff2' -o -name '*.woff' -o -name '*.ttf' -o -name '*.otf' \))
|
||||
IMAGE_SIZE=$(size_of \( -name '*.png' -o -name '*.jpg' -o -name '*.svg' \))
|
||||
ALL_SIZE=$(size_of -type f)
|
||||
|
||||
COMMENT_BODY="| 📦 **Web Build Complete for** $(git rev-parse HEAD) |
|
||||
|-|
|
||||
| $CF_URL |
|
||||
|
||||
Wasm: **$WASM_SIZE** — JS: **$JS_SIZE** — CSS: **$CSS_SIZE** — Fonts: **$FONT_SIZE** — Images: **$IMAGE_SIZE** — All Assets: **$ALL_SIZE**"
|
||||
| $CF_URL |"
|
||||
|
||||
if [ "${{ github.ref }}" = "refs/tags/latest-stable" ]; then
|
||||
# Push tag: skip commenting (commit was already commented on master merge)
|
||||
@@ -283,7 +257,7 @@ jobs:
|
||||
pull-requests: write
|
||||
|
||||
env:
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.121"
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.100"
|
||||
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
@@ -474,7 +448,7 @@ jobs:
|
||||
pull-requests: write
|
||||
|
||||
env:
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.121"
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.100"
|
||||
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
|
||||
@@ -57,8 +57,7 @@ jobs:
|
||||
|
||||
- name: 🧪 Run Rust tests
|
||||
env:
|
||||
# `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml`
|
||||
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
|
||||
RUSTFLAGS: -Dwarnings
|
||||
run: mold -run cargo test --all-features
|
||||
|
||||
# Rust format check on GitHub runner
|
||||
|
||||
@@ -22,14 +22,27 @@ jobs:
|
||||
- name: Install Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Install Valgrind
|
||||
run: |
|
||||
sudo apt update
|
||||
sudo apt install -y valgrind
|
||||
|
||||
- name: Cache Rust dependencies
|
||||
uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
# Cache on Cargo.lock file
|
||||
cache-on-failure: true
|
||||
|
||||
- name: Install gungraun-runner and valgrind
|
||||
uses: gungraun/setup-gungraun@v1
|
||||
- name: Cache iai-callgrind binary
|
||||
id: cache-iai
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: ~/.cargo/bin/iai-callgrind-runner
|
||||
key: ${{ runner.os }}-iai-callgrind-runner-0.16.1
|
||||
|
||||
- name: Install iai-callgrind
|
||||
if: steps.cache-iai.outputs.cache-hit != 'true'
|
||||
run: cargo install [email protected]
|
||||
|
||||
- name: Checkout master branch
|
||||
run: |
|
||||
@@ -53,21 +66,21 @@ jobs:
|
||||
id: cache-benchmark-baselines
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: target/gungraun
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-gungraun-benchmark-baselines-master-${{ steps.master-sha.outputs.sha }}
|
||||
path: target/iai
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-benchmark-baselines-master-${{ steps.master-sha.outputs.sha }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-gungraun-benchmark-baselines-master-
|
||||
${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-benchmark-baselines-master-
|
||||
|
||||
- name: Run baseline benchmarks
|
||||
if: steps.cache-benchmark-baselines.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
# Compile benchmarks
|
||||
cargo bench --bench compile_demo_art_gungraun -- --save-baseline=master
|
||||
cargo bench --bench compile_demo_art_iai -- --save-baseline=master
|
||||
|
||||
# Runtime benchmarks
|
||||
cargo bench --bench update_executor_gungraun -- --save-baseline=master
|
||||
cargo bench --bench run_once_gungraun -- --save-baseline=master
|
||||
cargo bench --bench run_cached_gungraun -- --save-baseline=master
|
||||
cargo bench --bench update_executor_iai -- --save-baseline=master
|
||||
cargo bench --bench run_once_iai -- --save-baseline=master
|
||||
cargo bench --bench run_cached_iai -- --save-baseline=master
|
||||
|
||||
- name: Checkout PR branch
|
||||
run: git checkout ${{ github.event.pull_request.head.sha }}
|
||||
@@ -75,12 +88,12 @@ jobs:
|
||||
- name: Run PR benchmarks
|
||||
run: |
|
||||
# Compile benchmarks
|
||||
cargo bench --bench compile_demo_art_gungraun -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/compile_output.json
|
||||
cargo bench --bench compile_demo_art_iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/compile_output.json
|
||||
|
||||
# Runtime benchmarks
|
||||
cargo bench --bench update_executor_gungraun -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/update_output.json
|
||||
cargo bench --bench run_once_gungraun -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/run_once_output.json
|
||||
cargo bench --bench run_cached_gungraun -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/run_cached_output.json
|
||||
cargo bench --bench update_executor_iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/update_output.json
|
||||
cargo bench --bench run_once_iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/run_once_output.json
|
||||
cargo bench --bench run_cached_iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/run_cached_output.json
|
||||
|
||||
- name: Make old comments collapsed by default
|
||||
# Only run if we have write permissions (not a fork)
|
||||
|
||||
@@ -12,4 +12,3 @@ flamegraph.svg
|
||||
.idea/
|
||||
.direnv
|
||||
.DS_Store
|
||||
.nvim.lua
|
||||
+5
-2
@@ -61,10 +61,13 @@ in
|
||||
graphite-bundle = (lib.call ./pkgs/graphite-bundle.nix) { };
|
||||
graphite-bundle-dev = (lib.call ./pkgs/graphite-bundle.nix) { graphite = graphite-dev; };
|
||||
graphite-flatpak-manifest = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { };
|
||||
graphite-flatpak-manifest-dev = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { graphite-bundle = graphite-bundle-dev; };
|
||||
graphite-cef = lib.call ./pkgs/graphite-cef.nix;
|
||||
graphite-flatpak-manifest-dev = (lib.call ./pkgs/graphite-flatpak-manifest.nix) {
|
||||
graphite-bundle = graphite-bundle-dev;
|
||||
};
|
||||
|
||||
# TODO: graphene-cli = lib.call ./pkgs/graphene-cli.nix;
|
||||
|
||||
graphite-cef = lib.call ./pkgs/graphite-cef/package.nix;
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
+4
-1
@@ -29,7 +29,7 @@ pkgs.mkShell (
|
||||
pkgs.lld
|
||||
pkgs.nodejs
|
||||
pkgs.binaryen
|
||||
pkgs.wasm-bindgen-cli_0_2_121
|
||||
pkgs.wasm-bindgen-cli_0_2_100
|
||||
pkgs.wasm-pack
|
||||
pkgs.cargo-about
|
||||
|
||||
@@ -61,6 +61,9 @@ pkgs.mkShell (
|
||||
LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libs}:${self.packages.${system}.graphite-cef}";
|
||||
XDG_DATA_DIRS = "${pkgs.gsettings-desktop-schemas}/share/gsettings-schemas/${pkgs.gsettings-desktop-schemas.name}:${pkgs.gtk3}/share/gsettings-schemas/${pkgs.gtk3.name}:$XDG_DATA_DIRS";
|
||||
|
||||
# shellHook = ''
|
||||
# alias cargo='mold --run cargo'
|
||||
# '';
|
||||
}
|
||||
// deps.rustGPU.env
|
||||
)
|
||||
@@ -1,11 +1,10 @@
|
||||
{ pkgs, ... }:
|
||||
|
||||
let
|
||||
version = "147.0.14+g76d2442+chromium-147.0.7727.138";
|
||||
hashes = {
|
||||
aarch64-linux = "sha256-Gy2Xs1NHwmIr+buzoqDso1QJVkKlA/UMXytHjNGqpNk=";
|
||||
x86_64-linux = "sha256-os7wAFJ+mVK65HCikvEjhMeQUj2ty7y+6Ad0OlOcbeA=";
|
||||
};
|
||||
versionFile = builtins.fromJSON (builtins.readFile ./version.json);
|
||||
|
||||
version = versionFile.version;
|
||||
hash = selectSystem versionFile.hashes;
|
||||
|
||||
selectSystem =
|
||||
attrs:
|
||||
@@ -19,7 +18,7 @@ let
|
||||
x86_64-linux = "linux64";
|
||||
}
|
||||
}_minimal.tar.bz2";
|
||||
hash = selectSystem hashes;
|
||||
hash = hash;
|
||||
};
|
||||
in
|
||||
pkgs.cef-binary.overrideAttrs (finalAttrs: {
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"version": "146.0.12+g6214c8e+chromium-146.0.7680.179",
|
||||
"hashes": {
|
||||
"aarch64-linux": "sha256-pi3fV3O31YMHcOh+/lnk2gWI6/MaSNAiUgFhD09d7u0=",
|
||||
"x86_64-linux": "sha256-b2HKaSEEXkZsnsBw9bL2JGmKWwRN5l2wu/O1DxfhAgE="
|
||||
}
|
||||
}
|
||||
@@ -83,7 +83,7 @@ deps.crane.lib.buildPackage (
|
||||
pkgs.lld
|
||||
pkgs.nodejs
|
||||
pkgs.binaryen
|
||||
pkgs.wasm-bindgen-cli_0_2_121
|
||||
pkgs.wasm-bindgen-cli_0_2_100
|
||||
pkgs.wasm-pack
|
||||
pkgs.cargo-about
|
||||
pkgs.removeReferencesTo
|
||||
@@ -152,7 +152,6 @@ deps.crane.lib.buildPackage (
|
||||
patchelf \
|
||||
--set-rpath "${pkgs.lib.makeLibraryPath libs}:${self.packages.${system}.graphite-cef}" \
|
||||
--add-needed libGL.so \
|
||||
--add-needed libEGL.so \
|
||||
$out/bin/graphite
|
||||
'';
|
||||
|
||||
|
||||
Vendored
+1
-2
@@ -70,6 +70,5 @@
|
||||
"*.graphite": "json"
|
||||
},
|
||||
"editor.renderWhitespace": "boundary",
|
||||
"editor.minimap.markSectionHeaderRegex": "// ===+\\n\\s*//\\s*(?<label>[^\\n]{1,18})[^\\n]*(\\n\\s*//[^\\n]*)*\\n\\s*// ===+",
|
||||
"git.addAICoAuthor": "off"
|
||||
"editor.minimap.markSectionHeaderRegex": "// ===+\\n\\s*//\\s*(?<label>[^\\n]{1,18})[^\\n]*(\\n\\s*//[^\\n]*)*\\n\\s*// ===+"
|
||||
}
|
||||
Generated
+403
-629
File diff suppressed because it is too large.
Load diff
+11
-24
@@ -7,12 +7,10 @@ members = [
|
||||
"desktop/platform/linux",
|
||||
"desktop/platform/mac",
|
||||
"desktop/platform/win",
|
||||
"document/container",
|
||||
"editor",
|
||||
"frontend/wrapper",
|
||||
"libraries/dyn-any",
|
||||
"libraries/math-parser",
|
||||
"node-graph/libraries/graphene-hash",
|
||||
"node-graph/libraries/*",
|
||||
"node-graph/nodes/*",
|
||||
"node-graph/nodes/raster/shaders",
|
||||
@@ -65,11 +63,9 @@ 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" }
|
||||
graphene-resource = { path = "node-graph/libraries/resources" }
|
||||
core-types = { path = "node-graph/libraries/core-types" }
|
||||
no-std-types = { path = "node-graph/libraries/no-std-types" }
|
||||
raster-types = { path = "node-graph/libraries/raster-types" }
|
||||
@@ -110,9 +106,6 @@ log = "0.4"
|
||||
bitflags = { version = "2.4", features = ["serde"] }
|
||||
ctor = "0.2"
|
||||
convert_case = "0.8"
|
||||
titlecase = "3.6"
|
||||
fancy-regex = "0.18.0"
|
||||
unicode-segmentation = "1.13.2"
|
||||
indoc = "2.0.5"
|
||||
derivative = "2.2"
|
||||
thiserror = "2"
|
||||
@@ -122,17 +115,17 @@ quote = "1.0"
|
||||
chrono = "0.4"
|
||||
ron = "0.12"
|
||||
fastnoise-lite = "1.1"
|
||||
wgpu = { version = "29.0", features = [
|
||||
wgpu = { version = "28.0", features = [
|
||||
# We don't have wgpu on multiple threads (yet) https://github.com/gfx-rs/wgpu/blob/trunk/CHANGELOG.md#wgpu-types-now-send-sync-on-wasm
|
||||
"fragile-send-sync-non-atomic-wasm",
|
||||
"spirv",
|
||||
"strict_asserts",
|
||||
] }
|
||||
once_cell = "1.13" # Remove and replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>)
|
||||
wasm-bindgen = "=0.2.121" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned across CI workflows, devcontainer, Nix, and the `cargo-run` tool. We pin this version because wasm-bindgen upgrades may break various things.
|
||||
wasm-bindgen = "=0.2.100" # NOTICE: ensure this stays in sync with the `wasm-bindgen-cli` version in `website/content/volunteer/guide/project-setup/_index.md`. We pin this version because wasm-bindgen upgrades may break various things.
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "=0.3.98"
|
||||
web-sys = { version = "=0.3.98", features = [
|
||||
js-sys = "=0.3.77"
|
||||
web-sys = { version = "=0.3.77", features = [
|
||||
"Document",
|
||||
"DomRect",
|
||||
"Element",
|
||||
@@ -156,14 +149,13 @@ url = "2.5"
|
||||
tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-multi-thread"] }
|
||||
# Linebender ecosystem (BEGIN)
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
vello = "0.9"
|
||||
vello_encoding = "0.9"
|
||||
vello = "0.8"
|
||||
vello_encoding = "0.8"
|
||||
resvg = "0.47"
|
||||
usvg = "0.47"
|
||||
parley = { version = "0.9", default-features = false, features = ["std"] }
|
||||
skrifa = "0.42"
|
||||
parley = "0.6"
|
||||
skrifa = "0.40"
|
||||
polycool = "0.4"
|
||||
color = "0.3"
|
||||
# Linebender ecosystem (END)
|
||||
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
|
||||
rand_chacha = "0.9"
|
||||
@@ -173,8 +165,6 @@ glam = { version = "0.32.1", default-features = false, features = [
|
||||
"bytemuck",
|
||||
] }
|
||||
base64 = "0.22"
|
||||
blake3 = "1.5"
|
||||
mmap-io = { version = "0.9", features = ["hugepages"] }
|
||||
image = { version = "0.25", default-features = false, features = [
|
||||
"png",
|
||||
"jpeg",
|
||||
@@ -203,12 +193,12 @@ petgraph = { version = "0.7", default-features = false, features = ["graphmap"]
|
||||
half = { version = "2.4", default-features = false, features = ["bytemuck"] }
|
||||
tinyvec = { version = "1", features = ["std"] }
|
||||
criterion = { version = "0.7", features = ["html_reports"] }
|
||||
gungraun = { version = "0.18" }
|
||||
iai-callgrind = { version = "0.16" }
|
||||
ndarray = "0.16"
|
||||
strum = { version = "0.27", features = ["derive"] }
|
||||
dirs = "6.0"
|
||||
cef = "148"
|
||||
cef-dll-sys = "148"
|
||||
cef = "146"
|
||||
cef-dll-sys = "146"
|
||||
include_dir = "0.7"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
tracing = "0.1"
|
||||
@@ -223,7 +213,6 @@ lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "e
|
||||
scraper = "0.25"
|
||||
linesweeper = "0.3"
|
||||
smallvec = "1.13.2"
|
||||
zip = { version = "8", default-features = false }
|
||||
|
||||
[workspace.lints.rust]
|
||||
unexpected_cfgs = { level = "allow", check-cfg = ['cfg(target_arch, values("spirv"))'] }
|
||||
@@ -250,5 +239,3 @@ debug = true
|
||||
# Force cargo to use only one version of the dpi crate (vendoring breaks without this)
|
||||
dpi = { git = "https://github.com/rust-windowing/winit.git" }
|
||||
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
|
||||
cef = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite" }
|
||||
cef-dll-sys = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite" }
|
||||
@@ -1,5 +1,4 @@
|
||||
accepted = [
|
||||
"0BSD", # Keep this list in sync with those in `/deny.toml`
|
||||
"Apache-2.0 WITH LLVM-exception", # Keep this list in sync with those in `/deny.toml`
|
||||
"Apache-2.0", # Keep this list in sync with those in `/deny.toml`
|
||||
"BSD-2-Clause", # Keep this list in sync with those in `/deny.toml`
|
||||
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Fill":{"Solid":{"red":0.9765625,"green":0.7715821,"blue":0.2861023,"alpha":1.0}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.9765625,"green":0.7715821,"blue":0.2861023,"alpha":1.0}},"exposed":false}},{"Value":{"tagged_value":{"FillGradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}]},"gradient_type":"Linear","start":[0.09778450863315612,0.7264556766766779],"end":[0.09778450863315612,0.3634234796342139],"spread_method":"Pad"}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1789832635968548900,{"inputs":[{"Node":{"node_id":1924303400883620400,"output_index":0}},{"Value":{"tagged_value":{"Fill":{"Solid":{"red":0.9921Line truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[10316247453530667000,{"inputs":[{"Node":{"node_id":9079109751490757000,"output_index":0}},{"Node":{"node_id":1250460246919467000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::SourceNodeIdNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":false,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[7954638344846060000,{"inputs":[{"Node":{"node_id":5991296268862790000,"output_index":0}},{"Value":{"tagged_value":{"Fill":{"Solid":{"red":0.1875,"green":0.0,"blue":0.0,"alpha":0.203125}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"element":[{"red":0.19140625,"green":0.0,"blue":0.0,"alpha":0.203125}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]},"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5]}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[17021405646895729000,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"GradientTable":{"element":[{"position":[0.0,0.5,1.0],"midpoint":[0.5,0.5,0.5],"color":[{"red":1.0,"green":0.31764707,"blue":0.15686275,"alpha":1.0},{"red":1.0,"green":0.5686275,"blue":0.25490198,"alpha":1.0},{"red":1.0,"green":0.7294118,"blue":0.16078432,"alpha":1.0}]}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"math_nodes::GradientValueNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[8366826746721323000,{"inputs":[{"Node":{"node_id":5591755359500854000,"output_index":0}},{"Node":{"node_id":13846904447064916285,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":3Line truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183952488591282082,{"inputs":[{"Node":{"node_id":17965270694495451178,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,-6.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exportsLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[10507084483235320484,{"inputs":[{"Node":{"node_id":9157963288496356916,"output_index":0}},{"Node":{"node_id":1396768435017101055,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::SourceNodeIdNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4741515246389989284,{"inputs":[{"Node":{"node_id":14255588039347536657,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[-261.2435565297001,-70.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4105329493214975815,{"inputs":[{"Node":{"node_id":12931264630175648107,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[-261.24355652969916,-70.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::conteLine truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5],"color":[{"red":0.28211805,"green":0.0,"blue":0.3046875,"alpha":1.0},{"red":0.13647461,"green":0.3989315,"blue":0.8125,"alpha":1.0},{"red":1.0,"green":0.9409449,"blue":0.625,"alpha":1.0},{"red":0.58431375,"green":0.92941177,"blue":0.92941177,"alpha":0.01}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},{"red":0.23828125,"green":0.0,"blue":0.08377075,"alpha":1.0},{"red":0.92578125,"green":0.8676921,"blue":0.5569153,"alpha":1.0},{"red":0.17333984,"green":0.625,"blue":0.625,"alpha":1.0},{"red":0.106292725,"green":0.3359375,"blue":0.3359375,"alpha":1.0}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_value":{"CellularReturnType":"CellValue"},"exposed":false}},{"Value":{"tagged_value":{"F64":1.0},"exposed":false}}],"call_argument":{"Concrete":{"nameLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientTable":{"element":[{"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},{"red":0.23828125,"green":0.0,"blue":0.08377075,"alpha":1.0},{"red":0.92578125,"green":0.8676921,"blue":0.5569153,"alpha":1.0},{"red":0.17333984,"green":0.625,"blue":0.625,"alpha":1.0},{"red":0.106292725,"green":0.3359375,"blue":0.3359375,"alpha":1.0}]}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[7624113397561636853,{"inputs":[{"Value":{"tagged_value":{"Graphic":{"element":[],"transform":[],"alpha_blending":[],"source_node_id":[]}},"exposed":true}},{"Node":{"node_id":3606681156406984991,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc:Line truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Fill":{"Solid":{"red":0.92156863,"green":0.6039216,"blue":0.18039216,"alpha":1.0}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8509804,"green":0.24313726,"blue":0.18431373,"alpha":1.0}},"exposed":false}},{"Value":{"tagged_value":{"FillGradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]},"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5],"spread_method":"Pad"}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::artboard::Artboard>"}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.93333334,"green":0.8627451,"blue":0.7254902,"alpha":1.0}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":4}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Value":{"tagged_value":{"String":"ediLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[13353438235848911576,{"inputs":[{"Value":{"tagged_value":{"Vector":{"element":[{"style":{"stroke":{"color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},"weight":0.0,"dash_lengths":[],"dash_offset":0.0,"cap":"Butt","join":"Miter","join_miter_limit":4.0,"align":"Center","transform":[1.0,0.0,0.0,1.0,0.0,0.0],"non_scaling":false,"paint_order":"StrokeAbove"},"fill":"None"},"colinear_manipulators":[],"point_domain":{"id":[],"position":[]},"segment_domain":{"id":[],"start_point":[],"end_point":[],"handles":[],"stroke":[]},"region_domain":{"id":[],"segment_range":[],"fill":[]},"upstream_data":null}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[6379137305818664393,18442321214082298093,18118267825025549699,6351696498298648253,17863574903157697896,4691860614575868200,301778328144628917,10625296323957562985,533731991408535384,13357220652574593654,15992617814592812350],"remove":[],"delta":[[18442321214082298093,[565.6296296296297,122.96296296296298]],[13357220652574593654,[574.2222222222222,108.44444444444449]],[6351696498298648253,[646.8148148148149,0.0]],[6379137305818664393,[625.4814814814813,0.0]],[17863574903157697896,[606.8148151308641,95.19407372365433]],[18118267825025549699,[642.0740740740741,0.0]],[10625296323957562985,[473.4814814814815,272.5925925925926]],[533731991408535384,[501.6296296296296,175.40740740740742]],[4691860614575868200,[528.2962962962963,283.8518518518518]],[15992617814592812350,[621.0370370370368,0.0]],[301778328144628917,[493.5149940383244,200.29629629629628]]]},"segments":{"add":[13662059715350867364,3384102572540409881,12035095010819582754,10146665273368938971,318560030360358929,8462655819889292900,3303411878775644985,8661113083384527971,2035327810332855521,11346538709718766144,3710133387837274291],"remove":[],"start_point":[[3303411878775644985,301778328144628917],[13662059715350867364,6379137305818664393],[318560030360358929,17863574903157697896],[3384102572540409881,18442321214082298093],[12035095010819582754,18118267825025549699],[10146665273368938971,6351696498298648253],[11346538709718766144,13357220652574593654],[8462655819889292900,4691860614575868200],[8661113083384527971,10625296323957562985],[3710133387837274291,15992617814592812350],[2035327810332855521,533731991408535384]],"end_point":[[2035327810332855521,13357220652574593654],[12035095010819582754,6351696498298648253],[10146665273368938971,17863574903157697896],[318560030360358929,4691860614575868200],[11346538709718766144,15992617814592812350],[3303411878775644985,10625296323957562985],[3710133387837274291,6379137305818664393],[8462655819889292900,301778328144628917],[13662059715350867364,18442321214082298093],[8661113083384527971,533731991408535384],[3384102572540409881,18118267825025549699]],"handle_primary":[[8661113083384527971,[0.2962962962963047,0.2962962962963047]],[3710133387837274291,[0.0,0.0]],[10146665273368938971,[0.0,0.0]],[3303411878775644985,[0.0,0.0]],[13662059715350867364,[0.0,0.0]],[12035095010819582754,[0.0,0.0]],[11346538709718766144,[9.925839724176626,-9.951533978271286]],[8462655819889292900,[0.0,0.0]],[2035327810332855521,[42.96296296296293,-41.7777777777778]],[3384102572540409881,[0.0,0.0]],[318560030360358929,[-46.95465552079859,46.40007297527743]]],"handle_end":[[3384102572540409881,[0.5807410754567854,77.36888852918523]],[13662059715350867364,[68.68148181185177,-54.8859262904691]],[3710133387837274291,[0.0,0.0]],[11346538709718766144,[1.1377781018271662,63.71555518874077]],[8661113083384527971,[-42.34888386913234,41.180638796880466]],[2035327810332855521,[-8.299214014278164,8.32069754812484]],[12035095010819582754,[0.0,0.0]],[318560030360358929,[-97.48148148148152,-81.18518518518522]],[10146665273368938971,[48.16592595101224,-47.597037061827145]],[3303411878775644985,[-6.2222222222222285,-40.59259259259261]],[8462655819889292900,[-21.74426522093495,47.99999999999997]]],"stroke":[[3303411878775644985,0],[8661113083384527971,0],[12035095010819582754,0],[2035327810332855521,0],[3710133387837274291,0],[8462655819889292900,0],[3384102572540409881,0],[318560030360358929,0],[11346538709718766144,0],[10146665273368938971,0],[13662059715350867364,0]]},"regions":{"add":[],"remove":[],"segment_range":[],"fill":[]},"add_g1_continuous":[[{"ty":"End","segment":8661113083384527971},{"ty":"Primary","segment":2035327810332855521}],[{"ty":"End","segment":10146665273368938971},{"ty":"Primary","segment":318560030360358929}],[{"ty":"Primary","segment":11346538709718766144},{"ty":"End","segment":2035327810332855521}],[{"ty":"End","segment":12035095010819582754},{"ty":"Primary","segment":10146665273368938971}]],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exportsLine truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.21176471,"green":0.21568628,"blue":0.23137255,"alpha":1.0}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.99607843,"green":0.827451,"blue":0.65882355,"alpha":1.0}},"exposed":false}},{"Value":{"tagged_value":{"FillGradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]},"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5],"spread_method":"Pad"}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"core_types::vector::SplineNode"}},"visible":truLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[17154757625902243313,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"element":[{"red":0.23529412,"green":0.23529412,"blue":0.24313726,"alpha":1.0}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}},{"Value":{"tagged_value":{"F64":1670.79570439},"exposed":false}},{"Value":{"tagged_value":{"F64":24.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"core_types::vector::SplineNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[14158287945315818946,{"inputs":[{"Node":{"node_id":16943732999059587742,"output_index":0}},{"Node":{"node_id":14577956936089455769,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.6181095265062186,3.496297826945966]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[11731553664207576737,{"inputs":[{"Node":{"node_id":757876048866560520,"output_index":0}},{"Value":{"tagged_value":{"F64":48.900000000000006},"exposed":false}},{"Node":{"node_id":7828034197076821310,"output_index":0}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"core_types::vector::JitterPointsNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[7828034197076821310,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":3}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"math_nodes::ToU32Node"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"element":[{"red":0.99607843,"green":0.827451,"blue":0.65882355,"alpha":1.0}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_nLine truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":6559102076450693000,"output_index":0}},{"Value":{"tagged_value":{"Fill":{"Gradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01}]},"gradient_type":"Radial","start":[0.4915209831246563,0.36613756613756576],"end":[0.49551110871305326,0.9947089947089944],"spread_method":"Pad"}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}},"exposed":false}},{"Value":{"tagged_value":{"FillGradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01}]},"gradient_type":"Radial","start":[0.4915209831246563,0.36613756613756576],"end":[0.49551110871305326,0.9947089947089944],"spread_method":"Pad"}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0Line truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::SourceNodeIdNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[665049002420596400,{"inputs":[{"Value":{"tagged_value":{"Vector":{"element":[{"style":{"stroke":{"color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},"weight":0.0,"dash_lengths":[],"dash_offset":0.0,"cap":"Butt","join":"Miter","join_miter_limit":4.0,"align":"Center","transform":[1.0,0.0,0.0,1.0,0.0,0.0],"non_scaling":false,"paint_order":"StrokeAbove"},"fill":"None"},"colinear_manipulators":[],"point_domain":{"id":[],"position":[]},"segment_domain":{"id":[],"start_point":[],"end_point":[],"handles":[],"stroke":[]},"region_domain":{"id":[],"segment_range":[],"fill":[]},"upstream_data":null}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"remove":[],"delta":[[3,[45.77777777777777,145.33333333333331]],[18,[145.77777777777777,-97.7777777777778]],[9,[156.4444444444444,97.33333333333331]],[21,[76.0,-202.22222222222223]],[28,[39.111111111111086,-58.22222222222226]],[23,[19.555555555555543,-139.55555555555557]],[6,[123.99999999999994,148.4444444444444]],[30,[-9.333333333333371,0.0]],[16,[159.5555555555555,-75.55555555555557]],[29,[-32.888888888888914,-14.666666666666686]],[20,[128.4444444444444,-142.22222222222223]],[13,[153.77777777777777,-1.3333333333333712]],[27,[-11.111111111111144,-72.00000000000003]],[4,[18.66666666666663,157.77777777777771]],[25,[0.8888888888888573,-94.66666666666669]],[11,[136.88888888888886,39.111111111111086]],[8,[252.4444444444444,124.88888888888886]],[32,[9.333333333333314,38.66666666666663]],[17,[123.99999999999994,-84.00000000000003]],[15,[111.11111111111114,-60.888888888888914]],[5,[66.22222222222223,152.88888888888886]],[33,[-78.22222222222223,75.55555555555554]],[24,[57.77777777777777,-129.33333333333334]],[19,[90.66666666666664,-129.33333333333334]],[12,[199.5555555555555,10.666666666666629]],[31,[-53.33333333333337,13.777777777777771]],[34,[-5.333333333333371,99.11111111111109]],[10,[216.4444444444444,72.4444444444444]],[14,[183.11111111111103,-19.111111111111143]],[26,[22.66666666666663,-81.33333333333337]],[7,[229.33333333333331,152.4444444444444]],[2,[-67.55555555555554,158.22222222222217]],[22,[71.11111111111109,-201.7777777777778]],[1,[-103.55555555555554,126.66666666666664]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"remove":[],"start_point":[[1,1],[14,14],[8,8],[33,33],[30,30],[9,9],[1Line truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Fill":{"Solid":{"red":0.8980392,"green":0.8,"blue":0.6117647,"alpha":1.0}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8980392,"green":0.8,"blue":0.6117647,"alpha":1.0}},"exposed":false}},{"Value":{"tagged_value":{"FillGradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]},"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5],"spread_method":"Pad"}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[10127467043900015225,{"inputs":[{"Value":{"tagged_value":{"Vector":{"element":[{"style":{"stroke":{"color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},"weight":0.0,"dash_lengths":[],"dash_offset":0.0,"cap":"Butt","join":"Miter","join_miter_limit":4.0,"align":"Center","transform":[1.0,0.0,0.0,1.0,0.0,0.0],"non_scaling":false,"paint_order":"StrokeAbove"},"fill":"None"},"colinear_manipulators":[],"point_domain":{"id":[],"position":[]},"segment_domain":{"id":[],"start_point":[],"end_point":[],"handles":[],"stroke":[]},"region_domain":{"id":[],"segment_range":[],"fill":[]},"upstream_data":null}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2],"remove":[],"delta":[[1,[258.00000000000006,994.6666666666664]],[2,[644.0,726.6666666666666]]]},"segments":{"add":[1],"remove":[],"start_point":[[1,1]],"end_point":[[1,2]],"handle_primary":[[1,[0.0,0.0]]],"handle_end":[[1,[-328.66666666666674,129.33333333333337]]],"stroke":[[1,0]]},"regions":{"add":[],"remove":[],"segment_range":[],"fill":[]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"graphene_core::table::Table<graphene_core::vector::vector_types::Vector>","alias":null}},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"graphene_core::vector::vector_modification::VectorModification","alias":null}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[15961046538654083626,{"inputs":[{"Node":{"node_id":1889157037801767612,"output_index":0}},{"Node":{"node_id":4332145463108161926,"output_index":0}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":10.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"core_types::vector::CopyToPointsNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[17378885078543074499,{"inputs":[{"Value":{"tagged_value":{"Vector":{"element":[{"style":{"stroke":{"color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},"weight":0.0,"dash_lengths":[],"dash_offset":0.0,"cap":"Butt","join":"Miter","join_miter_limit":4.0,"align":"Center","transform":[1.0,0.0,0.0,1.0,0.0,0.0],"non_scaling":false,"paint_order":"StrokeAbove"},"fill":"None"},"colinear_manipulators":[],"point_domain":{"id":[],"position":[]},"segment_domain":{"id":[],"start_point":[],"end_point":[],"handles":[],"stroke":[]},"region_domain":{"id":[],"segment_range":[],"fill":[]},"upstream_data":null}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8],"remove":[],"delta":[[5,[740.4444444444443,857.1111111111111]],[3,[707.5,1026.5]],[7,[727.5555555555554,1026.6666666666663]],[2,[745.5,826.0]],[1,[823.2222222222221,660.4444444444445]],[6,[725.7777777777779,1026.370370370371]],[4,[709.5555555555554,1026.6666666666667]],[8,[746.0000000000001,842.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8],"remove":[],"start_point":[[5,5],[2,2],[6,6],[8,8],[3,3],[4,4],[1,1],[7,7]],"end_point":[[6,7],[8,1],[2,3],[5,6],[1,2],[3,4],[4,5],[7,8]],"handle_primary":[[6,[0.0,0.0]],[8,[17.33333333333337,-84.99999999999989]],[3,[0.0,0.0]],[7,[0.0,0.0]],[5,[0.0,0.0]],[1,[0.0,0.0]],[4,[0.0,0.0]],[2,[-24.5,85.0]]],"handle_end":[[7,[-26.8034437596026,131.4399645903585]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[-23.11111111111109,Line truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[202,{"inputs":[{"Node":{"node_id":206,"output_index":0}},{"Value":{"tagged_value":{"Fill":{"Solid":{"red":0.5058824,"green":0.26666668,"blue":0.20392157,"alpha":1.0}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"element":[{"red":0.5058824,"green":0.26666668,"blue":0.20392157,"alpha":1.0}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]},"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5]}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[404,{"inputs":[{"Node":{"node_id":402,"output_index":0}},{"Value":{"tagged_value":{"Color":{"element":[{"red":0.24313726,"green":0.18431373,"blue":0.19215687,"alpha":1.0}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"StrokeAlign":"Center"},"exposed":false}},{"Value":{"tagged_value":{"StrokeCap":"Butt"},"exposed":false}},{"Value":{"tagged_value":{"StrokeJoin":"Miter"},"exposed":false}},{"Value":{"tagged_value":{"F64":4.0},"exposed":false}},{"Value":{"tagged_value":{"PaintOrder":"StrokeAbove"},"exposed":false}},{"Value":{"tagged_value":{"VecF64":[]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::StrokeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[93,{"inputs":[{"Node":{"node_id":94,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[851.1666666666667,668.5377104806669]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[39.677869315599935,39.67786931560005]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[155,{"inputs":[{"Node":{"node_id":159,"output_index":0}},{"Value":{"tagged_value":{"Fill":{"Gradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.7529412,"green":0.34117648,"blue":0.2,"alpha":1.0},{"red":0.6431373,"green":0.31764707,"blue":0.21176471,"alpha":1.0}]},"gradient_type":"Linear","start":[0.9001916129448388,0.7881778212017586],"end":[0.8902470335613286,0.6662432828529555]}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"element":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.7529412,"green":0.34117648,"blue":0.2,"alpha":1.0},{"red":0.6431373,"greeLine truncated
|
||||
@@ -42,7 +42,7 @@ ignore = [
|
||||
"RUSTSEC-2024-0388", # Unmaintained `derivative`, used directly by graphite-editor and graphite-desktop
|
||||
"RUSTSEC-2024-0436", # Unmaintained `paste`, pulled in by dependencies `metal` and `wgpu-hal`
|
||||
"RUSTSEC-2025-0134", # Unmaintained `rustls-pemfile`, pulled in by build dependency `download-cef`
|
||||
"RUSTSEC-2025-0141", # Unmaintained `bincode`, pulled in by dev dependency `gungraun`
|
||||
"RUSTSEC-2025-0141", # Unmaintained `bincode`, pulled in by dev dependency `iai-callgrind`
|
||||
]
|
||||
# Threshold for security vulnerabilities, any vulnerability with a CVSS score
|
||||
# lower than the range specified will be ignored. Note that ignored advisories
|
||||
@@ -63,7 +63,6 @@ ignore = [
|
||||
# [possible values: any SPDX 3.11 short identifier (+ optional exception)].
|
||||
#
|
||||
allow = [
|
||||
"0BSD", # Keep this list in sync with those in `/about.toml`
|
||||
"Apache-2.0 WITH LLVM-exception", # Keep this list in sync with those in `/about.toml`
|
||||
"Apache-2.0", # Keep this list in sync with those in `/about.toml`
|
||||
"BSD-2-Clause", # Keep this list in sync with those in `/about.toml`
|
||||
|
||||
@@ -48,7 +48,6 @@ lzma-rust2 = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
rand = { workspace = true, features = ["thread_rng"] }
|
||||
clap = { workspace = true, features = ["derive"] }
|
||||
interprocess = "2.4.2"
|
||||
fd-lock = "4.0.4"
|
||||
ctrlc = "3.5.1"
|
||||
window_clipboard = "0.5"
|
||||
|
||||
@@ -13,9 +13,6 @@ const EXEC_PATH: &str = "Contents/MacOS";
|
||||
const FRAMEWORKS_PATH: &str = "Contents/Frameworks";
|
||||
const RESOURCES_PATH: &str = "Contents/Resources";
|
||||
const CEF_FRAMEWORK: &str = "Chromium Embedded Framework.framework";
|
||||
const GRAPHITE_DOCUMENT_TYPE: &str = "art.graphite.document";
|
||||
const GRAPHITE_FILE_EXTENSION: &str = "graphite";
|
||||
const GRAPHITE_MIME_TYPE: &str = "application/graphite+json";
|
||||
|
||||
pub fn main() -> Result<(), Box<dyn Error>> {
|
||||
let app_bin = build_bin("graphite-desktop-platform-mac", None)?;
|
||||
@@ -76,7 +73,7 @@ fn create_info_plist(dir: &Path, id: &str, exec_name: &str, is_helper: bool) ->
|
||||
cf_bundle_identifier: id.to_string(),
|
||||
cf_bundle_display_name: exec_name.to_string(),
|
||||
cf_bundle_executable: exec_name.to_string(),
|
||||
cf_bundle_icon_file: if is_helper { None } else { Some(ICONS_FILE_NAME.to_string()) },
|
||||
cf_bundle_icon_file: ICONS_FILE_NAME.to_string(),
|
||||
cf_bundle_info_dictionary_version: "6.0".to_string(),
|
||||
cf_bundle_package_type: "APPL".to_string(),
|
||||
cf_bundle_signature: "????".to_string(),
|
||||
@@ -88,8 +85,6 @@ fn create_info_plist(dir: &Path, id: &str, exec_name: &str, is_helper: bool) ->
|
||||
ls_minimum_system_version: "11.0".to_string(),
|
||||
ls_ui_element: if is_helper { Some("1".to_string()) } else { None },
|
||||
ns_supports_automatic_graphics_switching: true,
|
||||
cf_bundle_document_types: (!is_helper).then(document_types),
|
||||
ut_exported_type_declarations: (!is_helper).then(exported_type_declarations),
|
||||
};
|
||||
|
||||
let plist_file = dir.join("Info.plist");
|
||||
@@ -97,47 +92,6 @@ fn create_info_plist(dir: &Path, id: &str, exec_name: &str, is_helper: bool) ->
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn document_types() -> Vec<DocumentType> {
|
||||
vec![
|
||||
DocumentType {
|
||||
cf_bundle_type_name: "Graphite Document".to_string(),
|
||||
cf_bundle_type_role: "Editor".to_string(),
|
||||
cf_bundle_type_extensions: Some(vec![GRAPHITE_FILE_EXTENSION.to_string()]),
|
||||
cf_bundle_type_icon_file: Some(ICONS_FILE_NAME.to_string()),
|
||||
ls_handler_rank: Some("Owner".to_string()),
|
||||
ls_item_content_types: vec![GRAPHITE_DOCUMENT_TYPE.to_string()],
|
||||
},
|
||||
DocumentType {
|
||||
cf_bundle_type_name: "SVG Image".to_string(),
|
||||
cf_bundle_type_role: "Editor".to_string(),
|
||||
cf_bundle_type_extensions: Some(vec!["svg".to_string()]),
|
||||
cf_bundle_type_icon_file: None,
|
||||
ls_handler_rank: Some("Alternate".to_string()),
|
||||
ls_item_content_types: vec!["public.svg-image".to_string()],
|
||||
},
|
||||
DocumentType {
|
||||
cf_bundle_type_name: "Image".to_string(),
|
||||
cf_bundle_type_role: "Editor".to_string(),
|
||||
cf_bundle_type_extensions: None,
|
||||
cf_bundle_type_icon_file: None,
|
||||
ls_handler_rank: Some("Alternate".to_string()),
|
||||
ls_item_content_types: vec!["public.image".to_string()],
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn exported_type_declarations() -> Vec<ExportedTypeDeclaration> {
|
||||
vec![ExportedTypeDeclaration {
|
||||
ut_type_identifier: GRAPHITE_DOCUMENT_TYPE.to_string(),
|
||||
ut_type_description: "Graphite Document".to_string(),
|
||||
ut_type_conforms_to: vec!["public.json".to_string()],
|
||||
ut_type_tag_specification: TypeTagSpecification {
|
||||
public_filename_extension: vec![GRAPHITE_FILE_EXTENSION.to_string()],
|
||||
public_mime_type: GRAPHITE_MIME_TYPE.to_string(),
|
||||
},
|
||||
}]
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
struct InfoPlist {
|
||||
#[serde(rename = "CFBundleName")]
|
||||
@@ -149,8 +103,7 @@ struct InfoPlist {
|
||||
#[serde(rename = "CFBundleExecutable")]
|
||||
cf_bundle_executable: String,
|
||||
#[serde(rename = "CFBundleIconFile")]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
cf_bundle_icon_file: Option<String>,
|
||||
cf_bundle_icon_file: String,
|
||||
#[serde(rename = "CFBundleInfoDictionaryVersion")]
|
||||
cf_bundle_info_dictionary_version: String,
|
||||
#[serde(rename = "CFBundlePackageType")]
|
||||
@@ -170,53 +123,7 @@ struct InfoPlist {
|
||||
#[serde(rename = "LSMinimumSystemVersion")]
|
||||
ls_minimum_system_version: String,
|
||||
#[serde(rename = "LSUIElement")]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
ls_ui_element: Option<String>,
|
||||
#[serde(rename = "NSSupportsAutomaticGraphicsSwitching")]
|
||||
ns_supports_automatic_graphics_switching: bool,
|
||||
#[serde(rename = "CFBundleDocumentTypes")]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
cf_bundle_document_types: Option<Vec<DocumentType>>,
|
||||
#[serde(rename = "UTExportedTypeDeclarations")]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
ut_exported_type_declarations: Option<Vec<ExportedTypeDeclaration>>,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
struct DocumentType {
|
||||
#[serde(rename = "CFBundleTypeName")]
|
||||
cf_bundle_type_name: String,
|
||||
#[serde(rename = "CFBundleTypeRole")]
|
||||
cf_bundle_type_role: String,
|
||||
#[serde(rename = "CFBundleTypeExtensions")]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
cf_bundle_type_extensions: Option<Vec<String>>,
|
||||
#[serde(rename = "CFBundleTypeIconFile")]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
cf_bundle_type_icon_file: Option<String>,
|
||||
#[serde(rename = "LSHandlerRank")]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
ls_handler_rank: Option<String>,
|
||||
#[serde(rename = "LSItemContentTypes")]
|
||||
ls_item_content_types: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
struct ExportedTypeDeclaration {
|
||||
#[serde(rename = "UTTypeIdentifier")]
|
||||
ut_type_identifier: String,
|
||||
#[serde(rename = "UTTypeDescription")]
|
||||
ut_type_description: String,
|
||||
#[serde(rename = "UTTypeConformsTo")]
|
||||
ut_type_conforms_to: Vec<String>,
|
||||
#[serde(rename = "UTTypeTagSpecification")]
|
||||
ut_type_tag_specification: TypeTagSpecification,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
struct TypeTagSpecification {
|
||||
#[serde(rename = "public.filename-extension")]
|
||||
public_filename_extension: Vec<String>,
|
||||
#[serde(rename = "public.mime-type")]
|
||||
public_mime_type: String,
|
||||
}
|
||||
+38
-65
@@ -2,7 +2,6 @@ use rand::Rng;
|
||||
use rfd::AsyncFileDialog;
|
||||
use std::fs;
|
||||
use std::io::Read;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{Receiver, Sender, SyncSender};
|
||||
@@ -15,15 +14,15 @@ 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::dirs;
|
||||
use crate::event::{AppEvent, AppEventScheduler};
|
||||
use crate::persist;
|
||||
use crate::preferences;
|
||||
use crate::render::{RenderError, RenderState};
|
||||
use crate::window::Window;
|
||||
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, InputMessage, MouseKeys, MouseState, Preferences};
|
||||
use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
|
||||
use crate::wrapper::{DesktopWrapper, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
|
||||
|
||||
pub(crate) struct App {
|
||||
render_state: Option<RenderState>,
|
||||
@@ -46,8 +45,9 @@ pub(crate) struct App {
|
||||
start_render_sender: SyncSender<()>,
|
||||
web_communication_initialized: bool,
|
||||
web_communication_startup_buffer: Vec<Vec<u8>>,
|
||||
#[cfg_attr(not(target_os = "macos"), expect(unused))]
|
||||
preferences: Preferences,
|
||||
launch_documents: Option<Vec<PathBuf>>,
|
||||
cli: Cli,
|
||||
startup_time: Option<Instant>,
|
||||
exiting: Arc<AtomicBool>,
|
||||
exit_reason: ExitReason,
|
||||
@@ -58,7 +58,6 @@ impl App {
|
||||
Window::init();
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn new(
|
||||
cef_context: Box<dyn cef::CefContext>,
|
||||
cef_view_info_sender: Sender<cef::ViewInfoUpdate>,
|
||||
@@ -66,7 +65,7 @@ impl App {
|
||||
app_event_receiver: Receiver<AppEvent>,
|
||||
app_event_scheduler: AppEventScheduler,
|
||||
preferences: Preferences,
|
||||
launch_documents: Vec<PathBuf>,
|
||||
cli: Cli,
|
||||
) -> Self {
|
||||
let ctrlc_app_event_scheduler = app_event_scheduler.clone();
|
||||
ctrlc::set_handler(move || {
|
||||
@@ -92,14 +91,7 @@ impl App {
|
||||
}
|
||||
});
|
||||
|
||||
let resource_storage = MmapResourceStorage::new(dirs::app_resources_dir()).expect("Failed to initialize on-disk resource storage");
|
||||
|
||||
// Wake the winit event loop when an editor future completes.
|
||||
let wake_scheduler = app_event_scheduler.clone();
|
||||
let wake = Arc::new(move || {
|
||||
wake_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Wake));
|
||||
});
|
||||
let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), wgpu_context.clone(), wake);
|
||||
let desktop_wrapper = DesktopWrapper::new(rand::rng().random());
|
||||
|
||||
Self {
|
||||
render_state: None,
|
||||
@@ -123,7 +115,7 @@ impl App {
|
||||
web_communication_initialized: false,
|
||||
web_communication_startup_buffer: Vec::new(),
|
||||
preferences,
|
||||
launch_documents: Some(launch_documents),
|
||||
cli,
|
||||
startup_time: None,
|
||||
exiting,
|
||||
exit_reason: ExitReason::Shutdown,
|
||||
@@ -205,7 +197,7 @@ impl App {
|
||||
};
|
||||
self.send_or_queue_web_message(bytes);
|
||||
}
|
||||
DesktopFrontendMessage::OpenFileDialog { title, filters, multiple, context } => {
|
||||
DesktopFrontendMessage::OpenFileDialog { title, filters, context } => {
|
||||
let app_event_scheduler = self.app_event_scheduler.clone();
|
||||
let _ = thread::spawn(move || {
|
||||
let mut dialog = AsyncFileDialog::new().set_title(title);
|
||||
@@ -213,21 +205,13 @@ impl App {
|
||||
dialog = dialog.add_filter(filter.name, &filter.extensions);
|
||||
}
|
||||
|
||||
let handles = if multiple {
|
||||
futures::executor::block_on(dialog.pick_files()).unwrap_or_default()
|
||||
} else {
|
||||
futures::executor::block_on(dialog.pick_file()).into_iter().collect()
|
||||
};
|
||||
let show_dialog = async move { dialog.pick_file().await.map(|f| f.path().to_path_buf()) };
|
||||
|
||||
for handle in handles {
|
||||
let path = handle.path().to_path_buf();
|
||||
match fs::read(&path) {
|
||||
Ok(content) => {
|
||||
let message = DesktopWrapperMessage::FileDialogResult { path, content, context };
|
||||
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
Err(e) => tracing::error!("Failed to read file {}: {}", path.display(), e),
|
||||
}
|
||||
if let Some(path) = futures::executor::block_on(show_dialog)
|
||||
&& let Ok(content) = fs::read(&path)
|
||||
{
|
||||
let message = DesktopWrapperMessage::FileDialogResult { path, content, context };
|
||||
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -323,11 +307,22 @@ impl App {
|
||||
responses.push(message);
|
||||
}
|
||||
DesktopFrontendMessage::OpenLaunchDocuments => {
|
||||
let Some(launch_documents) = std::mem::take(&mut self.launch_documents) else {
|
||||
tracing::error!("OpenLaunchDocuments should only be sent once");
|
||||
if self.cli.files.is_empty() {
|
||||
return;
|
||||
};
|
||||
self.app_event_scheduler.schedule(AppEvent::OpenFiles(launch_documents));
|
||||
}
|
||||
let app_event_scheduler = self.app_event_scheduler.clone();
|
||||
let launch_documents = std::mem::take(&mut self.cli.files);
|
||||
let _ = thread::spawn(move || {
|
||||
for path in launch_documents {
|
||||
tracing::info!("Opening file from command line: {}", path.display());
|
||||
if let Ok(content) = fs::read(&path) {
|
||||
let message = DesktopWrapperMessage::OpenFile { path, content };
|
||||
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
} else {
|
||||
tracing::error!("Failed to read file: {}", path.display());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
DesktopFrontendMessage::UpdateMenu { entries } => {
|
||||
if let Some(window) = &self.window {
|
||||
@@ -375,11 +370,6 @@ impl App {
|
||||
window.start_drag();
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::WindowFocus => {
|
||||
if let Some(window) = &self.window {
|
||||
window.focus();
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::WindowHide => {
|
||||
if let Some(window) = &self.window {
|
||||
window.hide();
|
||||
@@ -485,29 +475,6 @@ impl App {
|
||||
tracing::info!("Exiting main event loop");
|
||||
event_loop.exit();
|
||||
}
|
||||
AppEvent::OpenFiles(paths) => {
|
||||
// Accumulate launch documents until OpenLaunchDocuments message is received
|
||||
if let Some(launch_documents) = &mut self.launch_documents {
|
||||
launch_documents.extend(paths);
|
||||
return;
|
||||
}
|
||||
|
||||
if paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
let app_event_scheduler = self.app_event_scheduler.clone();
|
||||
let _ = thread::spawn(move || {
|
||||
for path in paths {
|
||||
tracing::info!("Opening file: {}", path.display());
|
||||
if let Ok(content) = fs::read(&path) {
|
||||
let message = DesktopWrapperMessage::OpenFile { path, content };
|
||||
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
} else {
|
||||
tracing::error!("Failed to read file: {}", path.display());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
AppEvent::MenuEvent { id } => {
|
||||
self.dispatch_desktop_wrapper_message(DesktopWrapperMessage::MenuEvent { id });
|
||||
@@ -534,6 +501,8 @@ impl ApplicationHandler for App {
|
||||
|
||||
self.resize();
|
||||
|
||||
self.desktop_wrapper.init(self.wgpu_context.clone());
|
||||
|
||||
self.startup_time = Some(Instant::now());
|
||||
}
|
||||
|
||||
@@ -588,16 +557,20 @@ impl ApplicationHandler for App {
|
||||
Err(RenderError::OutdatedUITextureError) => {
|
||||
self.cef_context.notify_view_info_changed();
|
||||
}
|
||||
Err(RenderError::SurfaceLost) => {
|
||||
Err(RenderError::SurfaceError(wgpu::SurfaceError::Lost)) => {
|
||||
tracing::warn!("lost surface");
|
||||
}
|
||||
Err(other) => tracing::error!("Render error: {:?}", other),
|
||||
Err(RenderError::SurfaceError(wgpu::SurfaceError::OutOfMemory)) => {
|
||||
tracing::error!("GPU out of memory");
|
||||
self.exit(None);
|
||||
}
|
||||
Err(RenderError::SurfaceError(e)) => tracing::error!("Render error: {:?}", e),
|
||||
}
|
||||
let _ = self.start_render_sender.try_send(());
|
||||
}
|
||||
|
||||
if !self.cef_init_successful
|
||||
&& !self.preferences.disable_ui_acceleration
|
||||
&& !self.cli.disable_ui_acceleration
|
||||
&& self.web_communication_initialized
|
||||
&& let Some(startup_time) = self.startup_time
|
||||
&& startup_time.elapsed() > Duration::from_secs(3)
|
||||
|
||||
+34
-2
@@ -190,8 +190,40 @@ impl CefEventHandler for CefHandler {
|
||||
#[cfg(feature = "accelerated_paint")]
|
||||
fn draw_gpu(&self, shared_texture: SharedTextureHandle) {
|
||||
match shared_texture.import_texture(&self.wgpu_context.device) {
|
||||
Ok(texture) => {
|
||||
self.app_event_scheduler.schedule(AppEvent::UiUpdate(texture));
|
||||
Ok(src) => {
|
||||
let desc = wgpu::TextureDescriptor {
|
||||
label: Some("duplicated_texture"),
|
||||
usage: wgpu::TextureUsages::COPY_DST | src.usage(),
|
||||
size: src.size(),
|
||||
mip_level_count: src.mip_level_count(),
|
||||
sample_count: src.sample_count(),
|
||||
dimension: src.dimension(),
|
||||
format: src.format(),
|
||||
view_formats: &[],
|
||||
};
|
||||
|
||||
let copy = self.wgpu_context.device.create_texture(&desc);
|
||||
|
||||
let mut encoder = self.wgpu_context.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("texture_copy_encoder"),
|
||||
});
|
||||
|
||||
encoder.copy_texture_to_texture(
|
||||
src.as_image_copy(),
|
||||
copy.as_image_copy(),
|
||||
desc.size,
|
||||
);
|
||||
|
||||
// Wait for the GPU to finish the copy before allowing the source texture to be released by CEF
|
||||
let submission_index = self.wgpu_context.queue.submit([encoder.finish()]);
|
||||
if let Err(error) = self.wgpu_context.device.poll(wgpu::PollType::Wait {
|
||||
submission_index: Some(submission_index),
|
||||
timeout: None,
|
||||
}) {
|
||||
tracing::error!("Failed while waiting for texture copy completion: {error}");
|
||||
}
|
||||
|
||||
self.app_event_scheduler.schedule(AppEvent::UiUpdate(copy));
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to import shared texture: {}", e);
|
||||
|
||||
@@ -24,13 +24,14 @@ unsafe impl<H: CefEventHandler> Send for CefContextBuilder<H> {}
|
||||
|
||||
impl<H: CefEventHandler> CefContextBuilder<H> {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self::new_impl(false)
|
||||
}
|
||||
pub(crate) fn new_helper() -> Self {
|
||||
Self::new_impl(true)
|
||||
Self::new_inner(false)
|
||||
}
|
||||
|
||||
fn new_impl(helper: bool) -> Self {
|
||||
pub(crate) fn new_helper() -> Self {
|
||||
Self::new_inner(true)
|
||||
}
|
||||
|
||||
fn new_inner(helper: bool) -> Self {
|
||||
#[cfg(target_os = "macos")]
|
||||
let _loader = {
|
||||
let loader = cef::library_loader::LibraryLoader::new(&std::env::current_exe().unwrap(), helper);
|
||||
@@ -41,8 +42,11 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
|
||||
let _ = helper;
|
||||
|
||||
let _ = api_hash(CEF_API_VERSION_LAST, 0);
|
||||
|
||||
let args = Args::new();
|
||||
let is_sub_process = args.as_cmd_line().unwrap().has_switch(Some(&"type".into())) == 1;
|
||||
let cmd = args.as_cmd_line().unwrap();
|
||||
let is_sub_process = cmd.has_switch(Some(&"type".into())) == 1;
|
||||
|
||||
Self {
|
||||
args,
|
||||
is_sub_process,
|
||||
@@ -66,96 +70,103 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
|
||||
}
|
||||
}
|
||||
|
||||
fn common_settings(instance_dir: &Path) -> Settings {
|
||||
let log_severity = match std::env::var("GRAPHITE_BROWSER_LOG") {
|
||||
Ok(level) => match level.to_lowercase().as_str() {
|
||||
"debug" => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_VERBOSE),
|
||||
"info" => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_INFO),
|
||||
"warn" => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_WARNING),
|
||||
"error" => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_ERROR),
|
||||
"none" => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_DISABLE),
|
||||
_ => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_FATAL),
|
||||
},
|
||||
Err(_) => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_FATAL),
|
||||
};
|
||||
|
||||
Settings {
|
||||
windowless_rendering_enabled: 1,
|
||||
root_cache_path: instance_dir.to_str().map(CefString::from).unwrap(),
|
||||
cache_path: "".into(),
|
||||
disable_signal_handlers: 1,
|
||||
log_severity,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) fn create(self, event_handler: H, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
|
||||
pub(crate) fn initialize(self, event_handler: H, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
|
||||
let instance_dir = TempDir::new().expect("Failed to create temporary directory for CEF instance");
|
||||
let accelerated_paint = accelerated_paint(disable_gpu_acceleration);
|
||||
self.build_inner(&event_handler, instance_dir.as_ref(), accelerated_paint)?;
|
||||
create_browser(event_handler, instance_dir, accelerated_paint)
|
||||
|
||||
let exe = std::env::current_exe().expect("cannot get current exe path");
|
||||
let app_root = exe.parent().and_then(|p| p.parent()).expect("bad path structure").parent().expect("bad path structure");
|
||||
|
||||
let settings = Settings {
|
||||
main_bundle_path: app_root.to_str().map(CefString::from).unwrap(),
|
||||
multi_threaded_message_loop: 0,
|
||||
external_message_pump: 1,
|
||||
no_sandbox: 1, // GPU helper crashes when running with sandbox
|
||||
..Self::common_settings(instance_dir.as_ref())
|
||||
};
|
||||
|
||||
self.initialize_inner(&event_handler, settings)?;
|
||||
|
||||
create_browser(event_handler, instance_dir, disable_gpu_acceleration)
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub(crate) fn create(self, event_handler: H, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
|
||||
pub(crate) fn initialize(self, event_handler: H, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
|
||||
let instance_dir = TempDir::new().expect("Failed to create temporary directory for CEF instance");
|
||||
let accelerated_paint = accelerated_paint(disable_gpu_acceleration);
|
||||
self.build_inner(&event_handler, instance_dir.as_ref(), accelerated_paint)?;
|
||||
super::multithreaded::run_on_ui_thread(move || match create_browser(event_handler, instance_dir, accelerated_paint) {
|
||||
Ok(context) => super::multithreaded::CONTEXT.with(|b| *b.borrow_mut() = Some(context)),
|
||||
Err(e) => panic!("Failed to initialize CEF context: {:?}", e),
|
||||
|
||||
let settings = Settings {
|
||||
multi_threaded_message_loop: 1,
|
||||
#[cfg(target_os = "linux")]
|
||||
no_sandbox: 1,
|
||||
..Self::common_settings(instance_dir.as_ref())
|
||||
};
|
||||
|
||||
self.initialize_inner(&event_handler, settings)?;
|
||||
|
||||
super::multithreaded::run_on_ui_thread(move || match create_browser(event_handler, instance_dir, disable_gpu_acceleration) {
|
||||
Ok(context) => {
|
||||
super::multithreaded::CONTEXT.with(|b| {
|
||||
*b.borrow_mut() = Some(context);
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
panic!("Failed to initialize CEF context: {:?}", e);
|
||||
}
|
||||
});
|
||||
|
||||
Ok(super::multithreaded::MultiThreadedCefContextProxy)
|
||||
}
|
||||
|
||||
fn build_inner(self, event_handler: &H, instance_dir: &Path, accelerated_paint: bool) -> Result<(), InitError> {
|
||||
let mut cef_app = App::new(BrowserProcessAppImpl::new(event_handler.duplicate(), accelerated_paint));
|
||||
let result = cef::initialize(Some(self.args.as_main_args()), Some(&platform_settings(instance_dir)), Some(&mut cef_app), std::ptr::null_mut());
|
||||
fn initialize_inner(self, event_handler: &H, settings: Settings) -> Result<(), InitError> {
|
||||
// Attention! Wrapping this in an extra App is necessary, otherwise the program still compiles but segfaults
|
||||
let mut cef_app = App::new(BrowserProcessAppImpl::new(event_handler.duplicate()));
|
||||
|
||||
let result = cef::initialize(Some(self.args.as_main_args()), Some(&settings), Some(&mut cef_app), std::ptr::null_mut());
|
||||
if result != 1 {
|
||||
return Err(InitError::InitializationFailureCode(cef::get_exit_code() as u32));
|
||||
let cef_exit_code = cef::get_exit_code() as u32;
|
||||
return Err(InitError::InitializationFailureCode(cef_exit_code));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn accelerated_paint(disable_gpu_acceleration: bool) -> bool {
|
||||
#[cfg(feature = "accelerated_paint")]
|
||||
{
|
||||
!disable_gpu_acceleration && crate::cef::platform::should_enable_hardware_acceleration()
|
||||
}
|
||||
#[cfg(not(feature = "accelerated_paint"))]
|
||||
{
|
||||
let _ = disable_gpu_acceleration;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn platform_settings(instance_dir: &Path) -> Settings {
|
||||
let log_severity = match std::env::var("GRAPHITE_BROWSER_LOG").unwrap_or_default().to_lowercase().as_str() {
|
||||
"debug" => cef_log_severity_t::LOGSEVERITY_VERBOSE,
|
||||
"info" => cef_log_severity_t::LOGSEVERITY_INFO,
|
||||
"warn" => cef_log_severity_t::LOGSEVERITY_WARNING,
|
||||
"error" => cef_log_severity_t::LOGSEVERITY_ERROR,
|
||||
"none" => cef_log_severity_t::LOGSEVERITY_DISABLE,
|
||||
_ => cef_log_severity_t::LOGSEVERITY_FATAL,
|
||||
};
|
||||
|
||||
let base = Settings {
|
||||
windowless_rendering_enabled: 1,
|
||||
root_cache_path: instance_dir.to_str().map(CefString::from).unwrap(),
|
||||
cache_path: "".into(),
|
||||
disable_signal_handlers: 1,
|
||||
log_severity: LogSeverity::from(log_severity),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let exe = std::env::current_exe().expect("cannot get current exe path");
|
||||
let app_root = exe.parent().and_then(|p| p.parent()).expect("bad path structure").parent().expect("bad path structure");
|
||||
Settings {
|
||||
main_bundle_path: app_root.to_str().map(CefString::from).unwrap(),
|
||||
multi_threaded_message_loop: 0,
|
||||
external_message_pump: 1,
|
||||
no_sandbox: 1, // GPU helper crashes when running with sandbox
|
||||
..base
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
Settings {
|
||||
multi_threaded_message_loop: 1,
|
||||
#[cfg(target_os = "linux")]
|
||||
no_sandbox: 1,
|
||||
..base
|
||||
}
|
||||
}
|
||||
|
||||
fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: TempDir, accelerated_paint: bool) -> Result<SingleThreadedCefContext, InitError> {
|
||||
fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: TempDir, disable_gpu_acceleration: bool) -> Result<SingleThreadedCefContext, InitError> {
|
||||
let mut client = Client::new(BrowserProcessClientImpl::new(&event_handler));
|
||||
|
||||
#[cfg(feature = "accelerated_paint")]
|
||||
let use_accelerated_paint = if disable_gpu_acceleration {
|
||||
false
|
||||
} else {
|
||||
crate::cef::platform::should_enable_hardware_acceleration()
|
||||
};
|
||||
|
||||
let window_info = WindowInfo {
|
||||
windowless_rendering_enabled: 1,
|
||||
#[cfg(feature = "accelerated_paint")]
|
||||
shared_texture_enabled: accelerated_paint as i32,
|
||||
shared_texture_enabled: use_accelerated_paint as i32,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
@@ -181,24 +192,27 @@ fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: TempDir, a
|
||||
incognito_request_context.register_scheme_handler_factory(Some(&RESOURCE_SCHEME.into()), Some(&RESOURCE_DOMAIN.into()), Some(&mut scheme_handler_factory));
|
||||
|
||||
let url = format!("{RESOURCE_SCHEME}://{RESOURCE_DOMAIN}/");
|
||||
browser_host_create_browser_sync(
|
||||
|
||||
let browser = browser_host_create_browser_sync(
|
||||
Some(&window_info),
|
||||
Some(&mut client),
|
||||
Some(&url.as_str().into()),
|
||||
Some(&settings),
|
||||
Option::<&mut DictionaryValue>::None,
|
||||
Some(&mut incognito_request_context),
|
||||
)
|
||||
.map(|browser| SingleThreadedCefContext {
|
||||
event_handler: Box::new(event_handler),
|
||||
browser,
|
||||
input_state: InputState::default(),
|
||||
_instance_dir: instance_dir,
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
);
|
||||
|
||||
if let Some(browser) = browser {
|
||||
Ok(SingleThreadedCefContext {
|
||||
event_handler: Box::new(event_handler),
|
||||
browser,
|
||||
input_state: InputState::default(),
|
||||
_instance_dir: instance_dir,
|
||||
})
|
||||
} else {
|
||||
tracing::error!("Failed to create browser");
|
||||
InitError::BrowserCreationFailed
|
||||
})
|
||||
Err(InitError::BrowserCreationFailed)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
|
||||
@@ -9,14 +9,12 @@ use crate::cef::CefEventHandler;
|
||||
pub(crate) struct BrowserProcessAppImpl<H: CefEventHandler> {
|
||||
object: *mut RcImpl<_cef_app_t, Self>,
|
||||
event_handler: H,
|
||||
accelerated_paint: bool,
|
||||
}
|
||||
impl<H: CefEventHandler> BrowserProcessAppImpl<H> {
|
||||
pub(crate) fn new(event_handler: H, accelerated_paint: bool) -> Self {
|
||||
pub(crate) fn new(event_handler: H) -> Self {
|
||||
Self {
|
||||
object: std::ptr::null_mut(),
|
||||
event_handler,
|
||||
accelerated_paint,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -54,41 +52,37 @@ impl<H: CefEventHandler> ImplApp for BrowserProcessAppImpl<H> {
|
||||
|
||||
let extra_disabled_features = ["OptimizationHints", "OnDeviceModelService", "TranslateUI"];
|
||||
let disabled_features_switch = Some(&"disable-features".into());
|
||||
let mut disabled_features: Vec<String> = CefString::from(&cmd.switch_value(disabled_features_switch))
|
||||
let disabled_features: String = CefString::from(&cmd.switch_value(disabled_features_switch))
|
||||
.to_string()
|
||||
.split(',')
|
||||
.filter(|feature| !feature.is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
.collect();
|
||||
disabled_features.extend(extra_disabled_features.into_iter().map(ToOwned::to_owned));
|
||||
cmd.append_switch_with_value(disabled_features_switch, Some(&disabled_features.join(",").as_str().into()));
|
||||
.chain(extra_disabled_features)
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
cmd.append_switch_with_value(disabled_features_switch, Some(&disabled_features.as_str().into()));
|
||||
|
||||
if self.accelerated_paint {
|
||||
cmd.append_switch(Some(&"enable-gpu".into()));
|
||||
cmd.append_switch(Some(&"enable-gpu-compositing".into()));
|
||||
cmd.append_switch(Some(&"enable-begin-frame-scheduling".into()));
|
||||
cmd.append_switch(Some(&"off-screen-rendering-enabled".into()));
|
||||
cmd.append_switch(Some(&"enable-accelerated-2d-canvas".into()));
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
cmd.append_switch_with_value(Some(&"use-angle".into()), Some(&"gl-egl".into()));
|
||||
|
||||
let use_wayland = std::env::var("WAYLAND_DISPLAY")
|
||||
.ok()
|
||||
.filter(|var| !var.is_empty())
|
||||
.or_else(|| std::env::var("WAYLAND_SOCKET").ok())
|
||||
.filter(|var| !var.is_empty())
|
||||
.is_some();
|
||||
if use_wayland {
|
||||
cmd.append_switch_with_value(Some(&"ozone-platform".into()), Some(&"wayland".into()));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
#[cfg(not(feature = "accelerated_paint"))]
|
||||
{
|
||||
// Disable GPU acceleration when accelerated_paint feature is not enabled
|
||||
cmd.append_switch(Some(&"disable-gpu".into()));
|
||||
cmd.append_switch(Some(&"disable-gpu-compositing".into()));
|
||||
}
|
||||
|
||||
#[cfg(feature = "accelerated_paint")]
|
||||
{
|
||||
// cmd.append_switch(Some(&"transparent-painting-enabled".into()));
|
||||
cmd.append_switch(Some(&"enable-zero-copy".into()));
|
||||
// cmd.append_switch(Some(&"off-screen-rendering-enabled".into()));
|
||||
// cmd.append_switch(Some(&"use-views".into()));
|
||||
cmd.append_switch(Some(&"enable-gpu-rasterization".into()));
|
||||
cmd.append_switch(Some(&"enable-accelerated-2d-canvas".into()));
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "accelerated_paint", target_os = "linux"))]
|
||||
{
|
||||
cmd.append_switch_with_value(Some(&"use-angle".into()), Some(&"gl-egl".into()));
|
||||
cmd.append_switch_with_value(Some(&"ozone-platform".into()), Some(&"headless".into()));
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
// Hide user prompt asking for keychain access
|
||||
@@ -119,7 +113,6 @@ impl<H: CefEventHandler> Clone for BrowserProcessAppImpl<H> {
|
||||
Self {
|
||||
object: self.object,
|
||||
event_handler: self.event_handler.duplicate(),
|
||||
accelerated_paint: self.accelerated_paint,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +52,11 @@ impl ImplRenderProcessHandler for RenderProcessHandlerImpl {
|
||||
|
||||
let function_call = format!("window.{function_name}(window.{property_name})");
|
||||
|
||||
global.set_value_bykey(Some(&property_name.into()), Some(&mut value), cef_v8_propertyattribute_t::V8_PROPERTY_ATTRIBUTE_READONLY.wrap_result());
|
||||
global.set_value_bykey(
|
||||
Some(&property_name.into()),
|
||||
Some(&mut value),
|
||||
cef_v8_propertyattribute_t::V8_PROPERTY_ATTRIBUTE_READONLY.wrap_result(),
|
||||
);
|
||||
|
||||
if global.value_bykey(Some(&function_name.into())).is_some() {
|
||||
frame.execute_java_script(Some(&function_call.as_str().into()), None, 0);
|
||||
|
||||
@@ -7,11 +7,9 @@ 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";
|
||||
pub(crate) const APP_RESOURCES_DIRECTORY_NAME: &str = "resources";
|
||||
|
||||
// CEF configuration constants
|
||||
pub(crate) const CEF_WINDOWLESS_FRAME_RATE: i32 = 60;
|
||||
|
||||
+1
-7
@@ -2,7 +2,7 @@ use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::consts::{APP_DIRECTORY_NAME, APP_DOCUMENTS_DIRECTORY_NAME, APP_RESOURCES_DIRECTORY_NAME};
|
||||
use crate::consts::{APP_DIRECTORY_NAME, APP_DOCUMENTS_DIRECTORY_NAME};
|
||||
|
||||
pub(crate) fn ensure_dir_exists(path: &PathBuf) {
|
||||
if !path.exists() {
|
||||
@@ -51,12 +51,6 @@ pub(crate) fn app_autosave_documents_dir() -> PathBuf {
|
||||
path
|
||||
}
|
||||
|
||||
pub(crate) fn app_resources_dir() -> PathBuf {
|
||||
let path = app_data_dir().join(APP_RESOURCES_DIRECTORY_NAME);
|
||||
ensure_dir_exists(&path);
|
||||
path
|
||||
}
|
||||
|
||||
/// Temporary directory that is automatically deleted when dropped.
|
||||
pub struct TempDir {
|
||||
path: PathBuf,
|
||||
|
||||
@@ -9,7 +9,6 @@ pub(crate) enum AppEvent {
|
||||
DesktopWrapperMessage(DesktopWrapperMessage),
|
||||
NodeGraphExecutionResult(NodeGraphExecutionResult),
|
||||
Exit,
|
||||
OpenFiles(Vec<std::path::PathBuf>),
|
||||
#[cfg(target_os = "macos")]
|
||||
MenuEvent {
|
||||
id: String,
|
||||
|
||||
+6
-17
@@ -19,7 +19,6 @@ mod gpu_context;
|
||||
mod persist;
|
||||
mod preferences;
|
||||
mod render;
|
||||
mod socket;
|
||||
mod window;
|
||||
|
||||
pub(crate) mod consts;
|
||||
@@ -59,13 +58,7 @@ pub fn start() {
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::error!("Another instance is already running, Exiting.");
|
||||
if !cli.files.is_empty()
|
||||
&& let Err(error) = socket::send(socket::Message::OpenFiles(cli.files))
|
||||
{
|
||||
tracing::error!("Failed to send socket message to running instance: {}", error);
|
||||
std::process::exit(1);
|
||||
}
|
||||
return;
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -74,7 +67,7 @@ pub fn start() {
|
||||
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory
|
||||
dirs::delete_old_cef_browser_directory();
|
||||
|
||||
let mut prefs = preferences::read();
|
||||
let prefs = preferences::read();
|
||||
|
||||
// Must be called before event loop initialization or native window integrations will break
|
||||
App::init();
|
||||
@@ -85,19 +78,15 @@ pub fn start() {
|
||||
let (app_event_sender, app_event_receiver) = std::sync::mpsc::channel();
|
||||
let app_event_scheduler = event_loop.create_app_event_scheduler(app_event_sender);
|
||||
|
||||
let _socket_handle = socket::start(app_event_scheduler.clone());
|
||||
|
||||
let (cef_view_info_sender, cef_view_info_receiver) = std::sync::mpsc::channel();
|
||||
|
||||
if cli.disable_ui_acceleration {
|
||||
prefs.disable_ui_acceleration = true;
|
||||
}
|
||||
if prefs.disable_ui_acceleration {
|
||||
let disable_ui_acceleration = prefs.disable_ui_acceleration || cli.disable_ui_acceleration;
|
||||
if disable_ui_acceleration {
|
||||
println!("UI acceleration is disabled");
|
||||
}
|
||||
|
||||
let cef_handler = cef::CefHandler::new(wgpu_context.clone(), app_event_scheduler.clone(), cef_view_info_receiver);
|
||||
let cef_context = match cef_context_builder.create(cef_handler, prefs.disable_ui_acceleration) {
|
||||
let cef_context = match cef_context_builder.initialize(cef_handler, disable_ui_acceleration) {
|
||||
Ok(context) => {
|
||||
tracing::info!("CEF initialized successfully");
|
||||
context
|
||||
@@ -113,7 +102,7 @@ pub fn start() {
|
||||
}
|
||||
};
|
||||
|
||||
let app = App::new(Box::new(cef_context), cef_view_info_sender, wgpu_context, app_event_receiver, app_event_scheduler, prefs, cli.files);
|
||||
let app = App::new(Box::new(cef_context), cef_view_info_sender, wgpu_context, app_event_receiver, app_event_scheduler, prefs, cli);
|
||||
|
||||
let exit_reason = app.run(event_loop);
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ pub(crate) fn write_state(state: PersistedState) {
|
||||
if let Err(e) = std::fs::write(state_file_path(), data) {
|
||||
tracing::error!("Failed to write persistent data to disk: {e}");
|
||||
}
|
||||
garbage_collect_document_files(state);
|
||||
garbage_collect_document_files(&state);
|
||||
}
|
||||
|
||||
pub(crate) fn write_document_content(id: DocumentId, document_content: String) {
|
||||
|
||||
+16
-35
@@ -1,7 +1,8 @@
|
||||
use std::borrow::Cow;
|
||||
use wgpu::PresentMode;
|
||||
|
||||
use crate::window::Window;
|
||||
use crate::wrapper::{WgpuContext, WgpuExecutor};
|
||||
use crate::wrapper::{TargetTexture, WgpuContext, WgpuExecutor};
|
||||
|
||||
#[derive(derivative::Derivative)]
|
||||
#[derivative(Debug)]
|
||||
@@ -18,7 +19,7 @@ pub(crate) struct RenderState {
|
||||
viewport_scale: [f32; 2],
|
||||
viewport_offset: [f32; 2],
|
||||
viewport_texture: Option<std::sync::Arc<wgpu::Texture>>,
|
||||
overlays_texture: Option<std::sync::Arc<wgpu::Texture>>,
|
||||
overlays_texture: Option<TargetTexture>,
|
||||
ui_texture: Option<wgpu::Texture>,
|
||||
bind_group: Option<wgpu::BindGroup>,
|
||||
#[derivative(Debug = "ignore")]
|
||||
@@ -120,7 +121,7 @@ impl RenderState {
|
||||
|
||||
let render_pipeline_layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Render Pipeline Layout"),
|
||||
bind_group_layouts: &[Some(&texture_bind_group_layout)],
|
||||
bind_group_layouts: &[&texture_bind_group_layout],
|
||||
immediate_size: size_of::<Immediates>() as u32,
|
||||
});
|
||||
|
||||
@@ -232,17 +233,11 @@ impl RenderState {
|
||||
return;
|
||||
};
|
||||
let size = glam::UVec2::new(viewport_texture.width(), viewport_texture.height());
|
||||
let result = futures::executor::block_on(self.executor.render_vello_scene(&scene, size, &Default::default(), None));
|
||||
match result {
|
||||
Ok(texture) => {
|
||||
self.overlays_texture = Some(texture);
|
||||
}
|
||||
Err(e) => {
|
||||
self.overlays_texture = None;
|
||||
tracing::error!("Error rendering overlays: {:?}", e);
|
||||
}
|
||||
let result = futures::executor::block_on(self.executor.render_vello_scene_to_target_texture(&scene, size, &Default::default(), &mut self.overlays_texture));
|
||||
if let Err(e) = result {
|
||||
tracing::error!("Error rendering overlays: {:?}", e);
|
||||
return;
|
||||
}
|
||||
|
||||
self.update_bindgroup();
|
||||
}
|
||||
|
||||
@@ -262,17 +257,7 @@ impl RenderState {
|
||||
self.render_overlays(scene);
|
||||
}
|
||||
|
||||
let (output, suboptimal) = match self.surface.get_current_texture() {
|
||||
wgpu::CurrentSurfaceTexture::Success(t) => (t, false),
|
||||
// wgpu reports the swapchain no longer matches the underlying surface; present this frame and reconfigure after present, since `Surface::configure` panics while an acquired `SurfaceTexture` is still alive
|
||||
wgpu::CurrentSurfaceTexture::Suboptimal(t) => (t, true),
|
||||
// Window is minimized or behind another window: skip the frame silently and try again once it becomes visible
|
||||
wgpu::CurrentSurfaceTexture::Occluded => return Ok(()),
|
||||
wgpu::CurrentSurfaceTexture::Lost => return Err(RenderError::SurfaceLost),
|
||||
wgpu::CurrentSurfaceTexture::Outdated => return Err(RenderError::SurfaceOutdated),
|
||||
wgpu::CurrentSurfaceTexture::Timeout => return Err(RenderError::SurfaceTimeout),
|
||||
wgpu::CurrentSurfaceTexture::Validation => return Err(RenderError::SurfaceValidation),
|
||||
};
|
||||
let output = self.surface.get_current_texture().map_err(RenderError::SurfaceError)?;
|
||||
|
||||
let view = output.texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
@@ -318,10 +303,6 @@ impl RenderState {
|
||||
window.pre_present_notify();
|
||||
output.present();
|
||||
|
||||
if suboptimal {
|
||||
self.surface.configure(&self.context.device, &self.config);
|
||||
}
|
||||
|
||||
if ui_scale.is_some() {
|
||||
return Err(RenderError::OutdatedUITextureError);
|
||||
}
|
||||
@@ -333,7 +314,11 @@ impl RenderState {
|
||||
fn update_bindgroup(&mut self) {
|
||||
self.surface_outdated = true;
|
||||
let viewport_texture_view = self.viewport_texture.as_ref().unwrap_or(&self.transparent_texture).create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let overlays_texture_view = self.overlays_texture.as_ref().unwrap_or(&self.transparent_texture).create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let overlays_texture_view = self
|
||||
.overlays_texture
|
||||
.as_ref()
|
||||
.map(|target| Cow::Borrowed(target.view()))
|
||||
.unwrap_or_else(|| Cow::Owned(self.transparent_texture.create_view(&wgpu::TextureViewDescriptor::default())));
|
||||
let ui_texture_view = self.ui_texture.as_ref().unwrap_or(&self.transparent_texture).create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
let bind_group = self.context.device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
@@ -345,7 +330,7 @@ impl RenderState {
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::TextureView(&overlays_texture_view),
|
||||
resource: wgpu::BindingResource::TextureView(overlays_texture_view.as_ref()),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
@@ -363,13 +348,9 @@ impl RenderState {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum RenderError {
|
||||
OutdatedUITextureError,
|
||||
SurfaceLost,
|
||||
SurfaceOutdated,
|
||||
SurfaceTimeout,
|
||||
SurfaceValidation,
|
||||
SurfaceError(wgpu::SurfaceError),
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
use interprocess::local_socket::{GenericFilePath, GenericNamespaced, ListenerNonblockingMode, ListenerOptions, Name, prelude::*};
|
||||
use std::io::{ErrorKind, Read, Write};
|
||||
use std::sync::mpsc;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::consts::APP_SOCKET_FILE_NAME;
|
||||
use crate::event::{AppEvent, AppEventScheduler};
|
||||
|
||||
// TODO: Needs to be integrated/replaced with the action system.
|
||||
// TODO: At that point this should just wrap the action, meaning all actions bindable by the user can also be accessed via the socket.
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) enum Message {
|
||||
OpenFiles(Vec<std::path::PathBuf>),
|
||||
}
|
||||
|
||||
fn handle_message(message: Message, app_event_scheduler: &AppEventScheduler) {
|
||||
match message {
|
||||
Message::OpenFiles(paths) => {
|
||||
app_event_scheduler.schedule(AppEvent::OpenFiles(paths));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn send(message: Message) -> std::io::Result<()> {
|
||||
let data = ron::ser::to_string(&message).map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
|
||||
let mut connection = interprocess::local_socket::Stream::connect(socket_name())?;
|
||||
connection.write_all(data.as_bytes())
|
||||
}
|
||||
|
||||
pub(crate) struct SocketHandle {
|
||||
thread: Option<thread::JoinHandle<()>>,
|
||||
shutdown_sender: mpsc::Sender<()>,
|
||||
}
|
||||
impl Drop for SocketHandle {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.shutdown_sender.send(());
|
||||
let _ = self.thread.take().expect("SocketHandle can only be dropped once").join();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn start(app_event_scheduler: AppEventScheduler) -> SocketHandle {
|
||||
let (shutdown_sender, shutdown_receiver) = mpsc::channel();
|
||||
|
||||
let thread = thread::Builder::new()
|
||||
.name("socket".to_string())
|
||||
.spawn(move || run(app_event_scheduler, shutdown_receiver))
|
||||
.expect("Failed to spawn socket thread");
|
||||
|
||||
SocketHandle {
|
||||
shutdown_sender,
|
||||
thread: Some(thread),
|
||||
}
|
||||
}
|
||||
|
||||
fn run(app_event_scheduler: AppEventScheduler, shutdown_receiver: mpsc::Receiver<()>) {
|
||||
let listener = match ListenerOptions::new()
|
||||
.name(socket_name())
|
||||
.nonblocking(ListenerNonblockingMode::Accept)
|
||||
.try_overwrite(true)
|
||||
.max_spin_time(Duration::from_millis(100))
|
||||
.create_sync()
|
||||
{
|
||||
Ok(listener) => listener,
|
||||
Err(error) => {
|
||||
tracing::error!("Failed to bind socket: {}", error);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let max_backoff = Duration::from_millis(100);
|
||||
let mut backoff = Duration::ZERO;
|
||||
|
||||
loop {
|
||||
if backoff.is_zero() {
|
||||
match shutdown_receiver.try_recv() {
|
||||
Ok(()) | Err(mpsc::TryRecvError::Disconnected) => break,
|
||||
Err(mpsc::TryRecvError::Empty) => {}
|
||||
}
|
||||
backoff = Duration::from_nanos(1);
|
||||
} else {
|
||||
match shutdown_receiver.recv_timeout(backoff) {
|
||||
Ok(()) | Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => {}
|
||||
}
|
||||
backoff = (backoff * 2).min(max_backoff);
|
||||
}
|
||||
|
||||
match listener.accept() {
|
||||
Ok(mut connection) => {
|
||||
backoff = Duration::ZERO;
|
||||
|
||||
let app_event_scheduler = app_event_scheduler.clone();
|
||||
let spawn_result = thread::Builder::new().name("socket-connection".to_string()).spawn(move || {
|
||||
let mut data = String::new();
|
||||
if let Err(error) = connection.read_to_string(&mut data) {
|
||||
tracing::error!("Failed to read socket message: {}", error);
|
||||
return;
|
||||
}
|
||||
|
||||
match ron::de::from_str(&data) {
|
||||
Ok(message) => handle_message(message, &app_event_scheduler),
|
||||
Err(error) => tracing::error!("Failed to deserialize socket message: {}", error),
|
||||
}
|
||||
});
|
||||
if let Err(error) = spawn_result {
|
||||
tracing::error!("Failed to spawn socket connection thread: {}", error);
|
||||
}
|
||||
}
|
||||
Err(error) if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted) => {}
|
||||
Err(error) => {
|
||||
tracing::error!("Failed to accept socket connection: {}", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn socket_name() -> Name<'static> {
|
||||
if cfg!(target_os = "windows") {
|
||||
let user = std::env::var("USERNAME").unwrap_or_default();
|
||||
let name = format!("{user}-{app}-{APP_SOCKET_FILE_NAME}", app = crate::consts::APP_NAME);
|
||||
name.to_ns_name::<GenericNamespaced>().expect("valid named pipe name")
|
||||
} else {
|
||||
crate::dirs::app_data_dir().join(APP_SOCKET_FILE_NAME).to_fs_name::<GenericFilePath>().expect("valid socket path")
|
||||
}
|
||||
}
|
||||
@@ -140,11 +140,6 @@ impl Window {
|
||||
let _ = self.winit_window.drag_window();
|
||||
}
|
||||
|
||||
pub(crate) fn focus(&self) {
|
||||
self.winit_window.set_minimized(false);
|
||||
self.winit_window.focus_window();
|
||||
}
|
||||
|
||||
pub(crate) fn hide(&self) {
|
||||
self.native_handle.hide();
|
||||
}
|
||||
|
||||
@@ -26,8 +26,8 @@ impl super::NativeWindow for NativeWindowImpl {
|
||||
}
|
||||
|
||||
fn new(_window: &dyn Window, app_event_scheduler: AppEventScheduler) -> Self {
|
||||
app::setup(app_event_scheduler.clone());
|
||||
let menu = menu::Menu::new(app_event_scheduler);
|
||||
|
||||
NativeWindowImpl { menu }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,75 +1,6 @@
|
||||
use std::ffi::CStr;
|
||||
use std::ffi::OsStr;
|
||||
use std::ops::Deref;
|
||||
use std::ops::DerefMut;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Mutex, Once};
|
||||
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::ProtocolObject;
|
||||
use objc2::{ClassType, MainThreadMarker, MainThreadOnly, define_class, msg_send};
|
||||
use objc2_app_kit::{NSApplication, NSApplicationDelegate, NSEvent, NSEventType, NSResponder};
|
||||
use objc2_foundation::{NSArray, NSObject, NSObjectProtocol, NSURL};
|
||||
|
||||
use crate::event::{AppEvent, AppEventScheduler};
|
||||
|
||||
static APP_EVENT_SCHEDULER: Mutex<Option<AppEventScheduler>> = Mutex::new(None);
|
||||
static PENDING_EVENTS: Mutex<Option<Vec<AppEvent>>> = Mutex::new(Some(Vec::new()));
|
||||
|
||||
fn dispatch_event(event: AppEvent) {
|
||||
let app_event_scheduler_guard = APP_EVENT_SCHEDULER.lock().unwrap();
|
||||
if let Some(app_event_scheduler) = app_event_scheduler_guard.deref() {
|
||||
app_event_scheduler.schedule(event);
|
||||
} else if let Some(pending_events) = PENDING_EVENTS.lock().unwrap().deref_mut() {
|
||||
pending_events.push(event);
|
||||
} else {
|
||||
tracing::error!("Failed to dispatch event");
|
||||
}
|
||||
}
|
||||
|
||||
fn instance() -> objc2::rc::Retained<NSApplication> {
|
||||
unsafe { msg_send![GraphiteApplication::class(), sharedApplication] }
|
||||
}
|
||||
|
||||
static INSTALL_DELEGATE: Once = Once::new();
|
||||
|
||||
pub(super) fn init() {
|
||||
let _ = instance();
|
||||
|
||||
INSTALL_DELEGATE.call_once(|| {
|
||||
let mtm = MainThreadMarker::new().expect("should only ever be called from main thread");
|
||||
let delegate: Retained<GraphiteApplicationDelegate> = unsafe { msg_send![super(GraphiteApplicationDelegate::alloc(mtm).set_ivars(())), init] };
|
||||
instance().setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
|
||||
std::mem::forget(delegate);
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn setup(app_event_scheduler: AppEventScheduler) {
|
||||
let mut app_event_scheduler_guard = APP_EVENT_SCHEDULER.lock().unwrap();
|
||||
|
||||
if let Some(mut pending_events) = PENDING_EVENTS.lock().unwrap().take() {
|
||||
pending_events.drain(..).for_each(|event| {
|
||||
app_event_scheduler.schedule(event);
|
||||
});
|
||||
} else {
|
||||
tracing::error!("Failed to take PENDING_EVENTS and schedule them. This a bug.");
|
||||
}
|
||||
|
||||
*app_event_scheduler_guard = Some(app_event_scheduler);
|
||||
}
|
||||
|
||||
pub(super) fn hide() {
|
||||
instance().hide(None);
|
||||
}
|
||||
|
||||
pub(super) fn hide_others() {
|
||||
instance().hideOtherApplications(None);
|
||||
}
|
||||
|
||||
pub(super) fn show_all() {
|
||||
instance().unhideAllApplications(None);
|
||||
}
|
||||
use objc2::{ClassType, define_class, msg_send};
|
||||
use objc2_app_kit::{NSApplication, NSEvent, NSEventType, NSResponder};
|
||||
use objc2_foundation::NSObject;
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super(NSApplication, NSResponder, NSObject))]
|
||||
@@ -89,31 +20,22 @@ define_class!(
|
||||
}
|
||||
);
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super(NSObject))]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[name = "GraphiteApplicationDelegate"]
|
||||
struct GraphiteApplicationDelegate;
|
||||
fn instance() -> objc2::rc::Retained<NSApplication> {
|
||||
unsafe { msg_send![GraphiteApplication::class(), sharedApplication] }
|
||||
}
|
||||
|
||||
unsafe impl NSObjectProtocol for GraphiteApplicationDelegate {}
|
||||
pub(super) fn init() {
|
||||
let _ = instance();
|
||||
}
|
||||
|
||||
unsafe impl NSApplicationDelegate for GraphiteApplicationDelegate {
|
||||
#[unsafe(method(application:openURLs:))]
|
||||
fn application_open_urls(&self, _application: &NSApplication, urls: &NSArray<NSURL>) {
|
||||
let paths = (0..urls.count())
|
||||
.filter_map(|index| {
|
||||
let url = urls.objectAtIndex(index);
|
||||
if !url.isFileURL() {
|
||||
tracing::error!("Ignoring open URL event for non-file URL: {:?}", url);
|
||||
return None;
|
||||
}
|
||||
let cstr = unsafe { CStr::from_ptr(url.fileSystemRepresentation().as_ptr()) };
|
||||
let path = PathBuf::from(OsStr::from_bytes(cstr.to_bytes()));
|
||||
Some(path)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
pub(super) fn hide() {
|
||||
instance().hide(None);
|
||||
}
|
||||
|
||||
dispatch_event(AppEvent::OpenFiles(paths));
|
||||
}
|
||||
}
|
||||
);
|
||||
pub(super) fn hide_others() {
|
||||
instance().hideOtherApplications(None);
|
||||
}
|
||||
|
||||
pub(super) fn show_all() {
|
||||
instance().unhideAllApplications(None);
|
||||
}
|
||||
@@ -20,6 +20,7 @@ wgpu-executor = { workspace = true }
|
||||
|
||||
wgpu = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
dirs = { workspace = true }
|
||||
ron = { workspace = true}
|
||||
|
||||
@@ -9,9 +9,6 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
||||
DesktopWrapperMessage::FromWeb(message) => {
|
||||
dispatcher.queue_editor_message(*message);
|
||||
}
|
||||
DesktopWrapperMessage::Wake => {
|
||||
dispatcher.queue_editor_message(EditorMessage::Future(FutureMessage::Wake));
|
||||
}
|
||||
DesktopWrapperMessage::Input(message) => {
|
||||
dispatcher.queue_editor_message(EditorMessage::InputPreprocessor(message));
|
||||
}
|
||||
|
||||
@@ -14,7 +14,6 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
|
||||
title: "Open Document".to_string(),
|
||||
filters: vec![],
|
||||
multiple: true,
|
||||
context: OpenFileDialogContext::Open,
|
||||
});
|
||||
}
|
||||
@@ -22,7 +21,6 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
|
||||
title: "Import File".to_string(),
|
||||
filters: vec![],
|
||||
multiple: false,
|
||||
context: OpenFileDialogContext::Import,
|
||||
});
|
||||
}
|
||||
@@ -139,9 +137,6 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
FrontendMessage::WindowDrag => {
|
||||
dispatcher.respond(DesktopFrontendMessage::WindowDrag);
|
||||
}
|
||||
FrontendMessage::WindowFocus => {
|
||||
dispatcher.respond(DesktopFrontendMessage::WindowFocus);
|
||||
}
|
||||
FrontendMessage::WindowHide => {
|
||||
dispatcher.respond(DesktopFrontendMessage::WindowHide);
|
||||
}
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
use graph_craft::application_io::PlatformApplicationIo;
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
use graphite_editor::application::{Editor, Environment, Host, Platform};
|
||||
use graphite_editor::messages::prelude::{FrontendMessage, Message, Wake};
|
||||
use graphite_editor::messages::prelude::{FrontendMessage, Message};
|
||||
use message_dispatcher::DesktopWrapperMessageDispatcher;
|
||||
use messages::{DesktopFrontendMessage, DesktopWrapperMessage};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub use graph_craft::application_io::resource::MmapResourceStorage;
|
||||
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
|
||||
pub use wgpu_executor::TargetTexture;
|
||||
pub use wgpu_executor::WgpuContext;
|
||||
pub use wgpu_executor::WgpuContextBuilder;
|
||||
pub use wgpu_executor::WgpuExecutor;
|
||||
@@ -25,7 +23,7 @@ pub struct DesktopWrapper {
|
||||
}
|
||||
|
||||
impl DesktopWrapper {
|
||||
pub fn new(uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self {
|
||||
pub fn new(uuid_random_seed: u64) -> Self {
|
||||
#[cfg(target_os = "windows")]
|
||||
let host = Host::Windows;
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -33,13 +31,17 @@ impl DesktopWrapper {
|
||||
#[cfg(target_os = "linux")]
|
||||
let host = Host::Linux;
|
||||
let env = Environment { platform: Platform::Desktop, host };
|
||||
let application_io = PlatformApplicationIo::new_with_context(wgpu_context);
|
||||
|
||||
Self {
|
||||
editor: Editor::new(env, uuid_random_seed, resource_storage, application_io, schedule_wake),
|
||||
editor: Editor::new(env, uuid_random_seed),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init(&self, wgpu_context: WgpuContext) {
|
||||
let application_io = PlatformApplicationIo::new_with_context(wgpu_context);
|
||||
futures::executor::block_on(graphite_editor::node_graph_executor::replace_application_io(application_io));
|
||||
}
|
||||
|
||||
pub fn dispatch(&mut self, message: DesktopWrapperMessage) -> Vec<DesktopFrontendMessage> {
|
||||
let mut executor = DesktopWrapperMessageDispatcher::new(&mut self.editor);
|
||||
executor.queue_desktop_wrapper_message(message);
|
||||
|
||||
@@ -16,7 +16,6 @@ pub enum DesktopFrontendMessage {
|
||||
OpenFileDialog {
|
||||
title: String,
|
||||
filters: Vec<FileFilter>,
|
||||
multiple: bool,
|
||||
context: OpenFileDialogContext,
|
||||
},
|
||||
SaveFileDialog {
|
||||
@@ -72,7 +71,6 @@ pub enum DesktopFrontendMessage {
|
||||
WindowMaximize,
|
||||
WindowFullscreen,
|
||||
WindowDrag,
|
||||
WindowFocus,
|
||||
WindowHide,
|
||||
WindowHideOthers,
|
||||
WindowShowAll,
|
||||
@@ -82,7 +80,6 @@ pub enum DesktopFrontendMessage {
|
||||
|
||||
pub enum DesktopWrapperMessage {
|
||||
FromWeb(Box<EditorMessage>),
|
||||
Wake,
|
||||
Input(InputMessage),
|
||||
FileDialogResult { path: PathBuf, content: Vec<u8>, context: OpenFileDialogContext },
|
||||
SaveFileDialogResult { path: PathBuf, context: SaveFileDialogContext },
|
||||
@@ -105,7 +102,6 @@ pub struct FileFilter {
|
||||
pub extensions: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum OpenFileDialogContext {
|
||||
Open,
|
||||
Import,
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
[package]
|
||||
name = "document-container"
|
||||
description = "Container abstraction for the on-disk side of the .gdd document format"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
zip = ["dep:zip"]
|
||||
xz = ["dep:lzma-rust2", "dep:tar"]
|
||||
|
||||
[dependencies]
|
||||
thiserror = "2.0"
|
||||
log = { workspace = true }
|
||||
zip = { workspace = true, optional = true, features = ["deflate-flate2-zlib-rs"], default-features = false}
|
||||
lzma-rust2 = { workspace = true, optional = true }
|
||||
tar = { version = "0.4", optional = true, default-features = false }
|
||||
|
||||
[target.'cfg(not(target_family = "wasm"))'.dependencies]
|
||||
mmap-io = { workspace = true }
|
||||
|
||||
[target.'cfg(target_family = "wasm")'.dependencies]
|
||||
web-sys = { workspace = true, features = [
|
||||
"Navigator",
|
||||
"DomException",
|
||||
"Window",
|
||||
"StorageManager",
|
||||
"FileSystemCreateWritableOptions",
|
||||
"FileSystemDirectoryHandle",
|
||||
"FileSystemFileHandle",
|
||||
"FileSystemGetFileOptions",
|
||||
"FileSystemGetDirectoryOptions",
|
||||
"FileSystemHandle",
|
||||
"FileSystemHandleKind",
|
||||
"FileSystemWritableFileStream",
|
||||
"WritableStream",
|
||||
"Blob",
|
||||
] }
|
||||
js-sys = { workspace = true }
|
||||
wasm-bindgen = { workspace = true }
|
||||
wasm-bindgen-futures = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
futures = { workspace = true }
|
||||
@@ -1,97 +0,0 @@
|
||||
//! Archive codecs (zip, xz).
|
||||
//!
|
||||
//! Each codec streams entries in both directions: writers wrap an `io::Write` sink, and
|
||||
//! `deserialize` reads from any `io::Read + Seek` source and streams entries into any [`Container`].
|
||||
|
||||
#[cfg(any(feature = "zip", feature = "xz"))]
|
||||
use crate::ContainerError;
|
||||
use crate::{Container, Result};
|
||||
use std::io::{Read, Seek, Write};
|
||||
|
||||
/// Hard cap on the total decompressed size a codec will materialize from one archive.
|
||||
/// Defends against decompression bombs at the cost of refusing legitimately huge archives.
|
||||
#[cfg(any(feature = "zip", feature = "xz"))]
|
||||
pub(crate) const MAX_DECOMPRESSED_SIZE: u64 = 4 * 1024 * 1024 * 1024; // 4GB
|
||||
|
||||
/// Fold one entry's declared `size` into the running `total` and return it as a `usize` for `write_sized`.
|
||||
/// Both codecs route entries through here so the decompression-bomb cap and 32-bit-safe conversion live in
|
||||
/// one place. `write_sized` pre-allocates the declared size, so an over-large one is rejected before that.
|
||||
#[cfg(any(feature = "zip", feature = "xz"))]
|
||||
pub(crate) fn checked_entry_size(total: &mut u64, size: u64) -> Result<usize> {
|
||||
*total = total.saturating_add(size);
|
||||
if *total > MAX_DECOMPRESSED_SIZE {
|
||||
return Err(ContainerError::SizeLimitExceeded {
|
||||
declared: *total,
|
||||
limit: MAX_DECOMPRESSED_SIZE,
|
||||
});
|
||||
}
|
||||
|
||||
// `usize` is 32-bit on wasm, so convert fallibly to rule out a silent truncation into a smaller allocation.
|
||||
usize::try_from(size).map_err(|_| ContainerError::SizeLimitExceeded {
|
||||
declared: size,
|
||||
limit: usize::MAX as u64,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(feature = "zip")]
|
||||
mod zip;
|
||||
#[cfg(feature = "zip")]
|
||||
pub use zip::{Zip, ZipWriter};
|
||||
|
||||
#[cfg(feature = "xz")]
|
||||
mod xz;
|
||||
#[cfg(feature = "xz")]
|
||||
pub use xz::{Xz, XzWriter};
|
||||
|
||||
/// Streaming archive codec. The associated `Writer` type wraps a `Write + Seek` sink (zip needs
|
||||
/// `Seek` for the central directory; xz doesn't but `Seek` is free on file-like sinks) and
|
||||
/// accepts entries one at a time. `finish` flushes the codec's trailer and consumes the wrapper.
|
||||
pub trait Archive {
|
||||
type Writer<W: Write + Seek>: ArchiveWriter
|
||||
where
|
||||
W: Write + Seek;
|
||||
|
||||
fn writer<W: Write + Seek>(output: W) -> Result<Self::Writer<W>>;
|
||||
|
||||
/// Read entries from `source` and write each into `dest`, streaming so neither the full
|
||||
/// archive nor the full container ever sits in memory at once.
|
||||
fn open<R: Read + Seek, C: Container>(source: R, dest: &mut C) -> Result<()>;
|
||||
}
|
||||
|
||||
pub trait ArchiveWriter {
|
||||
fn write_entry(&mut self, path: &str, bytes: &[u8]) -> Result<()>;
|
||||
fn finish(self) -> Result<()>;
|
||||
}
|
||||
|
||||
/// Archive container formats distinguishable by their leading magic bytes.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ArchiveFormat {
|
||||
Xz,
|
||||
Zip,
|
||||
}
|
||||
|
||||
impl ArchiveFormat {
|
||||
/// Sniff the format from the leading magic bytes: xz streams start with `FD 37 7A 58 5A 00`,
|
||||
/// zip archives with `50 4B 03 04` (`PK\x03\x04`). Returns `None` for anything else.
|
||||
pub fn detect(bytes: &[u8]) -> Option<Self> {
|
||||
if bytes.starts_with(&[0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00]) {
|
||||
Some(Self::Xz)
|
||||
} else if bytes.starts_with(&[0x50, 0x4B, 0x03, 0x04]) {
|
||||
Some(Self::Zip)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Deserialize an archive into `dest`, auto-detecting the format from `bytes`' magic header.
|
||||
/// Errors if the bytes are neither a recognized xz nor zip archive.
|
||||
#[cfg(all(feature = "xz", feature = "zip"))]
|
||||
pub fn open_auto<C: Container>(bytes: &[u8], dest: &mut C) -> Result<()> {
|
||||
let source = std::io::Cursor::new(bytes);
|
||||
match ArchiveFormat::detect(bytes) {
|
||||
Some(ArchiveFormat::Xz) => Xz::open(source, dest),
|
||||
Some(ArchiveFormat::Zip) => Zip::open(source, dest),
|
||||
None => Err(ContainerError::Codec("unrecognized archive format (not xz or zip)".into())),
|
||||
}
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
//! Xz-compressed tarball archive codec.
|
||||
|
||||
use crate::archive::{Archive, ArchiveWriter, MAX_DECOMPRESSED_SIZE, checked_entry_size};
|
||||
use crate::{Container, ContainerError, Result, validate_path};
|
||||
use lzma_rust2::{XzOptions, XzReader, XzWriter as InnerXzWriter};
|
||||
use std::io::{Read, Seek, Write};
|
||||
|
||||
pub struct Xz;
|
||||
|
||||
/// xz-tar writer. Held as an `Option` so `finish` can take ownership and unwind the layered
|
||||
/// writers in the right order: drop the tar builder first to flush its trailer, then finish xz.
|
||||
pub struct XzWriter<W: Write + Seek> {
|
||||
tar: Option<tar::Builder<InnerXzWriter<W>>>,
|
||||
}
|
||||
|
||||
impl Archive for Xz {
|
||||
type Writer<W: Write + Seek> = XzWriter<W>;
|
||||
|
||||
fn writer<W: Write + Seek>(output: W) -> Result<Self::Writer<W>> {
|
||||
let xz_writer = InnerXzWriter::new(output, XzOptions::default()).map_err(lzma_err)?;
|
||||
Ok(XzWriter {
|
||||
tar: Some(tar::Builder::new(xz_writer)),
|
||||
})
|
||||
}
|
||||
|
||||
fn open<R: Read + Seek, C: Container>(source: R, dest: &mut C) -> Result<()> {
|
||||
// `take` bounds how many bytes we decompress from the xz stream, but each tar entry's declared
|
||||
// size is fed to `write_sized`, which pre-allocates from it before reading. Cap the cumulative
|
||||
// declared size too so a header claiming a huge size can't trigger a giant allocation up front.
|
||||
let xz_reader = XzReader::new(source, false);
|
||||
let bounded = xz_reader.take(MAX_DECOMPRESSED_SIZE);
|
||||
|
||||
let mut tar_reader = tar::Archive::new(bounded);
|
||||
let mut total_size = 0u64;
|
||||
|
||||
for entry in tar_reader.entries()? {
|
||||
let mut entry = entry?;
|
||||
if entry.header().entry_type() != tar::EntryType::Regular {
|
||||
continue;
|
||||
}
|
||||
// Reject non-UTF8 entry names rather than lossily rewriting them, so the path we store matches
|
||||
// the archive exactly.
|
||||
let path = entry.path()?;
|
||||
let path = path.to_str().ok_or_else(|| ContainerError::Codec(format!("tar: non-UTF8 entry name {path:?}")))?.to_owned();
|
||||
validate_path(&path)?;
|
||||
|
||||
let size = checked_entry_size(&mut total_size, entry.size())?;
|
||||
|
||||
dest.write_sized(&path, size, &mut |buffer| {
|
||||
entry.read_exact(buffer).map_err(ContainerError::Io)?;
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<W: Write + Seek> ArchiveWriter for XzWriter<W> {
|
||||
fn write_entry(&mut self, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
validate_path(path)?;
|
||||
let tar = self.tar.as_mut().ok_or_else(|| ContainerError::Codec("XzWriter already finished".into()))?;
|
||||
let mut header = tar::Header::new_gnu();
|
||||
header.set_path(path).map_err(|error| ContainerError::Codec(format!("tar: invalid path {path}: {error}")))?;
|
||||
header.set_size(bytes.len() as u64);
|
||||
header.set_mode(0o644);
|
||||
header.set_cksum();
|
||||
tar.append(&header, bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finish(mut self) -> Result<()> {
|
||||
self.finish_inner()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<W: Write + Seek> XzWriter<W> {
|
||||
/// Finish the archive and return the underlying sink, for in-memory archives where the caller
|
||||
/// wants the written bytes (e.g. `Cursor<Vec<u8>>`) back.
|
||||
pub fn finish_into(mut self) -> Result<W> {
|
||||
self.finish_inner()
|
||||
}
|
||||
|
||||
/// Unwind the layered writers in order (flush the tar trailer, then finish xz) and hand back the
|
||||
/// innermost sink. Shared by `finish` and `finish_into`.
|
||||
fn finish_inner(&mut self) -> Result<W> {
|
||||
let mut tar = self.tar.take().ok_or_else(|| ContainerError::Codec("XzWriter already finished".into()))?;
|
||||
tar.finish()?;
|
||||
let xz_writer = tar.into_inner()?;
|
||||
xz_writer.finish().map_err(lzma_err)
|
||||
}
|
||||
}
|
||||
|
||||
fn lzma_err(error: std::io::Error) -> ContainerError {
|
||||
ContainerError::Codec(format!("lzma: {error}"))
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
//! Zip archive codec.
|
||||
|
||||
use crate::archive::{Archive, ArchiveWriter, checked_entry_size};
|
||||
use crate::{Container, ContainerError, Result, validate_path};
|
||||
use std::io::{Read, Seek, Write};
|
||||
|
||||
use zip::ZipArchive;
|
||||
use zip::write::{SimpleFileOptions, ZipWriter as InnerZipWriter};
|
||||
|
||||
pub struct Zip;
|
||||
|
||||
pub struct ZipWriter<W: Write + Seek> {
|
||||
inner: InnerZipWriter<W>,
|
||||
options: SimpleFileOptions,
|
||||
}
|
||||
|
||||
impl Archive for Zip {
|
||||
type Writer<W: Write + Seek> = ZipWriter<W>;
|
||||
|
||||
fn writer<W: Write + Seek>(output: W) -> Result<Self::Writer<W>> {
|
||||
Ok(ZipWriter {
|
||||
inner: InnerZipWriter::new(output),
|
||||
options: SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated),
|
||||
})
|
||||
}
|
||||
|
||||
fn open<R: Read + Seek, C: Container>(source: R, dest: &mut C) -> Result<()> {
|
||||
let mut archive = ZipArchive::new(source).map_err(zip_err)?;
|
||||
|
||||
// Zip headers declare each entry's uncompressed size up front; `checked_entry_size` caps the running
|
||||
// total so a malicious archive can't exhaust memory or disk before any bytes are read.
|
||||
let mut total_size = 0u64;
|
||||
|
||||
for index in 0..archive.len() {
|
||||
let mut entry = archive.by_index(index).map_err(zip_err)?;
|
||||
if !entry.is_file() {
|
||||
continue;
|
||||
}
|
||||
let name = entry.name().to_string();
|
||||
validate_path(&name)?;
|
||||
|
||||
let size = checked_entry_size(&mut total_size, entry.size())?;
|
||||
|
||||
dest.write_sized(&name, size, &mut |buffer| {
|
||||
entry.read_exact(buffer).map_err(ContainerError::Io)?;
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<W: Write + Seek> ArchiveWriter for ZipWriter<W> {
|
||||
fn write_entry(&mut self, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
validate_path(path)?;
|
||||
self.inner.start_file(path, self.options).map_err(zip_err)?;
|
||||
self.inner.write_all(bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finish(self) -> Result<()> {
|
||||
self.inner.finish().map_err(zip_err)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<W: Write + Seek> ZipWriter<W> {
|
||||
/// Finish the archive and return the underlying sink, for in-memory archives where the caller
|
||||
/// wants the written bytes (e.g. `Cursor<Vec<u8>>`) back.
|
||||
pub fn finish_into(self) -> Result<W> {
|
||||
self.inner.finish().map_err(zip_err)
|
||||
}
|
||||
}
|
||||
|
||||
fn zip_err(error: zip::result::ZipError) -> ContainerError {
|
||||
// Preserve a real I/O failure (disk full, etc.) as a structured `Io` so callers can tell it apart from a
|
||||
// corrupt-archive `Codec` error; only the genuinely archive-format errors collapse into `Codec`.
|
||||
match error {
|
||||
zip::result::ZipError::Io(io) => ContainerError::Io(io),
|
||||
other => ContainerError::Codec(format!("zip: {other}")),
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
//! Container backend implementations.
|
||||
|
||||
pub mod memory;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub mod folder;
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub mod opfs;
|
||||
@@ -1,191 +0,0 @@
|
||||
//! Loose-folder backend.
|
||||
|
||||
use crate::{ByteHolder, Container, ContainerError, MmappedBytes, Result, validate_path, validate_prefix};
|
||||
use mmap_io::mmap::{MemoryMappedFile, MmapMode};
|
||||
use std::fs::{self, OpenOptions};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub struct FolderBackend {
|
||||
root: PathBuf,
|
||||
}
|
||||
|
||||
impl FolderBackend {
|
||||
/// Open an existing folder. Errors if `root` is not a directory.
|
||||
pub fn open(root: impl Into<PathBuf>) -> Result<Self> {
|
||||
let root = root.into();
|
||||
if !root.is_dir() {
|
||||
return Err(ContainerError::NotFound(root.display().to_string()));
|
||||
}
|
||||
Ok(Self { root })
|
||||
}
|
||||
|
||||
/// Create the folder if it does not exist, then open it.
|
||||
pub fn create(root: impl Into<PathBuf>) -> Result<Self> {
|
||||
let root = root.into();
|
||||
fs::create_dir_all(&root)?;
|
||||
Ok(Self { root })
|
||||
}
|
||||
|
||||
pub fn root(&self) -> &std::path::Path {
|
||||
&self.root
|
||||
}
|
||||
|
||||
fn resolve(&self, path: &str) -> Result<PathBuf> {
|
||||
validate_path(path)?;
|
||||
self.reject_symlinked_components(path)?;
|
||||
Ok(self.root.join(path))
|
||||
}
|
||||
|
||||
/// Reject any existing component along `root/relative` that is a symlink. `validate_path`/`validate_prefix`
|
||||
/// block `..` and absolute paths, but a symlink stored under the root could still point outside it, so every
|
||||
/// path that gets joined onto the root must pass through here before it is opened or traversed.
|
||||
fn reject_symlinked_components(&self, relative: &str) -> Result<()> {
|
||||
let mut partial = self.root.clone();
|
||||
for component in Path::new(relative).components() {
|
||||
partial.push(component);
|
||||
if let Ok(metadata) = fs::symlink_metadata(&partial)
|
||||
&& metadata.file_type().is_symlink()
|
||||
{
|
||||
return Err(ContainerError::InvalidPath(relative.to_string()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn list_filtered(&self, prefix: &str, want_files: bool) -> Result<Vec<String>> {
|
||||
validate_prefix(prefix)?;
|
||||
let base = if prefix.is_empty() || prefix == "." {
|
||||
self.root.clone()
|
||||
} else {
|
||||
self.reject_symlinked_components(prefix)?;
|
||||
self.root.join(prefix)
|
||||
};
|
||||
|
||||
// A missing prefix has no entries; a prefix that names a file is a misuse.
|
||||
if base.is_file() {
|
||||
return Err(ContainerError::NotADirectory(prefix.to_string()));
|
||||
}
|
||||
if !base.is_dir() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let mut results = Vec::new();
|
||||
for entry in fs::read_dir(&base)? {
|
||||
let entry = entry?;
|
||||
|
||||
// `file_type` does not follow symlinks, unlike `is_file`/`is_dir`. Skip symlink entries so a
|
||||
// listing never advertises a path that `resolve` would then reject as a container escape.
|
||||
let Ok(file_type) = entry.file_type() else { continue };
|
||||
let matches = if want_files { file_type.is_file() } else { file_type.is_dir() };
|
||||
if !matches {
|
||||
continue;
|
||||
}
|
||||
|
||||
let path = entry.path();
|
||||
let relative = path.strip_prefix(&self.root).map_err(|_| ContainerError::Backend("path escaped root".into()))?;
|
||||
results.push(relative.to_string_lossy().replace('\\', "/"));
|
||||
}
|
||||
Ok(results)
|
||||
}
|
||||
}
|
||||
|
||||
impl Container for FolderBackend {
|
||||
fn read(&self, path: &str) -> Result<ByteHolder> {
|
||||
let full = self.resolve(path)?;
|
||||
if !full.is_file() {
|
||||
return Err(ContainerError::NotFound(path.to_string()));
|
||||
}
|
||||
|
||||
// Mmapping a zero-length file is platform-dependent and often fails, so serve empty files as owned
|
||||
// bytes and reserve mmap for files that actually have content.
|
||||
if fs::metadata(&full).map(|metadata| metadata.len() == 0).unwrap_or(false) {
|
||||
return Ok(ByteHolder::Owned(Vec::new()));
|
||||
}
|
||||
|
||||
Ok(ByteHolder::Mmapped(MmappedBytes::new(open_mmap(&full)?)?))
|
||||
}
|
||||
|
||||
fn write(&self, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
let full = self.resolve(path)?;
|
||||
if let Some(parent) = full.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
fs::write(&full, bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn append(&self, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
let full = self.resolve(path)?;
|
||||
if let Some(parent) = full.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
let mut file = OpenOptions::new().create(true).append(true).open(&full)?;
|
||||
file.write_all(bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_sized(&self, path: &str, size: usize, fill: &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()> {
|
||||
if size == 0 {
|
||||
return self.write(path, &[]);
|
||||
}
|
||||
|
||||
let full = self.resolve(path)?;
|
||||
if let Some(parent) = full.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
|
||||
let file = MemoryMappedFile::create_rw(&full, size as u64).map_err(|error| ContainerError::Backend(format!("create_rw {full:?} failed: {error}")))?;
|
||||
|
||||
let result = {
|
||||
let mut slice = file
|
||||
.as_slice_mut(0, size as u64)
|
||||
.map_err(|error| ContainerError::Backend(format!("as_slice_mut {full:?} failed: {error}")))?;
|
||||
fill(slice.as_mut())?;
|
||||
drop(slice);
|
||||
file.flush().map_err(|error| ContainerError::Backend(format!("flush {full:?} failed: {error}")))
|
||||
};
|
||||
|
||||
// `create_rw` materializes the full-size file before `fill` runs, so remove it on failure rather
|
||||
// than leave a zeroed or half-written remnant.
|
||||
if result.is_err() {
|
||||
drop(file);
|
||||
let _ = fs::remove_file(&full);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn list(&self, prefix: &str) -> Result<Vec<String>> {
|
||||
self.list_filtered(prefix, true)
|
||||
}
|
||||
|
||||
fn list_dirs(&self, prefix: &str) -> Result<Vec<String>> {
|
||||
self.list_filtered(prefix, false)
|
||||
}
|
||||
|
||||
fn exists(&self, path: &str) -> bool {
|
||||
match self.resolve(path) {
|
||||
Ok(full) => full.is_file(),
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn remove(&self, path: &str) -> Result<()> {
|
||||
let full = self.resolve(path)?;
|
||||
// Idempotent: a missing file is not an error. Directories are left alone.
|
||||
if full.is_file() {
|
||||
fs::remove_file(full)?;
|
||||
}
|
||||
// TODO: decide if we should remove empty parent directories
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a memory-mapped read-only view of `path`, trying huge pages first. Callers must ensure `path`
|
||||
/// is non-empty, since mmapping a zero-length file is platform-dependent.
|
||||
fn open_mmap(path: &Path) -> Result<MemoryMappedFile> {
|
||||
match MemoryMappedFile::builder(path).mode(MmapMode::ReadOnly).huge_pages(true).open() {
|
||||
Ok(file) => Ok(file),
|
||||
Err(_) => MemoryMappedFile::open_ro(path).map_err(|error| ContainerError::Backend(format!("mmap of {path:?} failed: {error}"))),
|
||||
}
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
//! In-memory backend. Useful for tests and as the deserialize target for archive codecs.
|
||||
|
||||
use crate::{ByteHolder, Container, ContainerError, Result, validate_path, validate_prefix, with_trailing_slash};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Mutex;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct MemoryBackend {
|
||||
files: Mutex<HashMap<String, Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl MemoryBackend {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
impl Container for MemoryBackend {
|
||||
fn read(&self, path: &str) -> Result<ByteHolder> {
|
||||
validate_path(path)?;
|
||||
self.files
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(path)
|
||||
.map(|bytes| ByteHolder::Owned(bytes.clone()))
|
||||
.ok_or_else(|| ContainerError::NotFound(path.to_string()))
|
||||
}
|
||||
|
||||
fn write(&self, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
validate_path(path)?;
|
||||
self.files.lock().unwrap().insert(path.to_string(), bytes.to_vec());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn append(&self, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
validate_path(path)?;
|
||||
self.files.lock().unwrap().entry(path.to_string()).or_default().extend_from_slice(bytes);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn list(&self, prefix: &str) -> Result<Vec<String>> {
|
||||
validate_prefix(prefix)?;
|
||||
let files = self.files.lock().unwrap();
|
||||
// A prefix that is itself a stored key names a file, not a directory.
|
||||
if files.contains_key(prefix) {
|
||||
return Err(ContainerError::NotADirectory(prefix.to_string()));
|
||||
}
|
||||
|
||||
let normalized = with_trailing_slash(prefix);
|
||||
let results = files.keys().filter(|path| path.starts_with(&normalized) && !path[normalized.len()..].contains('/')).cloned().collect();
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
fn list_dirs(&self, prefix: &str) -> Result<Vec<String>> {
|
||||
validate_prefix(prefix)?;
|
||||
let files = self.files.lock().unwrap();
|
||||
if files.contains_key(prefix) {
|
||||
return Err(ContainerError::NotADirectory(prefix.to_string()));
|
||||
}
|
||||
|
||||
let normalized = with_trailing_slash(prefix);
|
||||
let mut seen = HashSet::new();
|
||||
let mut results = Vec::new();
|
||||
for path in files.keys() {
|
||||
if !path.starts_with(&normalized) {
|
||||
continue;
|
||||
}
|
||||
let remainder = &path[normalized.len()..];
|
||||
if let Some((segment, _)) = remainder.split_once('/') {
|
||||
let dir = format!("{normalized}{segment}");
|
||||
if seen.insert(dir.clone()) {
|
||||
results.push(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
fn exists(&self, path: &str) -> bool {
|
||||
validate_path(path).is_ok() && self.files.lock().unwrap().contains_key(path)
|
||||
}
|
||||
|
||||
fn remove(&self, path: &str) -> Result<()> {
|
||||
validate_path(path)?;
|
||||
// Idempotent: removing a missing path is not an error.
|
||||
self.files.lock().unwrap().remove(path);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,475 +0,0 @@
|
||||
//! OPFS (Origin Private File System) backend for browser wasm.
|
||||
|
||||
use crate::{AsyncContainer, ByteHolder, ContainerError, Result, validate_path, validate_prefix, with_trailing_slash};
|
||||
use futures::channel::oneshot;
|
||||
use js_sys::Uint8Array;
|
||||
use std::collections::{HashSet, VecDeque};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use wasm_bindgen::JsCast;
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen_futures::{JsFuture, spawn_local};
|
||||
use web_sys::{
|
||||
Blob, DomException, FileSystemCreateWritableOptions, FileSystemDirectoryHandle, FileSystemFileHandle, FileSystemGetDirectoryOptions, FileSystemGetFileOptions, FileSystemWritableFileStream,
|
||||
WritableStream,
|
||||
};
|
||||
|
||||
enum Mutation {
|
||||
Write {
|
||||
path: String,
|
||||
bytes: Vec<u8>,
|
||||
},
|
||||
Append {
|
||||
path: String,
|
||||
bytes: Vec<u8>,
|
||||
},
|
||||
Delete {
|
||||
path: String,
|
||||
},
|
||||
/// In-band flush barrier. The worker fulfills the sender once it dequeues this, which (by FIFO
|
||||
/// order) signals that every mutation enqueued before it has been applied to disk.
|
||||
Barrier(oneshot::Sender<()>),
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
directory: FileSystemDirectoryHandle,
|
||||
/// Paths believed to be on disk, letting `exists_non_blocking` answer without OPFS's missing sync API.
|
||||
/// Optimistic: a path is inserted when its write is queued and kept even if that write later fails, so it
|
||||
/// can briefly over-report. Rebuilt from real disk state on the next `open`.
|
||||
on_disk: HashSet<String>,
|
||||
queue: VecDeque<Mutation>,
|
||||
worker_active: bool,
|
||||
}
|
||||
|
||||
pub struct OpfsBackend {
|
||||
inner: Arc<Mutex<Inner>>,
|
||||
}
|
||||
|
||||
// Safety: only built for browser wasm where JS handles never leave the main thread.
|
||||
unsafe impl Send for OpfsBackend {}
|
||||
unsafe impl Sync for OpfsBackend {}
|
||||
|
||||
impl OpfsBackend {
|
||||
/// Open (or create) `directory_name` under the OPFS root.
|
||||
pub async fn open(directory_name: &str) -> Result<Self> {
|
||||
let directory = open_directory(directory_name).await.map_err(js_err)?;
|
||||
let on_disk = enumerate_paths(&directory, "").await.map_err(js_err)?;
|
||||
Ok(Self {
|
||||
inner: Arc::new(Mutex::new(Inner {
|
||||
directory,
|
||||
on_disk,
|
||||
queue: VecDeque::new(),
|
||||
worker_active: false,
|
||||
})),
|
||||
})
|
||||
}
|
||||
|
||||
fn directory(&self) -> FileSystemDirectoryHandle {
|
||||
self.inner.lock().unwrap().directory.clone()
|
||||
}
|
||||
|
||||
/// Wait until all queued non-blocking mutations have hit disk, so awaited reads observe them. Plants a
|
||||
/// barrier at the back of the queue and awaits the worker reaching it; by FIFO order, everything ahead is
|
||||
/// then applied. Draining stays the worker's job so it remains the sole mutator.
|
||||
async fn flush(&self) {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
{
|
||||
let mut guard = self.inner.lock().unwrap();
|
||||
guard.queue.push_back(Mutation::Barrier(sender));
|
||||
kick_worker(&self.inner, &mut guard);
|
||||
}
|
||||
// The sender is only dropped without sending if the worker is torn down mid-drain; either way
|
||||
// there is nothing left to wait for, so a receive error is treated as "already flushed".
|
||||
let _ = receiver.await;
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncContainer for OpfsBackend {
|
||||
async fn read(&self, path: &str) -> Result<ByteHolder> {
|
||||
validate_path(path)?;
|
||||
|
||||
// Non-blocking writes only land on disk once the queue drains, so flush first and then treat
|
||||
// disk as authoritative. Draining (rather than folding the queue against an awaited base read)
|
||||
// avoids racing the background worker, which could otherwise double-apply a queued append.
|
||||
self.flush().await;
|
||||
|
||||
let bytes = read_file(&self.directory(), path).await.map_err(js_err)?;
|
||||
Ok(ByteHolder::Owned(bytes))
|
||||
}
|
||||
|
||||
async fn write(&self, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
validate_path(path)?;
|
||||
// Flush first so this awaited write lands after any non-blocking mutation already queued for the
|
||||
// same path, then apply directly so the real disk error still propagates to the caller.
|
||||
self.flush().await;
|
||||
write_file(&self.directory(), path, bytes).await.map_err(js_err)?;
|
||||
self.inner.lock().unwrap().on_disk.insert(path.to_string());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn append(&self, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
validate_path(path)?;
|
||||
self.flush().await;
|
||||
append_file(&self.directory(), path, bytes).await.map_err(js_err)?;
|
||||
self.inner.lock().unwrap().on_disk.insert(path.to_string());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn write_sized(&self, path: &str, size: usize, fill: &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()> {
|
||||
validate_path(path)?;
|
||||
let mut buffer = vec![0; size];
|
||||
fill(&mut buffer)?;
|
||||
self.flush().await;
|
||||
write_file(&self.directory(), path, &buffer).await.map_err(js_err)?;
|
||||
self.inner.lock().unwrap().on_disk.insert(path.to_string());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn list(&self, prefix: &str) -> Result<Vec<String>> {
|
||||
validate_prefix(prefix)?;
|
||||
self.flush().await;
|
||||
list_entries(&self.directory(), prefix, EntryKind::File).await.map_err(|error| list_error(prefix, error))
|
||||
}
|
||||
|
||||
async fn list_dirs(&self, prefix: &str) -> Result<Vec<String>> {
|
||||
validate_prefix(prefix)?;
|
||||
self.flush().await;
|
||||
list_entries(&self.directory(), prefix, EntryKind::Directory).await.map_err(|error| list_error(prefix, error))
|
||||
}
|
||||
|
||||
async fn exists(&self, path: &str) -> bool {
|
||||
if validate_path(path).is_err() {
|
||||
return false;
|
||||
}
|
||||
self.flush().await;
|
||||
file_exists(&self.directory(), path).await
|
||||
}
|
||||
|
||||
async fn remove(&self, path: &str) -> Result<()> {
|
||||
validate_path(path)?;
|
||||
self.flush().await;
|
||||
// Idempotent: a missing entry is not an error, matching the other backends.
|
||||
if let Err(error) = remove_file(&self.directory(), path).await
|
||||
&& !is_not_found(&error)
|
||||
{
|
||||
return Err(js_err(error));
|
||||
}
|
||||
self.inner.lock().unwrap().on_disk.remove(path);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
validate_path(path)?;
|
||||
let mut guard = self.inner.lock().unwrap();
|
||||
guard.on_disk.insert(path.to_string());
|
||||
guard.queue.push_back(Mutation::Write {
|
||||
path: path.to_string(),
|
||||
bytes: bytes.to_vec(),
|
||||
});
|
||||
kick_worker(&self.inner, &mut guard);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn append_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
validate_path(path)?;
|
||||
let mut guard = self.inner.lock().unwrap();
|
||||
guard.on_disk.insert(path.to_string());
|
||||
guard.queue.push_back(Mutation::Append {
|
||||
path: path.to_string(),
|
||||
bytes: bytes.to_vec(),
|
||||
});
|
||||
kick_worker(&self.inner, &mut guard);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove_non_blocking(&self, path: &str) -> Result<()> {
|
||||
validate_path(path)?;
|
||||
let mut guard = self.inner.lock().unwrap();
|
||||
guard.on_disk.remove(path);
|
||||
guard.queue.push_back(Mutation::Delete { path: path.to_string() });
|
||||
kick_worker(&self.inner, &mut guard);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn exists_non_blocking(&self, path: &str) -> bool {
|
||||
validate_path(path).is_ok() && self.inner.lock().unwrap().on_disk.contains(path)
|
||||
}
|
||||
}
|
||||
|
||||
fn kick_worker(inner: &Arc<Mutex<Inner>>, guard: &mut Inner) {
|
||||
if guard.worker_active {
|
||||
return;
|
||||
}
|
||||
guard.worker_active = true;
|
||||
let inner = inner.clone();
|
||||
spawn_local(drain_queue(inner));
|
||||
}
|
||||
|
||||
/// Apply every queued mutation to disk, in FIFO order, until the queue is empty, then mark the worker
|
||||
/// idle. Spawned once via [`kick_worker`] and runs as the sole mutator; the awaited read paths wait on
|
||||
/// a [`Mutation::Barrier`] rather than draining themselves, so there is never more than one drainer.
|
||||
///
|
||||
/// Consecutive appends to the same path are coalesced into one combined append. Each `createWritable`
|
||||
/// on OPFS copies the whole existing file, so appending N frames one at a time is O(N^2) in bytes
|
||||
/// copied (every per-op autosave queues one append per hot op). Concatenating a run into a single
|
||||
/// append collapses that to one file copy, while staying byte-identical to applying them in order.
|
||||
async fn drain_queue(inner: Arc<Mutex<Inner>>) {
|
||||
loop {
|
||||
// Pop the front mutation, coalescing a run of same-path appends behind it into one batch.
|
||||
let (directory, mutation) = {
|
||||
let mut guard = inner.lock().unwrap();
|
||||
let Some(mut mutation) = guard.queue.pop_front() else {
|
||||
guard.worker_active = false;
|
||||
return;
|
||||
};
|
||||
|
||||
if let Mutation::Append { path, bytes } = &mut mutation {
|
||||
while let Some(Mutation::Append { path: next_path, .. }) = guard.queue.front()
|
||||
&& next_path == path
|
||||
{
|
||||
let Some(Mutation::Append { bytes: next_bytes, .. }) = guard.queue.pop_front() else {
|
||||
unreachable!()
|
||||
};
|
||||
bytes.extend_from_slice(&next_bytes);
|
||||
}
|
||||
}
|
||||
|
||||
(guard.directory.clone(), mutation)
|
||||
};
|
||||
|
||||
match mutation {
|
||||
Mutation::Write { path, bytes } => {
|
||||
if let Err(error) = write_file(&directory, &path, &bytes).await {
|
||||
log::error!("OPFS background write for {path} failed: {error:?}");
|
||||
}
|
||||
}
|
||||
Mutation::Append { path, bytes } => {
|
||||
if let Err(error) = append_file(&directory, &path, &bytes).await {
|
||||
log::error!("OPFS background append for {path} failed: {error:?}");
|
||||
}
|
||||
}
|
||||
Mutation::Delete { path } => {
|
||||
// Removal is idempotent, so a missing entry is the expected outcome of a redundant delete, not an error.
|
||||
if let Err(error) = remove_file(&directory, &path).await
|
||||
&& !is_not_found(&error)
|
||||
{
|
||||
log::error!("OPFS background delete for {path} failed: {error:?}");
|
||||
}
|
||||
}
|
||||
// A receive error on the waiter side just means the reader gave up; nothing to apply.
|
||||
Mutation::Barrier(sender) => {
|
||||
let _ = sender.send(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn js_err(error: JsValue) -> ContainerError {
|
||||
ContainerError::Backend(format!("{error:?}"))
|
||||
}
|
||||
|
||||
/// Resolve `directory_path` (a `/`-separated relative path) under the OPFS root, creating each
|
||||
/// segment. OPFS rejects directory names containing `/`, so a multi-segment path like
|
||||
/// `documents/<id>` must be descended one segment at a time rather than passed whole.
|
||||
async fn open_directory(directory_path: &str) -> std::result::Result<FileSystemDirectoryHandle, JsValue> {
|
||||
let storage = web_sys::window().ok_or_else(|| JsValue::from_str("no window"))?.navigator().storage();
|
||||
let mut current: FileSystemDirectoryHandle = JsFuture::from(storage.get_directory()).await?.dyn_into()?;
|
||||
|
||||
for segment in directory_path.split('/').filter(|segment| !segment.is_empty()) {
|
||||
let options = FileSystemGetDirectoryOptions::new();
|
||||
options.set_create(true);
|
||||
current = JsFuture::from(current.get_directory_handle_with_options(segment, &options)).await?.dyn_into()?;
|
||||
}
|
||||
|
||||
Ok(current)
|
||||
}
|
||||
|
||||
/// Descend the `/`-separated path against `root` and return the directory handle plus the final segment.
|
||||
async fn descend<'a>(root: &FileSystemDirectoryHandle, relative: &'a str, create_dirs: bool) -> std::result::Result<(FileSystemDirectoryHandle, &'a str), JsValue> {
|
||||
let mut current = root.clone();
|
||||
let mut segments = relative.split('/').filter(|s| !s.is_empty()).collect::<Vec<_>>();
|
||||
let file = segments.pop().ok_or_else(|| JsValue::from_str("empty path"))?;
|
||||
|
||||
for segment in segments {
|
||||
let options = FileSystemGetDirectoryOptions::new();
|
||||
options.set_create(create_dirs);
|
||||
current = JsFuture::from(current.get_directory_handle_with_options(segment, &options)).await?.dyn_into()?;
|
||||
}
|
||||
Ok((current, file))
|
||||
}
|
||||
|
||||
async fn read_file(root: &FileSystemDirectoryHandle, path: &str) -> std::result::Result<Vec<u8>, JsValue> {
|
||||
let (directory, name) = descend(root, path, false).await?;
|
||||
|
||||
let handle: FileSystemFileHandle = JsFuture::from(directory.get_file_handle(name)).await?.dyn_into()?;
|
||||
let file_value = JsFuture::from(handle.get_file()).await?;
|
||||
let blob: Blob = file_value.dyn_into()?;
|
||||
let buffer = JsFuture::from(blob.array_buffer()).await?;
|
||||
Ok(Uint8Array::new(&buffer).to_vec())
|
||||
}
|
||||
|
||||
async fn write_file(root: &FileSystemDirectoryHandle, path: &str, bytes: &[u8]) -> std::result::Result<(), JsValue> {
|
||||
let (directory, name) = descend(root, path, true).await?;
|
||||
|
||||
let options = FileSystemGetFileOptions::new();
|
||||
options.set_create(true);
|
||||
|
||||
let handle: FileSystemFileHandle = JsFuture::from(directory.get_file_handle_with_options(name, &options)).await?.dyn_into()?;
|
||||
let writable: FileSystemWritableFileStream = JsFuture::from(handle.create_writable()).await?.dyn_into()?;
|
||||
let stream: WritableStream = writable.clone().unchecked_into();
|
||||
|
||||
// Wrap in an async block so any failure, including a synchronous JS throw from `write_with_js_u8_array`,
|
||||
// aborts the stream before returning instead of leaving a dangling locked writable.
|
||||
let write = async {
|
||||
let array = Uint8Array::from(bytes);
|
||||
JsFuture::from(writable.write_with_js_u8_array(&array)?).await?;
|
||||
Ok::<(), JsValue>(())
|
||||
}
|
||||
.await;
|
||||
|
||||
if let Err(error) = write {
|
||||
let _ = JsFuture::from(stream.abort()).await;
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
JsFuture::from(stream.close()).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn append_file(root: &FileSystemDirectoryHandle, path: &str, bytes: &[u8]) -> std::result::Result<(), JsValue> {
|
||||
let (directory, name) = descend(root, path, true).await?;
|
||||
|
||||
let file_options = FileSystemGetFileOptions::new();
|
||||
file_options.set_create(true);
|
||||
let handle: FileSystemFileHandle = JsFuture::from(directory.get_file_handle_with_options(name, &file_options)).await?.dyn_into()?;
|
||||
|
||||
// Determine the current end-of-file so we can seek there before writing.
|
||||
let file_value = JsFuture::from(handle.get_file()).await?;
|
||||
let blob: Blob = file_value.dyn_into()?;
|
||||
let offset = blob.size();
|
||||
|
||||
// `keepExistingData: true` preserves bytes outside the written range; without it OPFS truncates to the written length.
|
||||
let writable_options = FileSystemCreateWritableOptions::new();
|
||||
writable_options.set_keep_existing_data(true);
|
||||
let writable: FileSystemWritableFileStream = JsFuture::from(handle.create_writable_with_options(&writable_options)).await?.dyn_into()?;
|
||||
let stream: WritableStream = writable.clone().unchecked_into();
|
||||
|
||||
// Wrap in an async block so a synchronous JS throw from `seek_with_f64`/`write_with_js_u8_array`
|
||||
// aborts the stream instead of bypassing the abort via `?`.
|
||||
let seek_and_write = async {
|
||||
JsFuture::from(writable.seek_with_f64(offset)?).await?;
|
||||
let array = Uint8Array::from(bytes);
|
||||
JsFuture::from(writable.write_with_js_u8_array(&array)?).await?;
|
||||
Ok::<(), JsValue>(())
|
||||
}
|
||||
.await;
|
||||
|
||||
if let Err(error) = seek_and_write {
|
||||
let _ = JsFuture::from(stream.abort()).await;
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
JsFuture::from(stream.close()).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn remove_file(root: &FileSystemDirectoryHandle, path: &str) -> std::result::Result<(), JsValue> {
|
||||
let (directory, name) = descend(root, path, false).await?;
|
||||
JsFuture::from(directory.remove_entry(name)).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn file_exists(root: &FileSystemDirectoryHandle, path: &str) -> bool {
|
||||
let Ok((directory, name)) = descend(root, path, false).await else {
|
||||
return false;
|
||||
};
|
||||
JsFuture::from(directory.get_file_handle(name)).await.is_ok()
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum EntryKind {
|
||||
File,
|
||||
Directory,
|
||||
}
|
||||
|
||||
async fn list_entries(root: &FileSystemDirectoryHandle, prefix: &str, want: EntryKind) -> std::result::Result<Vec<String>, JsValue> {
|
||||
// `.` and the empty string both name the container root.
|
||||
let prefix = if prefix == "." { "" } else { prefix };
|
||||
|
||||
let directory = if prefix.is_empty() {
|
||||
root.clone()
|
||||
} else {
|
||||
let mut current = root.clone();
|
||||
for segment in prefix.split('/').filter(|s| !s.is_empty()) {
|
||||
let options = FileSystemGetDirectoryOptions::new();
|
||||
options.set_create(false);
|
||||
current = match JsFuture::from(current.get_directory_handle_with_options(segment, &options)).await {
|
||||
Ok(value) => value.dyn_into()?,
|
||||
Err(error) if is_not_found(&error) => return Ok(Vec::new()),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
}
|
||||
current
|
||||
};
|
||||
|
||||
let entries = directory.entries();
|
||||
let iterator: js_sys::AsyncIterator = entries.unchecked_into();
|
||||
let mut results = Vec::new();
|
||||
let prefix_with_slash = with_trailing_slash(prefix);
|
||||
|
||||
let want_kind = match want {
|
||||
EntryKind::File => web_sys::FileSystemHandleKind::File,
|
||||
EntryKind::Directory => web_sys::FileSystemHandleKind::Directory,
|
||||
};
|
||||
|
||||
loop {
|
||||
let next: js_sys::IteratorNext = JsFuture::from(iterator.next()?).await?.unchecked_into();
|
||||
if next.done() {
|
||||
break;
|
||||
}
|
||||
let pair: js_sys::Array = next.value().unchecked_into();
|
||||
let Some(name) = pair.get(0).as_string() else { continue };
|
||||
let handle: web_sys::FileSystemHandle = pair.get(1).unchecked_into();
|
||||
if handle.kind() != want_kind {
|
||||
continue;
|
||||
}
|
||||
results.push(format!("{prefix_with_slash}{name}"));
|
||||
}
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
/// Walk every file under `prefix` (recursively) and collect their full container paths.
|
||||
/// Used at open time to populate the in-memory tracking set.
|
||||
async fn enumerate_paths(root: &FileSystemDirectoryHandle, prefix: &str) -> std::result::Result<HashSet<String>, JsValue> {
|
||||
let mut paths = HashSet::new();
|
||||
let mut to_visit = vec![prefix.to_string()];
|
||||
|
||||
while let Some(current_prefix) = to_visit.pop() {
|
||||
for file in list_entries(root, ¤t_prefix, EntryKind::File).await? {
|
||||
paths.insert(file);
|
||||
}
|
||||
for dir in list_entries(root, ¤t_prefix, EntryKind::Directory).await? {
|
||||
to_visit.push(dir);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(paths)
|
||||
}
|
||||
|
||||
fn is_not_found(error: &JsValue) -> bool {
|
||||
error.dyn_ref::<DomException>().is_some_and(|error| error.name() == "NotFoundError")
|
||||
}
|
||||
|
||||
/// OPFS raises `TypeMismatchError` when a path segment used as a directory is actually a file.
|
||||
fn is_type_mismatch(error: &JsValue) -> bool {
|
||||
error.dyn_ref::<DomException>().is_some_and(|error| error.name() == "TypeMismatchError")
|
||||
}
|
||||
|
||||
/// Map a listing error: a prefix that names a file becomes [`ContainerError::NotADirectory`], anything
|
||||
/// else passes through as a backend error.
|
||||
fn list_error(prefix: &str, error: JsValue) -> ContainerError {
|
||||
if is_type_mismatch(&error) {
|
||||
ContainerError::NotADirectory(prefix.to_string())
|
||||
} else {
|
||||
js_err(error)
|
||||
}
|
||||
}
|
||||
@@ -1,500 +0,0 @@
|
||||
//! Container abstraction for the on-disk side of the `.gdd` document format.
|
||||
//!
|
||||
//! A [`Container`] is a virtual filesystem of named byte payloads.
|
||||
//! Backends include a loose folder, an in-memory map, and an OPFS-backed wasm store.
|
||||
//! Archive codecs ([`archive::Zip`], [`archive::Xz`]) round-trip a container's contents
|
||||
//! through a compressed byte stream.
|
||||
//!
|
||||
//! Reads return a [`ByteHolder`], an ownership-carrying handle whose variant depends on
|
||||
//! how the backend produced the bytes (mmap region, owned vector, external file mmap).
|
||||
//! [`AsyncContainer`] mirrors [`Container`] for inherently async backends; every sync
|
||||
//! [`Container`] is reachable from async code via a blanket impl.
|
||||
|
||||
pub mod archive;
|
||||
pub mod backends;
|
||||
|
||||
pub enum ByteHolder {
|
||||
/// Bytes synthesized in memory (decompressed from an archive, produced by serialization).
|
||||
/// The only variant available on `target_family = "wasm"`.
|
||||
Owned(Vec<u8>),
|
||||
/// Bytes mmap'd from a file inside the container.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
Mmapped(MmappedBytes),
|
||||
/// Bytes mmap'd from a file outside the container (e.g. a linked resource).
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
External { path: std::path::PathBuf, bytes: MmappedBytes },
|
||||
}
|
||||
|
||||
impl ByteHolder {
|
||||
pub fn as_slice(&self) -> &[u8] {
|
||||
match self {
|
||||
ByteHolder::Owned(bytes) => bytes,
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
ByteHolder::Mmapped(bytes) => bytes.as_ref(),
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
ByteHolder::External { bytes, .. } => bytes.as_ref(),
|
||||
}
|
||||
}
|
||||
|
||||
/// If the bytes are backed by a real filesystem path, return it. Enables consumers to
|
||||
/// short-circuit byte copies with `fs::copy` (CoW on supported filesystems).
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub fn source_path(&self) -> Option<&std::path::Path> {
|
||||
match self {
|
||||
ByteHolder::Owned(_) => None,
|
||||
ByteHolder::Mmapped(bytes) => Some(bytes.path()),
|
||||
ByteHolder::External { path, .. } => Some(path),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub fn source_path(&self) -> Option<&std::path::Path> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Open an external file and produce a [`ByteHolder::External`] backed by mmap.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub fn open_external(path: impl Into<std::path::PathBuf>) -> Result<Self> {
|
||||
let path = path.into();
|
||||
let file = mmap_io::mmap::MemoryMappedFile::open_ro(&path).map_err(|error| ContainerError::Backend(format!("mmap of {path:?} failed: {error}")))?;
|
||||
let bytes = MmappedBytes::new(file)?;
|
||||
Ok(ByteHolder::External { path, bytes })
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<[u8]> for ByteHolder {
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
self.as_slice()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ByteHolder {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
ByteHolder::Owned(bytes) => f.debug_tuple("Owned").field(&format_args!("{} bytes", bytes.len())).finish(),
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
ByteHolder::Mmapped(bytes) => f.debug_tuple("Mmapped").field(&format_args!("{} bytes", bytes.as_ref().len())).finish(),
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
ByteHolder::External { path, bytes } => f.debug_struct("External").field("path", path).field("len", &bytes.as_ref().len()).finish(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Owning wrapper around a memory-mapped file that exposes the mapped region as `&[u8]`.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub struct MmappedBytes(mmap_io::mmap::MemoryMappedFile);
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl MmappedBytes {
|
||||
/// Wrap a mapped file, probing that its region is sliceable so the failure surfaces here rather than
|
||||
/// later degrading to the `&[]` fallback in [`AsRef::as_ref`], which cannot return an error.
|
||||
pub fn new(file: mmap_io::mmap::MemoryMappedFile) -> Result<Self> {
|
||||
let len = file.len();
|
||||
file.as_slice(0, len)
|
||||
.map_err(|error| ContainerError::Backend(format!("mmap slice of {:?} failed: {error}", file.path())))?;
|
||||
Ok(Self(file))
|
||||
}
|
||||
|
||||
pub fn path(&self) -> &std::path::Path {
|
||||
self.0.path()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl AsRef<[u8]> for MmappedBytes {
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
let len = self.0.len();
|
||||
match self.0.as_slice(0, len) {
|
||||
Ok(slice) => slice,
|
||||
Err(error) => {
|
||||
log::error!("Failed to obtain mmap slice: {error}");
|
||||
&[]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ContainerError {
|
||||
#[error("path not found: {0}")]
|
||||
NotFound(String),
|
||||
|
||||
#[error("invalid path: {0}")]
|
||||
InvalidPath(String),
|
||||
|
||||
#[error("not a directory: {0}")]
|
||||
NotADirectory(String),
|
||||
|
||||
#[error("I/O error: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
|
||||
/// An archive declared more decompressed data (`declared` bytes) than the codec is willing to
|
||||
/// materialize (`limit` bytes).
|
||||
#[error("declared decompressed size {declared} exceeds the {limit}-byte limit")]
|
||||
SizeLimitExceeded { declared: u64, limit: u64 },
|
||||
|
||||
/// Failure inside an archive codec (zip, lzma, tar). Wraps a foreign error as text since those
|
||||
/// error types don't share a common Rust trait we can chain through.
|
||||
#[error("codec error: {0}")]
|
||||
Codec(String),
|
||||
|
||||
/// Failure inside a storage backend (mmap, OPFS/JS). Wraps a foreign error as text for the same reason.
|
||||
#[error("backend error: {0}")]
|
||||
Backend(String),
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, ContainerError>;
|
||||
|
||||
/// Normalize a listing prefix to end with a trailing slash (unless it names the container root).
|
||||
/// The root (empty string or `.`) normalizes to the empty string, so backends concatenate child paths
|
||||
/// as `prefix/child` without a double, missing, or `./`-rooted slash.
|
||||
pub(crate) fn with_trailing_slash(prefix: &str) -> String {
|
||||
if prefix.is_empty() || prefix == "." {
|
||||
String::new()
|
||||
} else if prefix.ends_with('/') {
|
||||
prefix.to_string()
|
||||
} else {
|
||||
format!("{prefix}/")
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate that `path` names a container-safe file: relative, no `.`/`..` segments, no backslashes,
|
||||
/// no redundant separators (`a//b`, `a/b/`). Dotfile names like `.gitignore` are fine. Requiring a canonical
|
||||
/// form gives a file one identity across backends, some of which key on the raw string rather than path
|
||||
/// components. Used by backends to block container escapes and by archive codecs on untrusted entry names.
|
||||
/// For listing prefixes, which may name the container root, use [`validate_prefix`] instead.
|
||||
pub fn validate_path(path: &str) -> Result<()> {
|
||||
let invalid = || ContainerError::InvalidPath(path.to_string());
|
||||
|
||||
if path.is_empty() || path.contains('\\') || path.starts_with('/') {
|
||||
return Err(invalid());
|
||||
}
|
||||
|
||||
// `Path::components` silently folds away `//`, trailing `/`, and interior `.` segments, but backends key
|
||||
// on the raw string, so a non-canonical path would resolve to one file on a path-joining backend yet a
|
||||
// different identity on a string-keyed backend. Reject the redundant segments the component loop below
|
||||
// can't see (it never observes a folded-away `CurDir`/empty segment).
|
||||
if path.split('/').any(|segment| segment.is_empty() || segment == ".") {
|
||||
return Err(invalid());
|
||||
}
|
||||
|
||||
// Reject Windows drive-letter prefixes (`C:foo`, `C:/foo`) that platform-agnostic Path doesn't recognize as absolute on Linux.
|
||||
let bytes = path.as_bytes();
|
||||
if bytes.len() >= 2 && bytes[1] == b':' && bytes[0].is_ascii_alphabetic() {
|
||||
return Err(invalid());
|
||||
}
|
||||
|
||||
for component in std::path::Path::new(path).components() {
|
||||
use std::path::Component;
|
||||
match component {
|
||||
Component::Normal(_) => {}
|
||||
Component::CurDir | Component::ParentDir | Component::Prefix(_) | Component::RootDir => return Err(invalid()),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate a listing prefix. Same rules as [`validate_path`], except the container root is also a valid
|
||||
/// prefix, named by either the empty string or `.`. Backends pass this to `list`/`list_dirs`.
|
||||
pub fn validate_prefix(prefix: &str) -> Result<()> {
|
||||
if prefix.is_empty() || prefix == "." {
|
||||
return Ok(());
|
||||
}
|
||||
validate_path(prefix)
|
||||
}
|
||||
|
||||
/// Synchronous virtual filesystem of named byte payloads.
|
||||
pub trait Container {
|
||||
/// Read the contents of `path` into a [`ByteHolder`].
|
||||
fn read(&self, path: &str) -> Result<ByteHolder>;
|
||||
|
||||
/// Write `bytes` at `path`, creating intermediate directories as needed.
|
||||
fn write(&self, path: &str, bytes: &[u8]) -> Result<()>;
|
||||
|
||||
/// Append `bytes` to the file at `path`, creating it (and any intermediate directories)
|
||||
/// if it does not yet exist. Equivalent to `write` on a fresh path.
|
||||
fn append(&self, path: &str, bytes: &[u8]) -> Result<()>;
|
||||
|
||||
/// Write `size` bytes whose contents are produced by `fill`.
|
||||
/// The default implementation allocates and forwards to [`Container::write`];
|
||||
/// backends that can mmap a writable region may override to fill in place.
|
||||
fn write_sized(&self, path: &str, size: usize, fill: &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()> {
|
||||
let mut buffer = vec![0; size];
|
||||
fill(&mut buffer)?;
|
||||
self.write(path, &buffer)
|
||||
}
|
||||
|
||||
/// List file entries directly under `prefix` (non-recursive).
|
||||
/// Returned paths include the `prefix` (e.g. `list("resources")` returns
|
||||
/// `["resources/abc123", ...]`). A missing prefix yields an empty list; a prefix that names a
|
||||
/// file (not a directory) is an error.
|
||||
fn list(&self, prefix: &str) -> Result<Vec<String>>;
|
||||
|
||||
/// List subdirectory entries directly under `prefix` (non-recursive).
|
||||
/// Returned names include the `prefix`, without a trailing slash
|
||||
/// (e.g. `list_dirs("")` returns `["resources"]`). Same missing/file-prefix semantics as [`Container::list`].
|
||||
fn list_dirs(&self, prefix: &str) -> Result<Vec<String>>;
|
||||
|
||||
/// Whether a file exists at `path`. Directories return `false`.
|
||||
fn exists(&self, path: &str) -> bool;
|
||||
|
||||
/// Remove the file at `path`. Idempotent: removing a missing path succeeds. Directories are never
|
||||
/// removed (they exist only implicitly as parents of files).
|
||||
fn remove(&self, path: &str) -> Result<()>;
|
||||
}
|
||||
|
||||
/// Asynchronous virtual filesystem of named byte payloads. Mirrors [`Container`].
|
||||
///
|
||||
/// The returned futures are intentionally not `Send`: native uses `block_on` at the save seam
|
||||
/// and wasm is single-threaded, so neither needs cross-thread futures. Revisit if we ever want
|
||||
/// to run container I/O on a thread pool.
|
||||
#[expect(async_fn_in_trait, reason = "see trait docs — Send is not required")]
|
||||
pub trait AsyncContainer {
|
||||
async fn read(&self, path: &str) -> Result<ByteHolder>;
|
||||
|
||||
async fn write(&self, path: &str, bytes: &[u8]) -> Result<()>;
|
||||
|
||||
async fn append(&self, path: &str, bytes: &[u8]) -> Result<()>;
|
||||
|
||||
async fn write_sized(&self, path: &str, size: usize, fill: &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()>;
|
||||
|
||||
async fn list(&self, prefix: &str) -> Result<Vec<String>>;
|
||||
|
||||
async fn list_dirs(&self, prefix: &str) -> Result<Vec<String>>;
|
||||
|
||||
async fn exists(&self, path: &str) -> bool;
|
||||
|
||||
async fn remove(&self, path: &str) -> Result<()>;
|
||||
|
||||
/// Synchronous write. On backends with sync I/O (folder, memory) the write completes durably
|
||||
/// before return and reports real errors. On OPFS the write is enqueued onto a background task
|
||||
/// and `Ok` is returned eagerly; a later failure is logged.
|
||||
fn write_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()>;
|
||||
|
||||
/// Synchronous append. Same eager-enqueue semantics on OPFS as [`write_non_blocking`](Self::write_non_blocking);
|
||||
/// queued appends preserve order relative to earlier queued writes/appends.
|
||||
fn append_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()>;
|
||||
|
||||
/// Synchronous remove. Same semantics as [`write_non_blocking`](Self::write_non_blocking).
|
||||
fn remove_non_blocking(&self, path: &str) -> Result<()>;
|
||||
|
||||
/// Non-blocking existence check. On OPFS this reads from an in-memory tracking set populated by
|
||||
/// the sync write/remove paths, since the underlying OPFS existence API is async only.
|
||||
fn exists_non_blocking(&self, path: &str) -> bool;
|
||||
}
|
||||
|
||||
impl<C: Container + ?Sized> AsyncContainer for C {
|
||||
async fn read(&self, path: &str) -> Result<ByteHolder> {
|
||||
Container::read(self, path)
|
||||
}
|
||||
|
||||
async fn write(&self, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
Container::write(self, path, bytes)
|
||||
}
|
||||
|
||||
async fn append(&self, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
Container::append(self, path, bytes)
|
||||
}
|
||||
|
||||
async fn write_sized(&self, path: &str, size: usize, fill: &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()> {
|
||||
Container::write_sized(self, path, size, fill)
|
||||
}
|
||||
|
||||
async fn list(&self, prefix: &str) -> Result<Vec<String>> {
|
||||
Container::list(self, prefix)
|
||||
}
|
||||
|
||||
async fn list_dirs(&self, prefix: &str) -> Result<Vec<String>> {
|
||||
Container::list_dirs(self, prefix)
|
||||
}
|
||||
|
||||
async fn exists(&self, path: &str) -> bool {
|
||||
Container::exists(self, path)
|
||||
}
|
||||
|
||||
async fn remove(&self, path: &str) -> Result<()> {
|
||||
Container::remove(self, path)
|
||||
}
|
||||
|
||||
fn write_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
Container::write(self, path, bytes)
|
||||
}
|
||||
|
||||
fn append_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
Container::append(self, path, bytes)
|
||||
}
|
||||
|
||||
fn remove_non_blocking(&self, path: &str) -> Result<()> {
|
||||
Container::remove(self, path)
|
||||
}
|
||||
|
||||
fn exists_non_blocking(&self, path: &str) -> bool {
|
||||
Container::exists(self, path)
|
||||
}
|
||||
}
|
||||
|
||||
/// Type-erased container that dispatches to one of the in-tree backends.
|
||||
///
|
||||
/// `AsyncContainer::read` returns `impl Future`, so `dyn AsyncContainer` is not object-safe.
|
||||
/// `AnyContainer` is the workaround: `Gdd` holds one of these by value, and the `AsyncContainer`
|
||||
/// impl forwards to the active variant.
|
||||
pub enum AnyContainer {
|
||||
Memory(backends::memory::MemoryBackend),
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
Folder(backends::folder::FolderBackend),
|
||||
#[cfg(target_family = "wasm")]
|
||||
Opfs(backends::opfs::OpfsBackend),
|
||||
}
|
||||
|
||||
impl AsyncContainer for AnyContainer {
|
||||
async fn read(&self, path: &str) -> Result<ByteHolder> {
|
||||
match self {
|
||||
Self::Memory(backend) => AsyncContainer::read(backend, path).await,
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
Self::Folder(backend) => AsyncContainer::read(backend, path).await,
|
||||
#[cfg(target_family = "wasm")]
|
||||
Self::Opfs(backend) => AsyncContainer::read(backend, path).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn write(&self, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
match self {
|
||||
Self::Memory(backend) => AsyncContainer::write(backend, path, bytes).await,
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
Self::Folder(backend) => AsyncContainer::write(backend, path, bytes).await,
|
||||
#[cfg(target_family = "wasm")]
|
||||
Self::Opfs(backend) => AsyncContainer::write(backend, path, bytes).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn append(&self, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
match self {
|
||||
Self::Memory(backend) => AsyncContainer::append(backend, path, bytes).await,
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
Self::Folder(backend) => AsyncContainer::append(backend, path, bytes).await,
|
||||
#[cfg(target_family = "wasm")]
|
||||
Self::Opfs(backend) => AsyncContainer::append(backend, path, bytes).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn write_sized(&self, path: &str, size: usize, fill: &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()> {
|
||||
match self {
|
||||
Self::Memory(backend) => AsyncContainer::write_sized(backend, path, size, fill).await,
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
Self::Folder(backend) => AsyncContainer::write_sized(backend, path, size, fill).await,
|
||||
#[cfg(target_family = "wasm")]
|
||||
Self::Opfs(backend) => AsyncContainer::write_sized(backend, path, size, fill).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn list(&self, prefix: &str) -> Result<Vec<String>> {
|
||||
match self {
|
||||
Self::Memory(backend) => AsyncContainer::list(backend, prefix).await,
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
Self::Folder(backend) => AsyncContainer::list(backend, prefix).await,
|
||||
#[cfg(target_family = "wasm")]
|
||||
Self::Opfs(backend) => AsyncContainer::list(backend, prefix).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn list_dirs(&self, prefix: &str) -> Result<Vec<String>> {
|
||||
match self {
|
||||
Self::Memory(backend) => AsyncContainer::list_dirs(backend, prefix).await,
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
Self::Folder(backend) => AsyncContainer::list_dirs(backend, prefix).await,
|
||||
#[cfg(target_family = "wasm")]
|
||||
Self::Opfs(backend) => AsyncContainer::list_dirs(backend, prefix).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn exists(&self, path: &str) -> bool {
|
||||
match self {
|
||||
Self::Memory(backend) => AsyncContainer::exists(backend, path).await,
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
Self::Folder(backend) => AsyncContainer::exists(backend, path).await,
|
||||
#[cfg(target_family = "wasm")]
|
||||
Self::Opfs(backend) => AsyncContainer::exists(backend, path).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn remove(&self, path: &str) -> Result<()> {
|
||||
match self {
|
||||
Self::Memory(backend) => AsyncContainer::remove(backend, path).await,
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
Self::Folder(backend) => AsyncContainer::remove(backend, path).await,
|
||||
#[cfg(target_family = "wasm")]
|
||||
Self::Opfs(backend) => AsyncContainer::remove(backend, path).await,
|
||||
}
|
||||
}
|
||||
|
||||
fn write_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
match self {
|
||||
Self::Memory(backend) => AsyncContainer::write_non_blocking(backend, path, bytes),
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
Self::Folder(backend) => AsyncContainer::write_non_blocking(backend, path, bytes),
|
||||
#[cfg(target_family = "wasm")]
|
||||
Self::Opfs(backend) => AsyncContainer::write_non_blocking(backend, path, bytes),
|
||||
}
|
||||
}
|
||||
|
||||
fn append_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
match self {
|
||||
Self::Memory(backend) => AsyncContainer::append_non_blocking(backend, path, bytes),
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
Self::Folder(backend) => AsyncContainer::append_non_blocking(backend, path, bytes),
|
||||
#[cfg(target_family = "wasm")]
|
||||
Self::Opfs(backend) => AsyncContainer::append_non_blocking(backend, path, bytes),
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_non_blocking(&self, path: &str) -> Result<()> {
|
||||
match self {
|
||||
Self::Memory(backend) => AsyncContainer::remove_non_blocking(backend, path),
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
Self::Folder(backend) => AsyncContainer::remove_non_blocking(backend, path),
|
||||
#[cfg(target_family = "wasm")]
|
||||
Self::Opfs(backend) => AsyncContainer::remove_non_blocking(backend, path),
|
||||
}
|
||||
}
|
||||
|
||||
fn exists_non_blocking(&self, path: &str) -> bool {
|
||||
match self {
|
||||
Self::Memory(backend) => AsyncContainer::exists_non_blocking(backend, path),
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
Self::Folder(backend) => AsyncContainer::exists_non_blocking(backend, path),
|
||||
#[cfg(target_family = "wasm")]
|
||||
Self::Opfs(backend) => AsyncContainer::exists_non_blocking(backend, path),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{ContainerError, validate_path, validate_prefix};
|
||||
|
||||
#[test]
|
||||
fn validate_path_accepts_well_formed() {
|
||||
// `..` and `.` are only rejected as whole path components; as substrings of a name they are fine.
|
||||
for ok in ["manifest.json", "resources/abc", "a/b/c.bin", "my..file.txt", "..hidden", ".gitignore"] {
|
||||
assert!(validate_path(ok).is_ok(), "{ok:?} should be accepted");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_path_rejects_unsafe() {
|
||||
for bad in ["", "../escape", "a/../b", ".", "./leading", "/abs", "back\\slash", "C:/win", "\\\\?\\unc"] {
|
||||
let result = validate_path(bad);
|
||||
assert!(matches!(result, Err(ContainerError::InvalidPath(_))), "{bad:?} should be rejected, got {result:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_prefix_accepts_root_tokens() {
|
||||
// The container root is a valid listing prefix, named by either the empty string or `.`.
|
||||
for root in ["", ".", "resources", "a/b"] {
|
||||
assert!(validate_prefix(root).is_ok(), "{root:?} should be accepted as a prefix");
|
||||
}
|
||||
// Unsafe prefixes are still rejected, same as paths.
|
||||
assert!(validate_prefix("../escape").is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
#![cfg(any(feature = "zip", feature = "xz"))]
|
||||
|
||||
use document_container::Container;
|
||||
use document_container::archive::{Archive, ArchiveWriter};
|
||||
use document_container::backends::folder::FolderBackend;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
|
||||
fn entries() -> Vec<(&'static str, &'static [u8])> {
|
||||
vec![
|
||||
("manifest.json", br#"{"format":"gdd"}"#),
|
||||
("document.json", b"{\"registry\":\"...\"}"),
|
||||
("history.jsonl", b"{\"rev\":1}\n{\"rev\":2}\n"),
|
||||
("resources/abc123", &[0xDE, 0xAD, 0xBE, 0xEF]),
|
||||
("resources/xyz789", b"another resource"),
|
||||
]
|
||||
}
|
||||
|
||||
fn assert_round_trip(restored: &MemoryBackend) {
|
||||
assert_eq!(restored.read("manifest.json").unwrap().as_slice(), br#"{"format":"gdd"}"#);
|
||||
assert_eq!(restored.read("document.json").unwrap().as_slice(), b"{\"registry\":\"...\"}");
|
||||
assert_eq!(restored.read("history.jsonl").unwrap().as_slice(), b"{\"rev\":1}\n{\"rev\":2}\n");
|
||||
assert_eq!(restored.read("resources/abc123").unwrap().as_slice(), &[0xDE, 0xAD, 0xBE, 0xEF]);
|
||||
assert_eq!(restored.read("resources/xyz789").unwrap().as_slice(), b"another resource");
|
||||
}
|
||||
|
||||
#[cfg(feature = "zip")]
|
||||
#[test]
|
||||
fn zip_round_trip() {
|
||||
use document_container::archive::Zip;
|
||||
use std::io::Cursor;
|
||||
|
||||
let mut buffer = Cursor::new(Vec::new());
|
||||
let mut writer = Zip::writer(&mut buffer).unwrap();
|
||||
for (path, bytes) in entries() {
|
||||
writer.write_entry(path, bytes).unwrap();
|
||||
}
|
||||
writer.finish().unwrap();
|
||||
|
||||
let mut restored = MemoryBackend::new();
|
||||
<Zip as Archive>::open(Cursor::new(buffer.get_ref()), &mut restored).unwrap();
|
||||
assert_round_trip(&restored);
|
||||
}
|
||||
|
||||
#[cfg(feature = "zip")]
|
||||
#[test]
|
||||
fn zip_deserialize_streams_into_folder_backend() {
|
||||
use document_container::archive::Zip;
|
||||
use std::io::Cursor;
|
||||
|
||||
let mut buffer = Cursor::new(Vec::new());
|
||||
let mut writer = Zip::writer(&mut buffer).unwrap();
|
||||
for (path, bytes) in entries() {
|
||||
writer.write_entry(path, bytes).unwrap();
|
||||
}
|
||||
writer.finish().unwrap();
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut restored = FolderBackend::create(dir.path()).unwrap();
|
||||
<Zip as Archive>::open(Cursor::new(buffer.get_ref()), &mut restored).unwrap();
|
||||
|
||||
assert_eq!(restored.read("manifest.json").unwrap().as_slice(), br#"{"format":"gdd"}"#);
|
||||
assert_eq!(restored.read("resources/abc123").unwrap().as_slice(), &[0xDE, 0xAD, 0xBE, 0xEF]);
|
||||
}
|
||||
|
||||
#[cfg(feature = "xz")]
|
||||
#[test]
|
||||
fn xz_round_trip() {
|
||||
use document_container::archive::Xz;
|
||||
use std::io::Cursor;
|
||||
|
||||
let mut buffer = Cursor::new(Vec::new());
|
||||
let mut writer = Xz::writer(&mut buffer).unwrap();
|
||||
for (path, bytes) in entries() {
|
||||
writer.write_entry(path, bytes).unwrap();
|
||||
}
|
||||
writer.finish().unwrap();
|
||||
|
||||
let mut restored = MemoryBackend::new();
|
||||
<Xz as Archive>::open(Cursor::new(buffer.get_ref()), &mut restored).unwrap();
|
||||
assert_round_trip(&restored);
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
use document_container::backends::folder::FolderBackend;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_container::{AnyContainer, Container, ContainerError};
|
||||
|
||||
fn run_round_trip<C: Container>(container: C) {
|
||||
container.write("manifest.json", br#"{"format":"gdd"}"#).unwrap();
|
||||
container.write("resources/abc123", &[0xDE, 0xAD, 0xBE, 0xEF]).unwrap();
|
||||
container.write("resources/xyz789", b"another resource").unwrap();
|
||||
|
||||
assert!(container.exists("manifest.json"));
|
||||
assert!(container.exists("resources/abc123"));
|
||||
assert!(!container.exists("does-not-exist"));
|
||||
|
||||
let manifest = container.read("manifest.json").unwrap();
|
||||
assert_eq!(manifest.as_slice(), br#"{"format":"gdd"}"#);
|
||||
|
||||
let blob = container.read("resources/abc123").unwrap();
|
||||
assert_eq!(blob.as_slice(), &[0xDE, 0xAD, 0xBE, 0xEF]);
|
||||
|
||||
let top_level = container.list("").unwrap();
|
||||
assert!(top_level.iter().any(|p| p == "manifest.json"));
|
||||
assert!(
|
||||
top_level.iter().all(|p| !p.starts_with("resources/")),
|
||||
"list(\"\") must not descend into subdirectories, got {top_level:?}"
|
||||
);
|
||||
|
||||
let mut resources = container.list("resources").unwrap();
|
||||
resources.sort();
|
||||
assert_eq!(resources, vec!["resources/abc123".to_string(), "resources/xyz789".to_string()]);
|
||||
|
||||
container.remove("resources/abc123").unwrap();
|
||||
assert!(!container.exists("resources/abc123"));
|
||||
assert!(matches!(container.read("resources/abc123"), Err(ContainerError::NotFound(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_backend_round_trip() {
|
||||
run_round_trip(MemoryBackend::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folder_backend_round_trip() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let backend = FolderBackend::create(dir.path()).unwrap();
|
||||
run_round_trip(backend);
|
||||
}
|
||||
|
||||
fn run_list_and_remove_semantics<C: Container>(container: C) {
|
||||
container.write("dir/file", b"x").unwrap();
|
||||
|
||||
// Removing a missing path is idempotent.
|
||||
container.remove("dir/missing").unwrap();
|
||||
container.remove("dir/file").unwrap();
|
||||
container.remove("dir/file").unwrap();
|
||||
|
||||
// Listing a missing prefix yields an empty list.
|
||||
assert_eq!(container.list("nonexistent").unwrap(), Vec::<String>::new());
|
||||
|
||||
// Listing a prefix that names a file is an error.
|
||||
container.write("manifest.json", b"{}").unwrap();
|
||||
assert!(matches!(container.list("manifest.json"), Err(ContainerError::NotADirectory(_))));
|
||||
assert!(matches!(container.list_dirs("manifest.json"), Err(ContainerError::NotADirectory(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_backend_list_and_remove_semantics() {
|
||||
run_list_and_remove_semantics(MemoryBackend::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folder_backend_list_and_remove_semantics() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
run_list_and_remove_semantics(FolderBackend::create(dir.path()).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn folder_backend_rejects_symlink_escape() {
|
||||
let outside = tempfile::tempdir().unwrap();
|
||||
std::fs::write(outside.path().join("secret"), b"sensitive").unwrap();
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let backend = FolderBackend::create(dir.path()).unwrap();
|
||||
// A symlink planted inside the root pointing outside it must not be traversable.
|
||||
std::os::unix::fs::symlink(outside.path(), dir.path().join("link")).unwrap();
|
||||
|
||||
let result = backend.read("link/secret");
|
||||
assert!(matches!(result, Err(ContainerError::InvalidPath(_))), "symlink escape should be rejected, got {result:?}");
|
||||
|
||||
// Listing must reject the symlinked prefix too, not just reads, so it can't leak entry names from outside the root.
|
||||
assert!(matches!(backend.list("link"), Err(ContainerError::InvalidPath(_))), "list through symlink should be rejected");
|
||||
assert!(matches!(backend.list_dirs("link"), Err(ContainerError::InvalidPath(_))), "list_dirs through symlink should be rejected");
|
||||
|
||||
// A symlink entry directly under root must not appear in listings, since `resolve` would reject reading it.
|
||||
std::os::unix::fs::symlink(outside.path().join("secret"), dir.path().join("file_link")).unwrap();
|
||||
std::fs::write(dir.path().join("real"), b"ok").unwrap();
|
||||
assert_eq!(backend.list("").unwrap(), vec!["real".to_string()], "symlink entries should be omitted from file listings");
|
||||
assert!(backend.list_dirs("").unwrap().is_empty(), "symlink-to-dir entries should be omitted from dir listings");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folder_backend_rejects_path_traversal() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let backend = FolderBackend::create(dir.path()).unwrap();
|
||||
for bad in ["../escape", "subdir/../escape", "/abs", "back\\slash", "a//b", "trailing/", "a/./b"] {
|
||||
let result = backend.write(bad, b"nope");
|
||||
assert!(matches!(result, Err(ContainerError::InvalidPath(_))), "expected InvalidPath for {bad:?}, got {result:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn run_append<C: Container>(container: C) {
|
||||
// Appending to a non-existent path creates it — same semantics as `OpenOptions::append().create(true)`.
|
||||
container.append("history.jsonl", b"{\"op\":1}\n").unwrap();
|
||||
container.append("history.jsonl", b"{\"op\":2}\n").unwrap();
|
||||
container.append("history.jsonl", b"{\"op\":3}\n").unwrap();
|
||||
|
||||
let log = container.read("history.jsonl").unwrap();
|
||||
assert_eq!(log.as_slice(), b"{\"op\":1}\n{\"op\":2}\n{\"op\":3}\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_backend_append() {
|
||||
run_append(MemoryBackend::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folder_backend_append() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let backend = FolderBackend::create(dir.path()).unwrap();
|
||||
run_append(backend);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn any_container_dispatches_to_active_variant() {
|
||||
use document_container::AsyncContainer;
|
||||
|
||||
let container = AnyContainer::Memory(MemoryBackend::new());
|
||||
|
||||
futures::executor::block_on(async {
|
||||
container.write("manifest.json", br#"{"format":"gdd"}"#).await.unwrap();
|
||||
container.append("history.jsonl", b"frame-1\n").await.unwrap();
|
||||
container.append("history.jsonl", b"frame-2\n").await.unwrap();
|
||||
|
||||
assert!(container.exists("manifest.json").await);
|
||||
let manifest = container.read("manifest.json").await.unwrap();
|
||||
assert_eq!(manifest.as_slice(), br#"{"format":"gdd"}"#);
|
||||
|
||||
let history = container.read("history.jsonl").await.unwrap();
|
||||
assert_eq!(history.as_slice(), b"frame-1\nframe-2\n");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folder_backend_reads_empty_file() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let backend = FolderBackend::create(dir.path()).unwrap();
|
||||
|
||||
backend.write("empty.bin", &[]).unwrap();
|
||||
let read_back = backend.read("empty.bin").unwrap();
|
||||
assert_eq!(read_back.as_slice(), &[] as &[u8]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folder_backend_write_sized_fills_via_mmap() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let backend = FolderBackend::create(dir.path()).unwrap();
|
||||
|
||||
let payload = b"hello world";
|
||||
backend
|
||||
.write_sized("resources/sized", payload.len(), &mut |buffer| {
|
||||
buffer.copy_from_slice(payload);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let read_back = backend.read("resources/sized").unwrap();
|
||||
assert_eq!(read_back.as_slice(), payload);
|
||||
}
|
||||
+1
-11
@@ -19,7 +19,6 @@ gpu = ["interpreted-executor/gpu", "dep:wgpu-executor"]
|
||||
# Local dependencies
|
||||
graphite-proc-macros = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
interpreted-executor = { workspace = true }
|
||||
graphene-std = { workspace = true } # NOTE: `core-types` should not be added here because `graphene-std` re-exports its contents
|
||||
preprocessor = { workspace = true }
|
||||
@@ -46,10 +45,6 @@ vello = { workspace = true }
|
||||
base64 = { workspace = true }
|
||||
spin = { workspace = true }
|
||||
image = { workspace = true }
|
||||
color = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
reqwest = { workspace = true }
|
||||
url = { workspace = true }
|
||||
|
||||
# Optional local dependencies
|
||||
wgpu-executor = { workspace = true, optional = true }
|
||||
@@ -57,13 +52,8 @@ wgpu-executor = { workspace = true, optional = true }
|
||||
# Optional workspace dependencies
|
||||
wasm-bindgen = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(not(target_family = "wasm"))'.dependencies]
|
||||
tokio = { workspace = true }
|
||||
|
||||
[target.'cfg(target_family = "wasm")'.dependencies]
|
||||
wasm-bindgen-futures = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# Workspace dependencies
|
||||
env_logger = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
@@ -1,25 +1,18 @@
|
||||
use crate::dispatcher::Dispatcher;
|
||||
use crate::messages::prelude::*;
|
||||
use graph_craft::application_io::PlatformApplicationIo;
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
pub use graphene_std::uuid::*;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
pub struct Editor {
|
||||
pub dispatcher: Dispatcher,
|
||||
}
|
||||
|
||||
impl Editor {
|
||||
pub fn new(environment: Environment, uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, mut application_io: PlatformApplicationIo, wake: Wake) -> Self {
|
||||
pub fn new(environment: Environment, uuid_random_seed: u64) -> Self {
|
||||
ENVIRONMENT.set(environment).expect("Editor shoud only be initialized once");
|
||||
graphene_std::uuid::set_uuid_seed(uuid_random_seed);
|
||||
|
||||
let mut dispatcher = Dispatcher::new(resource_storage);
|
||||
dispatcher.message_handlers.future_message_handler.set_wake(wake);
|
||||
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
|
||||
crate::node_graph_executor::replace_application_io(application_io);
|
||||
|
||||
Self { dispatcher }
|
||||
Self { dispatcher: Dispatcher::new() }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -27,15 +20,11 @@ impl Editor {
|
||||
let _ = ENVIRONMENT.set(*Editor::environment());
|
||||
graphene_std::uuid::set_uuid_seed(0);
|
||||
|
||||
let (mut runtime, executor) = crate::node_graph_executor::NodeGraphExecutor::new_with_local_runtime();
|
||||
let (runtime, executor) = crate::node_graph_executor::NodeGraphExecutor::new_with_local_runtime();
|
||||
let editor = Self {
|
||||
dispatcher: Dispatcher::with_executor(executor),
|
||||
};
|
||||
|
||||
let mut application_io = PlatformApplicationIo::default();
|
||||
application_io.inject_resource_proxy(editor.dispatcher.message_handlers.resource_storage_message_handler.resources());
|
||||
runtime.replace_application_io(application_io);
|
||||
|
||||
(editor, runtime)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
// GRAPH
|
||||
pub const GRID_SIZE: u32 = 24;
|
||||
pub const HALF_GRID_SIZE: u32 = GRID_SIZE / 2;
|
||||
pub const EXPORTS_TO_TOP_EDGE_PIXEL_GAP: u32 = 72;
|
||||
pub const EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP: u32 = 120;
|
||||
pub const IMPORTS_TO_TOP_EDGE_PIXEL_GAP: u32 = 72;
|
||||
|
||||
+20
-43
@@ -6,8 +6,6 @@ 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;
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Dispatcher {
|
||||
@@ -21,10 +19,8 @@ pub struct Dispatcher {
|
||||
pub struct DispatcherMessageHandlers {
|
||||
animation_message_handler: AnimationMessageHandler,
|
||||
app_window_message_handler: AppWindowMessageHandler,
|
||||
pub(crate) future_message_handler: FutureMessageHandler,
|
||||
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,
|
||||
@@ -32,26 +28,17 @@ pub struct DispatcherMessageHandlers {
|
||||
key_mapping_message_handler: KeyMappingMessageHandler,
|
||||
layout_message_handler: LayoutMessageHandler,
|
||||
menu_bar_message_handler: MenuBarMessageHandler,
|
||||
network_message_handler: NetworkMessageHandler,
|
||||
pub(crate) portfolio_message_handler: PortfolioMessageHandler,
|
||||
preferences_message_handler: PreferencesMessageHandler,
|
||||
pub(crate) resource_storage_message_handler: ResourceStorageMessageHandler,
|
||||
tool_message_handler: ToolMessageHandler,
|
||||
viewport_message_handler: ViewportMessageHandler,
|
||||
}
|
||||
|
||||
impl DispatcherMessageHandlers {
|
||||
pub fn with_resource_storage(resource_storage: Arc<dyn ResourceStorage>) -> Self {
|
||||
Self {
|
||||
resource_storage_message_handler: ResourceStorageMessageHandler::new(resource_storage),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self {
|
||||
Self {
|
||||
portfolio_message_handler: PortfolioMessageHandler::with_executor(executor),
|
||||
..Self::default()
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -66,6 +53,7 @@ const SIDE_EFFECT_FREE_MESSAGES: &[MessageDiscriminant] = &[
|
||||
))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::SubmitActiveGraphRender),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::SubmitEyedropperPreviewRender),
|
||||
MessageDiscriminant::Frontend(FrontendMessageDiscriminant::TriggerFontDataLoad),
|
||||
MessageDiscriminant::Frontend(FrontendMessageDiscriminant::UpdateUIScale),
|
||||
];
|
||||
/// Since we don't need to update the frontend multiple times per frame,
|
||||
@@ -89,16 +77,15 @@ const DEBUG_MESSAGE_BLOCK_LIST: &[MessageDiscriminant] = &[
|
||||
const DEBUG_MESSAGE_ENDING_BLOCK_LIST: &[&str] = &["PointerMove", "PointerOutsideViewport", "Overlays", "Draw", "CurrentTime", "Time"];
|
||||
|
||||
impl Dispatcher {
|
||||
pub fn new(resource_storage: Arc<dyn ResourceStorage>) -> Self {
|
||||
let mut s = Self::default();
|
||||
s.message_handlers.resource_storage_message_handler = ResourceStorageMessageHandler::new(resource_storage);
|
||||
s
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self {
|
||||
let mut s = Self::default();
|
||||
s.message_handlers.portfolio_message_handler = PortfolioMessageHandler::with_executor(executor);
|
||||
s
|
||||
Self {
|
||||
message_handlers: DispatcherMessageHandlers::with_executor(executor),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
// If the deepest queues (higher index in queues list) are now empty (after being popped from) then remove them
|
||||
@@ -126,13 +113,6 @@ impl Dispatcher {
|
||||
pub fn handle_message<T: Into<Message>>(&mut self, message: T, process_after_all_current: bool) {
|
||||
let message = message.into();
|
||||
|
||||
// Drain async results into the queue before processing the new message.
|
||||
let mut async_results = VecDeque::new();
|
||||
self.message_handlers.future_message_handler.drain_results(&mut async_results);
|
||||
if !async_results.is_empty() {
|
||||
Self::schedule_execution(&mut self.message_queues, true, async_results);
|
||||
}
|
||||
|
||||
// If we are not maintaining the buffer, simply add to the current queue
|
||||
Self::schedule_execution(&mut self.message_queues, process_after_all_current, [message]);
|
||||
|
||||
@@ -182,12 +162,8 @@ impl Dispatcher {
|
||||
Message::AppWindow(message) => {
|
||||
self.message_handlers.app_window_message_handler.process_message(message, &mut queue, ());
|
||||
}
|
||||
Message::Future(message) => {
|
||||
self.message_handlers.future_message_handler.process_message(message, &mut queue, FutureMessageContext {});
|
||||
}
|
||||
Message::Broadcast(message) => self.message_handlers.broadcast_message_handler.process_message(message, &mut queue, ()),
|
||||
Message::Clipboard(message) => self.message_handlers.clipboard_message_handler.process_message(message, &mut queue, ()),
|
||||
Message::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, ());
|
||||
}
|
||||
@@ -205,7 +181,17 @@ impl Dispatcher {
|
||||
self.message_handlers.dialog_message_handler.process_message(message, &mut queue, context);
|
||||
}
|
||||
Message::Frontend(message) => {
|
||||
self.responses.push(message);
|
||||
// Handle these messages immediately by returning early
|
||||
if let FrontendMessage::TriggerFontDataLoad { .. } | FrontendMessage::TriggerFontCatalogLoad = message {
|
||||
self.responses.push(message);
|
||||
self.cleanup_queues(false);
|
||||
|
||||
// Return early to avoid running the code after the match block
|
||||
return;
|
||||
} else {
|
||||
// `FrontendMessage`s are saved and will be sent to the frontend after the message queue is done being processed
|
||||
self.responses.push(message);
|
||||
}
|
||||
}
|
||||
Message::InputPreprocessor(message) => {
|
||||
self.message_handlers.input_preprocessor_message_handler.process_message(
|
||||
@@ -230,14 +216,6 @@ impl Dispatcher {
|
||||
|
||||
self.message_handlers.layout_message_handler.process_message(message, &mut queue, context);
|
||||
}
|
||||
Message::Network(message) => {
|
||||
self.message_handlers.network_message_handler.process_message(message, &mut queue, NetworkMessageContext {});
|
||||
}
|
||||
Message::ResourceStorage(message) => {
|
||||
self.message_handlers
|
||||
.resource_storage_message_handler
|
||||
.process_message(message, &mut queue, ResourceStorageMessageContext {});
|
||||
}
|
||||
Message::Portfolio(message) => {
|
||||
self.message_handlers.portfolio_message_handler.process_message(
|
||||
message,
|
||||
@@ -250,7 +228,6 @@ impl Dispatcher {
|
||||
timing_information: self.message_handlers.animation_message_handler.timing_information(),
|
||||
animation: &self.message_handlers.animation_message_handler,
|
||||
viewport: &self.message_handlers.viewport_message_handler,
|
||||
resource_storage: &self.message_handlers.resource_storage_message_handler,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -318,7 +295,7 @@ impl Dispatcher {
|
||||
document_id,
|
||||
document,
|
||||
input: &self.message_handlers.input_preprocessor_message_handler,
|
||||
fonts: &self.message_handlers.portfolio_message_handler.fonts,
|
||||
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,7 +1,3 @@
|
||||
// Bumped past the default 128 because the deeply-generic message-passing types pull in wgpu/naga
|
||||
// trait chains that overflow the trait resolver under `--tests`. Set to the same value the compiler suggests.
|
||||
#![recursion_limit = "256"]
|
||||
|
||||
extern crate graphite_proc_macros;
|
||||
|
||||
// `macro_use` puts these macros into scope for all descendant code files
|
||||
|
||||
@@ -11,7 +11,6 @@ pub enum AppWindowMessage {
|
||||
Maximize,
|
||||
Fullscreen,
|
||||
Drag,
|
||||
Focus,
|
||||
Hide,
|
||||
HideOthers,
|
||||
ShowAll,
|
||||
|
||||
@@ -36,10 +36,6 @@ impl MessageHandler<AppWindowMessage, ()> for AppWindowMessageHandler {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
responses.add(FrontendMessage::WindowDrag);
|
||||
}
|
||||
AppWindowMessage::Focus => {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
responses.add(FrontendMessage::WindowFocus);
|
||||
}
|
||||
AppWindowMessage::Hide => {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
responses.add(FrontendMessage::WindowHide);
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
use crate::messages::layout::utility_types::widgets::input_widgets::{SpectrumInputUpdate, VisualColorPickersInputUpdate};
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
|
||||
/// Identifies which RGB channel a numeric input change targets.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum RgbChannel {
|
||||
Red,
|
||||
Green,
|
||||
Blue,
|
||||
}
|
||||
|
||||
/// Identifies which HSV channel a numeric input change targets.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum HsvChannel {
|
||||
Hue,
|
||||
Saturation,
|
||||
Value,
|
||||
}
|
||||
|
||||
#[impl_message(Message, ColorPicker)]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ColorPickerMessage {
|
||||
/// Initialize the picker state from an external color/gradient and announce its options. Called by the frontend when a `<ColorPicker />` opens.
|
||||
Open { initial_value: FillChoice, allow_none: bool, disabled: bool },
|
||||
/// Clear the picker state. Called by the frontend when the popover closes.
|
||||
Close,
|
||||
|
||||
/// Visual sat/val/hue/alpha drag updates from `VisualColorPickersInput`.
|
||||
VisualUpdate { update: VisualColorPickersInputUpdate },
|
||||
/// Numeric RGB channel update.
|
||||
SetChannelRgb { channel: RgbChannel, value: Option<f64> },
|
||||
/// Numeric HSV channel update.
|
||||
SetChannelHsv { channel: HsvChannel, value: Option<f64> },
|
||||
/// Alpha percentage update from the alpha slider numeric input.
|
||||
SetAlphaPercent { value: Option<f64> },
|
||||
/// CSS / hex color string from the hex `TextInput`.
|
||||
SetHexCode { code: String },
|
||||
|
||||
/// Pick a preset (specific solid color or "None").
|
||||
PickPreset { preset: FillChoice },
|
||||
/// Color picked via the browser-native eyedropper. The string is the eyedropper's returned hex code.
|
||||
EyedropperColorCode { code: String },
|
||||
|
||||
/// Swap the current "new" color with the captured "old" color.
|
||||
SwapNewWithOld,
|
||||
|
||||
/// `SpectrumInput` change: marker move/insert/delete, midpoint move/reset, or active marker selection changed.
|
||||
GradientUpdate { update: SpectrumInputUpdate },
|
||||
|
||||
/// Tell the frontend to start an undo transaction (forwarded as a `FrontendMessage` it bridges out to the picker's parent).
|
||||
StartTransaction,
|
||||
/// Tell the frontend to commit the in-flight undo transaction.
|
||||
CommitTransaction,
|
||||
}
|
||||
@@ -1,664 +0,0 @@
|
||||
use crate::messages::color_picker::color_picker_message::{HsvChannel, RgbChannel};
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::layout::utility_types::widgets::input_widgets::{ColorPresetsInputUpdate, SpectrumInputUpdate, SpectrumMarker, VisualColorPickersInputUpdate};
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::core_types::misc::parse_css_color;
|
||||
use graphene_std::vector::style::{FillChoice, FillChoiceUI, GradientStops, GradientStopsUI};
|
||||
|
||||
/// Bounds for a midpoint position (relative to the interval between two adjacent gradient stops).
|
||||
const MIN_MIDPOINT: f64 = 0.01;
|
||||
const MAX_MIDPOINT: f64 = 0.99;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, ExtractField)]
|
||||
pub struct ColorPickerMessageHandler {
|
||||
// HSV is the source of truth so the hue is preserved when the user desaturates the color (or drives the value to black) and back.
|
||||
hue: f64,
|
||||
saturation: f64,
|
||||
value: f64,
|
||||
alpha: f64,
|
||||
is_none: bool,
|
||||
|
||||
// Snapshot of the color when the picker opened, used by the new/old comparison swatch and the swap button.
|
||||
old_hue: f64,
|
||||
old_saturation: f64,
|
||||
old_value: f64,
|
||||
old_alpha: f64,
|
||||
old_is_none: bool,
|
||||
|
||||
// When set, the picker is editing a gradient: the visual pickers and inputs target the active stop's color.
|
||||
gradient: Option<GradientStops>,
|
||||
active_marker_index: Option<u32>,
|
||||
active_marker_is_midpoint: bool,
|
||||
|
||||
allow_none: bool,
|
||||
disabled: bool,
|
||||
}
|
||||
|
||||
impl Default for ColorPickerMessageHandler {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
hue: 0.,
|
||||
saturation: 0.,
|
||||
value: 0.,
|
||||
alpha: 1.,
|
||||
is_none: true,
|
||||
old_hue: 0.,
|
||||
old_saturation: 0.,
|
||||
old_value: 0.,
|
||||
old_alpha: 1.,
|
||||
old_is_none: true,
|
||||
gradient: None,
|
||||
active_marker_index: None,
|
||||
active_marker_is_midpoint: false,
|
||||
allow_none: true,
|
||||
disabled: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<ColorPickerMessage, ()> for ColorPickerMessageHandler {
|
||||
fn process_message(&mut self, message: ColorPickerMessage, responses: &mut VecDeque<Message>, _context: ()) {
|
||||
match message {
|
||||
ColorPickerMessage::Open { initial_value, allow_none, disabled } => {
|
||||
self.allow_none = allow_none;
|
||||
self.disabled = disabled;
|
||||
|
||||
match initial_value {
|
||||
FillChoice::None => {
|
||||
self.set_new_hsva(0., 0., 0., 1., true);
|
||||
self.gradient = None;
|
||||
self.active_marker_index = None;
|
||||
self.active_marker_is_midpoint = false;
|
||||
}
|
||||
FillChoice::Solid(color) => {
|
||||
self.gradient = None;
|
||||
self.active_marker_index = None;
|
||||
self.active_marker_is_midpoint = false;
|
||||
self.adopt_color(color);
|
||||
}
|
||||
FillChoice::Gradient(stops) => {
|
||||
self.active_marker_index = Some(0);
|
||||
self.active_marker_is_midpoint = false;
|
||||
let first_color = stops.color.first().copied().unwrap_or(Color::BLACK);
|
||||
self.gradient = Some(stops);
|
||||
self.adopt_color(first_color);
|
||||
}
|
||||
}
|
||||
|
||||
self.snapshot_old();
|
||||
self.send_layouts(responses);
|
||||
}
|
||||
ColorPickerMessage::Close => {
|
||||
responses.add(DocumentMessage::EndTransaction);
|
||||
}
|
||||
ColorPickerMessage::VisualUpdate { update } => {
|
||||
self.hue = update.hue;
|
||||
self.saturation = update.saturation;
|
||||
self.value = update.value;
|
||||
self.alpha = update.alpha;
|
||||
self.is_none = false;
|
||||
self.emit_color(responses);
|
||||
self.send_layouts(responses);
|
||||
}
|
||||
ColorPickerMessage::SetChannelRgb { channel, value } => {
|
||||
let Some(strength) = value else { return };
|
||||
let Some(current) = self.current_color() else { return };
|
||||
// The RGB inputs are 0..255 sRGB display values; substitute the new channel into the gamma triple and lift back to linear for storage.
|
||||
let new_gamma_channel = (strength / 255.) as f32;
|
||||
let [cur_r, cur_g, cur_b, cur_a] = current.to_gamma_srgb_channels();
|
||||
let updated = match channel {
|
||||
RgbChannel::Red => Color::from_gamma_srgb_channels(new_gamma_channel, cur_g, cur_b, cur_a),
|
||||
RgbChannel::Green => Color::from_gamma_srgb_channels(cur_r, new_gamma_channel, cur_b, cur_a),
|
||||
RgbChannel::Blue => Color::from_gamma_srgb_channels(cur_r, cur_g, new_gamma_channel, cur_a),
|
||||
};
|
||||
self.adopt_color(updated);
|
||||
self.emit_color(responses);
|
||||
self.send_layouts(responses);
|
||||
}
|
||||
ColorPickerMessage::SetChannelHsv { channel, value } => {
|
||||
let Some(strength) = value else { return };
|
||||
match channel {
|
||||
HsvChannel::Hue => self.hue = strength / 360.,
|
||||
HsvChannel::Saturation => self.saturation = strength / 100.,
|
||||
HsvChannel::Value => self.value = strength / 100.,
|
||||
}
|
||||
self.is_none = false;
|
||||
self.emit_color(responses);
|
||||
self.send_layouts(responses);
|
||||
}
|
||||
ColorPickerMessage::SetAlphaPercent { value } => {
|
||||
let Some(strength) = value else { return };
|
||||
self.alpha = strength / 100.;
|
||||
self.is_none = false;
|
||||
self.emit_color(responses);
|
||||
self.send_layouts(responses);
|
||||
}
|
||||
ColorPickerMessage::SetHexCode { code } => {
|
||||
let Some(color) = parse_css_color(&code) else {
|
||||
// Parse failed: re-send the layouts so the TextInput's displayed value reverts from the user's bad input
|
||||
// back to the current color's hex string. The TextInput dispatch arm has already mutated the stored
|
||||
// widget's `value` to the bad input, so the diff between (stored = bad) and (new = correct) sends an update.
|
||||
self.send_layouts(responses);
|
||||
return;
|
||||
};
|
||||
responses.add(FrontendMessage::ColorPickerStartHistoryTransaction);
|
||||
self.adopt_color(color);
|
||||
self.emit_color(responses);
|
||||
self.send_layouts(responses);
|
||||
}
|
||||
ColorPickerMessage::PickPreset { preset } => {
|
||||
responses.add(FrontendMessage::ColorPickerStartHistoryTransaction);
|
||||
match preset {
|
||||
FillChoice::None => {
|
||||
self.set_new_hsva(0., 0., 0., 1., true);
|
||||
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoiceUI::None });
|
||||
}
|
||||
FillChoice::Solid(color) => {
|
||||
self.adopt_color(color);
|
||||
self.emit_color(responses);
|
||||
}
|
||||
FillChoice::Gradient(_) => {
|
||||
// The presets row only emits solid colors or "None"; the gradient case is unreachable, so safely ignore.
|
||||
}
|
||||
}
|
||||
self.send_layouts(responses);
|
||||
}
|
||||
ColorPickerMessage::EyedropperColorCode { code } => {
|
||||
let Some(color) = parse_css_color(&code) else { return };
|
||||
responses.add(FrontendMessage::ColorPickerStartHistoryTransaction);
|
||||
self.adopt_color(color);
|
||||
self.emit_color(responses);
|
||||
self.send_layouts(responses);
|
||||
}
|
||||
ColorPickerMessage::SwapNewWithOld => {
|
||||
let temp = (self.hue, self.saturation, self.value, self.alpha, self.is_none);
|
||||
self.set_new_hsva(self.old_hue, self.old_saturation, self.old_value, self.old_alpha, self.old_is_none);
|
||||
self.set_old_hsva(temp.0, temp.1, temp.2, temp.3, temp.4);
|
||||
|
||||
if self.is_none {
|
||||
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoiceUI::None });
|
||||
} else {
|
||||
self.emit_color(responses);
|
||||
}
|
||||
self.send_layouts(responses);
|
||||
}
|
||||
ColorPickerMessage::GradientUpdate { update } => self.apply_gradient_update(update, responses),
|
||||
ColorPickerMessage::StartTransaction => {
|
||||
responses.add(FrontendMessage::ColorPickerStartHistoryTransaction);
|
||||
}
|
||||
ColorPickerMessage::CommitTransaction => {
|
||||
responses.add(FrontendMessage::ColorPickerCommitHistoryTransaction);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn actions(&self) -> ActionList {
|
||||
actions!(ColorPickerMessageDiscriminant;)
|
||||
}
|
||||
}
|
||||
|
||||
impl ColorPickerMessageHandler {
|
||||
// The picker's internal HSV state is HSV of sRGB display values
|
||||
fn current_color(&self) -> Option<Color> {
|
||||
if self.is_none {
|
||||
None
|
||||
} else {
|
||||
Some(Color::from_hsva(self.hue as f32, self.saturation as f32, self.value as f32, self.alpha as f32))
|
||||
}
|
||||
}
|
||||
|
||||
fn old_color(&self) -> Option<Color> {
|
||||
if self.old_is_none {
|
||||
None
|
||||
} else {
|
||||
Some(Color::from_hsva(self.old_hue as f32, self.old_saturation as f32, self.old_value as f32, self.old_alpha as f32))
|
||||
}
|
||||
}
|
||||
|
||||
fn set_new_hsva(&mut self, h: f64, s: f64, v: f64, a: f64, is_none: bool) {
|
||||
self.hue = h;
|
||||
self.saturation = s;
|
||||
self.value = v;
|
||||
self.alpha = a;
|
||||
self.is_none = is_none;
|
||||
}
|
||||
|
||||
fn set_old_hsva(&mut self, h: f64, s: f64, v: f64, a: f64, is_none: bool) {
|
||||
self.old_hue = h;
|
||||
self.old_saturation = s;
|
||||
self.old_value = v;
|
||||
self.old_alpha = a;
|
||||
self.old_is_none = is_none;
|
||||
}
|
||||
|
||||
fn snapshot_old(&mut self) {
|
||||
self.old_hue = self.hue;
|
||||
self.old_saturation = self.saturation;
|
||||
self.old_value = self.value;
|
||||
self.old_alpha = self.alpha;
|
||||
self.old_is_none = self.is_none;
|
||||
}
|
||||
|
||||
/// Set HSV state from a Color, preserving hue and saturation in degenerate cases.
|
||||
fn adopt_color(&mut self, color: Color) {
|
||||
let [target_h, target_s, target_v, target_a] = color.to_hsva();
|
||||
let (target_h, target_s, target_v, target_a) = (target_h as f64, target_s as f64, target_v as f64, target_a as f64);
|
||||
|
||||
// Preserve hue: avoid jumping from 360° (top) to 0° (bottom) and don't reset hue when the color is desaturated or fully dark.
|
||||
if !(target_h == 0. && self.hue == 1.) && target_s > 0. && target_v > 0. {
|
||||
self.hue = target_h;
|
||||
}
|
||||
// Preserve saturation when value is black (saturation is meaningless on the bottom edge of the saturation-value box).
|
||||
if target_v != 0. {
|
||||
self.saturation = target_s;
|
||||
}
|
||||
self.value = target_v;
|
||||
self.alpha = target_a;
|
||||
self.is_none = false;
|
||||
}
|
||||
|
||||
/// Compute the FillChoice and forward it via `FrontendMessage::ColorPickerColorChanged`. In gradient mode, the active stop's color is updated in place.
|
||||
fn emit_color(&mut self, responses: &mut VecDeque<Message>) {
|
||||
let Some(color) = self.current_color() else { return };
|
||||
|
||||
if let Some(gradient) = &mut self.gradient
|
||||
&& let Some(active_index) = self.active_marker_index
|
||||
&& let Some(stop_color) = gradient.color.get_mut(active_index as usize)
|
||||
{
|
||||
*stop_color = color;
|
||||
let stops = gradient.clone();
|
||||
let fill_choice = FillChoice::Gradient(stops);
|
||||
responses.add(FrontendMessage::ColorPickerColorChanged {
|
||||
value: FillChoiceUI::from(&fill_choice),
|
||||
});
|
||||
} else {
|
||||
let fill_choice = FillChoice::Solid(color);
|
||||
responses.add(FrontendMessage::ColorPickerColorChanged {
|
||||
value: FillChoiceUI::from(&fill_choice),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn send_layouts(&self, responses: &mut VecDeque<Message>) {
|
||||
responses.add(LayoutMessage::SendLayout {
|
||||
layout: self.pickers_and_gradient_layout(),
|
||||
layout_target: LayoutTarget::ColorPickerPickersAndGradient,
|
||||
});
|
||||
responses.add(LayoutMessage::SendLayout {
|
||||
layout: self.details_layout(),
|
||||
layout_target: LayoutTarget::ColorPickerDetails,
|
||||
});
|
||||
}
|
||||
|
||||
/// Apply an incoming `SpectrumInput` intent to the gradient state and broadcast the result.
|
||||
fn apply_gradient_update(&mut self, update: SpectrumInputUpdate, responses: &mut VecDeque<Message>) {
|
||||
// Active marker selection is the one update that doesn't mutate the gradient
|
||||
if let SpectrumInputUpdate::ActiveMarker {
|
||||
active_marker_index,
|
||||
active_marker_is_midpoint,
|
||||
} = update
|
||||
{
|
||||
self.active_marker_index = active_marker_index;
|
||||
self.active_marker_is_midpoint = active_marker_is_midpoint;
|
||||
if let Some(index) = active_marker_index
|
||||
&& let Some(gradient) = &self.gradient
|
||||
&& let Some(color) = gradient.color.get(index as usize).copied()
|
||||
{
|
||||
self.adopt_color(color);
|
||||
self.snapshot_old();
|
||||
}
|
||||
self.send_layouts(responses);
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(mut gradient) = self.gradient.clone() else { return };
|
||||
|
||||
match update {
|
||||
SpectrumInputUpdate::MoveMarker { index, position } => {
|
||||
let new_index = gradient.move_stop(index as usize, position);
|
||||
if Some(index) == self.active_marker_index {
|
||||
self.active_marker_index = Some(new_index as u32);
|
||||
}
|
||||
}
|
||||
SpectrumInputUpdate::MoveMidpoint { index, position } => {
|
||||
if let Some(midpoint) = gradient.midpoint.get_mut(index as usize) {
|
||||
*midpoint = position.clamp(MIN_MIDPOINT, MAX_MIDPOINT);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
SpectrumInputUpdate::InsertMarker { position } => {
|
||||
let new_index = gradient.insert_stop(position);
|
||||
self.active_marker_index = Some(new_index as u32);
|
||||
self.active_marker_is_midpoint = false;
|
||||
if let Some(color) = gradient.color.get(new_index).copied() {
|
||||
self.adopt_color(color);
|
||||
self.snapshot_old();
|
||||
}
|
||||
}
|
||||
SpectrumInputUpdate::DeleteMarker { index } => {
|
||||
// Enforce minimum stop count. The gradient editor needs at least 2 stops to remain meaningful.
|
||||
if gradient.position.len() <= 2 || (index as usize) >= gradient.position.len() {
|
||||
return;
|
||||
}
|
||||
gradient.remove(index as usize);
|
||||
let new_active = (index as usize).min(gradient.position.len() - 1);
|
||||
self.active_marker_index = Some(new_active as u32);
|
||||
self.active_marker_is_midpoint = false;
|
||||
if let Some(color) = gradient.color.get(new_active).copied() {
|
||||
self.adopt_color(color);
|
||||
self.snapshot_old();
|
||||
}
|
||||
}
|
||||
SpectrumInputUpdate::ResetMidpoint { index } => {
|
||||
gradient.reset_midpoint(index as usize);
|
||||
}
|
||||
SpectrumInputUpdate::ResetMarker { index } => {
|
||||
let i = index as usize;
|
||||
let count = gradient.position.len();
|
||||
if i >= count {
|
||||
return;
|
||||
}
|
||||
// Each stop's "natural" position is its evenly-spaced fraction along 0..1, e.g., for 5 stops: 0, 0.25, 0.5, 0.75, 1. Falls back to the midpoint between neighbors when the natural position would push the stop past another.
|
||||
let left = if i == 0 { 0. } else { gradient.position[i - 1] };
|
||||
let right = gradient.position.get(i + 1).copied().unwrap_or(1.);
|
||||
let natural = if count <= 1 { 0. } else { i as f64 / (count - 1) as f64 };
|
||||
let new_position = if (left..=right).contains(&natural) { natural } else { (left + right) / 2. };
|
||||
let new_index = gradient.move_stop(i, new_position);
|
||||
if Some(index) == self.active_marker_index {
|
||||
self.active_marker_index = Some(new_index as u32);
|
||||
}
|
||||
}
|
||||
SpectrumInputUpdate::ActiveMarker { .. } => unreachable!("handled above"),
|
||||
}
|
||||
|
||||
self.gradient = Some(gradient.clone());
|
||||
let fill_choice = FillChoice::Gradient(gradient);
|
||||
responses.add(FrontendMessage::ColorPickerColorChanged {
|
||||
value: FillChoiceUI::from(&fill_choice),
|
||||
});
|
||||
self.send_layouts(responses);
|
||||
}
|
||||
|
||||
fn pickers_and_gradient_layout(&self) -> Layout {
|
||||
let mut groups = Vec::new();
|
||||
|
||||
// Visual H/S/V/A pickers
|
||||
groups.push(LayoutGroup::row(vec![
|
||||
VisualColorPickersInput::default()
|
||||
.hue(self.hue)
|
||||
.saturation(self.saturation)
|
||||
.value(self.value)
|
||||
.alpha(self.alpha)
|
||||
.is_none(self.is_none)
|
||||
.disabled(self.disabled)
|
||||
.on_update(|update: &VisualColorPickersInputUpdate| ColorPickerMessage::VisualUpdate { update: update.clone() }.into())
|
||||
.on_commit(|_| ColorPickerMessage::CommitTransaction.into())
|
||||
.widget_instance(),
|
||||
]));
|
||||
|
||||
// Gradient editor (only present when the picker is in gradient mode)
|
||||
if let Some(gradient) = &self.gradient {
|
||||
// For gradient editing, the markers' handle colors mirror their gradient stop colors
|
||||
let markers = gradient.iter().map(|stop| SpectrumMarker::new(stop.position, stop.midpoint, stop.color)).collect();
|
||||
let mut row_widgets = vec![
|
||||
SpectrumInput::new(GradientStopsUI::from(gradient))
|
||||
.markers(markers)
|
||||
.active_marker_index(self.active_marker_index)
|
||||
.active_marker_is_midpoint(self.active_marker_is_midpoint)
|
||||
.show_midpoints(true)
|
||||
.allow_insert(!self.disabled)
|
||||
.allow_delete(!self.disabled)
|
||||
.allow_reorder(true)
|
||||
.disabled(self.disabled)
|
||||
.on_update(|update: &SpectrumInputUpdate| ColorPickerMessage::GradientUpdate { update: update.clone() }.into())
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
if let Some(active) = self.active_marker_index {
|
||||
let active_index = active as usize;
|
||||
let position_value = if self.active_marker_is_midpoint {
|
||||
gradient.midpoint.get(active_index).copied().unwrap_or(0.)
|
||||
} else {
|
||||
gradient.position.get(active_index).copied().unwrap_or(0.)
|
||||
};
|
||||
let is_midpoint = self.active_marker_is_midpoint;
|
||||
let captured_index = active;
|
||||
row_widgets.push(
|
||||
NumberInput::new(Some(position_value * 100.))
|
||||
.disabled(self.disabled)
|
||||
.display_decimal_places(0)
|
||||
.min(if is_midpoint { 1. } else { 0. })
|
||||
.max(if is_midpoint { 99. } else { 100. })
|
||||
.unit("%")
|
||||
.on_update(move |widget: &NumberInput| {
|
||||
let Some(new_value) = widget.value else {
|
||||
return Message::NoOp;
|
||||
};
|
||||
let update = if is_midpoint {
|
||||
SpectrumInputUpdate::MoveMidpoint {
|
||||
index: captured_index,
|
||||
position: new_value / 100.,
|
||||
}
|
||||
} else {
|
||||
SpectrumInputUpdate::MoveMarker {
|
||||
index: captured_index,
|
||||
position: new_value / 100.,
|
||||
}
|
||||
};
|
||||
ColorPickerMessage::GradientUpdate { update }.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
);
|
||||
}
|
||||
|
||||
groups.push(LayoutGroup::row(row_widgets));
|
||||
}
|
||||
|
||||
Layout(groups)
|
||||
}
|
||||
|
||||
fn details_layout(&self) -> Layout {
|
||||
let new_color = self.current_color();
|
||||
let old_color = self.old_color();
|
||||
|
||||
let hex_value = new_color.map(|c| color_to_hex_optional_alpha(&c)).unwrap_or_else(|| "-".to_string());
|
||||
// RGB readouts display sRGB byte values to the user, so we convert from linear-light to gamma here before quantizing.
|
||||
let rgb_255 = new_color.map(|c| {
|
||||
let [r, g, b, _] = c.to_gamma_srgb_channels();
|
||||
(r as f64 * 255., g as f64 * 255., b as f64 * 255.)
|
||||
});
|
||||
|
||||
// Epsilon comparison since the picker round-trips through HSV
|
||||
let differs = match (new_color, old_color) {
|
||||
(Some(a), Some(b)) => {
|
||||
const EPSILON: f32 = 1e-6;
|
||||
(a.r() - b.r()).abs() >= EPSILON || (a.g() - b.g()).abs() >= EPSILON || (a.b() - b.b()).abs() >= EPSILON || (a.a() - b.a()).abs() >= EPSILON
|
||||
}
|
||||
(None, None) => false,
|
||||
_ => true,
|
||||
};
|
||||
let outline_amount = contrasting_outline_factor(new_color).max(contrasting_outline_factor(old_color));
|
||||
|
||||
let mut groups = Vec::new();
|
||||
|
||||
// New/old comparison swatch with swap button
|
||||
groups.push(LayoutGroup::row(vec![
|
||||
ColorComparisonInput::new(new_color.map(SRGBA8::from), old_color.map(SRGBA8::from))
|
||||
.is_none(self.is_none)
|
||||
.old_is_none(self.old_is_none)
|
||||
.disabled(self.disabled)
|
||||
.differs(differs)
|
||||
.outline_amount(outline_amount)
|
||||
.on_update(|_: &()| ColorPickerMessage::SwapNewWithOld.into())
|
||||
.widget_instance(),
|
||||
]));
|
||||
|
||||
// Hex
|
||||
groups.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("Hex").tooltip_label("Hex Color Code").tooltip_description(HEX_DESCRIPTION).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
TextInput::new(hex_value)
|
||||
.centered(true)
|
||||
.disabled(self.disabled)
|
||||
.tooltip_label("Hex Color Code")
|
||||
.tooltip_description(HEX_DESCRIPTION)
|
||||
.on_update(|widget: &TextInput| ColorPickerMessage::SetHexCode { code: widget.value.clone() }.into())
|
||||
.widget_instance(),
|
||||
]));
|
||||
|
||||
// RGB
|
||||
groups.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("RGB").tooltip_label("Red/Green/Blue").tooltip_description("Integers 0–255.").widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
rgb_input(RgbChannel::Red, rgb_255.map(|(r, _, _)| r), "Red Channel", self.disabled),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
rgb_input(RgbChannel::Green, rgb_255.map(|(_, g, _)| g), "Green Channel", self.disabled),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
rgb_input(RgbChannel::Blue, rgb_255.map(|(_, _, b)| b), "Blue Channel", self.disabled),
|
||||
]));
|
||||
|
||||
// HSV
|
||||
groups.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("HSV")
|
||||
.tooltip_label("Hue/Saturation/Value")
|
||||
.tooltip_description("Also known as Hue/Saturation/Brightness (HSB). Not to be confused with Hue/Saturation/Lightness (HSL), a different color model.")
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
hsv_input(
|
||||
HsvChannel::Hue,
|
||||
if self.is_none { None } else { Some(self.hue * 360.) },
|
||||
360.,
|
||||
"°",
|
||||
"Hue Component",
|
||||
HUE_DESCRIPTION,
|
||||
self.disabled,
|
||||
),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
hsv_input(
|
||||
HsvChannel::Saturation,
|
||||
if self.is_none { None } else { Some(self.saturation * 100.) },
|
||||
100.,
|
||||
"%",
|
||||
"Saturation Component",
|
||||
SATURATION_DESCRIPTION,
|
||||
self.disabled,
|
||||
),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
hsv_input(
|
||||
HsvChannel::Value,
|
||||
if self.is_none { None } else { Some(self.value * 100.) },
|
||||
100.,
|
||||
"%",
|
||||
"Value Component",
|
||||
VALUE_DESCRIPTION,
|
||||
self.disabled,
|
||||
),
|
||||
]));
|
||||
|
||||
// Alpha
|
||||
groups.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("Alpha").tooltip_label("Alpha").tooltip_description(ALPHA_DESCRIPTION).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
NumberInput::new(if self.is_none { None } else { Some(self.alpha * 100.) })
|
||||
.disabled(self.disabled)
|
||||
.min(0.)
|
||||
.max(100.)
|
||||
.mode_range()
|
||||
.unit("%")
|
||||
.display_decimal_places(1)
|
||||
.tooltip_label("Alpha")
|
||||
.tooltip_description(ALPHA_DESCRIPTION)
|
||||
.on_update(|widget: &NumberInput| ColorPickerMessage::SetAlphaPercent { value: widget.value }.into())
|
||||
.on_commit(|_| ColorPickerMessage::StartTransaction.into())
|
||||
.widget_instance(),
|
||||
]));
|
||||
|
||||
// Color presets (None / Black / White / pure colors / eyedropper)
|
||||
groups.push(LayoutGroup::row(vec![
|
||||
ColorPresetsInput::default()
|
||||
.disabled(self.disabled)
|
||||
.show_none_option(self.allow_none && self.gradient.is_none())
|
||||
.on_update(|update: &ColorPresetsInputUpdate| match update {
|
||||
ColorPresetsInputUpdate::Preset(fill_choice) => ColorPickerMessage::PickPreset {
|
||||
preset: FillChoice::from(fill_choice),
|
||||
}
|
||||
.into(),
|
||||
ColorPresetsInputUpdate::EyedropperColorCode(code) => ColorPickerMessage::EyedropperColorCode { code: code.clone() }.into(),
|
||||
})
|
||||
.widget_instance(),
|
||||
]));
|
||||
|
||||
Layout(groups)
|
||||
}
|
||||
}
|
||||
|
||||
fn rgb_input(channel: RgbChannel, value: Option<f64>, tooltip_label: &'static str, disabled: bool) -> WidgetInstance {
|
||||
NumberInput::new(value)
|
||||
.disabled(disabled)
|
||||
.min(0.)
|
||||
.max(255.)
|
||||
.min_width(1)
|
||||
.display_decimal_places(0)
|
||||
.tooltip_label(tooltip_label)
|
||||
.tooltip_description("Integers 0–255.")
|
||||
.on_update(move |widget: &NumberInput| ColorPickerMessage::SetChannelRgb { channel, value: widget.value }.into())
|
||||
.on_commit(|_| ColorPickerMessage::StartTransaction.into())
|
||||
.widget_instance()
|
||||
}
|
||||
|
||||
fn hsv_input(channel: HsvChannel, value: Option<f64>, max: f64, unit: &'static str, tooltip_label: &'static str, tooltip_description: &'static str, disabled: bool) -> WidgetInstance {
|
||||
NumberInput::new(value)
|
||||
.disabled(disabled)
|
||||
.min(0.)
|
||||
.max(max)
|
||||
.min_width(1)
|
||||
.unit(unit)
|
||||
.display_decimal_places(1)
|
||||
.tooltip_label(tooltip_label)
|
||||
.tooltip_description(tooltip_description)
|
||||
.on_update(move |widget: &NumberInput| ColorPickerMessage::SetChannelHsv { channel, value: widget.value }.into())
|
||||
.on_commit(|_| ColorPickerMessage::StartTransaction.into())
|
||||
.widget_instance()
|
||||
}
|
||||
|
||||
const HEX_DESCRIPTION: &str = "Color code in hexadecimal format. 6 digits if opaque, 8 with alpha. Accepts input of CSS color values including named colors.";
|
||||
const HUE_DESCRIPTION: &str = "The shade along the spectrum of the rainbow.";
|
||||
const SATURATION_DESCRIPTION: &str = "The vividness from grayscale to full color.";
|
||||
const VALUE_DESCRIPTION: &str = "The brightness from black to full color.";
|
||||
const ALPHA_DESCRIPTION: &str = "The level of translucency, from transparent (0%) to opaque (100%).";
|
||||
|
||||
/// The popover's background color as sRGB gamma-encoded channels (the `--color-2-mildblack` design token, `#222`).
|
||||
/// Used by the comparison swatch's outline computation to brighten the inset border for colors close to this background.
|
||||
const POPOVER_BACKGROUND_GAMMA_CHANNELS: [f32; 4] = [0x22 as f32 / 255., 0x22 as f32 / 255., 0x22 as f32 / 255., 1.];
|
||||
/// The luminance window within which a color is considered close enough to the popover background
|
||||
/// to warrant an outline. Mirrors the `proximityRange` argument the legacy frontend passed to `contrastingOutlineFactor`.
|
||||
const OUTLINE_PROXIMITY_RANGE: f64 = 0.01;
|
||||
|
||||
/// Returns a 0..1 outline strength for the comparison swatch, growing toward 1 as the color's luminance and saturation
|
||||
/// both approach the popover background's luminance, when a color would otherwise visually blend into the popover.
|
||||
fn contrasting_outline_factor(color: Option<Color>) -> f64 {
|
||||
let Some(color) = color else { return 0. };
|
||||
|
||||
// WCAG-style relative luminance, with alpha composited over white in sRGB gamma space (matching the perceptual intent of `SRGBA8::contrasting_text_color`).
|
||||
let luminance_from_gamma_channels = |[r, g, b, a]: [f32; 4]| -> f64 {
|
||||
let inv_a = 1. - a;
|
||||
Color::from_gamma_srgb_channels(inv_a + r * a, inv_a + g * a, inv_a + b * a, 1.).luminance_rec_709() as f64
|
||||
};
|
||||
|
||||
let color_gamma_channels = color.to_gamma_srgb_channels();
|
||||
let distance = (luminance_from_gamma_channels(POPOVER_BACKGROUND_GAMMA_CHANNELS) - luminance_from_gamma_channels(color_gamma_channels))
|
||||
.abs()
|
||||
.max(0.);
|
||||
let proximity = 1. - (distance / OUTLINE_PROXIMITY_RANGE).min(1.);
|
||||
let [_, saturation, _, _] = color.to_hsva();
|
||||
proximity * (1. - saturation as f64)
|
||||
}
|
||||
|
||||
/// Format a linear `Color` as a `#`-prefixed hex string, including the alpha component only if it's not fully opaque.
|
||||
fn color_to_hex_optional_alpha(color: &Color) -> String {
|
||||
SRGBA8::from(*color).to_css_hex()
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
mod color_picker_message;
|
||||
pub mod color_picker_message_handler;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use color_picker_message::{ColorPickerMessage, ColorPickerMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use color_picker_message_handler::ColorPickerMessageHandler;
|
||||
@@ -126,7 +126,7 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
||||
DialogMessage::RequestNewDocumentDialog => {
|
||||
self.on_dismiss = Some(DialogMessage::Close.into());
|
||||
self.new_document_dialog = NewDocumentDialogMessageHandler {
|
||||
name: portfolio.generate_new_document_name(None),
|
||||
name: portfolio.generate_new_document_name(),
|
||||
infinite: false,
|
||||
dimensions: glam::UVec2::new(1920, 1080),
|
||||
};
|
||||
|
||||
+8
-14
@@ -1,7 +1,7 @@
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::prelude::*;
|
||||
use glam::UVec2;
|
||||
use glam::{IVec2, UVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
|
||||
@@ -35,22 +35,14 @@ impl MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHa
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetDisplayNameImpl {
|
||||
node_id,
|
||||
network_path: Vec::new(),
|
||||
alias: "Background".to_string(),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetLocked {
|
||||
node_id,
|
||||
network_path: Vec::new(),
|
||||
locked: true,
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetLocked { node_id, locked: true });
|
||||
} else if self.dimensions.x > 0 && self.dimensions.y > 0 {
|
||||
// Finite canvas: create an artboard with the specified dimensions
|
||||
responses.add(GraphOperationMessage::NewArtboard {
|
||||
id: NodeId::new(),
|
||||
location: glam::DVec2::ZERO,
|
||||
dimensions: self.dimensions.as_dvec2(),
|
||||
background: Color::WHITE,
|
||||
clip: true,
|
||||
artboard: graphene_std::Artboard::new(IVec2::ZERO, self.dimensions.as_ivec2()),
|
||||
});
|
||||
responses.add(NavigationMessage::CanvasPan { delta: self.dimensions.as_dvec2() });
|
||||
}
|
||||
@@ -58,10 +50,12 @@ impl MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHa
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(ViewportMessage::RepropagateUpdate);
|
||||
|
||||
responses.add(DocumentMessage::DeselectAllLayers);
|
||||
|
||||
responses.add(DeferMessage::AfterNavigationReady {
|
||||
messages: vec![DocumentMessage::ZoomCanvasToFitAll.into(), PortfolioMessage::AutoSaveActiveDocument.into()],
|
||||
messages: vec![
|
||||
DocumentMessage::ZoomCanvasToFitAll.into(),
|
||||
DocumentMessage::DeselectAllLayers.into(),
|
||||
PortfolioMessage::AutoSaveActiveDocument.into(),
|
||||
],
|
||||
});
|
||||
|
||||
responses.add(DocumentMessage::MarkAsSaved);
|
||||
|
||||
@@ -3,7 +3,7 @@ use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
|
||||
use crate::messages::preferences::SelectionMode;
|
||||
use crate::messages::prelude::*;
|
||||
use graph_craft::application_io::EditorPreferences;
|
||||
use graphene_std::render_node::{EditorPreferences, wgpu_available};
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct PreferencesDialogMessageContext<'a> {
|
||||
@@ -307,7 +307,7 @@ impl PreferencesDialogMessageHandler {
|
||||
// COMPATIBILITY
|
||||
// =============
|
||||
{
|
||||
let wgpu_available = graph_craft::application_io::wgpu_available().unwrap_or(false);
|
||||
let wgpu_available = wgpu_available().unwrap_or(false);
|
||||
let is_desktop = cfg!(not(target_family = "wasm"));
|
||||
if wgpu_available || is_desktop {
|
||||
let header = vec![TextLabel::new("Compatibility").italic(true).widget_instance()];
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
pub struct FailedToLoadDocumentsDialog {
|
||||
pub failed_document_names: Vec<String>,
|
||||
}
|
||||
|
||||
impl DialogLayoutHolder for FailedToLoadDocumentsDialog {
|
||||
const ICON: &'static str = "Warning";
|
||||
const TITLE: &'static str = "Failed to Open Documents";
|
||||
|
||||
fn layout_buttons(&self) -> Layout {
|
||||
let widgets = vec![
|
||||
TextButton::new("Download")
|
||||
.emphasized(true)
|
||||
.tooltip_description("Save the raw document data to disk so it can be recovered later.")
|
||||
.on_update(|_| {
|
||||
DialogMessage::CloseAndThen {
|
||||
followups: vec![PortfolioMessage::DownloadFailedToLoadDocuments.into()],
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
TextButton::new("Discard")
|
||||
.tooltip_description("Permanently delete the autosaved data for these documents.")
|
||||
.on_update(|_| {
|
||||
DialogMessage::CloseAndThen {
|
||||
followups: vec![PortfolioMessage::DiscardFailedToLoadDocuments.into()],
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
TextButton::new("Dismiss")
|
||||
.tooltip_description("Close this dialog. The autosaved data is kept and this dialog will reappear on next launch.")
|
||||
.on_update(|_| FrontendMessage::DialogClose.into())
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
Layout(vec![LayoutGroup::row(widgets)])
|
||||
}
|
||||
}
|
||||
|
||||
impl LayoutHolder for FailedToLoadDocumentsDialog {
|
||||
fn layout(&self) -> Layout {
|
||||
let count = self.failed_document_names.len();
|
||||
let header = format!("{count} document{} couldn't be reopened.", if count == 1 { "" } else { "s" });
|
||||
let list = "• ".to_string() + &self.failed_document_names.join("\n• ");
|
||||
let plural_s = if count == 1 { "" } else { "s" };
|
||||
let plural_it_them = if count == 1 { "it" } else { "them" };
|
||||
|
||||
Layout(vec![
|
||||
LayoutGroup::row(vec![TextLabel::new(header).bold(true).multiline(true).widget_instance()]),
|
||||
LayoutGroup::row(vec![
|
||||
TextLabel::new(format!(
|
||||
"Sorry about that!\n\
|
||||
This shouldn't happen, and we'd like to help.\n\
|
||||
\n\
|
||||
Click \"Download\" to save a copy of the affected file{plural_s},\n\
|
||||
then please share {plural_it_them} with us so we can investigate:"
|
||||
))
|
||||
.multiline(true)
|
||||
.widget_instance(),
|
||||
]),
|
||||
LayoutGroup::row(vec![
|
||||
TextButton::new("Ask on Discord")
|
||||
.icon("Volunteer")
|
||||
.flush(true)
|
||||
.on_update(|_| {
|
||||
FrontendMessage::TriggerVisitLink {
|
||||
url: "https://discord.graphite.art".into(),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
]),
|
||||
LayoutGroup::row(vec![
|
||||
TextButton::new("Report on GitHub")
|
||||
.icon("Bug")
|
||||
.flush(true)
|
||||
.on_update(|_| {
|
||||
FrontendMessage::TriggerVisitLink {
|
||||
url: "https://github.com/GraphiteEditor/Graphite/issues/new".into(),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
]),
|
||||
LayoutGroup::row(vec![
|
||||
TextLabel::new(
|
||||
"In the meantime, you can keep working in the\n\
|
||||
previous version of Graphite:",
|
||||
)
|
||||
.multiline(true)
|
||||
.widget_instance(),
|
||||
]),
|
||||
LayoutGroup::row(vec![
|
||||
TextButton::new("Sept. 2025 Release")
|
||||
.icon("GraphiteLogo")
|
||||
.flush(true)
|
||||
.on_update(|_| {
|
||||
FrontendMessage::TriggerVisitLink {
|
||||
url: "https://57130155.graphite.pages.dev/".into(),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
]),
|
||||
LayoutGroup::row(vec![TextLabel::new(format!("Affected document{plural_s}:\n{list}")).multiline(true).widget_instance()]),
|
||||
])
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
pub struct FailedToOpenDocumentDialog {
|
||||
pub document_name: String,
|
||||
}
|
||||
|
||||
impl DialogLayoutHolder for FailedToOpenDocumentDialog {
|
||||
const ICON: &'static str = "Warning";
|
||||
const TITLE: &'static str = "Failed to Open Document";
|
||||
|
||||
fn layout_buttons(&self) -> Layout {
|
||||
let widgets = vec![TextButton::new("OK").emphasized(true).on_update(|_| FrontendMessage::DialogClose.into()).widget_instance()];
|
||||
Layout(vec![LayoutGroup::row(widgets)])
|
||||
}
|
||||
}
|
||||
|
||||
impl LayoutHolder for FailedToOpenDocumentDialog {
|
||||
fn layout(&self) -> Layout {
|
||||
let header = if self.document_name.trim().is_empty() {
|
||||
"The document couldn't be opened.".to_string()
|
||||
} else {
|
||||
format!("\"{}\" couldn't be opened.", self.document_name)
|
||||
};
|
||||
|
||||
Layout(vec![
|
||||
LayoutGroup::row(vec![TextLabel::new(header).bold(true).multiline(true).widget_instance()]),
|
||||
LayoutGroup::row(vec![
|
||||
TextLabel::new(
|
||||
"Sorry about that!\n\
|
||||
This shouldn't happen, and we'd like to help.\n\
|
||||
\n\
|
||||
Please share the file with us so we can investigate:",
|
||||
)
|
||||
.multiline(true)
|
||||
.widget_instance(),
|
||||
]),
|
||||
LayoutGroup::row(vec![
|
||||
TextButton::new("Ask on Discord")
|
||||
.icon("Volunteer")
|
||||
.flush(true)
|
||||
.on_update(|_| {
|
||||
FrontendMessage::TriggerVisitLink {
|
||||
url: "https://discord.graphite.art".into(),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
]),
|
||||
LayoutGroup::row(vec![
|
||||
TextButton::new("Report on GitHub")
|
||||
.icon("Bug")
|
||||
.flush(true)
|
||||
.on_update(|_| {
|
||||
FrontendMessage::TriggerVisitLink {
|
||||
url: "https://github.com/GraphiteEditor/Graphite/issues/new".into(),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
]),
|
||||
LayoutGroup::row(vec![
|
||||
TextLabel::new(
|
||||
"In the meantime, you can keep working in the\n\
|
||||
previous version of Graphite:",
|
||||
)
|
||||
.multiline(true)
|
||||
.widget_instance(),
|
||||
]),
|
||||
LayoutGroup::row(vec![
|
||||
TextButton::new("Sept. 2025 Release")
|
||||
.icon("GraphiteLogo")
|
||||
.flush(true)
|
||||
.on_update(|_| {
|
||||
FrontendMessage::TriggerVisitLink {
|
||||
url: "https://57130155.graphite.pages.dev/".into(),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
]),
|
||||
])
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,6 @@ mod close_document_dialog;
|
||||
mod confirm_restart_dialog;
|
||||
mod demo_artwork_dialog;
|
||||
mod error_dialog;
|
||||
mod failed_to_load_documents_dialog;
|
||||
mod failed_to_open_document_dialog;
|
||||
mod licenses_dialog;
|
||||
mod licenses_third_party_dialog;
|
||||
|
||||
@@ -16,7 +14,5 @@ pub use confirm_restart_dialog::ConfirmRestartDialog;
|
||||
pub use demo_artwork_dialog::ARTWORK;
|
||||
pub use demo_artwork_dialog::DemoArtworkDialog;
|
||||
pub use error_dialog::ErrorDialog;
|
||||
pub use failed_to_load_documents_dialog::FailedToLoadDocumentsDialog;
|
||||
pub use failed_to_open_document_dialog::FailedToOpenDocumentDialog;
|
||||
pub use licenses_dialog::LicensesDialog;
|
||||
pub use licenses_third_party_dialog::LicensesThirdPartyDialog;
|
||||
@@ -13,9 +13,9 @@ use crate::messages::portfolio::utility_types::WorkspacePanelLayout;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::tool_messages::eyedropper_tool::PrimarySecondary;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::vector::style::FillChoiceUI;
|
||||
use graphene_std::raster::color::Color;
|
||||
use graphene_std::text::{Font, TextAlign};
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
@@ -50,9 +50,7 @@ pub enum FrontendMessage {
|
||||
max_width: Option<f64>,
|
||||
#[serde(rename = "maxHeight")]
|
||||
max_height: Option<f64>,
|
||||
align: String,
|
||||
#[serde(rename = "alignLast")]
|
||||
align_last: String,
|
||||
align: TextAlign,
|
||||
},
|
||||
DisplayEditableTextboxUpdateFontData {
|
||||
#[serde(rename = "fontData")]
|
||||
@@ -110,6 +108,11 @@ pub enum FrontendMessage {
|
||||
name: String,
|
||||
filename: String,
|
||||
},
|
||||
TriggerFontCatalogLoad,
|
||||
TriggerFontDataLoad {
|
||||
font: Font,
|
||||
url: String,
|
||||
},
|
||||
TriggerPersistenceReadState,
|
||||
TriggerPersistenceReadDocument {
|
||||
#[serde(rename = "documentId")]
|
||||
@@ -136,11 +139,6 @@ pub enum FrontendMessage {
|
||||
preferences: PreferencesMessageHandler,
|
||||
},
|
||||
TriggerTextCommit,
|
||||
/// Asks the frontend to enter inline-rename mode for a layer in the graph view.
|
||||
TriggerEditLayerNameInGraph {
|
||||
#[serde(rename = "nodeId")]
|
||||
node_id: NodeId,
|
||||
},
|
||||
TriggerVisitLink {
|
||||
url: String,
|
||||
},
|
||||
@@ -161,17 +159,9 @@ pub enum FrontendMessage {
|
||||
document_id: DocumentId,
|
||||
},
|
||||
UpdateGradientStopColorPickerPosition {
|
||||
color: SRGBA8, // TODO: Color (without `none`) -> Color (with `none`)
|
||||
color: Color, // TODO: Color (without `none`) -> Color (with `none`)
|
||||
position: (f64, f64),
|
||||
},
|
||||
/// The Rust color picker handler picked a new color/gradient. The frontend `<ColorPicker />` forwards this as its `colorOrGradient` event.
|
||||
ColorPickerColorChanged {
|
||||
value: FillChoiceUI,
|
||||
},
|
||||
/// The Rust color picker handler is starting an undo transaction. The frontend `<ColorPicker />` forwards this as its `startHistoryTransaction` event.
|
||||
ColorPickerStartHistoryTransaction,
|
||||
/// The Rust color picker handler is committing the in-flight undo transaction. The frontend `<ColorPicker />` forwards this as its `commitHistoryTransaction` event.
|
||||
ColorPickerCommitHistoryTransaction,
|
||||
UpdateImportsExports {
|
||||
/// If the primary import is not visible, then it is None.
|
||||
imports: Vec<Option<FrontendGraphOutput>>,
|
||||
@@ -235,7 +225,7 @@ pub enum FrontendMessage {
|
||||
svg: String,
|
||||
},
|
||||
UpdateImageData {
|
||||
image_data: Vec<(u64, Image<SRGBA8>)>,
|
||||
image_data: Vec<(u64, Image<Color>)>,
|
||||
},
|
||||
UpdateDocumentLayerDetails {
|
||||
data: LayerPanelEntry,
|
||||
@@ -249,10 +239,6 @@ pub enum FrontendMessage {
|
||||
spacing: f64,
|
||||
interval: f64,
|
||||
visible: bool,
|
||||
tilt: f64,
|
||||
flip: bool,
|
||||
#[serde(rename = "selectionQuad")]
|
||||
selection_quad: Option<[(f64, f64); 4]>,
|
||||
},
|
||||
UpdateDocumentScrollbars {
|
||||
position: (f64, f64),
|
||||
@@ -356,8 +342,6 @@ pub enum FrontendMessage {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
WindowHide,
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
WindowFocus,
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
WindowHideOthers,
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
WindowShowAll,
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use graph_craft::application_io::resource::ResourceHash;
|
||||
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::utility_types::WorkspacePanelLayout;
|
||||
use crate::messages::prelude::*;
|
||||
@@ -12,14 +10,11 @@ pub struct DocumentInfo {
|
||||
pub id: DocumentId,
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
#[cfg_attr(feature = "wasm", tsify(type = "unknown"))]
|
||||
pub resources: Option<Box<[ResourceHash]>>,
|
||||
#[serde(default)]
|
||||
pub path: Option<PathBuf>,
|
||||
pub is_saved: bool,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints, from_wasm_abi))]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
|
||||
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PersistedState {
|
||||
pub documents: Vec<DocumentInfo>,
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
use crate::messages::future::MessageFuture;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[impl_message(Message, Future)]
|
||||
#[derive(derivative::Derivative, Clone, serde::Serialize, serde::Deserialize)]
|
||||
#[derivative(Debug, PartialEq)]
|
||||
pub enum FutureMessage {
|
||||
/// Spawn `future`; its resolved [`Message`] re-enters the dispatcher on the next tick.
|
||||
Await {
|
||||
#[serde(skip, default)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
future: MessageFuture,
|
||||
},
|
||||
/// Sent by a wake callback to nudge an idle event loop into a dispatch tick.
|
||||
Wake,
|
||||
}
|
||||
@@ -1,193 +0,0 @@
|
||||
use std::future::{Future, IntoFuture};
|
||||
use std::pin::Pin;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use dyn_any::WasmNotSend;
|
||||
use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender, unbounded};
|
||||
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
type InnerMessageFuture = Pin<Box<dyn Future<Output = Message> + Send + 'static>>;
|
||||
#[cfg(target_family = "wasm")]
|
||||
type InnerMessageFuture = Pin<Box<dyn Future<Output = Message> + 'static>>;
|
||||
|
||||
/// Invoked by the spawner after a result is sent, to wake the platform event loop.
|
||||
pub type Wake = Arc<dyn Fn() + Send + Sync>;
|
||||
|
||||
fn noop_wake() -> Wake {
|
||||
Arc::new(|| {})
|
||||
}
|
||||
|
||||
/// One-shot async work whose result re-enters the dispatcher as a [`Message`].
|
||||
/// Resolves to [`Message::NoOp`] if polled after the inner future has already been taken.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct MessageFuture {
|
||||
inner: Arc<Mutex<Option<InnerMessageFuture>>>,
|
||||
}
|
||||
|
||||
impl MessageFuture {
|
||||
pub fn new(future: impl Future<Output = Message> + WasmNotSend + 'static) -> Self {
|
||||
Self {
|
||||
inner: Arc::new(Mutex::new(Some(Box::pin(future)))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoFuture for MessageFuture {
|
||||
type Output = Message;
|
||||
type IntoFuture = InnerMessageFuture;
|
||||
|
||||
fn into_future(self) -> Self::IntoFuture {
|
||||
let taken = self.inner.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).take();
|
||||
match taken {
|
||||
Some(future) => future,
|
||||
None => Box::pin(async { Message::NoOp }),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<MessageFuture> for Message {
|
||||
fn from(future: MessageFuture) -> Self {
|
||||
FutureMessage::Await { future }.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<T> for Message
|
||||
where
|
||||
T: Future<Output = Message> + WasmNotSend + 'static,
|
||||
{
|
||||
fn from(future: T) -> Self {
|
||||
MessageFuture::new(future).into()
|
||||
}
|
||||
}
|
||||
|
||||
/// Platform-specific async-task executor.
|
||||
/// Runs `future`, sends the resolved message on `results`, then calls `wake`.
|
||||
pub trait MessageSpawner: Send + Sync {
|
||||
fn spawn(&self, future: InnerMessageFuture, results: UnboundedSender<Message>, wake: Wake);
|
||||
}
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct FutureMessageContext {}
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct FutureMessageHandler {
|
||||
spawner: Arc<dyn MessageSpawner>,
|
||||
wake: Wake,
|
||||
results_sender: UnboundedSender<Message>,
|
||||
results_receiver: UnboundedReceiver<Message>,
|
||||
}
|
||||
|
||||
impl FutureMessageHandler {
|
||||
pub fn with_wake(wake: Wake) -> Self {
|
||||
let (results_sender, results_receiver) = unbounded();
|
||||
Self {
|
||||
spawner: default_spawner(),
|
||||
wake,
|
||||
results_sender,
|
||||
results_receiver,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_wake(&mut self, wake: Wake) {
|
||||
self.wake = wake;
|
||||
}
|
||||
|
||||
/// Pull every resolved async result into `out`.
|
||||
pub fn drain_results(&mut self, out: &mut VecDeque<Message>) {
|
||||
while let Ok(Some(message)) = self.results_receiver.try_next() {
|
||||
out.push_back(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for FutureMessageHandler {
|
||||
fn default() -> Self {
|
||||
Self::with_wake(noop_wake())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for FutureMessageHandler {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("FutureMessageHandler").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<FutureMessage, FutureMessageContext> for FutureMessageHandler {
|
||||
fn process_message(&mut self, message: FutureMessage, _responses: &mut VecDeque<Message>, _context: FutureMessageContext) {
|
||||
match message {
|
||||
FutureMessage::Await { future } => {
|
||||
self.spawner.spawn(future.into_future(), self.results_sender.clone(), self.wake.clone());
|
||||
}
|
||||
FutureMessage::Wake => {
|
||||
// Tick-only message: the dispatcher's top-of-tick drain handles the real work.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
advertise_actions!(FutureMessageDiscriminant;);
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
fn default_spawner() -> Arc<dyn MessageSpawner> {
|
||||
Arc::new(TokioSpawner::default())
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
fn default_spawner() -> Arc<dyn MessageSpawner> {
|
||||
Arc::new(WasmSpawner)
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
struct TokioSpawner {
|
||||
/// Built lazily on first spawn. `multi_thread(1)` lets Tokio manage its own driver.
|
||||
runtime: std::sync::OnceLock<tokio::runtime::Runtime>,
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl Default for TokioSpawner {
|
||||
fn default() -> Self {
|
||||
Self { runtime: std::sync::OnceLock::new() }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl TokioSpawner {
|
||||
fn runtime(&self) -> &tokio::runtime::Runtime {
|
||||
self.runtime.get_or_init(|| {
|
||||
tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(1)
|
||||
.thread_name("graphite-async")
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("failed to construct async-message tokio runtime")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl MessageSpawner for TokioSpawner {
|
||||
fn spawn(&self, future: InnerMessageFuture, results: UnboundedSender<Message>, wake: Wake) {
|
||||
self.runtime().spawn(async move {
|
||||
let message = future.await;
|
||||
let _ = results.unbounded_send(message);
|
||||
wake();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
struct WasmSpawner;
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
impl MessageSpawner for WasmSpawner {
|
||||
fn spawn(&self, future: InnerMessageFuture, results: UnboundedSender<Message>, wake: Wake) {
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let message = future.await;
|
||||
let _ = results.unbounded_send(message);
|
||||
wake();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
mod future_message;
|
||||
mod future_message_handler;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use future_message::{FutureMessage, FutureMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use future_message_handler::{FutureMessageContext, FutureMessageHandler, MessageFuture, MessageSpawner, Wake};
|
||||
@@ -26,8 +26,4 @@ pub enum LayoutMessage {
|
||||
widget_id: WidgetId,
|
||||
value: serde_json::Value,
|
||||
},
|
||||
WidgetValueDragDrop {
|
||||
layout_target: LayoutTarget,
|
||||
widget_id: WidgetId,
|
||||
},
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::vector::style::FillChoiceUI;
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -62,19 +61,6 @@ impl MessageHandler<LayoutMessage, LayoutMessageContext<'_>> for LayoutMessageHa
|
||||
LayoutMessage::WidgetValueUpdate { layout_target, widget_id, value } => {
|
||||
self.handle_widget_callback(layout_target, widget_id, value, WidgetValueAction::Update, responses);
|
||||
}
|
||||
LayoutMessage::WidgetValueDragDrop { layout_target, widget_id } => {
|
||||
let Some(layout) = self.layouts.get_mut(layout_target as usize) else {
|
||||
warn!("WidgetValueDragDrop referenced an invalid layout. `widget_id: {widget_id}`, `layout_target: {layout_target:?}`");
|
||||
return;
|
||||
};
|
||||
let Some(widget_instance) = layout.iter_mut().find(|widget| widget.widget_id == widget_id) else {
|
||||
warn!("WidgetValueDragDrop referenced an invalid widget ID. `widget_id: {widget_id}`, `layout_target: {layout_target:?}`");
|
||||
return;
|
||||
};
|
||||
if let Widget::IconButton(icon_button) = &mut *widget_instance.widget {
|
||||
responses.add((icon_button.on_drag_drop.callback)(icon_button));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,22 +102,22 @@ impl LayoutMessageHandler {
|
||||
}
|
||||
LayoutGroup::Table(WidgetTable { rows, .. }) => {
|
||||
for (row_index, row) in rows.iter().enumerate() {
|
||||
for (value_index, value) in row.iter().enumerate() {
|
||||
for (cell_index, cell) in row.iter().enumerate() {
|
||||
// Return if this is the correct ID
|
||||
if value.widget_id == widget_id {
|
||||
if cell.widget_id == widget_id {
|
||||
widget_path.push(row_index);
|
||||
widget_path.push(value_index);
|
||||
return Some((value, widget_path));
|
||||
widget_path.push(cell_index);
|
||||
return Some((cell, widget_path));
|
||||
}
|
||||
|
||||
if let Widget::PopoverButton(popover) = &*value.widget {
|
||||
if let Widget::PopoverButton(popover) = &*cell.widget {
|
||||
stack.extend(
|
||||
popover
|
||||
.popover_layout
|
||||
.0
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(child, val)| ([widget_path.as_slice(), &[row_index, value_index, child]].concat(), val)),
|
||||
.map(|(child, val)| ([widget_path.as_slice(), &[row_index, cell_index, child]].concat(), val)),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -181,38 +167,31 @@ impl LayoutMessageHandler {
|
||||
};
|
||||
responses.add(callback_message);
|
||||
}
|
||||
Widget::ColorComparisonInput(color_comparison_input) => {
|
||||
let callback_message = match action {
|
||||
WidgetValueAction::Commit => (color_comparison_input.on_commit.callback)(&()),
|
||||
WidgetValueAction::Update => (color_comparison_input.on_update.callback)(&()),
|
||||
};
|
||||
|
||||
responses.add(callback_message);
|
||||
}
|
||||
Widget::ColorInput(color_button) => {
|
||||
let callback_message = match action {
|
||||
WidgetValueAction::Commit => (color_button.on_commit.callback)(&()),
|
||||
WidgetValueAction::Update => {
|
||||
let Ok(fill_choice_ui) = serde_json::from_value::<FillChoiceUI>(value) else {
|
||||
warn!("ColorInput update was not able to be parsed as FillChoiceUI: {color_button:?}");
|
||||
let Ok(fill_choice) = serde_json::from_value::<FillChoice>(value) else {
|
||||
warn!("ColorInput update was not able to be parsed as FillChoice: {color_button:?}");
|
||||
return;
|
||||
};
|
||||
color_button.value = fill_choice_ui;
|
||||
color_button.value = fill_choice;
|
||||
(color_button.on_update.callback)(color_button)
|
||||
}
|
||||
};
|
||||
|
||||
responses.add(callback_message);
|
||||
}
|
||||
Widget::ColorPresetsInput(color_presets_input) => {
|
||||
Widget::CurveInput(curve_input) => {
|
||||
let callback_message = match action {
|
||||
WidgetValueAction::Commit => (color_presets_input.on_commit.callback)(&()),
|
||||
WidgetValueAction::Commit => (curve_input.on_commit.callback)(&()),
|
||||
WidgetValueAction::Update => {
|
||||
let Ok(update) = serde_json::from_value::<ColorPresetsInputUpdate>(value) else {
|
||||
warn!("ColorPresetsInput update was not able to be parsed as ColorPresetsInputUpdate");
|
||||
let Some(curve) = serde_json::from_value(value).ok() else {
|
||||
error!("CurveInput event data could not be deserialized");
|
||||
return;
|
||||
};
|
||||
(color_presets_input.on_update.callback)(&update)
|
||||
curve_input.value = curve;
|
||||
(curve_input.on_update.callback)(curve_input)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -247,25 +226,6 @@ impl LayoutMessageHandler {
|
||||
|
||||
responses.add(callback_message);
|
||||
}
|
||||
Widget::SpectrumInput(spectrum_input) => {
|
||||
let callback_message = match action {
|
||||
WidgetValueAction::Commit => (spectrum_input.on_commit.callback)(&()),
|
||||
WidgetValueAction::Update => {
|
||||
let Ok(update) = serde_json::from_value::<SpectrumInputUpdate>(value) else {
|
||||
warn!("SpectrumInput update was not able to be parsed as SpectrumInputUpdate");
|
||||
return;
|
||||
};
|
||||
// Don't mutate the stored widget here: leaving its old values lets the layout diff detect a change
|
||||
// when the new layout is rebuilt with the updated state. Otherwise the frontend's stored layout
|
||||
// keeps stale values for `activeMarkerIndex`, etc., and any other widget's diff (e.g. the position
|
||||
// NumberInput) will trigger Svelte to re-spread those stale props onto SpectrumInput, clobbering
|
||||
// its local `activeMarkerIndex` and making subsequent drags target the wrong stop.
|
||||
(spectrum_input.on_update.callback)(&update)
|
||||
}
|
||||
};
|
||||
|
||||
responses.add(callback_message);
|
||||
}
|
||||
Widget::IconButton(icon_button) => {
|
||||
let callback_message = match action {
|
||||
WidgetValueAction::Commit => (icon_button.on_commit.callback)(&()),
|
||||
@@ -423,23 +383,6 @@ impl LayoutMessageHandler {
|
||||
responses.add(callback_message);
|
||||
}
|
||||
Widget::TextLabel(_) => {}
|
||||
Widget::VisualColorPickersInput(visual_color_pickers_input) => {
|
||||
let callback_message = match action {
|
||||
WidgetValueAction::Commit => (visual_color_pickers_input.on_commit.callback)(&()),
|
||||
WidgetValueAction::Update => {
|
||||
let Ok(update) = serde_json::from_value::<VisualColorPickersInputUpdate>(value) else {
|
||||
warn!("VisualColorPickersInput update was not able to be parsed as VisualColorPickersInputUpdate");
|
||||
return;
|
||||
};
|
||||
// Don't mutate the stored widget here: leaving its old values lets the layout diff detect a change
|
||||
// when the new layout is rebuilt with the updated state, so the visual indicators (selection circle,
|
||||
// hue/alpha needles, saturation-val ue gradient background) actually re-render after a drag.
|
||||
(visual_color_pickers_input.on_update.callback)(&update)
|
||||
}
|
||||
};
|
||||
|
||||
responses.add(callback_message);
|
||||
}
|
||||
Widget::WorkingColorsInput(_) => {}
|
||||
};
|
||||
}
|
||||
@@ -452,17 +395,14 @@ impl LayoutMessageHandler {
|
||||
responses: &mut VecDeque<Message>,
|
||||
action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>,
|
||||
) {
|
||||
// Collect CheckboxId mappings from new layout
|
||||
// Step 1: Collect CheckboxId mappings from new layout
|
||||
let mut checkbox_map = HashMap::new();
|
||||
new_layout.collect_checkbox_ids(layout_target, &mut Vec::new(), &mut checkbox_map);
|
||||
|
||||
// Replace all IDs in new layout with deterministic ones
|
||||
// Step 2: Replace all IDs in new layout with deterministic ones
|
||||
new_layout.replace_widget_ids(layout_target, &mut Vec::new(), &checkbox_map);
|
||||
|
||||
// Populate computed display fields on widgets that need derived values
|
||||
populate_computed_display_fields(&mut new_layout);
|
||||
|
||||
// Diff with deterministic IDs
|
||||
// Step 3: Diff with deterministic IDs
|
||||
let mut widget_diffs = Vec::new();
|
||||
|
||||
self.layouts[layout_target as usize].diff(new_layout, &mut Vec::new(), &mut widget_diffs);
|
||||
@@ -500,27 +440,3 @@ enum WidgetValueAction {
|
||||
Commit,
|
||||
Update,
|
||||
}
|
||||
|
||||
/// Walk all widgets in the layout and populate computed display fields (e.g., precomputed CSS gradient strings) so the frontend can render them without making Wasm round-trip calls. Mutates fields in place.
|
||||
fn populate_computed_display_fields(layout: &mut Layout) {
|
||||
for instance in layout.iter_mut() {
|
||||
match &mut *instance.widget {
|
||||
Widget::ColorInput(color_input) => {
|
||||
color_input.chosen_gradient = color_input.value.to_css_background_image();
|
||||
}
|
||||
Widget::SpectrumInput(spectrum_input) => {
|
||||
spectrum_input.track_css = spectrum_input.track.to_css_linear_gradient();
|
||||
spectrum_input.track_start_css = spectrum_input.track.color.first().map(|color| color.to_css_hex()).unwrap_or_else(|| "black".to_string());
|
||||
spectrum_input.track_end_css = spectrum_input.track.color.last().map(|color| color.to_css_hex()).unwrap_or_else(|| "black".to_string());
|
||||
}
|
||||
Widget::ColorComparisonInput(comparison) => {
|
||||
let contrasting = |color: Option<SRGBA8>| color.map_or(SRGBA8::BLACK, |color| color.contrasting_text_color()).to_css_hex();
|
||||
comparison.new_color_css = comparison.new_color.map(|color| color.to_css_hex()).unwrap_or_default();
|
||||
comparison.new_color_contrasting = contrasting(comparison.new_color);
|
||||
comparison.old_color_css = comparison.old_color.map(|color| color.to_css_hex()).unwrap_or_default();
|
||||
comparison.old_color_contrasting = contrasting(comparison.old_color);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,7 @@ impl core::fmt::Display for WidgetId {
|
||||
|
||||
macro_rules! define_layout_target {
|
||||
($($(#[$attr:meta])* $variant:ident),* $(,)?) => {
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(PartialEq, Clone, Debug, Hash, Eq, Copy, serde::Serialize, serde::Deserialize)]
|
||||
#[repr(u8)]
|
||||
pub enum LayoutTarget {
|
||||
@@ -44,11 +44,7 @@ macro_rules! define_layout_target {
|
||||
};
|
||||
}
|
||||
define_layout_target!(
|
||||
/// Left column of the color picker popover, containing the visual H/S/V/A sliders and (optionally) the gradient editor.
|
||||
ColorPickerPickersAndGradient,
|
||||
/// Right column of the color picker popover, containing the new/old color comparison swatch, hex/RGB/HSV/alpha numeric inputs, and color preset buttons.
|
||||
ColorPickerDetails,
|
||||
/// The Data panel visualizes the output data flowing through the selected node in the graph.
|
||||
/// The spreadsheet panel allows for the visualisation of data in the graph.
|
||||
DataPanel,
|
||||
/// Contains the action buttons at the bottom of the dialog. Must be shown with the `FrontendMessage::DisplayDialog` message.
|
||||
DialogButtons,
|
||||
@@ -428,6 +424,7 @@ impl LayoutGroup {
|
||||
let val = match &mut *widget.widget {
|
||||
Widget::CheckboxInput(x) => &mut x.tooltip_description,
|
||||
Widget::ColorInput(x) => &mut x.tooltip_description,
|
||||
Widget::CurveInput(x) => &mut x.tooltip_description,
|
||||
Widget::DropdownInput(x) => &mut x.tooltip_description,
|
||||
Widget::IconButton(x) => &mut x.tooltip_description,
|
||||
Widget::IconLabel(x) => &mut x.tooltip_description,
|
||||
@@ -446,11 +443,7 @@ impl LayoutGroup {
|
||||
| Widget::ShortcutLabel(_)
|
||||
| Widget::WorkingColorsInput(_)
|
||||
| Widget::NodeCatalog(_)
|
||||
| Widget::ParameterExposeButton(_)
|
||||
| Widget::ColorComparisonInput(_)
|
||||
| Widget::ColorPresetsInput(_)
|
||||
| Widget::SpectrumInput(_)
|
||||
| Widget::VisualColorPickersInput(_) => continue,
|
||||
| Widget::ParameterExposeButton(_) => continue,
|
||||
};
|
||||
if val.is_empty() {
|
||||
val.clone_from(&description);
|
||||
@@ -668,7 +661,6 @@ impl Diffable for WidgetInstance {
|
||||
&& button1.tooltip_description == button2.tooltip_description
|
||||
&& button1.tooltip_shortcut == button2.tooltip_shortcut
|
||||
&& button1.popover_min_width == button2.popover_min_width
|
||||
&& button1.popover_layout.0.len() == button2.popover_layout.0.len()
|
||||
{
|
||||
// Only the popover layout differs, diff it recursively
|
||||
for (i, (a, b)) in button1.popover_layout.0.iter_mut().zip(button2.popover_layout.0.iter()).enumerate() {
|
||||
@@ -766,9 +758,8 @@ impl<T> Default for WidgetCallback<T> {
|
||||
pub enum Widget {
|
||||
BreadcrumbTrailButtons(BreadcrumbTrailButtons),
|
||||
CheckboxInput(CheckboxInput),
|
||||
ColorComparisonInput(ColorComparisonInput),
|
||||
ColorInput(ColorInput),
|
||||
ColorPresetsInput(ColorPresetsInput),
|
||||
CurveInput(CurveInput),
|
||||
DropdownInput(DropdownInput),
|
||||
IconButton(IconButton),
|
||||
IconLabel(IconLabel),
|
||||
@@ -782,12 +773,10 @@ pub enum Widget {
|
||||
PopoverButton(PopoverButton),
|
||||
RadioInput(RadioInput),
|
||||
Separator(Separator),
|
||||
SpectrumInput(SpectrumInput),
|
||||
TextAreaInput(TextAreaInput),
|
||||
TextButton(TextButton),
|
||||
TextInput(TextInput),
|
||||
TextLabel(TextLabel),
|
||||
VisualColorPickersInput(VisualColorPickersInput),
|
||||
WorkingColorsInput(WorkingColorsInput),
|
||||
}
|
||||
|
||||
@@ -796,7 +785,7 @@ pub enum Widget {
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct WidgetDiff {
|
||||
/// A path to the change
|
||||
/// e.g. [0, 1, 2] in the Properties panel is the first section, second row and third widget.
|
||||
/// e.g. [0, 1, 2] in the properties panel is the first section, second row and third widget.
|
||||
/// An empty path [] shows that the entire panel has changed and is sent when the UI is first created.
|
||||
#[serde(rename = "widgetPath")]
|
||||
pub widget_path: Vec<usize>,
|
||||
@@ -837,6 +826,7 @@ impl DiffUpdate {
|
||||
Widget::ShortcutLabel(widget) => widget.shortcut.as_mut(),
|
||||
Widget::IconLabel(_)
|
||||
| Widget::ImageLabel(_)
|
||||
| Widget::CurveInput(_)
|
||||
| Widget::NodeCatalog(_)
|
||||
| Widget::ReferencePointInput(_)
|
||||
| Widget::RadioInput(_)
|
||||
@@ -844,11 +834,7 @@ impl DiffUpdate {
|
||||
| Widget::TextAreaInput(_)
|
||||
| Widget::TextInput(_)
|
||||
| Widget::TextLabel(_)
|
||||
| Widget::WorkingColorsInput(_)
|
||||
| Widget::ColorComparisonInput(_)
|
||||
| Widget::ColorPresetsInput(_)
|
||||
| Widget::SpectrumInput(_)
|
||||
| Widget::VisualColorPickersInput(_) => None,
|
||||
| Widget::WorkingColorsInput(_) => None,
|
||||
};
|
||||
|
||||
// Convert `ActionShortcut::Action` to `ActionShortcut::Shortcut`
|
||||
|
||||
@@ -4,7 +4,7 @@ use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::WidgetCallback;
|
||||
use derivative::*;
|
||||
use graphene_std::vector::style::FillChoiceUI;
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
use graphite_proc_macros::WidgetBuilder;
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -39,9 +39,6 @@ pub struct IconButton {
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_drag_drop: WidgetCallback<IconButton>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -190,13 +187,9 @@ pub struct ImageButton {
|
||||
#[derivative(Debug, PartialEq, Default)]
|
||||
pub struct ColorInput {
|
||||
// Content
|
||||
/// WARNING: The colors are gamma, not linear!
|
||||
#[widget_builder(constructor)]
|
||||
pub value: FillChoiceUI,
|
||||
/// CSS `linear-gradient(...)` (or solid-color stand-in) for the swatch's `background-image`. Auto-populated from `value` at layout-send time.
|
||||
/// `None` when `value` is `FillChoiceUI::None`, in which case the frontend uses its "none" fallback styling.
|
||||
#[serde(rename = "chosenGradient")]
|
||||
#[widget_builder(skip)]
|
||||
pub chosen_gradient: Option<String>,
|
||||
pub value: FillChoice,
|
||||
#[serde(rename = "allowNone")]
|
||||
#[derivative(Default(value = "true"))]
|
||||
pub allow_none: bool,
|
||||
@@ -204,13 +197,6 @@ pub struct ColorInput {
|
||||
#[serde(rename = "menuDirection")]
|
||||
pub menu_direction: Option<MenuDirection>,
|
||||
pub disabled: bool,
|
||||
pub mixed: bool,
|
||||
|
||||
// Sizing
|
||||
#[serde(rename = "minWidth")]
|
||||
pub min_width: u32,
|
||||
#[serde(rename = "maxWidth")]
|
||||
pub max_width: u32,
|
||||
|
||||
// Styling
|
||||
pub narrow: bool,
|
||||
|
||||
@@ -4,9 +4,8 @@ use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use derivative::*;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::raster::curve::Curve;
|
||||
use graphene_std::transform::ReferencePoint;
|
||||
use graphene_std::vector::style::{FillChoiceUI, GradientStopsUI};
|
||||
use graphite_proc_macros::WidgetBuilder;
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -21,7 +20,6 @@ pub struct CheckboxInput {
|
||||
#[serde(rename = "forLabel")]
|
||||
pub for_label: CheckboxId,
|
||||
pub disabled: bool,
|
||||
pub mixed: bool,
|
||||
|
||||
// Tooltips
|
||||
#[serde(rename = "tooltipLabel")]
|
||||
@@ -350,9 +348,9 @@ pub struct RadioEntryData {
|
||||
pub struct WorkingColorsInput {
|
||||
// Content
|
||||
#[widget_builder(constructor)]
|
||||
pub primary: SRGBA8,
|
||||
pub primary: Color,
|
||||
#[widget_builder(constructor)]
|
||||
pub secondary: SRGBA8,
|
||||
pub secondary: Color,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -364,7 +362,6 @@ pub struct TextAreaInput {
|
||||
pub value: String,
|
||||
pub label: Option<String>,
|
||||
pub disabled: bool,
|
||||
pub monospace: bool,
|
||||
|
||||
// Tooltips
|
||||
#[serde(rename = "tooltipLabel")]
|
||||
@@ -421,237 +418,31 @@ pub struct TextInput {
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
}
|
||||
|
||||
// #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
// #[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder)]
|
||||
// #[derivative(Debug, PartialEq, Default)]
|
||||
// pub struct CurveInput {
|
||||
// // Content
|
||||
// #[widget_builder(constructor)]
|
||||
// pub value: Curve,
|
||||
|
||||
// // Tooltips
|
||||
// #[serde(rename = "tooltipLabel")]
|
||||
// pub tooltip_label: String,
|
||||
// #[serde(rename = "tooltipDescription")]
|
||||
// pub tooltip_description: String,
|
||||
// #[serde(rename = "tooltipShortcut")]
|
||||
// pub tooltip_shortcut: Option<ActionShortcut>,
|
||||
|
||||
// // Callbacks
|
||||
// #[serde(skip)]
|
||||
// #[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
// pub on_update: WidgetCallback<CurveInput>,
|
||||
// #[serde(skip)]
|
||||
// #[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
// pub on_commit: WidgetCallback<()>,
|
||||
// }
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Default, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder)]
|
||||
#[derivative(Debug, PartialEq)]
|
||||
pub struct VisualColorPickersInput {
|
||||
// Content
|
||||
pub hue: f64,
|
||||
pub saturation: f64,
|
||||
pub value: f64,
|
||||
pub alpha: f64,
|
||||
#[serde(rename = "isNone")]
|
||||
pub is_none: bool,
|
||||
pub disabled: bool,
|
||||
|
||||
// Callbacks
|
||||
// `on_update` receives the raw `VisualColorPickersInputUpdate` (not the mutated widget) so the layout diffing can still detect a change between the stored layout and the rebuilt one, otherwise the selection circle and slider needles never re-render after a drag.
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_update: WidgetCallback<VisualColorPickersInputUpdate>,
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct VisualColorPickersInputUpdate {
|
||||
pub hue: f64,
|
||||
pub saturation: f64,
|
||||
pub value: f64,
|
||||
pub alpha: f64,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Default, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder)]
|
||||
#[derivative(Debug, PartialEq)]
|
||||
pub struct ColorComparisonInput {
|
||||
// Content
|
||||
#[widget_builder(constructor)]
|
||||
#[serde(rename = "newColor")]
|
||||
pub new_color: Option<SRGBA8>,
|
||||
#[widget_builder(constructor)]
|
||||
#[serde(rename = "oldColor")]
|
||||
pub old_color: Option<SRGBA8>,
|
||||
#[serde(rename = "isNone")]
|
||||
pub is_none: bool,
|
||||
#[serde(rename = "oldIsNone")]
|
||||
pub old_is_none: bool,
|
||||
pub disabled: bool,
|
||||
pub differs: bool,
|
||||
#[serde(rename = "outlineAmount")]
|
||||
pub outline_amount: f64,
|
||||
/// Hex CSS string for the new color (with alpha if not fully opaque), or empty when `is_none`. Auto-populated from `new_color` at layout-send time.
|
||||
#[serde(rename = "newColorCSS")]
|
||||
#[widget_builder(skip)]
|
||||
pub new_color_css: String,
|
||||
/// Black or white, whichever contrasts the new color for legible label text. Auto-populated.
|
||||
#[serde(rename = "newColorContrasting")]
|
||||
#[widget_builder(skip)]
|
||||
pub new_color_contrasting: String,
|
||||
/// Hex CSS string for the old color (with alpha if not fully opaque), or empty when `old_is_none`. Auto-populated.
|
||||
#[serde(rename = "oldColorCSS")]
|
||||
#[widget_builder(skip)]
|
||||
pub old_color_css: String,
|
||||
/// Black or white, whichever contrasts the old color for legible label text. Auto-populated.
|
||||
#[serde(rename = "oldColorContrasting")]
|
||||
#[widget_builder(skip)]
|
||||
pub old_color_contrasting: String,
|
||||
|
||||
// Callbacks
|
||||
// The `swap` event has no payload — it just signals the user requested a swap.
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_update: WidgetCallback<()>,
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Default, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder)]
|
||||
#[derivative(Debug, PartialEq)]
|
||||
pub struct ColorPresetsInput {
|
||||
// Content
|
||||
pub disabled: bool,
|
||||
#[serde(rename = "showNoneOption")]
|
||||
pub show_none_option: bool,
|
||||
|
||||
// Callbacks
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_update: WidgetCallback<ColorPresetsInputUpdate>,
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ColorPresetsInputUpdate {
|
||||
Preset(FillChoiceUI),
|
||||
EyedropperColorCode(String),
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder)]
|
||||
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder)]
|
||||
#[derivative(Debug, PartialEq, Default)]
|
||||
pub struct SpectrumInput {
|
||||
pub struct CurveInput {
|
||||
// Content
|
||||
/// The colored gradient drawn behind the markers (display-only, caller-owned).
|
||||
#[widget_builder(constructor)]
|
||||
pub track: GradientStopsUI,
|
||||
/// CSS `linear-gradient(...)` string for the track strip's `background-image`. Auto-populated from `track` at layout-send time.
|
||||
#[serde(rename = "trackCSS")]
|
||||
#[widget_builder(skip)]
|
||||
pub track_css: String,
|
||||
/// Hex string for the track strip's leftmost solid-color end-cap. Auto-populated from `track`'s first stop.
|
||||
#[serde(rename = "trackStartCSS")]
|
||||
#[widget_builder(skip)]
|
||||
pub track_start_css: String,
|
||||
/// Hex string for the track strip's rightmost solid-color end-cap. Auto-populated from `track`'s last stop.
|
||||
#[serde(rename = "trackEndCSS")]
|
||||
#[widget_builder(skip)]
|
||||
pub track_end_css: String,
|
||||
/// The handles the user can drag along the track. Their handle colors are caller-owned (e.g., for a gradient editor they follow the stop colors, for a "Shadows/Midpoints/Highlights" widget they're hardcoded).
|
||||
pub markers: Vec<SpectrumMarker>,
|
||||
#[serde(rename = "activeMarkerIndex")]
|
||||
pub active_marker_index: Option<u32>,
|
||||
#[serde(rename = "activeMarkerIsMidpoint")]
|
||||
pub active_marker_is_midpoint: bool,
|
||||
/// Whether to render midpoint diamonds between adjacent markers (only meaningful for gradient-like uses).
|
||||
#[serde(rename = "showMidpoints")]
|
||||
pub show_midpoints: bool,
|
||||
/// Whether clicking the track inserts a new marker at the click position.
|
||||
#[serde(rename = "allowInsert")]
|
||||
pub allow_insert: bool,
|
||||
/// Whether right-click or pressing Delete removes a marker. The handler still has the final say on whether the deletion goes through (e.g., enforcing a minimum count).
|
||||
#[serde(rename = "allowDelete")]
|
||||
pub allow_delete: bool,
|
||||
/// Whether dragging a marker past another reorders them. If false, the dragged marker is clamped between its neighbors.
|
||||
#[serde(rename = "allowReorder")]
|
||||
pub allow_reorder: bool,
|
||||
/// Compact mode: 8px track height with 8px top padding, for use in rows alongside other widgets.
|
||||
pub narrow: bool,
|
||||
/// Whether the input is disabled (dimmed and read-only).
|
||||
pub disabled: bool,
|
||||
pub value: Curve,
|
||||
|
||||
// Tooltips
|
||||
#[serde(rename = "tooltipLabel")]
|
||||
pub tooltip_label: String,
|
||||
#[serde(rename = "tooltipDescription")]
|
||||
pub tooltip_description: String,
|
||||
#[serde(rename = "tooltipShortcut")]
|
||||
pub tooltip_shortcut: Option<ActionShortcut>,
|
||||
|
||||
// Callbacks
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_update: WidgetCallback<SpectrumInputUpdate>,
|
||||
pub on_update: WidgetCallback<CurveInput>,
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct SpectrumMarker {
|
||||
/// Position (0..1) of the marker along the spectrum track.
|
||||
position: f64,
|
||||
/// Position (0..1) of the midpoint between this marker and the next, used only if `show_midpoints` is true. The last marker's value is ignored.
|
||||
midpoint: f64,
|
||||
/// CSS color string for the marker handle's fill. Set via `SpectrumMarker::new` from a linear [`Color`].
|
||||
#[serde(rename = "handleColorCSS")]
|
||||
handle_color_css: String,
|
||||
}
|
||||
|
||||
impl SpectrumMarker {
|
||||
pub fn new(position: f64, midpoint: f64, handle_color: Color) -> Self {
|
||||
let handle_color_css = SRGBA8::from(handle_color).to_css_hex();
|
||||
Self { position, midpoint, handle_color_css }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum SpectrumInputUpdate {
|
||||
MoveMarker {
|
||||
index: u32,
|
||||
position: f64,
|
||||
},
|
||||
MoveMidpoint {
|
||||
index: u32,
|
||||
position: f64,
|
||||
},
|
||||
InsertMarker {
|
||||
position: f64,
|
||||
},
|
||||
DeleteMarker {
|
||||
index: u32,
|
||||
},
|
||||
/// Emitted when the user double-clicks a marker. The consumer decides what (if anything) to reset the marker to.
|
||||
ResetMarker {
|
||||
index: u32,
|
||||
},
|
||||
ResetMidpoint {
|
||||
index: u32,
|
||||
},
|
||||
ActiveMarker {
|
||||
#[serde(rename = "activeMarkerIndex")]
|
||||
active_marker_index: Option<u32>,
|
||||
#[serde(rename = "activeMarkerIsMidpoint")]
|
||||
active_marker_is_midpoint: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Default, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder)]
|
||||
#[derivative(Debug, PartialEq)]
|
||||
|
||||
@@ -72,8 +72,6 @@ pub struct TextLabel {
|
||||
// Sizing
|
||||
#[serde(rename = "minWidth")]
|
||||
pub min_width: u32,
|
||||
#[serde(rename = "maxWidth")]
|
||||
pub max_width: u32,
|
||||
#[serde(rename = "minWidthCharacters")]
|
||||
pub min_width_characters: u32,
|
||||
|
||||
|
||||
@@ -514,11 +514,6 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon("NodeShape")
|
||||
.on_commit(|_| NodeGraphMessage::AddPathNode.into())
|
||||
.disabled(!make_path_editable_is_allowed),
|
||||
MenuListEntry::new("Expand Fill/Stroke")
|
||||
.label("Expand Fill/Stroke")
|
||||
.icon("ExpandFillStroke")
|
||||
.on_commit(|_| DocumentMessage::ExpandFillStrokeOnSelectedLayers.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
],
|
||||
])
|
||||
.widget_instance(),
|
||||
|
||||
@@ -14,8 +14,6 @@ pub enum Message {
|
||||
#[child]
|
||||
Clipboard(ClipboardMessage),
|
||||
#[child]
|
||||
ColorPicker(ColorPickerMessage),
|
||||
#[child]
|
||||
Debug(DebugMessage),
|
||||
#[child]
|
||||
Defer(DeferMessage),
|
||||
@@ -24,8 +22,6 @@ pub enum Message {
|
||||
#[child]
|
||||
Frontend(FrontendMessage),
|
||||
#[child]
|
||||
Future(FutureMessage),
|
||||
#[child]
|
||||
InputPreprocessor(InputPreprocessorMessage),
|
||||
#[child]
|
||||
KeyMapping(KeyMappingMessage),
|
||||
@@ -34,14 +30,10 @@ pub enum Message {
|
||||
#[child]
|
||||
MenuBar(MenuBarMessage),
|
||||
#[child]
|
||||
Network(NetworkMessage),
|
||||
#[child]
|
||||
Portfolio(PortfolioMessage),
|
||||
#[child]
|
||||
Preferences(PreferencesMessage),
|
||||
#[child]
|
||||
ResourceStorage(ResourceStorageMessage),
|
||||
#[child]
|
||||
Tool(ToolMessage),
|
||||
#[child]
|
||||
Viewport(ViewportMessage),
|
||||
|
||||
@@ -4,21 +4,17 @@ 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;
|
||||
pub mod frontend;
|
||||
pub mod future;
|
||||
pub mod input_mapper;
|
||||
pub mod input_preprocessor;
|
||||
pub mod layout;
|
||||
pub mod menu_bar;
|
||||
pub mod message;
|
||||
pub mod network;
|
||||
pub mod portfolio;
|
||||
pub mod preferences;
|
||||
pub mod prelude;
|
||||
pub mod resource_storage;
|
||||
pub mod tool;
|
||||
pub mod viewport;
|
||||
@@ -1,10 +0,0 @@
|
||||
mod network_message;
|
||||
mod network_message_handler;
|
||||
pub mod utility_types;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use network_message::{NetworkMessage, NetworkMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use network_message_handler::{NetworkMessageContext, NetworkMessageHandler};
|
||||
#[doc(inline)]
|
||||
pub use utility_types::Client;
|
||||
@@ -1,49 +0,0 @@
|
||||
use std::pin::Pin;
|
||||
|
||||
use dyn_any::WasmNotSend;
|
||||
|
||||
use crate::messages::network::utility_types::Client;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[impl_message(Message, Network)]
|
||||
#[derive(derivative::Derivative, serde::Serialize, serde::Deserialize)]
|
||||
#[derivative(Debug, PartialEq)]
|
||||
pub enum NetworkMessage {
|
||||
Request {
|
||||
#[serde(skip, default)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
request: Option<RequestFn>,
|
||||
},
|
||||
}
|
||||
impl NetworkMessage {
|
||||
pub fn request<F, Fut>(f: F) -> Self
|
||||
where
|
||||
F: FnOnce(Client) -> Fut + WasmNotSend + 'static,
|
||||
Fut: Future<Output = Message> + WasmNotSend + 'static,
|
||||
{
|
||||
NetworkMessage::Request {
|
||||
request: Some(Box::new(move |c| Box::pin(f(c)))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
type RequestFuture = Pin<Box<dyn Future<Output = Message> + Send>>;
|
||||
#[cfg(target_family = "wasm")]
|
||||
type RequestFuture = Pin<Box<dyn Future<Output = Message>>>;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
type RequestFn = Box<dyn FnOnce(Client) -> RequestFuture + Send>;
|
||||
#[cfg(target_family = "wasm")]
|
||||
type RequestFn = Box<dyn FnOnce(Client) -> RequestFuture>;
|
||||
|
||||
impl Clone for NetworkMessage {
|
||||
fn clone(&self) -> Self {
|
||||
match self {
|
||||
NetworkMessage::Request { .. } => {
|
||||
log::error!("Cloning a NetworkMessage::Request is not supported");
|
||||
NetworkMessage::Request { request: None }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
use crate::messages::network::utility_types::Client;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct NetworkMessageContext {}
|
||||
|
||||
#[derive(Debug, Default, ExtractField)]
|
||||
pub struct NetworkMessageHandler {
|
||||
client: Client,
|
||||
}
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<NetworkMessage, NetworkMessageContext> for NetworkMessageHandler {
|
||||
fn process_message(&mut self, message: NetworkMessage, responses: &mut VecDeque<Message>, _context: NetworkMessageContext) {
|
||||
match message {
|
||||
NetworkMessage::Request { request } => {
|
||||
if let Some(request) = request {
|
||||
responses.add(request(self.client.clone()));
|
||||
} else {
|
||||
log::error!("received a empty NetworkMessage::Request");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
advertise_actions!(NetworkMessageDiscriminant;
|
||||
);
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
use reqwest::IntoUrl;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Client {
|
||||
inner: Option<reqwest::Client>,
|
||||
}
|
||||
|
||||
impl Default for Client {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
inner: reqwest::Client::builder().timeout(std::time::Duration::from_secs(100)).build().ok(),
|
||||
#[cfg(target_family = "wasm")]
|
||||
inner: reqwest::Client::builder().build().ok(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Client {
|
||||
pub async fn fetch<U: IntoUrl>(&self, url: U) -> Option<Box<[u8]>> {
|
||||
let Some(client) = &self.inner else {
|
||||
log::error!("HTTP client failed to initialize, cannot fetch");
|
||||
return None;
|
||||
};
|
||||
let response = client.get(url).send().await;
|
||||
let response = response.and_then(|r| r.error_for_status()).map_err(|err| log::error!("failed to fetch: {err}")).ok()?;
|
||||
let bytes = response.bytes().await.map_err(|err| log::error!("failed to read response body: {err}")).ok()?;
|
||||
Some(bytes.to_vec().into_boxed_slice())
|
||||
}
|
||||
}
|
||||
@@ -10,12 +10,9 @@ pub enum DataPanelMessage {
|
||||
inspect_result: InspectResult,
|
||||
},
|
||||
ClearLayout,
|
||||
/// Re-render the existing layout against the latest network interface state. Use this when node metadata
|
||||
/// (display name, visibility, locked, etc.) changes but the introspected output value hasn't.
|
||||
Refresh,
|
||||
|
||||
PushToElementPath {
|
||||
step: PathStep,
|
||||
index: usize,
|
||||
},
|
||||
TruncateElementPath {
|
||||
len: usize,
|
||||
@@ -26,14 +23,6 @@ pub enum DataPanelMessage {
|
||||
},
|
||||
}
|
||||
|
||||
/// One hop in the breadcrumb path through nested data the Data panel is displaying.
|
||||
/// Drilling into an item's element produces an `Element` step; drilling into one of an item's attributes produces an `Attribute` step.
|
||||
#[derive(PartialEq, Eq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum PathStep {
|
||||
Element(usize),
|
||||
Attribute { row: usize, key: String },
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, Clone, Copy, Default, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum VectorTableTab {
|
||||
#[default]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -37,8 +37,6 @@ pub enum DocumentMessage {
|
||||
PropertiesPanel(PropertiesPanelMessage),
|
||||
#[child]
|
||||
DataPanel(DataPanelMessage),
|
||||
#[child]
|
||||
Resource(ResourceMessage),
|
||||
|
||||
// Messages
|
||||
AlignSelectedLayers {
|
||||
@@ -88,8 +86,6 @@ pub enum DocumentMessage {
|
||||
},
|
||||
BlendSelectedLayers,
|
||||
MorphSelectedLayers,
|
||||
ExpandFillStrokeOnSelectedLayers,
|
||||
ExpandFillStrokeOnSelectedLayersNoTransaction,
|
||||
GroupSelectedLayers {
|
||||
group_folder_type: GroupFolderType,
|
||||
},
|
||||
@@ -203,7 +199,7 @@ pub enum DocumentMessage {
|
||||
undo_count: usize,
|
||||
},
|
||||
ToggleLayerExpansion {
|
||||
tree_path: Vec<NodeId>,
|
||||
instance_path: Vec<NodeId>,
|
||||
recursive: bool,
|
||||
},
|
||||
ToggleSelectedVisibility,
|
||||
@@ -219,12 +215,6 @@ pub enum DocumentMessage {
|
||||
UpdateClickTargets {
|
||||
click_targets: HashMap<NodeId, Vec<Arc<ClickTarget>>>,
|
||||
},
|
||||
UpdateOutlines {
|
||||
outlines: HashMap<NodeId, Vec<Arc<ClickTarget>>>,
|
||||
},
|
||||
UpdateTextFrames {
|
||||
text_frames: HashMap<NodeId, DAffine2>,
|
||||
},
|
||||
UpdateClipTargets {
|
||||
clip_targets: HashSet<NodeId>,
|
||||
},
|
||||
|
||||
@@ -11,7 +11,7 @@ use crate::consts::{
|
||||
use crate::messages::input_mapper::utility_types::macros::action_shortcut;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::data_panel::{DataPanelMessageContext, DataPanelMessageHandler};
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::{ModifyInputsContext, TransformIn};
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::node_graph::NodeGraphMessageContext;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
||||
@@ -20,28 +20,28 @@ use crate::messages::portfolio::document::overlays::utility_types::{OverlaysType
|
||||
use crate::messages::portfolio::document::properties_panel::properties_panel_message_handler::PropertiesPanelMessageContext;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
|
||||
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, PTZ};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate, OutputConnector};
|
||||
use crate::messages::portfolio::utility_types::PanelType;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate};
|
||||
use crate::messages::portfolio::utility_types::{CachedData, PanelType};
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{self, get_blend_mode, get_fill, get_opacity};
|
||||
use crate::messages::tool::tool_messages::select_tool::SelectToolPointerKeys;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::Key;
|
||||
use crate::messages::tool::utility_types::ToolType;
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::application_io::resource::ResourceId;
|
||||
use graph_craft::application_io::wgpu_available;
|
||||
use graph_craft::descriptor;
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork};
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::path_bool_nodes::boolean_intersect;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster_types::Raster;
|
||||
use graphene_std::render_node::wgpu_available;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::table::Table;
|
||||
use graphene_std::vector::PointId;
|
||||
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
|
||||
use graphene_std::vector::misc::dvec2_to_point;
|
||||
use graphene_std::vector::style::{Fill, RenderMode};
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
use kurbo::{Affine, BezPath, Line, PathSeg};
|
||||
use std::collections::HashSet;
|
||||
use std::path::PathBuf;
|
||||
@@ -52,6 +52,7 @@ use std::time::Duration;
|
||||
pub struct DocumentMessageContext<'a> {
|
||||
pub document_id: DocumentId,
|
||||
pub ipp: &'a InputPreprocessorMessageHandler,
|
||||
pub cached_data: &'a CachedData,
|
||||
pub executor: &'a mut NodeGraphExecutor,
|
||||
pub current_tool: &'a ToolType,
|
||||
pub preferences: &'a PreferencesMessageHandler,
|
||||
@@ -59,8 +60,6 @@ pub struct DocumentMessageContext<'a> {
|
||||
pub layers_panel_open: bool,
|
||||
pub properties_panel_open: bool,
|
||||
pub viewport: &'a ViewportMessageHandler,
|
||||
pub resource_storage: &'a ResourceStorageMessageHandler,
|
||||
pub fonts: &'a FontsMessageHandler,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ExtractField)]
|
||||
@@ -87,10 +86,7 @@ pub struct DocumentMessageHandler {
|
||||
//
|
||||
// Contains the NodeNetwork and acts an an interface to manipulate the NodeNetwork with custom setters in order to keep NetworkMetadata in sync
|
||||
pub network_interface: NodeNetworkInterface,
|
||||
/// Resources embedded in the document.
|
||||
#[serde(default, skip_serializing_if = "ResourceMessageHandler::is_empty")]
|
||||
pub resources: ResourceMessageHandler,
|
||||
/// Tracks which layer occurrences are collapsed in the Layers panel, keyed by tree path.
|
||||
/// Tracks which layer instances are collapsed in the Layers panel, keyed by instance path.
|
||||
#[serde(deserialize_with = "deserialize_collapsed_layers", default)]
|
||||
pub collapsed: CollapsedLayers,
|
||||
/// The full Git commit hash of the Graphite repository that was used to build the editor.
|
||||
@@ -165,7 +161,6 @@ impl Default for DocumentMessageHandler {
|
||||
// Fields that are saved in the document format
|
||||
// ============================================
|
||||
network_interface: default_document_network_interface(),
|
||||
resources: ResourceMessageHandler::default(),
|
||||
collapsed: CollapsedLayers::default(),
|
||||
commit_hash: GRAPHITE_GIT_COMMIT_HASH.to_string(),
|
||||
document_ptz: PTZ::default(),
|
||||
@@ -198,6 +193,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
let DocumentMessageContext {
|
||||
document_id,
|
||||
ipp,
|
||||
cached_data,
|
||||
executor,
|
||||
viewport,
|
||||
current_tool,
|
||||
@@ -205,8 +201,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
data_panel_open,
|
||||
layers_panel_open,
|
||||
properties_panel_open,
|
||||
resource_storage,
|
||||
fonts,
|
||||
} = context;
|
||||
|
||||
match message {
|
||||
@@ -233,12 +227,11 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
DocumentMessage::PropertiesPanel(message) => {
|
||||
let context = PropertiesPanelMessageContext {
|
||||
executor,
|
||||
network_interface: &mut self.network_interface,
|
||||
resources: &self.resources,
|
||||
selection_network_path: &self.selection_network_path,
|
||||
document_name: self.name.as_str(),
|
||||
fonts,
|
||||
executor,
|
||||
cached_data,
|
||||
properties_panel_open,
|
||||
};
|
||||
self.properties_panel_message_handler.process_message(message, responses, context);
|
||||
@@ -282,10 +275,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
let mut graph_operation_message_handler = GraphOperationMessageHandler {};
|
||||
graph_operation_message_handler.process_message(message, responses, context);
|
||||
}
|
||||
DocumentMessage::Resource(message) => {
|
||||
let context = ResourceMessageContext { document_id, fonts };
|
||||
self.resources.process_message(message, responses, context);
|
||||
}
|
||||
DocumentMessage::AlignSelectedLayers { axis, aggregate } => {
|
||||
let axis = match axis {
|
||||
AlignAxis::X => DVec2::X,
|
||||
@@ -643,24 +632,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
DocumentMessage::MorphSelectedLayers => {
|
||||
self.handle_group_selected_layers(GroupFolderType::Morph, responses);
|
||||
}
|
||||
DocumentMessage::ExpandFillStrokeOnSelectedLayers => {
|
||||
// Snapshot must be taken before the mutations, so the actual work runs as a separate message
|
||||
// queued after AddTransaction (which prepends StartTransaction/CommitTransaction to the queue).
|
||||
// All mutations currently target the root document network, so guard against being invoked from inside a nested network.
|
||||
if !self.selection_network_path.is_empty() {
|
||||
log::error!("Expanding fill/stroke is only supported for the document network");
|
||||
return;
|
||||
}
|
||||
if self.network_interface.selected_nodes().selected_layers(self.metadata()).next().is_none() {
|
||||
return;
|
||||
}
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(DocumentMessage::ExpandFillStrokeOnSelectedLayersNoTransaction);
|
||||
}
|
||||
DocumentMessage::ExpandFillStrokeOnSelectedLayersNoTransaction => {
|
||||
// Mutates the network directly, so it must be queued to run after `AddTransaction` has snapshotted the document
|
||||
self.handle_expand_fill_stroke_on_selected_layers(responses);
|
||||
}
|
||||
DocumentMessage::GroupSelectedLayers { group_folder_type } => {
|
||||
self.handle_group_selected_layers(group_folder_type, responses);
|
||||
}
|
||||
@@ -725,12 +696,11 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
|
||||
let layer = graph_modification_utils::new_image_layer(image, layer_node_id, layer_parent, responses);
|
||||
let layer = graph_modification_utils::new_image_layer(Table::new_from_element(Raster::new_cpu(image)), layer_node_id, layer_parent, responses);
|
||||
|
||||
if let Some(name) = name {
|
||||
responses.add(NodeGraphMessage::SetDisplayName {
|
||||
node_id: layer.to_node(),
|
||||
network_path: Vec::new(),
|
||||
alias: name,
|
||||
skip_adding_history_step: false,
|
||||
});
|
||||
@@ -788,7 +758,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
if let Some(name) = name {
|
||||
responses.add(NodeGraphMessage::SetDisplayName {
|
||||
node_id: layer.to_node(),
|
||||
network_path: Vec::new(),
|
||||
alias: name,
|
||||
skip_adding_history_step: false,
|
||||
});
|
||||
@@ -815,15 +784,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
responses.add(EventMessage::SelectionChanged);
|
||||
}
|
||||
DocumentMessage::RenameDocument { new_name } => {
|
||||
let new_name = new_name.trim().to_string();
|
||||
|
||||
// No-op when the resolved name is unchangedL committing the rename field without edits (or with
|
||||
// only whitespace edits) shouldn't dissociate the document from its file on disk or mark it unsaved.
|
||||
if new_name == self.name {
|
||||
return;
|
||||
}
|
||||
|
||||
self.name = new_name;
|
||||
self.name = new_name.clone();
|
||||
|
||||
self.path = None;
|
||||
self.set_save_state(false);
|
||||
@@ -869,31 +830,11 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
|
||||
let ruler_spacing = ruler_interval * ruler_scale;
|
||||
|
||||
// Compute the selection bounding box as 4 viewport-space corners preserving orientation
|
||||
let selection_quad = if !self.graph_view_overlay_open {
|
||||
self.network_interface
|
||||
.selected_nodes()
|
||||
.0
|
||||
.iter()
|
||||
.filter(|node| self.network_interface.is_layer(node, &[]))
|
||||
.filter_map(|layer| self.metadata().bounding_box_document(LayerNodeIdentifier::new(*layer, &self.network_interface)))
|
||||
.reduce(Quad::combine_bounds)
|
||||
.map(|[min, max]| {
|
||||
let corners = [DVec2::new(min.x, min.y), DVec2::new(max.x, min.y), DVec2::new(max.x, max.y), DVec2::new(min.x, max.y)];
|
||||
corners.map(|c| document_to_viewport.transform_point2(c).into())
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
responses.add(FrontendMessage::UpdateDocumentRulers {
|
||||
origin: ruler_origin.into(),
|
||||
spacing: ruler_spacing,
|
||||
interval: ruler_interval,
|
||||
visible: self.rulers_visible,
|
||||
tilt: if self.graph_view_overlay_open { 0. } else { current_ptz.tilt() },
|
||||
flip: !self.graph_view_overlay_open && current_ptz.flip,
|
||||
selection_quad,
|
||||
});
|
||||
}
|
||||
DocumentMessage::RenderScrollbars => {
|
||||
@@ -924,29 +865,19 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
DocumentMessage::SaveDocument | DocumentMessage::SaveDocumentAs => {
|
||||
responses.add(PortfolioMessage::AutoSaveActiveDocument);
|
||||
|
||||
let name = format!("{}.{}", self.name.clone(), FILE_EXTENSION);
|
||||
let path = if let DocumentMessage::SaveDocumentAs = message { None } else { self.path.clone() };
|
||||
if path.is_some() {
|
||||
responses.add(DocumentMessage::MarkAsSaved);
|
||||
}
|
||||
|
||||
let folder = self.path.as_ref().and_then(|path| path.parent()).map(|parent| parent.to_path_buf());
|
||||
|
||||
let mut document = self.clone();
|
||||
let resources_load_handle = resource_storage.resources();
|
||||
|
||||
responses.add(async move {
|
||||
document.resources.collect_garbage(document.used_resources(false).as_ref());
|
||||
document.resources.embed_resources(resources_load_handle).await;
|
||||
|
||||
let content = document.serialize_document().into_bytes().into();
|
||||
|
||||
Message::Frontend(FrontendMessage::TriggerSaveDocument {
|
||||
document_id,
|
||||
name,
|
||||
path,
|
||||
folder,
|
||||
content,
|
||||
})
|
||||
responses.add(FrontendMessage::TriggerSaveDocument {
|
||||
document_id,
|
||||
name: format!("{}.{}", self.name.clone(), FILE_EXTENSION),
|
||||
path,
|
||||
folder,
|
||||
content: self.serialize_document().into_bytes().into(),
|
||||
});
|
||||
}
|
||||
DocumentMessage::SavedDocument { path } => {
|
||||
@@ -1244,27 +1175,27 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
}
|
||||
DocumentMessage::ToggleLayerExpansion { tree_path, recursive } => {
|
||||
let is_collapsed = self.collapsed.0.contains(&tree_path);
|
||||
DocumentMessage::ToggleLayerExpansion { instance_path, recursive } => {
|
||||
let is_collapsed = self.collapsed.0.contains(&instance_path);
|
||||
|
||||
if is_collapsed {
|
||||
if recursive {
|
||||
// Remove this path and all descendant paths (paths that start with this one)
|
||||
self.collapsed.0.retain(|path| !path.starts_with(&tree_path));
|
||||
self.collapsed.0.retain(|path| !path.starts_with(&instance_path));
|
||||
} else {
|
||||
self.collapsed.0.retain(|path| *path != tree_path);
|
||||
self.collapsed.0.retain(|path| *path != instance_path);
|
||||
}
|
||||
} else {
|
||||
if recursive {
|
||||
// Collapse all expanded descendant occurrences by collecting their tree paths from the structure tree
|
||||
let descendant_paths = self.collect_descendant_tree_paths(&tree_path);
|
||||
// Collapse all expanded descendant instances by collecting their paths from the structure tree
|
||||
let descendant_paths = self.collect_descendant_instance_paths(&instance_path);
|
||||
for path in descendant_paths {
|
||||
if !self.collapsed.0.contains(&path) {
|
||||
self.collapsed.0.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.collapsed.0.push(tree_path);
|
||||
self.collapsed.0.push(instance_path);
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
@@ -1311,31 +1242,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
.collect();
|
||||
self.network_interface.update_click_targets(layer_click_targets);
|
||||
}
|
||||
DocumentMessage::UpdateOutlines { outlines } => {
|
||||
let layer_outlines = outlines
|
||||
.into_iter()
|
||||
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id))
|
||||
.filter_map(|(node_id, outlines)| {
|
||||
self.network_interface.is_layer(&node_id, &[]).then(|| {
|
||||
let layer = LayerNodeIdentifier::new(node_id, &self.network_interface);
|
||||
(layer, outlines)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
self.network_interface.update_outlines(layer_outlines);
|
||||
}
|
||||
DocumentMessage::UpdateTextFrames { text_frames } => {
|
||||
let layer_text_frames = text_frames
|
||||
.into_iter()
|
||||
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id))
|
||||
.filter(|&(node_id, _)| self.network_interface.is_layer(&node_id, &[]))
|
||||
.map(|(node_id, frame)| {
|
||||
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);
|
||||
}
|
||||
@@ -1482,11 +1388,11 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
// When artboard_canvas is provided (SVG file-open flow), use the declared canvas origin and dimensions;
|
||||
// no content-shift Transform node needed since the SVG was already placed at its natural coordinates.
|
||||
let (artboard_location, artboard_dimensions, content_shift) = if let Some((origin, dimensions)) = artboard_canvas {
|
||||
(origin.as_dvec2(), dimensions.as_dvec2(), DVec2::ZERO)
|
||||
(origin, dimensions, DVec2::ZERO)
|
||||
} else {
|
||||
// No declared canvas (image or clipboard paste): derive location and dimensions from the content bounding box.
|
||||
let location = if place_artboard_at_origin { DVec2::ZERO } else { bounds[0].round() };
|
||||
(location, (bounds[1] - bounds[0]).round(), -bounds[0].round())
|
||||
let location = if place_artboard_at_origin { IVec2::ZERO } else { bounds[0].round().as_ivec2() };
|
||||
(location, (bounds[1] - bounds[0]).round().as_ivec2(), -bounds[0].round())
|
||||
};
|
||||
|
||||
// Create an artboard and set its dimensions to the bounding box size and location
|
||||
@@ -1689,11 +1595,6 @@ impl DocumentMessageHandler {
|
||||
subpath.apply_transform(layer_transform);
|
||||
subpath.is_inside_subpath(&viewport_polygon, None, None)
|
||||
}
|
||||
ClickTargetType::CompoundPath(subpaths) => subpaths.iter().all(|subpath| {
|
||||
let mut subpath = subpath.clone();
|
||||
subpath.apply_transform(layer_transform);
|
||||
subpath.is_inside_subpath(&viewport_polygon, None, None)
|
||||
}),
|
||||
ClickTargetType::FreePoint(point) => {
|
||||
let mut point = *point;
|
||||
point.apply_transform(layer_transform);
|
||||
@@ -1787,12 +1688,6 @@ impl DocumentMessageHandler {
|
||||
self.network_interface.document_metadata()
|
||||
}
|
||||
|
||||
/// Path to the subnetwork that the user's selection is currently scoped to.
|
||||
/// Empty when the selection lives in the root document network.
|
||||
pub fn selection_network_path(&self) -> &[NodeId] {
|
||||
&self.selection_network_path
|
||||
}
|
||||
|
||||
pub fn serialize_document(&self) -> String {
|
||||
let val = serde_json::to_string(self);
|
||||
// We fully expect the serialization to succeed
|
||||
@@ -1873,11 +1768,11 @@ impl DocumentMessageHandler {
|
||||
let selected_layers: HashSet<NodeId> = network.selected_nodes().selected_layers(self.metadata()).map(LayerNodeIdentifier::to_node).collect();
|
||||
|
||||
let ancestors = HashSet::new();
|
||||
let tree_path = Vec::new();
|
||||
let instance_path = Vec::new();
|
||||
let mut root_entries = Vec::new();
|
||||
|
||||
// The first root layer is the topmost entry
|
||||
root_entries.push(self.build_layer_entry(first_root_layer_id, &ancestors, &selected_layers, &tree_path));
|
||||
root_entries.push(self.build_layer_entry(first_root_layer_id, &ancestors, &selected_layers, &instance_path));
|
||||
|
||||
// Layers in the primary flow (input[0] chain) from the first root layer are root-level siblings
|
||||
let mut root_ancestors = HashSet::new();
|
||||
@@ -1885,7 +1780,7 @@ impl DocumentMessageHandler {
|
||||
|
||||
for sibling_id in network.upstream_flow_back_from_nodes(vec![first_root_layer_id], &[], FlowType::PrimaryFlow).skip(1) {
|
||||
if network.is_layer(&sibling_id, &[]) && !root_ancestors.contains(&sibling_id) {
|
||||
root_entries.push(self.build_layer_entry(sibling_id, &root_ancestors, &selected_layers, &tree_path));
|
||||
root_entries.push(self.build_layer_entry(sibling_id, &root_ancestors, &selected_layers, &instance_path));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1894,19 +1789,19 @@ impl DocumentMessageHandler {
|
||||
|
||||
/// Builds a single `LayerStructureEntry` for the given layer, including its `children_present` flag,
|
||||
/// `descendant_selected` flag, and (if expanded) its children collected from the graph.
|
||||
fn build_layer_entry(&self, layer_id: NodeId, ancestors: &HashSet<NodeId>, selected_layers: &HashSet<NodeId>, parent_tree_path: &[NodeId]) -> LayerStructureEntry {
|
||||
let mut tree_path = parent_tree_path.to_vec();
|
||||
tree_path.push(layer_id);
|
||||
fn build_layer_entry(&self, layer_id: NodeId, ancestors: &HashSet<NodeId>, selected_layers: &HashSet<NodeId>, parent_instance_path: &[NodeId]) -> LayerStructureEntry {
|
||||
let mut instance_path = parent_instance_path.to_vec();
|
||||
instance_path.push(layer_id);
|
||||
|
||||
let mut child_ancestors = ancestors.clone();
|
||||
child_ancestors.insert(layer_id);
|
||||
|
||||
let children_present = self.has_layer_children_in_graph(layer_id, &child_ancestors);
|
||||
|
||||
let collapsed = self.collapsed.0.contains(&tree_path);
|
||||
let collapsed = self.collapsed.0.contains(&instance_path);
|
||||
|
||||
let children = if children_present && !collapsed {
|
||||
self.collect_layer_children(layer_id, &child_ancestors, selected_layers, &tree_path)
|
||||
self.collect_layer_children(layer_id, &child_ancestors, selected_layers, &instance_path)
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
@@ -1987,7 +1882,7 @@ impl DocumentMessageHandler {
|
||||
/// The horizontal flow (a layer's secondary input chain) finds nested content layers, and the
|
||||
/// primary flow from those (their stack's top output) finds stacked siblings at the same depth.
|
||||
/// `ancestors` contains layer IDs in the current path from root, used for cycle prevention.
|
||||
fn collect_layer_children(&self, layer_id: NodeId, ancestors: &HashSet<NodeId>, selected_layers: &HashSet<NodeId>, tree_path: &[NodeId]) -> Vec<LayerStructureEntry> {
|
||||
fn collect_layer_children(&self, layer_id: NodeId, ancestors: &HashSet<NodeId>, selected_layers: &HashSet<NodeId>, instance_path: &[NodeId]) -> Vec<LayerStructureEntry> {
|
||||
let network = &self.network_interface;
|
||||
|
||||
// Find the first nested layer via horizontal flow (content inside this layer)
|
||||
@@ -2005,22 +1900,22 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
// The nested layer is the first child at this depth level
|
||||
let mut children = vec![self.build_layer_entry(nested_id, ancestors, selected_layers, tree_path)];
|
||||
let mut children = vec![self.build_layer_entry(nested_id, ancestors, selected_layers, instance_path)];
|
||||
|
||||
// Primary flow from the nested layer finds stacked siblings (more children of this layer)
|
||||
for sibling_id in network.upstream_flow_back_from_nodes(vec![nested_id], &[], FlowType::PrimaryFlow).skip(1) {
|
||||
if network.is_layer(&sibling_id, &[]) && !ancestors.contains(&sibling_id) {
|
||||
children.push(self.build_layer_entry(sibling_id, ancestors, selected_layers, tree_path));
|
||||
children.push(self.build_layer_entry(sibling_id, ancestors, selected_layers, instance_path));
|
||||
}
|
||||
}
|
||||
|
||||
children
|
||||
}
|
||||
|
||||
/// Collects tree paths for all descendant layers of the given tree path by traversing the graph.
|
||||
/// Collects instance paths for all descendant layers of the given instance path by traversing the graph.
|
||||
/// Used for recursive collapse to find all expandable descendants.
|
||||
fn collect_descendant_tree_paths(&self, tree_path: &[NodeId]) -> Vec<Vec<NodeId>> {
|
||||
let Some(&layer_id) = tree_path.last() else { return Vec::new() };
|
||||
fn collect_descendant_instance_paths(&self, instance_path: &[NodeId]) -> Vec<Vec<NodeId>> {
|
||||
let Some(&layer_id) = instance_path.last() else { return Vec::new() };
|
||||
let network = &self.network_interface;
|
||||
|
||||
let mut paths = Vec::new();
|
||||
@@ -2029,7 +1924,7 @@ impl DocumentMessageHandler {
|
||||
// Seed with child layers via horizontal flow
|
||||
for node_id in network.upstream_flow_back_from_nodes(vec![layer_id], &[], FlowType::HorizontalFlow).skip(1) {
|
||||
if network.is_layer(&node_id, &[]) {
|
||||
let mut child_path = tree_path.to_vec();
|
||||
let mut child_path = instance_path.to_vec();
|
||||
child_path.push(node_id);
|
||||
stack.push((node_id, child_path));
|
||||
}
|
||||
@@ -2037,14 +1932,14 @@ impl DocumentMessageHandler {
|
||||
|
||||
let mut visited = HashSet::new();
|
||||
|
||||
// Depth-first traversal collecting all unique descendant tree paths
|
||||
// Depth-first traversal collecting all unique descendant instance paths
|
||||
while let Some((current_id, current_path)) = stack.pop() {
|
||||
// Skip paths we've already visited to prevent cycles
|
||||
if !visited.insert(current_path.clone()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Record this descendant's tree path for collapsing
|
||||
// Record this descendant's instance path for collapsing
|
||||
paths.push(current_path.clone());
|
||||
|
||||
// Add nested content layers found via horizontal flow
|
||||
@@ -2251,7 +2146,7 @@ impl DocumentMessageHandler {
|
||||
network_interface.upstream_flow_back_from_nodes(vec![selected_id.to_node()], &[], FlowType::HorizontalFlow).find(|id| {
|
||||
network_interface
|
||||
.reference(id, &[])
|
||||
.is_some_and(|reference| reference == DefinitionIdentifier::ProtoNode(graphene_std::path_bool_nodes::boolean_operation::IDENTIFIER))
|
||||
.is_some_and(|reference| reference == DefinitionIdentifier::Network("Boolean Operation".into()))
|
||||
})
|
||||
});
|
||||
|
||||
@@ -2309,18 +2204,18 @@ impl DocumentMessageHandler {
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
|
||||
// The control path layer (Blend Path / Morph Path) should start collapsed.
|
||||
let tree_path = {
|
||||
// Build tree path from root down to the control path layer, which is a sibling of the main layer under `parent`.
|
||||
let mut tree_path: Vec<NodeId> = parent
|
||||
let instance_path = {
|
||||
// Build instance path from root down to the control path layer, which is a sibling of the main layer under `parent`.
|
||||
let mut instance_path: Vec<NodeId> = parent
|
||||
.ancestors(network_interface.document_metadata())
|
||||
.take_while(|&ancestor| ancestor != LayerNodeIdentifier::ROOT_PARENT)
|
||||
.map(LayerNodeIdentifier::to_node)
|
||||
.collect();
|
||||
tree_path.reverse();
|
||||
tree_path.push(control_path_id);
|
||||
tree_path
|
||||
instance_path.reverse();
|
||||
instance_path.push(control_path_id);
|
||||
instance_path
|
||||
};
|
||||
responses.add(DocumentMessage::ToggleLayerExpansion { tree_path, recursive: false });
|
||||
responses.add(DocumentMessage::ToggleLayerExpansion { instance_path, recursive: false });
|
||||
|
||||
return folder_id;
|
||||
}
|
||||
@@ -2389,86 +2284,6 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// For each selected layer, splits its fill and stroke into two stacked layers connected
|
||||
/// to a shared `Solidify Stroke` node via two `Index Elements` nodes (indices 0 and 1).
|
||||
/// Layers with only a stroke get just a `Solidify Stroke` added.
|
||||
/// Layers with only a fill, or neither, are left untouched.
|
||||
fn handle_expand_fill_stroke_on_selected_layers(&mut self, responses: &mut VecDeque<Message>) {
|
||||
let selected_layers: Vec<LayerNodeIdentifier> = self.network_interface.selected_nodes().selected_layers(self.metadata()).collect();
|
||||
if selected_layers.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let solidify_stroke_definition = document_node_definitions::resolve_proto_node_type(graphene_std::vector::solidify_stroke::IDENTIFIER).expect("Solidify Stroke node should exist");
|
||||
let index_elements_definition = document_node_definitions::resolve_proto_node_type(graphene_std::graphic::index_elements::IDENTIFIER).expect("Index Elements node should exist");
|
||||
|
||||
let mut resulting_layers: Vec<NodeId> = Vec::new();
|
||||
|
||||
for layer in selected_layers {
|
||||
let style = self.network_interface.document_metadata().layer_vector_data.get(&layer).map(|arc| arc.style.clone());
|
||||
let Some(style) = style else {
|
||||
resulting_layers.push(layer.to_node());
|
||||
continue;
|
||||
};
|
||||
|
||||
let has_fill = !matches!(style.fill, Fill::None);
|
||||
// `style.stroke` is `Some` whenever a `Stroke` node is in the chain, even with weight 0 or a transparent color.
|
||||
// So `is_some()` would treat invisibly-stroked fill-only layers as having a stroke.
|
||||
let has_stroke = style.stroke.as_ref().is_some_and(|s| s.has_renderable_stroke());
|
||||
|
||||
// No stroke means there's nothing to solidify. Fill-only layers are already in the desired form, so skip.
|
||||
if !has_stroke {
|
||||
resulting_layers.push(layer.to_node());
|
||||
continue;
|
||||
}
|
||||
|
||||
let solidify_id = NodeId::new();
|
||||
self.network_interface.insert_node(solidify_id, solidify_stroke_definition.default_node_template(), &[]);
|
||||
self.network_interface.move_node_to_chain_start(&solidify_id, layer, &[], false);
|
||||
|
||||
if has_fill && has_stroke {
|
||||
let (existing_index, new_index) = (0_f64, 1_f64);
|
||||
|
||||
let existing_index_template = index_elements_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(existing_index), false))]);
|
||||
let existing_index_id = NodeId::new();
|
||||
self.network_interface.insert_node(existing_index_id, existing_index_template, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&existing_index_id, layer, &[], false);
|
||||
|
||||
let parent = layer.parent(self.metadata()).unwrap_or(LayerNodeIdentifier::ROOT_PARENT);
|
||||
let insert_index = parent.children(self.metadata()).position(|c| c == layer).unwrap_or(0);
|
||||
|
||||
let new_layer_id = NodeId::new();
|
||||
let new_layer = ModifyInputsContext::new(&mut self.network_interface, responses).create_layer(new_layer_id);
|
||||
self.network_interface.move_layer_to_stack(new_layer, parent, insert_index, &[]);
|
||||
|
||||
// Copy the original layer's stored name so the new layer shares it
|
||||
let original_name = self
|
||||
.network_interface
|
||||
.node_metadata(&layer.to_node(), &[])
|
||||
.map(|m| m.persistent_metadata.display_name.clone())
|
||||
.unwrap_or_default();
|
||||
if !original_name.is_empty() {
|
||||
self.network_interface.set_display_name(&new_layer_id, original_name, &[]);
|
||||
}
|
||||
|
||||
let new_index_template = index_elements_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(new_index), false))]);
|
||||
let new_index_id = NodeId::new();
|
||||
self.network_interface.insert_node(new_index_id, new_index_template, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&new_index_id, new_layer, &[], false);
|
||||
|
||||
self.network_interface.create_wire(&OutputConnector::node(solidify_id, 0), &InputConnector::node(new_index_id, 0), &[]);
|
||||
|
||||
resulting_layers.push(layer.to_node());
|
||||
resulting_layers.push(new_layer.to_node());
|
||||
} else {
|
||||
resulting_layers.push(layer.to_node());
|
||||
}
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: resulting_layers });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
/// Helper method for MoveSelectedLayersTo message.
|
||||
/// Handles moving selected layers to a new parent with proper transform preservation.
|
||||
fn handle_move_selected_layers_to(&mut self, parent: LayerNodeIdentifier, insert_index: usize, responses: &mut VecDeque<Message>) {
|
||||
@@ -2546,7 +2361,7 @@ impl DocumentMessageHandler {
|
||||
});
|
||||
|
||||
if layer_to_move.parent(self.metadata()) != Some(parent) {
|
||||
// TODO: Fix this so it works when dragging a layer into a group parent which has a Transform node, which used to work before #2689 caused this regression by removing the empty `List<Vector>` item.
|
||||
// TODO: Fix this so it works when dragging a layer into a group parent which has a Transform node, which used to work before #2689 caused this regression by removing the empty vector table row.
|
||||
// TODO: See #2688 for this issue.
|
||||
let layer_local_transform = self.network_interface.document_metadata().transform_to_viewport(layer_to_move);
|
||||
let undo_transform = self.network_interface.document_metadata().transform_to_viewport(parent).inverse();
|
||||
@@ -2567,7 +2382,6 @@ impl DocumentMessageHandler {
|
||||
|
||||
/// Helper method for NudgeSelectedLayers message.
|
||||
/// Handles keyboard nudging of selected layers with optional resize mode.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn handle_nudge_selected_layers(
|
||||
&mut self,
|
||||
delta_x: f64,
|
||||
@@ -2657,6 +2471,23 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads all of the fonts in the document.
|
||||
pub fn load_layer_resources(&self, responses: &mut VecDeque<Message>) {
|
||||
let mut fonts_to_load = HashSet::new();
|
||||
|
||||
for (_, node, _) in self.document_network().recursive_nodes() {
|
||||
for input in &node.inputs {
|
||||
if let Some(TaggedValue::Font(font)) = input.as_value() {
|
||||
fonts_to_load.insert(font.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for font in fonts_to_load {
|
||||
responses.add(PortfolioMessage::LoadFontData { font });
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_document_widgets(&self, responses: &mut VecDeque<Message>, animation_is_playing: bool, time: Duration) {
|
||||
let mut snapping_state = self.snapping_state.clone();
|
||||
let mut snapping_state2 = self.snapping_state.clone();
|
||||
@@ -3293,23 +3124,17 @@ impl DocumentMessageHandler {
|
||||
let group_folder_type = GroupFolderType::Layer;
|
||||
DocumentMessage::GroupSelectedLayers { group_folder_type }.into()
|
||||
})
|
||||
.on_drag_drop(|_| {
|
||||
let group_folder_type = GroupFolderType::Layer;
|
||||
DocumentMessage::GroupSelectedLayers { group_folder_type }.into()
|
||||
})
|
||||
.disabled(!has_selection)
|
||||
.widget_instance(),
|
||||
IconButton::new("NewLayer", 24)
|
||||
.tooltip_label("New Layer")
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::CreateEmptyFolder))
|
||||
.on_update(|_| DocumentMessage::CreateEmptyFolder.into())
|
||||
.on_drag_drop(|_| DocumentMessage::DuplicateSelectedLayers.into())
|
||||
.widget_instance(),
|
||||
IconButton::new("Trash", 24)
|
||||
.tooltip_label("Delete Selected")
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::DeleteSelectedLayers))
|
||||
.on_update(|_| DocumentMessage::DeleteSelectedLayers.into())
|
||||
.on_drag_drop(|_| DocumentMessage::DeleteSelectedLayers.into())
|
||||
.disabled(!has_selection)
|
||||
.widget_instance(),
|
||||
];
|
||||
@@ -3449,27 +3274,12 @@ impl DocumentMessageHandler {
|
||||
pub fn graph_view_overlay_open(&self) -> bool {
|
||||
self.graph_view_overlay_open
|
||||
}
|
||||
|
||||
pub fn garbage_collect_resources(&mut self) {
|
||||
let used_resources = self.used_resources(true);
|
||||
self.resources.collect_garbage(&used_resources);
|
||||
}
|
||||
|
||||
pub fn used_resources(&self, include_history: bool) -> Box<[ResourceId]> {
|
||||
let mut resources = HashSet::new();
|
||||
self.network_interface.collect_used_resources(&mut resources);
|
||||
if include_history {
|
||||
self.document_undo_history.iter().for_each(|interface| interface.collect_used_resources(&mut resources));
|
||||
self.document_redo_history.iter().for_each(|interface| interface.collect_used_resources(&mut resources));
|
||||
}
|
||||
resources.into_iter().collect::<Vec<_>>().into_boxed_slice()
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a network interface with a single export
|
||||
fn default_document_network_interface() -> NodeNetworkInterface {
|
||||
let mut network_interface = NodeNetworkInterface::default();
|
||||
network_interface.add_export(TaggedValue::TypeDefault(descriptor!(graphene_std::list::List<graphene_std::Artboard>)), -1, "", &[]);
|
||||
network_interface.add_export(TaggedValue::Artboard(Default::default()), -1, "", &[]);
|
||||
network_interface
|
||||
}
|
||||
|
||||
|
||||
@@ -2,16 +2,18 @@ use super::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use glam::{DAffine2, IVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::brush::brush_stroke::BrushStroke;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster_types::Image;
|
||||
use graphene_std::raster_types::{CPU, Raster};
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::table::Table;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{Fill, GradientSpreadMethod, GradientType, Stroke};
|
||||
use graphene_std::vector::{GradientStops, PointId, VectorModificationType};
|
||||
use graphene_std::vector::PointId;
|
||||
use graphene_std::vector::VectorModificationType;
|
||||
use graphene_std::vector::style::{Fill, Stroke};
|
||||
use graphene_std::{Artboard, Color};
|
||||
|
||||
#[impl_message(Message, DocumentMessage, GraphOperation)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
@@ -24,23 +26,6 @@ pub enum GraphOperationMessage {
|
||||
layer: LayerNodeIdentifier,
|
||||
fill: f64,
|
||||
},
|
||||
GradientStopsSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
stops: GradientStops,
|
||||
},
|
||||
GradientLineSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
start: DVec2,
|
||||
end: DVec2,
|
||||
},
|
||||
GradientTypeSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
gradient_type: GradientType,
|
||||
},
|
||||
GradientSpreadMethodSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
spread_method: GradientSpreadMethod,
|
||||
},
|
||||
OpacitySet {
|
||||
layer: LayerNodeIdentifier,
|
||||
opacity: f64,
|
||||
@@ -81,14 +66,11 @@ pub enum GraphOperationMessage {
|
||||
},
|
||||
NewArtboard {
|
||||
id: NodeId,
|
||||
location: DVec2,
|
||||
dimensions: DVec2,
|
||||
background: Color,
|
||||
clip: bool,
|
||||
artboard: Artboard,
|
||||
},
|
||||
NewBitmapLayer {
|
||||
id: NodeId,
|
||||
image: Image<Color>,
|
||||
image_frame: Table<Raster<CPU>>,
|
||||
parent: LayerNodeIdentifier,
|
||||
insert_index: usize,
|
||||
},
|
||||
@@ -137,8 +119,8 @@ pub enum GraphOperationMessage {
|
||||
},
|
||||
ResizeArtboard {
|
||||
layer: LayerNodeIdentifier,
|
||||
location: DVec2,
|
||||
dimensions: DVec2,
|
||||
location: IVec2,
|
||||
dimensions: IVec2,
|
||||
},
|
||||
RemoveArtboards,
|
||||
NewSvg {
|
||||
|
||||
+24
-48
@@ -8,14 +8,14 @@ use crate::messages::portfolio::document::utility_types::nodes::CollapsedLayers;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_clip_mode;
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::descriptor;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
|
||||
use graphene_std::table::Table;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{Fill, Gradient, GradientSpreadMethod, GradientStop, GradientStops, GradientType, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::{Artboard, Color};
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct GraphOperationMessageContext<'a> {
|
||||
@@ -27,12 +27,12 @@ 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 {
|
||||
fn process_message(&mut self, message: GraphOperationMessage, responses: &mut VecDeque<Message>, context: GraphOperationMessageContext) {
|
||||
let GraphOperationMessageContext { network_interface, .. } = context;
|
||||
let network_interface = context.network_interface;
|
||||
|
||||
match message {
|
||||
GraphOperationMessage::FillSet { layer, fill } => {
|
||||
@@ -42,27 +42,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
}
|
||||
GraphOperationMessage::BlendingFillSet { layer, fill } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.opacity_fill_set(fill);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::GradientStopsSet { layer, stops } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.gradient_stops_set(stops);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::GradientLineSet { layer, start, end } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.gradient_line_set(start, end);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::GradientTypeSet { layer, gradient_type } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.gradient_type_set(gradient_type);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::GradientSpreadMethodSet { layer, spread_method } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.gradient_spread_method_set(spread_method);
|
||||
modify_inputs.blending_fill_set(fill);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::OpacitySet { layer, opacity } => {
|
||||
@@ -128,16 +108,11 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
|
||||
network_interface.force_set_upstream_to_chain(&first_chain_node, &[]);
|
||||
}
|
||||
GraphOperationMessage::NewArtboard {
|
||||
id,
|
||||
location,
|
||||
dimensions,
|
||||
background,
|
||||
clip,
|
||||
} => {
|
||||
GraphOperationMessage::NewArtboard { id, artboard } => {
|
||||
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
|
||||
|
||||
let artboard_layer = modify_inputs.create_artboard(id, location, dimensions, background, clip);
|
||||
let artboard_location = artboard.location;
|
||||
let artboard_layer = modify_inputs.create_artboard(id, artboard);
|
||||
network_interface.move_layer_to_stack(artboard_layer, LayerNodeIdentifier::ROOT_PARENT, 0, &[]);
|
||||
|
||||
// If there is a non artboard feeding into the primary input of the artboard, move it to the secondary input
|
||||
@@ -163,14 +138,14 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
// Apply a translation to prevent the content from shifting
|
||||
responses.add(GraphOperationMessage::TransformChange {
|
||||
layer,
|
||||
transform: DAffine2::from_translation(-location),
|
||||
transform: DAffine2::from_translation(-artboard_location.as_dvec2()),
|
||||
transform_in: TransformIn::Local,
|
||||
skip_rerender: true,
|
||||
});
|
||||
}
|
||||
|
||||
// Set the bottom input of the artboard back to artboard
|
||||
let bottom_input = NodeInput::type_default(descriptor!(List<Artboard>), true);
|
||||
let bottom_input = NodeInput::value(TaggedValue::Artboard(Table::new()), true);
|
||||
network_interface.set_input(&InputConnector::node(artboard_layer.to_node(), 0), bottom_input, &[]);
|
||||
} else {
|
||||
// We have some non layers (e.g. just a rectangle node). We disconnect the bottom input and connect it to the left input.
|
||||
@@ -178,17 +153,22 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
network_interface.set_input(&InputConnector::node(artboard_layer.to_node(), 1), primary_input, &[]);
|
||||
|
||||
// Set the bottom input of the artboard back to artboard
|
||||
let bottom_input = NodeInput::type_default(descriptor!(List<Artboard>), true);
|
||||
let bottom_input = NodeInput::value(TaggedValue::Artboard(Table::new()), true);
|
||||
network_interface.set_input(&InputConnector::node(artboard_layer.to_node(), 0), bottom_input, &[]);
|
||||
}
|
||||
}
|
||||
responses.add_front(NodeGraphMessage::SelectedNodesSet { nodes: vec![id] });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
GraphOperationMessage::NewBitmapLayer { id, image, parent, insert_index } => {
|
||||
GraphOperationMessage::NewBitmapLayer {
|
||||
id,
|
||||
image_frame,
|
||||
parent,
|
||||
insert_index,
|
||||
} => {
|
||||
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
|
||||
let layer = modify_inputs.create_layer(id);
|
||||
modify_inputs.insert_image_data(image, layer);
|
||||
modify_inputs.insert_image_data(image_frame, layer);
|
||||
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
@@ -222,12 +202,10 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
|
||||
responses.add(NodeGraphMessage::SetDisplayNameImpl {
|
||||
node_id: id,
|
||||
network_path: Vec::new(),
|
||||
alias: layer_alias.to_string(),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetDisplayNameImpl {
|
||||
node_id: control_path_id,
|
||||
network_path: Vec::new(),
|
||||
alias: path_alias.to_string(),
|
||||
});
|
||||
}
|
||||
@@ -272,7 +250,6 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
|
||||
responses.add(NodeGraphMessage::SetDisplayNameImpl {
|
||||
node_id: id,
|
||||
network_path: Vec::new(),
|
||||
alias: "Boolean Operation".to_string(),
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
@@ -323,6 +300,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
let layer = modify_inputs.create_layer(id);
|
||||
modify_inputs.insert_text(text, font, typesetting, layer);
|
||||
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
|
||||
responses.add(GraphOperationMessage::StrokeSet { layer, stroke: Stroke::default() });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
GraphOperationMessage::ResizeArtboard { layer, location, dimensions } => {
|
||||
@@ -370,7 +348,6 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
|
||||
responses.add(NodeGraphMessage::SetDisplayName {
|
||||
node_id,
|
||||
network_path: Vec::new(),
|
||||
alias: network_interface.display_name(&artboard.to_node(), &[]),
|
||||
skip_adding_history_step: true,
|
||||
});
|
||||
@@ -485,8 +462,7 @@ struct ArtboardInfo {
|
||||
}
|
||||
|
||||
fn usvg_color(c: usvg::Color, a: f32) -> Color {
|
||||
// `usvg::Color` channels are u8 sRGB display values (gamma-encoded); lift to linear-light for the internal `Color`
|
||||
Color::from_gamma_srgb_channels(c.red as f32 / 255., c.green as f32 / 255., c.blue as f32 / 255., a)
|
||||
Color::from_rgbaf32_unchecked(c.red as f32 / 255., c.green as f32 / 255., c.blue as f32 / 255., a)
|
||||
}
|
||||
|
||||
fn usvg_transform(c: usvg::Transform) -> DAffine2 {
|
||||
@@ -692,7 +668,7 @@ fn import_usvg_path(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node,
|
||||
|
||||
modify_inputs.insert_vector(subpaths, layer, has_transform, path.fill().is_some(), path.stroke().is_some());
|
||||
|
||||
if has_transform && let Some(transform_node_id) = modify_inputs.existing_proto_node_id(graphene_std::transform_nodes::transform::IDENTIFIER, false) {
|
||||
if has_transform && let Some(transform_node_id) = modify_inputs.existing_network_node_id("Transform", false) {
|
||||
transform_utils::update_transform(modify_inputs.network_interface, &transform_node_id, node_transform);
|
||||
}
|
||||
|
||||
@@ -742,10 +718,10 @@ fn set_import_child_positions(
|
||||
let child_pos = IVec2::new(child_x, current_y);
|
||||
|
||||
if i == 0 {
|
||||
// Top of stack: set to `Absolute` position
|
||||
// Top of stack — set to `Absolute` position
|
||||
network_interface.set_layer_position_for_import(&child_layer.to_node(), LayerPosition::Absolute(child_pos), &[]);
|
||||
} else {
|
||||
// Below top: set `Stack` with `y_offset` based on previous sibling's subtree extent
|
||||
// Below top — set `Stack` with `y_offset` based on previous sibling's subtree extent
|
||||
let prev_sibling_svg_index = n - i;
|
||||
let y_offset = child_extents_svg_order[prev_sibling_svg_index] + STACK_VERTICAL_GAP as u32;
|
||||
network_interface.set_layer_position_for_import(&child_layer.to_node(), LayerPosition::Stack(y_offset), &[]);
|
||||
|
||||
@@ -1,22 +1,21 @@
|
||||
use super::transform_utils;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type, resolve_network_node_type, resolve_proto_node_type};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, OutputConnector};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{self, InputConnector, NodeNetworkInterface, OutputConnector};
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::application_io::resource::ResourceId;
|
||||
use glam::{DAffine2, IVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graph_craft::{ProtoNodeIdentifier, concrete, descriptor};
|
||||
use graph_craft::{ProtoNodeIdentifier, concrete};
|
||||
use graphene_std::brush::brush_stroke::BrushStroke;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster_types::Image;
|
||||
use graphene_std::raster_types::{CPU, Raster};
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::table::Table;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{Fill, GradientSpreadMethod, GradientType, Stroke};
|
||||
use graphene_std::vector::{GradientStops, PointId, Vector, VectorModification, VectorModificationType};
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::vector::style::{Fill, Stroke};
|
||||
use graphene_std::vector::{PointId, VectorModificationType};
|
||||
use graphene_std::{Artboard, Color, Graphic, NodeInputDecleration};
|
||||
|
||||
#[derive(PartialEq, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
|
||||
@@ -131,27 +130,25 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
LayerNodeIdentifier::new(new_id, self.network_interface)
|
||||
}
|
||||
|
||||
/// Creates an artboard as the primary export for the document network.
|
||||
pub fn create_artboard(&mut self, new_id: NodeId, location: DVec2, dimensions: DVec2, background: Color, clip: bool) -> LayerNodeIdentifier {
|
||||
/// Creates an artboard as the primary export for the document network
|
||||
pub fn create_artboard(&mut self, new_id: NodeId, artboard: Artboard) -> LayerNodeIdentifier {
|
||||
let artboard_node_template = resolve_network_node_type("Artboard").expect("Node").node_template_input_override([
|
||||
Some(NodeInput::type_default(descriptor!(List<Artboard>), true)),
|
||||
Some(NodeInput::type_default(descriptor!(List<Graphic>), true)),
|
||||
Some(NodeInput::value(TaggedValue::DVec2(location), false)),
|
||||
Some(NodeInput::value(TaggedValue::DVec2(dimensions), false)),
|
||||
Some(NodeInput::value(TaggedValue::Color(Some(background)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Bool(clip), false)),
|
||||
Some(NodeInput::value(TaggedValue::Artboard(Default::default()), true)),
|
||||
Some(NodeInput::value(TaggedValue::Graphic(Default::default()), true)),
|
||||
Some(NodeInput::value(TaggedValue::DVec2(artboard.location.into()), false)),
|
||||
Some(NodeInput::value(TaggedValue::DVec2(artboard.dimensions.into()), false)),
|
||||
Some(NodeInput::value(TaggedValue::Color(Table::new_from_element(artboard.background)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Bool(artboard.clip), false)),
|
||||
]);
|
||||
self.network_interface.insert_node(new_id, artboard_node_template, &[]);
|
||||
LayerNodeIdentifier::new(new_id, self.network_interface)
|
||||
}
|
||||
|
||||
pub fn insert_boolean_data(&mut self, operation: graphene_std::vector::misc::BooleanOperation, layer: LayerNodeIdentifier) {
|
||||
let boolean = resolve_proto_node_type(graphene_std::path_bool_nodes::boolean_operation::IDENTIFIER)
|
||||
.expect("Boolean node does not exist")
|
||||
.node_template_input_override([
|
||||
Some(NodeInput::type_default(descriptor!(List<Graphic>), true)),
|
||||
Some(NodeInput::value(TaggedValue::BooleanOperation(operation), false)),
|
||||
]);
|
||||
let boolean = resolve_network_node_type("Boolean Operation").expect("Boolean node does not exist").node_template_input_override([
|
||||
Some(NodeInput::value(TaggedValue::Graphic(Default::default()), true)),
|
||||
Some(NodeInput::value(TaggedValue::BooleanOperation(operation), false)),
|
||||
]);
|
||||
|
||||
let boolean_id = NodeId::new();
|
||||
self.network_interface.insert_node(boolean_id, boolean, &[]);
|
||||
@@ -159,9 +156,10 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
pub fn insert_blend_data(&mut self, layer: LayerNodeIdentifier, count: f64) -> NodeId {
|
||||
let blend = resolve_network_node_type("Blend")
|
||||
.expect("Blend node does not exist")
|
||||
.node_template_input_override([Some(NodeInput::type_default(descriptor!(List<Graphic>), true)), Some(NodeInput::value(TaggedValue::F64(count), false))]);
|
||||
let blend = resolve_network_node_type("Blend").expect("Blend node does not exist").node_template_input_override([
|
||||
Some(NodeInput::value(TaggedValue::Graphic(Default::default()), true)),
|
||||
Some(NodeInput::value(TaggedValue::F64(count), false)),
|
||||
]);
|
||||
|
||||
let blend_id = NodeId::new();
|
||||
self.network_interface.insert_node(blend_id, blend, &[]);
|
||||
@@ -173,7 +171,10 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
pub fn insert_morph_data(&mut self, layer: LayerNodeIdentifier) -> NodeId {
|
||||
let morph = resolve_proto_node_type(graphene_std::vector::morph::IDENTIFIER)
|
||||
.expect("Morph node does not exist")
|
||||
.node_template_input_override([Some(NodeInput::type_default(descriptor!(List<Graphic>), true)), Some(NodeInput::value(TaggedValue::F64(0.5), false))]);
|
||||
.node_template_input_override([
|
||||
Some(NodeInput::value(TaggedValue::Graphic(Default::default()), true)),
|
||||
Some(NodeInput::value(TaggedValue::F64(0.5), false)),
|
||||
]);
|
||||
|
||||
let morph_id = NodeId::new();
|
||||
self.network_interface.insert_node(morph_id, morph, &[]);
|
||||
@@ -210,21 +211,17 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
pub fn insert_vector(&mut self, subpaths: Vec<Subpath<PointId>>, layer: LayerNodeIdentifier, include_transform: bool, include_fill: bool, include_stroke: bool) {
|
||||
// Build a VectorModification that reproduces the geometry (same format the Pen tool uses)
|
||||
let vector = Vector::from_subpaths(subpaths, true);
|
||||
let modification = Box::new(VectorModification::create_from_vector(&vector));
|
||||
let vector = Table::new_from_element(Vector::from_subpaths(subpaths, true));
|
||||
|
||||
let shape = resolve_network_node_type("Path")
|
||||
.expect("Path node does not exist")
|
||||
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::VectorModification(modification), false))]);
|
||||
.node_template_input_override([Some(NodeInput::value(TaggedValue::Vector(vector), false))]);
|
||||
let shape_id = NodeId::new();
|
||||
self.network_interface.insert_node(shape_id, shape, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&shape_id, layer, &[], self.import);
|
||||
|
||||
if include_transform {
|
||||
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
|
||||
.expect("Transform node does not exist")
|
||||
.default_node_template();
|
||||
let transform = resolve_network_node_type("Transform").expect("Transform node does not exist").default_node_template();
|
||||
let transform_id = NodeId::new();
|
||||
self.network_interface.insert_node(transform_id, transform, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[], self.import);
|
||||
@@ -250,13 +247,12 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
pub fn insert_text(&mut self, text: String, font: Font, typesetting: TypesettingConfig, layer: LayerNodeIdentifier) {
|
||||
let font_resource_id = ResourceId::new();
|
||||
let text = resolve_proto_node_type(graphene_std::text::text::IDENTIFIER)
|
||||
.expect("Text node does not exist")
|
||||
.node_template_input_override([
|
||||
Some(NodeInput::value(TaggedValue::None, false)),
|
||||
Some(NodeInput::scope("editor-api")),
|
||||
Some(NodeInput::value(TaggedValue::String(text), false)),
|
||||
Some(NodeInput::value(TaggedValue::Resource(font_resource_id), false)),
|
||||
Some(NodeInput::value(TaggedValue::Font(font), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.font_size), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.line_height_ratio), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.character_spacing), false)),
|
||||
@@ -266,10 +262,10 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.max_height.unwrap_or(100.)), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.tilt), false)),
|
||||
Some(NodeInput::value(TaggedValue::TextAlign(typesetting.align), false)),
|
||||
Some(NodeInput::value(TaggedValue::Bool(false), false)),
|
||||
]);
|
||||
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
|
||||
.expect("Transform node does not exist")
|
||||
let transform = resolve_network_node_type("Transform").expect("Transform node does not exist").default_node_template();
|
||||
let stroke = resolve_proto_node_type(graphene_std::vector_nodes::stroke::IDENTIFIER)
|
||||
.expect("Stroke node does not exist")
|
||||
.default_node_template();
|
||||
let fill = resolve_proto_node_type(graphene_std::vector_nodes::fill::IDENTIFIER)
|
||||
.expect("Fill node does not exist")
|
||||
@@ -279,12 +275,14 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.network_interface.insert_node(text_id, text, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&text_id, layer, &[], self.import);
|
||||
|
||||
self.responses.add(DocumentMessage::Resource(ResourceMessage::AddFont { resource_id: font_resource_id, font }));
|
||||
|
||||
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);
|
||||
|
||||
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);
|
||||
@@ -293,31 +291,25 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
pub fn insert_color_value(&mut self, color: Color, layer: LayerNodeIdentifier) {
|
||||
let color_value = resolve_proto_node_type(graphene_std::math_nodes::color_value::IDENTIFIER)
|
||||
.expect("Color Value node does not exist")
|
||||
.node_template_input_override([Some(NodeInput::value(TaggedValue::None, false)), Some(NodeInput::value(TaggedValue::Color(Some(color)), false))]);
|
||||
.node_template_input_override([
|
||||
Some(NodeInput::value(TaggedValue::None, false)),
|
||||
Some(NodeInput::value(TaggedValue::Color(Table::new_from_element(color)), false)),
|
||||
]);
|
||||
|
||||
let color_value_id = NodeId::new();
|
||||
self.network_interface.insert_node(color_value_id, color_value, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&color_value_id, layer, &[], self.import);
|
||||
}
|
||||
|
||||
pub fn insert_image_data(&mut self, image: Image<Color>, layer: LayerNodeIdentifier) {
|
||||
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
|
||||
.expect("Transform node does not exist")
|
||||
.default_node_template();
|
||||
pub fn insert_image_data(&mut self, image_frame: Table<Raster<CPU>>, layer: LayerNodeIdentifier) {
|
||||
let transform = resolve_network_node_type("Transform").expect("Transform node does not exist").default_node_template();
|
||||
let image = resolve_proto_node_type(graphene_std::raster_nodes::std_nodes::image_value::IDENTIFIER)
|
||||
.expect("ImageValue node does not exist")
|
||||
.node_template_input_override([Some(NodeInput::value(TaggedValue::None, false)), Some(NodeInput::value(TaggedValue::Raster(image_frame), false))]);
|
||||
|
||||
let resource_id = ResourceId::new();
|
||||
self.responses.add(ResourceMessage::StoreEmbedded {
|
||||
resource_id,
|
||||
data: image.to_png().into(),
|
||||
});
|
||||
|
||||
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::Resource(resource_id), false))]);
|
||||
|
||||
let image_node_id = NodeId::new();
|
||||
self.network_interface.insert_node(image_node_id, image_node, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&image_node_id, layer, &[], self.import);
|
||||
let image_id = NodeId::new();
|
||||
self.network_interface.insert_node(image_id, image, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&image_id, layer, &[], self.import);
|
||||
|
||||
let transform_id = NodeId::new();
|
||||
self.network_interface.insert_node(transform_id, transform, &[]);
|
||||
@@ -340,37 +332,6 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.existing_node_id(&DefinitionIdentifier::Network(reference.into()), create_if_nonexistent)
|
||||
}
|
||||
|
||||
/// Like `existing_proto_node_id`, but walks/inserts at `target_input` instead of the layer's content input.
|
||||
/// Used when a chain lives on a non-layer input.
|
||||
pub fn existing_proto_node_id_at(&mut self, target_input: &InputConnector, reference: ProtoNodeIdentifier, create_if_nonexistent: bool) -> Option<NodeId> {
|
||||
let identifier = DefinitionIdentifier::ProtoNode(reference.clone());
|
||||
|
||||
// Walk upstream from whatever is currently connected to target_input
|
||||
let walk_start = self.network_interface.upstream_output_connector(target_input, &[]).and_then(|out| out.node_id());
|
||||
|
||||
let existing = walk_start.and_then(|start| {
|
||||
self.network_interface
|
||||
.upstream_flow_back_from_nodes(vec![start], &[], FlowType::HorizontalFlow)
|
||||
.take_while(|id| !self.network_interface.is_layer(id, &[]))
|
||||
.find(|id| self.network_interface.reference(id, &[]).as_ref() == Some(&identifier) && self.network_interface.is_visible(id, &[]))
|
||||
});
|
||||
|
||||
if let Some(id) = existing {
|
||||
return Some(id);
|
||||
}
|
||||
if !create_if_nonexistent {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Splice a new node onto the wire feeding `target_input`, positioning it sensibly within the chain.
|
||||
let node_definition = resolve_proto_node_type(reference)?;
|
||||
let node_id = NodeId::new();
|
||||
self.network_interface.insert_node(node_id, node_definition.default_node_template(), &[]);
|
||||
self.network_interface.insert_node_before_input(&node_id, target_input, &[]);
|
||||
|
||||
Some(node_id)
|
||||
}
|
||||
|
||||
/// Gets the node id of a proto node with a specific reference that is upstream from the layer node, and optionally creates it if it does not exist.
|
||||
pub fn existing_proto_node_id(&mut self, reference: ProtoNodeIdentifier, create_if_nonexistent: bool) -> Option<NodeId> {
|
||||
self.existing_node_id(&DefinitionIdentifier::ProtoNode(reference), create_if_nonexistent)
|
||||
@@ -427,10 +388,10 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
};
|
||||
|
||||
// If inserting a 'Path' node, insert a 'Flatten Path' node if the type is `Graphic`.
|
||||
// TODO: Allow the 'Path' node to operate on `List` data by utilizing the reference (index or ID?) for each item.
|
||||
// TODO: Allow the 'Path' node to operate on table data by utilizing the reference (index or ID?) for each row.
|
||||
if node_definition.identifier == "Path" {
|
||||
let layer_input_type = self.network_interface.input_type(&InputConnector::node(output_layer.to_node(), 1), &[]);
|
||||
if layer_input_type.compiled_nested_type() == Some(&concrete!(List<Graphic>)) {
|
||||
if layer_input_type.compiled_nested_type() == Some(&concrete!(Table<Graphic>)) {
|
||||
let Some(flatten_path_definition) = resolve_proto_node_type(graphene_std::vector_nodes::flatten_path::IDENTIFIER) else {
|
||||
log::error!("Flatten Path does not exist in ModifyInputsContext::existing_node_id");
|
||||
return None;
|
||||
@@ -457,15 +418,15 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
match &fill {
|
||||
Fill::None => {
|
||||
let input_connector = InputConnector::node(fill_node_id, backup_color_index);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(None), false), true);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(Table::new()), false), true);
|
||||
}
|
||||
Fill::Solid(color) => {
|
||||
let input_connector = InputConnector::node(fill_node_id, backup_color_index);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(Some(*color)), false), true);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(Table::new_from_element(*color)), false), true);
|
||||
}
|
||||
Fill::Gradient(gradient) => {
|
||||
let input_connector = InputConnector::node(fill_node_id, backup_gradient_index);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::FillGradient(gradient.clone()), false), true);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Gradient(gradient.clone()), false), true);
|
||||
}
|
||||
}
|
||||
let input_connector = InputConnector::node(fill_node_id, fill_index);
|
||||
@@ -473,173 +434,35 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
pub fn blend_mode_set(&mut self, blend_mode: BlendMode) {
|
||||
let Some(blend_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::blend_mode::IDENTIFIER, true) else {
|
||||
let Some(blend_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::blending::IDENTIFIER, true) else {
|
||||
return;
|
||||
};
|
||||
let input_connector = InputConnector::node(blend_node_id, graphene_std::blending_nodes::blend_mode::BlendModeInput::INDEX);
|
||||
let input_connector = InputConnector::node(blend_node_id, 1);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::BlendMode(blend_mode), false), false);
|
||||
}
|
||||
|
||||
pub fn opacity_set(&mut self, opacity: f64) {
|
||||
let Some(opacity_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::opacity::IDENTIFIER, true) else {
|
||||
let Some(blend_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::blending::IDENTIFIER, true) else {
|
||||
return;
|
||||
};
|
||||
// Enable the `has_opacity` checkbox so the value is applied
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::HasOpacityInput::INDEX),
|
||||
NodeInput::value(TaggedValue::Bool(true), false),
|
||||
false,
|
||||
);
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::OpacityInput::INDEX),
|
||||
NodeInput::value(TaggedValue::F64(opacity * 100.), false),
|
||||
false,
|
||||
);
|
||||
let input_connector = InputConnector::node(blend_node_id, 2);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(opacity * 100.), false), false);
|
||||
}
|
||||
|
||||
pub fn opacity_fill_set(&mut self, fill: f64) {
|
||||
// Reuse an existing Opacity node to avoid a redundant chain walk on slider drags
|
||||
let identifier = graphene_std::blending_nodes::opacity::IDENTIFIER;
|
||||
let existing = self.existing_proto_node_id(identifier.clone(), false);
|
||||
let existed = existing.is_some();
|
||||
let Some(opacity_node_id) = existing.or_else(|| self.existing_proto_node_id(identifier, true)) else {
|
||||
pub fn blending_fill_set(&mut self, fill: f64) {
|
||||
let Some(blend_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::blending::IDENTIFIER, true) else {
|
||||
return;
|
||||
};
|
||||
// Freshly-created node defaults to opacity enabled; disable it so the fill slider works independently
|
||||
if !existed {
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::HasOpacityInput::INDEX),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
false,
|
||||
);
|
||||
}
|
||||
// Enable the `has_fill` checkbox so the value is applied
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::HasFillInput::INDEX),
|
||||
NodeInput::value(TaggedValue::Bool(true), false),
|
||||
false,
|
||||
);
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::FillInput::INDEX),
|
||||
NodeInput::value(TaggedValue::F64(fill * 100.), false),
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
/// Write the gradient stops to the 'Gradient Value' node feeding the layer.
|
||||
pub fn gradient_stops_set(&mut self, stops: GradientStops) {
|
||||
let Some(output_layer) = self.get_output_layer() else { return };
|
||||
let Some(gradient_value_id) = get_upstream_gradient_value_node_id(output_layer, self.network_interface) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let input_connector = InputConnector::node(gradient_value_id, graphene_std::math_nodes::gradient_value::GradientInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Gradient(stops), false), false);
|
||||
}
|
||||
|
||||
/// Update the gradient line so its endpoints are at `new_start` and `new_end`.
|
||||
/// 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 walk_from = if let Some(fill_input_node_id) = get_fill_input_node_id(output_layer, self.network_interface) {
|
||||
// Some nodes are connected to a Fill node, this means that the primary path is a `List<Vector>`, so we need to traverse it
|
||||
fill_input_node_id
|
||||
} else {
|
||||
// No Fill node found, we will traverse the primary path to find transforms
|
||||
output_layer.to_node()
|
||||
};
|
||||
|
||||
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![walk_from], &[], FlowType::HorizontalFlow)
|
||||
.skip_while(|node_id| self.network_interface.is_layer(node_id, &[]))
|
||||
.take_while(|node_id| !self.network_interface.is_layer(node_id, &[]))
|
||||
.filter(|id| self.network_interface.reference(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_composed = build_transform_with_y_preservation(composed_old, new_start, new_end);
|
||||
let last_transform_value = new_composed * prior_combined.inverse();
|
||||
|
||||
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
|
||||
let transform_node_id = if let Some(id) = last_transform_node_id {
|
||||
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_at(&target_input, 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 Some(output_layer) = self.get_output_layer() else { return };
|
||||
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
|
||||
let identifier = graphene_std::math_nodes::gradient_type::IDENTIFIER;
|
||||
let create_if_nonexistent = gradient_type != GradientType::default();
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, 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 Some(output_layer) = self.get_output_layer() else { return };
|
||||
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
|
||||
let identifier = graphene_std::math_nodes::spread_method::IDENTIFIER;
|
||||
let create_if_nonexistent = spread_method != GradientSpreadMethod::default();
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, create_if_nonexistent) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::spread_method::SpreadMethodInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientSpreadMethod(spread_method), false), false);
|
||||
let input_connector = InputConnector::node(blend_node_id, 3);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(fill * 100.), false), false);
|
||||
}
|
||||
|
||||
pub fn clip_mode_toggle(&mut self, clip_mode: Option<bool>) {
|
||||
let clip = !clip_mode.unwrap_or(false);
|
||||
let Some(clip_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::clipping_mask::IDENTIFIER, true) else {
|
||||
let Some(clip_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::blending::IDENTIFIER, true) else {
|
||||
return;
|
||||
};
|
||||
let input_connector = InputConnector::node(clip_node_id, graphene_std::blending_nodes::clipping_mask::ClipInput::INDEX);
|
||||
let input_connector = InputConnector::node(clip_node_id, 4);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Bool(clip), false), false);
|
||||
}
|
||||
|
||||
@@ -648,8 +471,10 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
return;
|
||||
};
|
||||
|
||||
let stroke_color = if let Some(color) = stroke.color { Table::new_from_element(color) } else { Table::new() };
|
||||
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::ColorInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(stroke.color), false), true);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(stroke_color), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::WeightInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.weight), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::AlignInput::INDEX);
|
||||
@@ -662,8 +487,8 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.join_miter_limit), false), false);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintOrderInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::PaintOrder(stroke.paint_order), false), false);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashLengthsInput::<graphene_std::list::List<f64>>::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(stroke.dash_lengths), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashLengthsInput::<Vec<f64>>::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::VecF64(stroke.dash_lengths), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.dash_offset), false), true);
|
||||
}
|
||||
@@ -673,7 +498,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
pub fn transform_change_with_parent(&mut self, transform: DAffine2, transform_in: TransformIn, parent_transform: DAffine2, skip_rerender: bool) {
|
||||
// Get the existing upstream Transform node and its transform, if present, otherwise use the identity transform
|
||||
let (layer_transform, transform_node_id) = self
|
||||
.existing_proto_node_id(graphene_std::transform_nodes::transform::IDENTIFIER, false)
|
||||
.existing_network_node_id("Transform", false)
|
||||
.and_then(|transform_node_id| {
|
||||
let document_node = self.network_interface.document_network().nodes.get(&transform_node_id)?;
|
||||
Some((transform_utils::get_current_transform(&document_node.inputs), transform_node_id))
|
||||
@@ -697,32 +522,17 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
/// A new Transform node is created if one does not exist, unless it would be given the identity transform.
|
||||
pub fn transform_set(&mut self, transform: DAffine2, transform_in: TransformIn, skip_rerender: bool) {
|
||||
// Get the existing upstream Transform node, if present
|
||||
let transform_node_id = self.existing_proto_node_id(graphene_std::transform_nodes::transform::IDENTIFIER, false);
|
||||
let transform_node_id = self.existing_network_node_id("Transform", false);
|
||||
|
||||
// Compute the Transform node value so `transform_to_viewport` matches the target after re-render
|
||||
let final_transform = match transform_in {
|
||||
TransformIn::Local => transform,
|
||||
TransformIn::Scope { scope } => scope * transform,
|
||||
TransformIn::Viewport => {
|
||||
let Some(layer) = self.layer_node else { return };
|
||||
let metadata = self.network_interface.document_metadata();
|
||||
let parent_inverse = metadata.downstream_transform_to_viewport(layer).inverse();
|
||||
|
||||
// Compensate for item 0's baseline offset (multi-item Text only) so the layer doesn't jump by it.
|
||||
// Gated on `text_frames` because metadata can be stale mid-handler.
|
||||
if metadata.text_frames.contains_key(&layer) {
|
||||
let local_transform = metadata.local_transforms.get(&layer.to_node()).copied().unwrap_or(DAffine2::IDENTITY);
|
||||
let current_transform_node_value = transform_node_id
|
||||
.and_then(|id| self.network_interface.document_network().nodes.get(&id))
|
||||
.map(|node| transform_utils::get_current_transform(&node.inputs))
|
||||
.unwrap_or(DAffine2::IDENTITY);
|
||||
parent_inverse * transform * local_transform.inverse() * current_transform_node_value
|
||||
} else {
|
||||
parent_inverse * transform
|
||||
}
|
||||
}
|
||||
// Get a transform appropriate for the requested space
|
||||
let to_transform = match transform_in {
|
||||
TransformIn::Local => DAffine2::IDENTITY,
|
||||
TransformIn::Scope { scope } => scope,
|
||||
TransformIn::Viewport => self.network_interface.document_metadata().downstream_transform_to_viewport(self.layer_node.unwrap()).inverse(),
|
||||
};
|
||||
|
||||
// Set the transform value to the Transform node
|
||||
let final_transform = to_transform * transform;
|
||||
self.transform_set_direct(final_transform, skip_rerender, transform_node_id);
|
||||
}
|
||||
|
||||
@@ -737,7 +547,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
// Create the Transform node
|
||||
self.existing_proto_node_id(graphene_std::transform_nodes::transform::IDENTIFIER, true)
|
||||
self.existing_network_node_id("Transform", true)
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
@@ -762,13 +572,13 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
pub fn brush_modify(&mut self, strokes: Vec<BrushStroke>) {
|
||||
let Some(brush_node_id) = self.existing_proto_node_id(graphene_std::brush::brush::brush::IDENTIFIER, true) else {
|
||||
let Some(brush_node_id) = self.existing_network_node_id("Brush", true) else {
|
||||
return;
|
||||
};
|
||||
self.set_input_with_refresh(InputConnector::node(brush_node_id, 1), NodeInput::value(TaggedValue::BrushStrokes(strokes), false), false);
|
||||
}
|
||||
|
||||
pub fn resize_artboard(&mut self, location: DVec2, dimensions: DVec2) {
|
||||
pub fn resize_artboard(&mut self, location: IVec2, dimensions: IVec2) {
|
||||
let Some(artboard_node_id) = self.existing_network_node_id("Artboard", true) else {
|
||||
return;
|
||||
};
|
||||
@@ -776,19 +586,19 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
let mut dimensions = dimensions;
|
||||
let mut location = location;
|
||||
|
||||
if dimensions.x < 0. {
|
||||
dimensions.x = -dimensions.x;
|
||||
if dimensions.x < 0 {
|
||||
dimensions.x *= -1;
|
||||
location.x -= dimensions.x;
|
||||
}
|
||||
if dimensions.y < 0. {
|
||||
dimensions.y = -dimensions.y;
|
||||
if dimensions.y < 0 {
|
||||
dimensions.y *= -1;
|
||||
location.y -= dimensions.y;
|
||||
}
|
||||
self.set_input_with_refresh(InputConnector::node(artboard_node_id, 2), NodeInput::value(TaggedValue::DVec2(location), false), false);
|
||||
self.set_input_with_refresh(InputConnector::node(artboard_node_id, 3), NodeInput::value(TaggedValue::DVec2(dimensions), false), false);
|
||||
self.set_input_with_refresh(InputConnector::node(artboard_node_id, 2), NodeInput::value(TaggedValue::DVec2(location.into()), false), false);
|
||||
self.set_input_with_refresh(InputConnector::node(artboard_node_id, 3), NodeInput::value(TaggedValue::DVec2(dimensions.into()), false), false);
|
||||
}
|
||||
|
||||
/// Set the input, refresh the Properties panel, and run the document graph if skip_rerender is false
|
||||
/// Set the input, refresh the properties panel, and run the document graph if skip_rerender is false
|
||||
pub fn set_input_with_refresh(&mut self, input_connector: InputConnector, input: NodeInput, skip_rerender: bool) {
|
||||
self.network_interface.set_input(&input_connector, input, &[]);
|
||||
self.responses.add(PropertiesPanelMessage::Refresh);
|
||||
@@ -797,40 +607,3 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuild the y-axis so its (parallel, perpendicular) components in the x-axis-aligned frame stay constant, both
|
||||
/// rescaled by `|new_x| / |old_x|`. This holds the (x, y) parallelogram's aspect ratio and skew fixed across an endpoint
|
||||
/// drag, so a radial ellipse stays the same shape (just rotated and resized) instead of distorting as x grows or shrinks.
|
||||
/// Falls back to a +90° rotation of `new_x` when `old_x` is degenerate.
|
||||
fn scale_y_axis_to_match_new_x(old_x: DVec2, old_y: DVec2, new_x: DVec2) -> DVec2 {
|
||||
let old_x_length = old_x.length();
|
||||
if old_x_length < 1e-9 {
|
||||
return DVec2::new(-new_x.y, new_x.x);
|
||||
}
|
||||
let ex_old = old_x / old_x_length;
|
||||
let ey_old = DVec2::new(-ex_old.y, ex_old.x);
|
||||
|
||||
let new_x_length = new_x.length();
|
||||
if new_x_length < 1e-9 {
|
||||
return DVec2::ZERO;
|
||||
}
|
||||
let ex_new = new_x / new_x_length;
|
||||
let ey_new = DVec2::new(-ex_new.y, ex_new.x);
|
||||
|
||||
let parallel = old_y.dot(ex_old);
|
||||
let perpendicular = old_y.dot(ey_old);
|
||||
let scale = new_x_length / old_x_length;
|
||||
|
||||
scale * (parallel * ex_new + perpendicular * ey_new)
|
||||
}
|
||||
|
||||
/// Build a new affine that maps canonical (0,0) -> (1,0) to (new_start, new_end), preserving the y-axis
|
||||
/// shape of `old` proportionally to the x-axis length change.
|
||||
fn build_transform_with_y_preservation(old: DAffine2, new_start: DVec2, new_end: DVec2) -> DAffine2 {
|
||||
let new_x_axis = new_end - new_start;
|
||||
let preserved_y_axis = scale_y_axis_to_match_new_x(old.matrix2.x_axis, old.matrix2.y_axis, new_x_axis);
|
||||
DAffine2 {
|
||||
matrix2: glam::DMat2::from_cols(new_x_axis, preserved_y_axis),
|
||||
translation: new_start,
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,6 @@ pub mod navigation;
|
||||
pub mod node_graph;
|
||||
pub mod overlays;
|
||||
pub mod properties_panel;
|
||||
pub mod resource;
|
||||
pub mod utility_types;
|
||||
|
||||
#[doc(inline)]
|
||||
|
||||
Loaded 100 of 371 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user