Compare commits

..
Author SHA1 Message Date
Timon 43c780c5c0 safer cef texture import 2026-04-24 17:23:37 +00:00
Timon 3c04c2bb8b WIP 2026-04-24 17:23:31 +00:00
Timon e0d3c21429 Update CEF 2026-04-24 17:23:31 +00:00
Timon 96b18d2552 Fix gpu nodes 2026-04-24 16:46:16 +00:00
Timon 7afa1ced37 Review 2026-04-23 13:46:24 +00:00
firestar99 adee7fc46f rust-gpu alpha.1: update rust-gpu to 0.10.0-alpha.1 on crates 2026-04-21 13:54:35 +02:00
firestar99 9e2a274453 rust-gpu alpha.1: disable non-working mold shell hook 2026-04-21 13:12:06 +02:00
firestar99 97f44e8915 rust-gpu alpha.1: update nix flake 2026-04-21 13:11:58 +02:00
Timon 6c5e3c97f8 Refactor persistence to combine document handling and workspace layout (#4031)
* Unify editor state persistence

* Review

* Fix

* Remove redundant DocumentDetails

* LoadDocumentContent indirection
2026-04-19 09:31:21 +00:00
Timon 2a2a60883d Desktop: Use the OS temp directory for CEF caches (#4030)
* Desktop: Use the OS temp dir

* Review
2026-04-15 10:47:45 +00:00
Keavon ChambersandTimon 60f16d72a5 Refactor IndexedDB document persistence to reuse data structures of desktop persistence (#4020)
* Switch indexedDb document serialized struct from camelCase to snake_case

* Refactor and migrate old indexedDb format to the same shape as desktop persistence

* Avoid duplicate struct definitions in the desktop crate

* Refactor frontend message handling to consolidate auto-save document loading

* Code review

* Review

---------

Co-authored-by: Timon <[email protected]>
2026-04-15 02:29:23 -07:00
YohYamasaki 79d778a535 Add support for setting the spread method for gradient fills (#3953)
* Add spread method support for gradients

* Add GradientSpreadMethod enum (Pad, Repeat, Reflect) to vector-types

* Add radio buttons to gradient tool and fill properties panel

* Convert spread method when importing SVGs via usvg

* Sync backup gradient input when changing spread method

* Table<GradientStops> rendering is not yet updated for spread method

* Sync gradient tool options with layer's gradient

* Sync gradient_type and spread_method from the selected
  layer's existing gradient to the tool options bar when
  switching to the gradient tool

* Refactor has_gradient_on_selected_layers
  to reuse a new get_gradient_on_selected_layer helper

* Swap Reflect and Repeat order in UI radio buttons

* Fix alignment of the radio buttons in right panel

* Fix the position of the radio buttons in the tool

* Rename SpreadMethod to SetSpreadMethod

* Move default spread method omission logic
2026-04-14 08:09:57 +00:00
Keavon Chambers da45ab2f87 Add a checkered background to transparent artboards and the infinite canvas (#4022)
* Add checkered transparency rendering to infinite canvas and artboards

* Enable artboard clipping by default

* Make new infinite canvas documents begin with a white background layer

* Remove the export dialog's transparency option now that it's redundant

* Make exporting transparent JPGs use white not black

* Code review
2026-04-10 03:21:21 -07:00
Timon 661e8bc569 Remove surface and window from ApplicationIo (#3941)
* Remove surface and window from ApplicationIo

* Seperate Wasm and Native ApplicationIo

* Fix warnings

* Fix tests

* Remove redundant PlatformApplicationIo::new_offscreen

* Fixup

* Remove unused From implementaitions for ApplicationIo
2026-04-09 20:12:53 +00:00
Keavon Chambers b100892bfa Add support for persistent storage of panel layouts, sizes, and active tabs (#4017)
* Add persistence to panel layouts

* Fix and persist the Window > Focus Document mode

* Add a Window > Reset Workspace action

* workspace_layout.json -> workspace_layout.ron

* Fix native app hole punch

* Cleanup review pass
2026-04-08 21:05:58 -07:00
Keavon Chambers b099e2faca Add support for interactive panel docking (#4015)
* Add interactive panel docking

* Preserve active tab when a panel group is docked

* Add inter-panel gutter hover color

* Code review fixes

* More code review
2026-04-08 06:09:20 -07:00
Keavon Chambers 39656d4c73 Refactor panel layouts to generalize recursive panel group subdivision splits (#4014)
* Generalize recursive panel group splits

* Code review
2026-04-08 00:44:58 -07:00
Timon 0eb440db14 Desktop: Improve Nix build times with more caching (#4007) 2026-04-08 01:46:38 +02:00
Timon 211111a01f Desktop: Fix document tab reorder not being persisted (#4002)
* Desktop: Fix reorder not beeing persisted

* Desktop: Use rfd fork to support starting_directory with zenity dialog backend
2026-04-08 01:13:30 +02:00
Keavon Chambers 1d0337285a Fix CSS regressions breaking the native app hole punch
Regressions introduced in e0212ca4b9
2026-04-04 14:33:41 -07:00
Keavon Chambers 848ff5fd52 Add support for dragging panel tabs docked into other panel tab bars (#4006)
* Add support for dragging panel tabs docked into other panel tab bars

* Fix terminology

* Add Group suffix to PanelGroupId enums variants

* Code review
2026-04-04 06:28:53 -07:00
Dennis Kobert 19aaeb374b Remove sample based image hashing to avoid false equalities (#3980)
* Remove sample based image hashing to avoid false equalities

This was originally introduced to improve the performance of working with
image data, but since the memo hash wrapper got introduced this should no
longer be really necessary.

* Fix todo comment
2026-04-04 11:46:08 +00:00
Timon bf269d7693 Introduce development Nix binary cache (#3911)
* Desktop: Introduce development Nix binary cache

* Configure caches in CI

* Cache nix shell

* Fix
2026-04-04 11:12:57 +00:00
Keavon Chambers a99b2806ff Update npm dependencies (#4004) 2026-04-04 00:19:08 -07:00
Keavon Chambers e0212ca4b9 Remove the svelte-preprocess dev dependency, keeping global styles with a custom Vite plugin (#4003)
* Remove the svelte-preprocess dev dependency, keeping global styles with a custom Vite plugin

* More robust style tag detection

* Fix CSS regressions
2026-04-03 23:53:46 -07:00
Keavon Chambers 55463fe0aa Refactor platform detection to use import.meta.env.MODE instead of isPlatformNative() 2026-04-03 21:26:27 -07:00
Keavon ChambersandTimon 4360359d60 Finalize and unify the design of the 'Morph' and 'Blend' nodes (#3974)
* Fix Morph node transform interpolation and preservation in the table

* Fix click target positions for Morph's nested layers by pre-compensating upstream_data transforms

* Redesign Morph node (v3) with control path input and uniformly spaced progression, and fix Stroke::lerp interpolation weights

* Add migration from Morph node v2 to v3

* Redesign the 'Blend Shapes' node behavior and subgraph definition

* Add the Layer > Blend menu entry to easily set up a blend

* Optimize the Morph node

* Refactor the Morph node to remove the roundtrip through BezPath

* Fine-tune Morph node Bezier order promotion and handle interpolation

* Add the Layer > Morph menu bar entry

* Fix NaN and guard against other potential NaN bugs breaking the editor

* Add InterpolationDistribution parameter to Morph with weighted progression, swap parameter orders, and rename shear to skew

* Add the Reverse parameter to the Morph node

* Update the order of the inputs to Blend Shapes for consistency with Morph

* Make Layer > Morph create the Morph Path control layer

* Fix migrations

* Move 10 to a constant

* Avoid division by 0 in the Blend Shapes node internals

* Rename nodes 'Blend' -> 'Mix' and 'Blend Shapes' to 'Blend'

* Fix a crash encountered while testing

* Final code review

* Make domain push dupe checks debug-only and use push_unchecked in the Morph node

* Pre-allocate for pushes to the vector domains

* Add fast path at t=0

* Inline reserve()

* Set up the control path layer above not below, and starting collapsed

* Review fixes

---------

Co-authored-by: Timon <[email protected]>
2026-04-03 20:45:58 -07:00
Keavon Chambers 7077e877f9 Allow double-clicking a gutter between panels to reset its sizing to default (#4000)
Support double-clicking to reset inter-panel gutter sizing
2026-04-03 14:43:25 -07:00
Keavon Chambers b52bf7b7d4 Add support for reordering document tabs (#3999)
* Add support for reordering document tabs

* Fix tab bar scrolling

* Close tab without activating it on pointerdown
2026-04-03 06:35:52 -07:00
Keavon Chambers 55115d89d5 Fix several cases of errors appearing in the console
One appeared on load (a deprecated meta tag). One appeared when adding an Identity (Passthrough) node. One appeared when exposing the the Weight parameter of the Stroke node. This also fixes the intended behavior of the bisect script, which was involved when finding the prevenance of these errors.
2026-04-03 03:20:04 -07:00
Keavon Chambers 5edb00bd9a Fix virtual scrolling MenuList font family dropdowns shrinking when wider content is unmounted (#3987)
* Fix virtual scrolling MenuList dropdowns shrinking when wider content goes away

* Code review fixes

* Fix small CI workflow bug

* Stop scrolling in dropdowns from horizontally scrolling the control bar

* Use more robust way of getting commit hash in CI workflow
2026-04-02 19:24:41 -07:00
Keavon Chambers ab822afae4 Implement window-controls-overlay PWA window frameless mode (#3986)
* Implement window-controls-overlay PWA window frameless mode

* Avoid warning
2026-04-02 18:17:36 -07:00
Keavon Chambers 1a06d3ea80 Improve PWA support with service worker-based offline caching (#3985)
* Implement the service worker for cached offline mode

* Improve pre-loaded font menu preview visualization

* Code review fixes

* Simplify Response construction

* Attempt to fix ERR_FAILED when reloading page on CF Pages

* Reject service worker install if any precache fetch fails
2026-04-02 18:14:40 -07:00
Keavon Chambers 87bd3d41df Make Alt+click on a handle in the Path tool split it from its colinear pair 2026-04-01 23:04:56 -07:00
Keavon Chambers 662691f32a New node: 'Offset Points' 2026-04-01 23:02:59 -07:00
Keavon Chambers 1543d974ac Fix 'Jitter Points' and 'Sample Polylines' working incorrectly with X or Y scale of 0 content (#3984)
* Fix NaN points produced by Sample Polylines on 0-scaled input

* Fix Jitter Points inverse transform for zero-scale axes and stop resetting stroke transform

* Remove a couple confusing Debug nodes

* Fix edge case

* Update demo art

* Fix order change in Jitter Points causing different results from earlier

* Fix bug in bisect tool

* Break out functionality into helper functions
2026-04-01 22:51:48 -07:00
Keavon Chambers 79bf1ab688 Fix preprocessor crash when document nodes have outdated input counts 2026-04-01 19:39:12 -07:00
Keavon Chambers 211b9113a1 Add the "Along Normals" parameter to the 'Jitter Points' node (#3983)
* Add the "Along Normals" parameter to the 'Jitter Points' node

* Fix the edge case of a self-loops
2026-04-01 05:18:56 -07:00
Keavon Chambers d41883a942 Add Layers panel support for displaying multiple groups with instances of the same children layers (#3982)
* Add Layers panel support for displaying multiple groups with instances of the same children layers

* Fix insert folder box drawing
2026-04-01 00:13:42 -07:00
Keavon Chambers 86e41a110a Make the node macro include doc comments when hovering a node's function (#3979) 2026-03-31 02:55:27 -07:00
Keavon Chambers 203910a92f Replace the vite-multiple-assets dev dependency with a small custom Vite plugin (#3976)
* Replace the vite-multiple-assets dev dependency with a small custom Vite plugin

* Restore exception
2026-03-29 03:36:31 -07:00
Keavon Chambers a3ea6ab0af Refactor transform decomposition API with skew support, add 'Decompose Skew' node, and fix stroke transform interpolation (#3973)
* Refactor transform decomposition API with skew support, add Decompose Skew node, and fix stroke transform interpolation

* Fix bug in master with skew changing Area node calculated value

* Code review simplification

* More code review fixes

* Rename cases where "shear" terminology was used in place of "skew"
2026-03-28 20:47:32 -07:00
Keavon Chambers e2a142333f Fix the Auto-Tangents node for linear polylines, and track colinear handles in manipulator data (#3972)
* Fix the Auto-Tangents node for linear polylines, and track colinear handles in manipulator data

* Simplify
2026-03-28 18:26:08 -07:00
Keavon Chambers 71ff4c937f Update 'Solidify Stroke' to preserve the original fill (#3971)
* Update 'Solidify Stroke' to preserve the original fill

* Efficiency improvements
2026-03-28 18:11:26 -07:00
Keavon Chambers 50a618ad12 New node: Path is Closed (#3970)
Add the 'Path is Closed' node
2026-03-28 17:37:50 -07:00
Keavon Chambers 6388a32ac5 Fix an assortment of small bugs (#3968)
* Fix an assertion failure bug when scaling a line in the transform cage

* Fix missing defaults on node gradient inputs

* Fix Blend Shapes path input wire not updating to show in the UI after Layer > Blend

* Fix assertion failure due to browser non-monotonic timestamp

* Fix SVG renderer drawing 1px strokes as half-width when using stroke alignment

* Fix incorrect appearance of the ColorInput widget when set to "none" and "disabled"

* Fix lerp function in Fill enum to handle None cases correctly

* Fix stroke alignment bug
2026-03-28 17:12:13 -07:00
Keavon Chambers 865e9713ad Refactor eval_pathseg_euclidean() to use kurbo's faster/more accurate inv_arclen() (#3969) 2026-03-28 16:30:26 -07:00
Keavon Chambers e529f74495 Fix click target metadata not propagating through intermediate wrapper table rows (#3967) 2026-03-28 15:39:27 -07:00
Vishnu TejasandTimon 36366b34f2 Desktop: Fix drag followed by a click causing a double click (#3721)
* Fix drag followed by a click causing a double click

* Review

* Fix quadruple click bug and cleanup

bug: quadruple bypassing time and distance check logic

* Improve readability

---------

Co-authored-by: Timon <[email protected]>
2026-03-24 00:21:02 +00:00
Keavon Chambers 11b7af61ef Fix image and SVG import transform bugs (#3942)
* Fix half-pixel offset on imported images

* Break out reused function

* Fix SVG/image open flow placing content with unnecessary Transform nodes

* Fix redundant Transform nodes when opening SVG/image files as documents

* Offset the parent to its destination position not the child objects

* Fix SVG/image File > Open artboard dimensions, origin, and clipping

* Fix the SVG to drag in at the mouse position relative to its visible center

* Fix importing images into offset artboards so they don't get offset as well

* Code review
2026-03-23 16:26:10 -07:00
Keavon Chambers a10092c10c Fix abysmal O(n^2) SVG import performance (#3938)
* Remove O(n^2) import by disabling bumping

* Add an import mode to avoid acyclic checks

* Rebuild the layer tree at the end, not after each step

* Incrementally update outward wires instead of repeatedly rebuilding them

* Add import->export direct connection guard

* Code review fixes

* Replace magic number offsets with consts

* Add consts for magic numbers

* Improve code structuring
2026-03-22 23:33:58 -07:00
225 changed files with 8193 additions and 5491 deletions

No files matched your search

+2 -2
View File
@@ -1,2 +1,2 @@
https://github.com/Keavon/graphite-branded-assets/archive/8ae15dc9c51a3855475d8cab1d0f29d9d9bc622c.tar.gz
c19abe4ac848f3c835e43dc065c59e20e60233ae023ea0a064c5fed442be2d3d
https://github.com/Keavon/graphite-branded-assets/archive/1509880500e32cb21235343ba865adcf0579133f.tar.gz
89b4c58aee186b0c1610a8778bd199c9bdaf1191b4006e6b007dc40a402f4aa7
+19 -12
View File
@@ -20,9 +20,6 @@ on:
linux:
description: "Linux"
type: boolean
push_to_nix_cache:
description: "Linux: push to Nix cache"
type: boolean
debug:
description: "Debug build"
type: boolean
@@ -36,8 +33,6 @@ on:
type: boolean
linux:
type: boolean
push_to_nix_cache:
type: boolean
debug:
type: boolean
checkout_repo:
@@ -162,7 +157,7 @@ jobs:
REF="master"
ENVIRONMENT="graphite-dev (Production)"
else
REF="${{ inputs.checkout_ref || github.head_ref || github.ref_name }}"
REF="$(git rev-parse HEAD)"
ENVIRONMENT="graphite-dev (Preview)"
fi
DEPLOY_ID=$(gh api \
@@ -639,23 +634,35 @@ jobs:
- name: ❄ Install Nix
uses: DeterminateSystems/nix-installer-action@main
with:
extra-conf: |
extra-substituters = https://graphite.cachix.org https://graphite-dev.cachix.org
extra-trusted-public-keys = graphite.cachix.org-1:B7Il1yMpkquN/dXM+5GRmz+4Xmu2aaCS1GcWNfFhsOo= graphite-dev.cachix.org-1:RppXYpiV1qO2TYKTkXXGHsAEQDOB5G51b3VlrN9QmbI=
- name: 🗑 Free disk space
run: sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache
- name: 📦 Build Nix package
run: nix build .#graphite${{ inputs.debug && '-dev' || '' }} --no-link --print-out-paths
run: nix build .#graphite${{ inputs.debug && '-dev' || '' }} --no-link --print-out-paths --print-build-logs
- name: 📤 Push to Nix cache
if: (github.event_name == 'push' || inputs.push_to_nix_cache) && !inputs.debug
env:
NIX_CACHE_AUTH_TOKEN: ${{ secrets.NIX_CACHE_AUTH_TOKEN }}
NIX_CACHE_AUTH_TOKEN: ${{ (!inputs.debug && github.ref == 'refs/heads/master') && secrets.NIX_CACHE_AUTH_TOKEN || secrets.NIX_CACHE_AUTH_TOKEN_DEV }}
NIX_CACHE_NAME: ${{ (!inputs.debug && github.ref == 'refs/heads/master') && 'graphite' || 'graphite-dev' }}
run: |
nix run nixpkgs#cachix -- authtoken $NIX_CACHE_AUTH_TOKEN
nix build --no-link --print-out-paths | nix run nixpkgs#cachix -- push graphite
nix build .#graphite${{ inputs.debug && '-dev' || '' }} --no-link --print-out-paths | nix run nixpkgs#cachix -- push $NIX_CACHE_NAME
- name: 📤 Push Dependencies to dev Nix cache
env:
NIX_CACHE_AUTH_TOKEN: ${{ secrets.NIX_CACHE_AUTH_TOKEN_DEV }}
NIX_CACHE_NAME: graphite-dev
run: |
nix run nixpkgs#cachix -- authtoken $NIX_CACHE_AUTH_TOKEN
nix build .#graphite${{ inputs.debug && '-dev' || '' }}.deps --no-link --print-out-paths | nix run nixpkgs#cachix -- push $NIX_CACHE_NAME
- name: 🏗 Build Linux bundle
run: nix build .#graphite${{ inputs.debug && '-dev' || '' }}-bundle.tar.xz && cp ./result ./graphite-linux-bundle.tar.xz
run: nix build .#graphite-bundle${{ inputs.debug && '-dev' || '' }}.tar.xz && cp ./result ./graphite-linux-bundle.tar.xz
- name: 📦 Upload Linux bundle
uses: actions/upload-artifact@v6
@@ -693,7 +700,7 @@ jobs:
- name: 🏗 Build Flatpak
run: |
nix build .#graphite${{ inputs.debug && '-dev' || '' }}-flatpak-manifest
nix build .#graphite-flatpak-manifest${{ inputs.debug && '-dev' || '' }}
rm -rf .flatpak
mkdir -p .flatpak
+51
View File
@@ -0,0 +1,51 @@
name: "Nix Housekeeping"
on:
push:
branches:
- master
workflow_dispatch: {}
jobs:
cache-dev-shell:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: 📥 Clone repository
uses: actions/checkout@v6
with:
repository: ${{ inputs.checkout_repo || github.repository }}
ref: ${{ inputs.checkout_ref || '' }}
- name: ❄ Install Nix
uses: DeterminateSystems/nix-installer-action@main
with:
extra-conf: |
extra-substituters = https://graphite.cachix.org https://graphite-dev.cachix.org
extra-trusted-public-keys = graphite.cachix.org-1:B7Il1yMpkquN/dXM+5GRmz+4Xmu2aaCS1GcWNfFhsOo= graphite-dev.cachix.org-1:RppXYpiV1qO2TYKTkXXGHsAEQDOB5G51b3VlrN9QmbI=
- name: 🔎 Check whether development shell is already in binary cache
id: cache-check
run: |
out_path="$(nix eval --raw .#devShells.x86_64-linux.default.outPath)"
if nix path-info --store https://graphite-dev.cachix.org "$out_path" &>/dev/null; then
echo "cached=true" >> "$GITHUB_OUTPUT"
echo "Development shell is already cached at $out_path"
else
echo "cached=false" >> "$GITHUB_OUTPUT"
echo "Development shell is not cached"
fi
- name: 📦 Build Nix development shell
if: steps.cache-check.outputs.cached == 'false'
run: nix build .#devShells.x86_64-linux.default --no-link --print-out-paths
- name: 📤 Push Nix development shell to binary cache
if: steps.cache-check.outputs.cached == 'false'
env:
NIX_CACHE_AUTH_TOKEN: ${{ secrets.NIX_CACHE_AUTH_TOKEN_DEV }}
run: |
nix run nixpkgs#cachix -- authtoken $NIX_CACHE_AUTH_TOKEN
nix build .#devShells.x86_64-linux.default --no-link --print-out-paths | nix run nixpkgs#cachix -- push graphite-dev
+12 -3
View File
@@ -17,9 +17,10 @@ jobs:
- name: ❄ Install Nix
uses: DeterminateSystems/nix-installer-action@main
- name: 💾 Set up Nix cache
uses: DeterminateSystems/magic-nix-cache-action@main
with:
extra-conf: |
extra-substituters = https://graphite.cachix.org https://graphite-dev.cachix.org
extra-trusted-public-keys = graphite.cachix.org-1:B7Il1yMpkquN/dXM+5GRmz+4Xmu2aaCS1GcWNfFhsOo= graphite-dev.cachix.org-1:RppXYpiV1qO2TYKTkXXGHsAEQDOB5G51b3VlrN9QmbI=
- name: 🏗 Build graphene raster nodes shaders
run: nix build .#graphite-raster-nodes-shaders && cp result raster_nodes_shaders_entrypoint.wgsl
@@ -34,3 +35,11 @@ jobs:
raster_nodes_shaders_entrypoint.wgsl \
"${{ github.sha }} raster_nodes_shaders_entrypoint.wgsl" \
${{ secrets.ARTIFACTS_REPO_TOKEN }}
- name: 📤 Push shaders to dev Nix cache
env:
NIX_CACHE_AUTH_TOKEN: ${{ secrets.NIX_CACHE_AUTH_TOKEN_DEV }}
NIX_CACHE_NAME: graphite-dev
run: |
nix run nixpkgs#cachix -- authtoken $NIX_CACHE_AUTH_TOKEN
nix build .#graphite-raster-nodes-shaders --no-link --print-out-paths | nix run nixpkgs#cachix -- push $NIX_CACHE_NAME
+5 -6
View File
@@ -31,7 +31,6 @@ let
deps = {
crane = lib.call ./deps/crane.nix;
cef = lib.call ./deps/cef.nix;
rustGPU = lib.call ./deps/rust-gpu.nix;
};
@@ -60,15 +59,15 @@ in
graphite-raster-nodes-shaders = lib.call ./pkgs/graphite-raster-nodes-shaders.nix;
graphite-branding = lib.call ./pkgs/graphite-branding.nix;
graphite-bundle = (lib.call ./pkgs/graphite-bundle.nix) { };
graphite-dev-bundle = (lib.call ./pkgs/graphite-bundle.nix) { graphite = graphite-dev; };
graphite-bundle-dev = (lib.call ./pkgs/graphite-bundle.nix) { graphite = graphite-dev; };
graphite-flatpak-manifest = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { };
graphite-dev-flatpak-manifest = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { graphite-bundle = graphite-dev-bundle; };
graphite-flatpak-manifest-dev = (lib.call ./pkgs/graphite-flatpak-manifest.nix) {
graphite-bundle = graphite-bundle-dev;
};
# TODO: graphene-cli = lib.call ./pkgs/graphene-cli.nix;
tools = {
third-party-licenses = lib.call ./pkgs/tools/third-party-licenses.nix;
};
graphite-cef = lib.call ./pkgs/graphite-cef/package.nix;
}
);
-27
View File
@@ -1,27 +0,0 @@
{ pkgs, ... }:
let
cefPath = pkgs.cef-binary.overrideAttrs (finalAttrs: {
postInstall = ''
rm -r $out/* $out/.* || true
strip ./Release/*.so*
mv ./Release/* $out/
find "./Resources/locales" -maxdepth 1 -type f ! -name 'en-US.pak' -delete
mv ./Resources/* $out/
mv ./include $out/
cat ./CREDITS.html | ${pkgs.xz}/bin/xz -9 -e -c > $out/CREDITS.html.xz
echo '${
builtins.toJSON {
type = "minimal";
name = builtins.baseNameOf finalAttrs.src.url;
sha1 = "";
}
}' > $out/archive.json
'';
});
in
{
env.CEF_PATH = cefPath;
}
+25 -2
View File
@@ -1,5 +1,28 @@
{ pkgs, inputs, ... }:
{
pkgs,
inputs,
...
}:
{
lib = inputs.crane.mkLib pkgs;
lib = (inputs.crane.mkLib pkgs) // {
vendorCargoDepsFlatten =
src:
pkgs.stdenvNoCC.mkDerivation (finalAttrs: {
name = "graphite-cargo-vendored";
inherit src;
installPhase = ''
cp -rL --no-preserve=mode "$src" "$out"
chmod -R u+w "$out"
find "$out" -type f -print0 | xargs -r -0 sed -i "s|$src|$out|g"
'';
disallowedReferences = [ finalAttrs.src ];
dontUnpack = true;
dontConfigure = true;
dontBuild = true;
});
};
}
+14 -17
View File
@@ -1,16 +1,15 @@
{ pkgs, ... }:
let
extensions = [
"rust-src"
"rust-analyzer"
"clippy"
"cargo"
"rustc-dev"
"llvm-tools"
];
toolchain = pkgs.rust-bin.nightly."2025-06-23".default.override {
inherit extensions;
toolchain = pkgs.rust-bin.nightly."2026-04-11".default.override {
extensions = [
"rust-src"
"rust-analyzer"
"clippy"
"cargo"
"rustc-dev"
"llvm-tools"
];
};
cargo = pkgs.writeShellScriptBin "cargo" ''
#!${pkgs.lib.getExe pkgs.bash}
@@ -32,14 +31,12 @@ let
}).buildRustPackage
(finalAttrs: {
pname = "rustc_codegen_spirv";
version = "0-unstable-2025-08-04";
src = pkgs.fetchFromGitHub {
owner = "Firestar99";
repo = "rust-gpu-new";
rev = "c12f216121820580731440ee79ebc7403d6ea04f";
hash = "sha256-rG1cZvOV0vYb1dETOzzbJ0asYdE039UZImobXZfKIno=";
version = "0.10.0-alpha.1";
src = pkgs.fetchCrate {
inherit (finalAttrs) pname version;
sha256 = "sha256-zJEpExkPgYzwo7fR4ge4GxJNj7H5yo4bJ4eTOw36+7c=";
};
cargoHash = "sha256-AEigcEc5wiBd3zLqWN/2HSbkfOVFneAqNvg9HsouZf4=";
cargoHash = "sha256-J1rtbfGqrL2NJ7Bu2pYfDwCdUmnECB/kzxrpYluA0kY=";
cargoBuildFlags = [
"-p"
"rustc_codegen_spirv"
+12 -7
View File
@@ -1,4 +1,10 @@
{ pkgs, deps, ... }:
{
pkgs,
deps,
self,
system,
...
}:
let
libs = [
@@ -22,7 +28,6 @@ pkgs.mkShell (
pkgs.lld
pkgs.nodejs
pkgs.nodePackages.npm
pkgs.binaryen
pkgs.wasm-bindgen-cli_0_2_100
pkgs.wasm-pack
@@ -52,13 +57,13 @@ pkgs.mkShell (
pkgs.graphviz
];
LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libs}:${deps.cef.env.CEF_PATH}";
CEF_PATH = self.packages.${system}.graphite-cef;
LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libs}:${self.packages.${system}.graphite-cef}";
XDG_DATA_DIRS = "${pkgs.gsettings-desktop-schemas}/share/gsettings-schemas/${pkgs.gsettings-desktop-schemas.name}:${pkgs.gtk3}/share/gsettings-schemas/${pkgs.gtk3.name}:$XDG_DATA_DIRS";
shellHook = ''
alias cargo='mold --run cargo'
'';
# shellHook = ''
# alias cargo='mold --run cargo'
# '';
}
// deps.cef.env
// deps.rustGPU.env
)
+2 -1
View File
@@ -1,5 +1,6 @@
{
pkgs,
deps,
self,
system,
...
@@ -33,7 +34,7 @@ let
cp -r ${graphite}/share out/share
mkdir -p out/lib/cef
mkdir -p ./cef
tar -xvf ${pkgs.cef-binary.src} -C ./cef --strip-components=1
tar -xvf ${self.packages.${system}.graphite-cef.src} -C ./cef --strip-components=1
cp -r ./cef/Release/* out/lib/cef/
cp -r ./cef/Resources/* out/lib/cef/
find "out/lib/cef/locales" -type f ! -name 'en-US*' -delete
+45
View File
@@ -0,0 +1,45 @@
{ pkgs, ... }:
let
versionFile = builtins.fromJSON (builtins.readFile ./version.json);
version = versionFile.version;
hash = selectSystem versionFile.hashes;
selectSystem =
attrs:
attrs.${pkgs.stdenv.hostPlatform.system}
or (throw "Unsupported system ${pkgs.stdenv.hostPlatform.system}");
src = pkgs.fetchurl {
url = "https://cef-builds.spotifycdn.com/cef_binary_${version}_${
selectSystem {
aarch64-linux = "linuxarm64";
x86_64-linux = "linux64";
}
}_minimal.tar.bz2";
hash = hash;
};
in
pkgs.cef-binary.overrideAttrs (finalAttrs: {
version = builtins.head (builtins.split "\\+" version);
inherit src;
postInstall = ''
rm -r $out/* $out/.* || true
strip ./Release/*.so*
mv ./Release/* $out/
find "./Resources/locales" -maxdepth 1 -type f ! -name 'en-US.pak' -delete
mv ./Resources/* $out/
mv ./include $out/
cat ./CREDITS.html | ${pkgs.xz}/bin/xz -9 -e -c > $out/CREDITS.html.xz
echo '${
builtins.toJSON {
type = "minimal";
name = builtins.baseNameOf finalAttrs.src.url;
sha1 = "";
}
}' > $out/archive.json
'';
})
+7
View File
@@ -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="
}
}
+9 -9
View File
@@ -1,16 +1,16 @@
{ info, deps, ... }:
{
info,
deps,
self,
system,
...
}:
(deps.crane.lib.overrideToolchain (_: deps.rustGPU.toolchain)).buildPackage {
pname = "raster-nodes-shaders";
pname = "graphite-raster-nodes-shaders";
inherit (info) version src;
cargoVendorDir = deps.crane.lib.vendorMultipleCargoDeps {
inherit (deps.crane.lib.findCargoFiles (deps.crane.lib.cleanCargoSource info.src)) cargoConfigs;
cargoLockList = [
"${info.src}/Cargo.lock"
"${deps.rustGPU.toolchain.availableComponents.rust-src}/lib/rustlib/src/rust/library/Cargo.lock"
];
};
inherit (self.packages.${system}.graphite) cargoVendorDir cargoArtifacts;
strictDeps = true;
+79 -91
View File
@@ -14,125 +14,107 @@
let
branding = self.packages.${system}.graphite-branding;
cargoVendorDir = deps.crane.lib.vendorCargoDeps { inherit (info) src; };
resourcesCommon = {
pname = "${info.pname}-resources";
inherit (info) version src;
inherit cargoVendorDir;
strictDeps = true;
nativeBuildInputs = [
pkgs.pkg-config
pkgs.lld
pkgs.nodejs
pkgs.nodePackages.npm
pkgs.binaryen
pkgs.wasm-bindgen-cli_0_2_100
pkgs.wasm-pack
pkgs.cargo-about
];
buildInputs = [ pkgs.openssl ];
env.CARGO_PROFILE = if dev then "dev" else "release";
cargoExtraArgs = "--target wasm32-unknown-unknown -p graphite-wasm-wrapper --no-default-features --features native";
doCheck = false;
};
resources = deps.crane.lib.buildPackage (
resourcesCommon
// {
cargoArtifacts = deps.crane.lib.buildDepsOnly resourcesCommon;
npmDeps = pkgs.importNpmLock {
npmRoot = "${info.src}/frontend";
};
npmRoot = "frontend";
npmConfigScript = "setup";
makeCacheWritable = true;
nativeBuildInputs = [
pkgs.importNpmLock.npmConfigHook
pkgs.removeReferencesTo
]
++ resourcesCommon.nativeBuildInputs;
prePatch = ''
mkdir branding
cp -r ${branding}/* branding
cp ${info.src}/.branding branding/.branding
'';
buildPhase = ''
export HOME="$TMPDIR"
pushd frontend
npm run native:build-${if dev then "dev" else "production"}
popd
'';
installPhase = ''
mkdir -p $out
cp -r frontend/dist/* $out/
'';
postFixup = ''
find "$out" -type f -exec remove-references-to -t "${cargoVendorDir}" '{}' +
'';
}
);
libs = [
pkgs.wayland
pkgs.vulkan-loader
pkgs.libGL
pkgs.openssl
pkgs.libraw
# X11 Support
pkgs.libxkbcommon
pkgs.libXcursor
pkgs.libxcb
pkgs.libX11
];
common = {
inherit (info) pname version src;
inherit cargoVendorDir;
strictDeps = true;
cargoVendorDir = deps.crane.lib.vendorCargoDepsFlatten (
deps.crane.lib.vendorMultipleCargoDeps {
inherit (deps.crane.lib.findCargoFiles (deps.crane.lib.cleanCargoSource info.src)) cargoConfigs;
cargoLockList = [
"${info.src}/Cargo.lock"
"${deps.rustGPU.toolchain.availableComponents.rust-src}/lib/rustlib/src/rust/library/Cargo.lock"
];
}
);
buildInputs = libs;
nativeBuildInputs = [
pkgs.pkg-config
pkgs.cargo-about
pkgs.removeReferencesTo
];
env = deps.cef.env // {
CARGO_PROFILE = if dev then "dev" else "release";
};
cargoExtraArgs = "-p graphite-desktop";
strictDeps = true;
doCheck = false;
};
cargoArtifacts = deps.crane.lib.buildDepsOnly (
common
// {
nativeBuildInputs = [
pkgs.pkg-config
pkgs.lld
];
env.CEF_PATH = self.packages.${system}.graphite-cef;
buildPhase =
let
profile = if dev then "dev" else "release";
in
''
cargo check --profile ${profile} --locked -p graphite-desktop-platform-linux
cargo build --profile ${profile} --locked -p graphite-desktop-platform-linux
cargo check --profile ${profile} --target wasm32-unknown-unknown --locked -p graphite-wasm-wrapper --no-default-features --features native
cargo build --profile ${profile} --target wasm32-unknown-unknown --locked -p graphite-wasm-wrapper --no-default-features --features native
cargo check --locked -p third-party-licenses --features desktop
cargo build --locked -p third-party-licenses --features desktop
cargo check --profile ${profile} --locked -p graphite-desktop-bundle
cargo build --profile ${profile} --locked -p graphite-desktop-bundle
'';
}
);
in
deps.crane.lib.buildPackage (
common
// {
cargoArtifacts = deps.crane.lib.buildDepsOnly common;
inherit cargoArtifacts;
env = common.env // {
RASTER_NODES_SHADER_PATH = self.packages.${system}.graphite-raster-nodes-shaders;
EMBEDDED_RESOURCES = resources;
GRAPHITE_GIT_COMMIT_HASH = self.rev or "unknown";
GRAPHITE_GIT_COMMIT_DATE = self.lastModified or "unknown";
};
buildInputs = libs;
nativeBuildInputs = [
pkgs.pkg-config
pkgs.lld
pkgs.nodejs
pkgs.binaryen
pkgs.wasm-bindgen-cli_0_2_100
pkgs.wasm-pack
pkgs.cargo-about
pkgs.removeReferencesTo
pkgs.importNpmLock.npmConfigHook
];
npmDeps = pkgs.importNpmLock {
npmRoot = "${info.src}/frontend";
};
npmRoot = "frontend";
nativeBuildInputs = [
pkgs.importNpmLock.npmConfigHook
pkgs.nodePackages.npm
]
++ common.nativeBuildInputs;
npmConfigScript = "setup";
makeCacheWritable = true;
env = {
RASTER_NODES_SHADER_PATH = self.packages.${system}.graphite-raster-nodes-shaders;
GRAPHITE_GIT_COMMIT_HASH = self.rev or "unknown";
GRAPHITE_GIT_COMMIT_DATE = self.lastModified or "unknown";
CEF_PATH = self.packages.${system}.graphite-cef;
};
postPatch = ''
mkdir branding
cp -r ${branding}/* branding
cp ${info.src}/.branding branding/.branding
'';
preBuild = ''
${lib.getExe self.packages.${system}.tools.third-party-licenses}
# Prevent `package-installer.js` from trying to update npm dependencies
touch -r frontend/package-lock.json -d '+1 year' frontend/node_modules/.install-timestamp
export HOME="$TMPDIR"
''
+ (
if self ? rev then
@@ -143,6 +125,10 @@ deps.crane.lib.buildPackage (
""
);
buildPhaseCargoCommand = "cargo run build desktop${if dev then " debug" else ""}";
doNotPostBuildInstallCargoBinaries = true;
installPhase = ''
mkdir -p $out/bin
cp target/${if dev then "debug" else "release"}/graphite $out/bin/graphite
@@ -161,12 +147,14 @@ deps.crane.lib.buildPackage (
'';
postFixup = ''
remove-references-to -t "${cargoVendorDir}" $out/bin/graphite
remove-references-to -t "${common.cargoVendorDir}" $out/bin/graphite
patchelf \
--set-rpath "${pkgs.lib.makeLibraryPath libs}:${deps.cef.env.CEF_PATH}" \
--set-rpath "${pkgs.lib.makeLibraryPath libs}:${self.packages.${system}.graphite-cef}" \
--add-needed libGL.so \
$out/bin/graphite
'';
passthru.deps = cargoArtifacts;
}
)
-31
View File
@@ -1,31 +0,0 @@
{
info,
deps,
pkgs,
...
}:
let
cargoVendorDir = deps.crane.lib.vendorCargoDeps { inherit (info) src; };
common = {
pname = "third-party-licenses";
inherit (info) version src;
inherit cargoVendorDir;
nativeBuildInputs = [ pkgs.pkg-config ];
buildInputs = [ pkgs.openssl ];
strictDeps = true;
env = deps.cef.env // {
CARGO_PROFILE = "dev";
};
cargoExtraArgs = "-p third-party-licenses --features desktop";
doCheck = false;
};
in
deps.crane.lib.buildPackage (
common
// {
inherit cargoVendorDir;
cargoArtifacts = deps.crane.lib.buildDepsOnly common;
meta.mainProgram = "third-party-licenses";
}
)
Generated
+237 -700
View File
File diff suppressed because it is too large. Load diff
+12 -12
View File
@@ -89,6 +89,8 @@ interpreted-executor = { path = "node-graph/interpreted-executor" }
node-macro = { path = "node-graph/node-macro" }
wgpu-executor = { path = "node-graph/libraries/wgpu-executor" }
graphite-proc-macros = { path = "proc-macros" }
graphite-editor = { path = "editor" }
graphene-canvas-utils = { path = "node-graph/libraries/canvas-utils" }
# Workspace dependencies
rustc-hash = "2.0"
@@ -113,7 +115,7 @@ quote = "1.0"
chrono = "0.4"
ron = "0.12"
fastnoise-lite = "1.1"
wgpu = { version = "27.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",
@@ -147,8 +149,8 @@ url = "2.5"
tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-multi-thread"] }
# Linebender ecosystem (BEGIN)
kurbo = { version = "0.13", features = ["serde"] }
vello = "0.7"
vello_encoding = "0.7"
vello = "0.8"
vello_encoding = "0.8"
resvg = "0.47"
usvg = "0.47"
parley = "0.6"
@@ -157,7 +159,7 @@ polycool = "0.4"
# Linebender ecosystem (END)
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
rand_chacha = "0.9"
glam = { version = "0.29", default-features = false, features = [
glam = { version = "0.32.1", default-features = false, features = [
"nostd-libm",
"scalar-math",
"bytemuck",
@@ -195,17 +197,17 @@ iai-callgrind = { version = "0.16" }
ndarray = "0.16"
strum = { version = "0.27", features = ["derive"] }
dirs = "6.0"
cef = "142"
cef-dll-sys = "142"
cef = "146"
cef-dll-sys = "146"
include_dir = "0.7"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tracing = "0.1"
rfd = "0.15"
rfd = "0.17"
open = "5.3"
spin = "0.10"
clap = "4.5"
spirv-std = { git = "https://github.com/Firestar99/rust-gpu-new", rev = "c12f216121820580731440ee79ebc7403d6ea04f", features = ["bytemuck"] }
cargo-gpu = { git = "https://github.com/Firestar99/cargo-gpu", rev = "3952a22d16edbd38689f3a876e417899f21e1fe7", default-features = false }
spirv-std = { version = "0.10.0-alpha.1", features = ["bytemuck"] }
cargo-gpu-install = { version = "0.10.0-alpha.1", default-features = false }
qrcodegen = "1.8"
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
scraper = "0.25"
@@ -236,6 +238,4 @@ debug = true
[patch.crates-io]
# Force cargo to use only one version of the dpi crate (vendoring breaks without this)
dpi = { git = "https://github.com/rust-windowing/winit.git" }
download-cef = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite" }
vello = { git = "https://github.com/Keavon/vello.git", branch = "0.7.0-fix-images-rendering-blurry" }
vello_encoding = { git = "https://github.com/Keavon/vello.git", branch = "0.7.0-fix-images-rendering-blurry" }
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[17154757625902243313,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"element":[{"red":0.23529412,"green":0.23529412,"blue":0.24313726,"alpha":1.0}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}},{"Value":{"tagged_value":{"F64":1670.79570439},"exposed":false}},{"Value":{"tagged_value":{"F64":24.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[11731553664207576737,{"inputs":[{"Node":{"node_id":757876048866560520,"output_index":0}},{"Value":{"tagged_value":{"F64":48.900000000000006},"exposed":false}},{"Node":{"node_id":7828034197076821310,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"core_types::vector::JitterPointsNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[14158287945315818946,{"inputs":[{"Node":{"node_id":16943732999059587742,"output_index":0}},{"Node":{"node_id":14577956936089455769,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.6181095265062186,3.496297826945966]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"core_types::vector::SplineNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[7828034197076821310,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":3}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"math_nodes::ToU32Node"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"element":[{"red":0.99607843,"green":0.827451,"blue":0.65882355,"alpha":1.0}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}},{"Value":{"tagged_valueLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[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
+17 -50
View File
@@ -17,7 +17,7 @@ use crate::cef;
use crate::cli::Cli;
use crate::consts::CEF_MESSAGE_LOOP_MAX_ITERATIONS;
use crate::event::{AppEvent, AppEventScheduler};
use crate::persist::PersistentData;
use crate::persist;
use crate::preferences;
use crate::render::{RenderError, RenderState};
use crate::window::Window;
@@ -45,7 +45,6 @@ pub(crate) struct App {
start_render_sender: SyncSender<()>,
web_communication_initialized: bool,
web_communication_startup_buffer: Vec<Vec<u8>>,
persistent_data: PersistentData,
#[cfg_attr(not(target_os = "macos"), expect(unused))]
preferences: Preferences,
cli: Cli,
@@ -92,9 +91,6 @@ impl App {
}
});
let mut persistent_data = PersistentData::default();
persistent_data.load_from_disk();
let desktop_wrapper = DesktopWrapper::new(rand::rng().random());
Self {
@@ -118,7 +114,6 @@ impl App {
start_render_sender,
web_communication_initialized: false,
web_communication_startup_buffer: Vec::new(),
persistent_data,
preferences,
cli,
startup_time: None,
@@ -284,17 +279,24 @@ impl App {
window.request_redraw();
}
}
DesktopFrontendMessage::PersistenceWriteDocument { id, document } => {
self.persistent_data.write_document(id, document);
DesktopFrontendMessage::PersistenceWriteState { state } => {
persist::write_state(state);
}
DesktopFrontendMessage::PersistenceReadState => {
responses.push(DesktopWrapperMessage::LoadPersistedState { state: persist::read_state() });
}
DesktopFrontendMessage::PersistenceReadDocument { id } => {
if let Some(document) = persist::read_document_content(&id) {
responses.push(DesktopWrapperMessage::LoadDocumentContent { id, document });
} else {
tracing::error!("Failed to read document content for {id:?}");
}
}
DesktopFrontendMessage::PersistenceWriteDocument { id, document_serialized_content } => {
persist::write_document_content(id, document_serialized_content);
}
DesktopFrontendMessage::PersistenceDeleteDocument { id } => {
self.persistent_data.delete_document(&id);
}
DesktopFrontendMessage::PersistenceUpdateCurrentDocument { id } => {
self.persistent_data.set_current_document(id);
}
DesktopFrontendMessage::PersistenceUpdateDocumentsList { ids } => {
self.persistent_data.set_document_order(ids);
persist::delete_document(&id);
}
DesktopFrontendMessage::PersistenceWritePreferences { preferences } => {
preferences::write(preferences);
@@ -304,41 +306,6 @@ impl App {
let message = DesktopWrapperMessage::LoadPreferences { preferences };
responses.push(message);
}
DesktopFrontendMessage::PersistenceLoadCurrentDocument => {
if let Some((id, document)) = self.persistent_data.current_document() {
let message = DesktopWrapperMessage::LoadDocument {
id,
document,
to_front: false,
select_after_open: true,
};
responses.push(message);
}
}
DesktopFrontendMessage::PersistenceLoadRemainingDocuments => {
for (id, document) in self.persistent_data.documents_before_current().into_iter().rev() {
let message = DesktopWrapperMessage::LoadDocument {
id,
document,
to_front: true,
select_after_open: false,
};
responses.push(message);
}
for (id, document) in self.persistent_data.documents_after_current() {
let message = DesktopWrapperMessage::LoadDocument {
id,
document,
to_front: false,
select_after_open: false,
};
responses.push(message);
}
if let Some(id) = self.persistent_data.current_document_id() {
let message = DesktopWrapperMessage::SelectDocument { id };
responses.push(message);
}
}
DesktopFrontendMessage::OpenLaunchDocuments => {
if self.cli.files.is_empty() {
return;
+34 -3
View File
@@ -27,7 +27,6 @@ use crate::wrapper::{WgpuContext, deserialize_editor_message};
mod consts;
mod context;
mod dirs;
mod input;
mod internal;
mod ipc;
@@ -191,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);
+2 -1
View File
@@ -1,3 +1,4 @@
use graphite_desktop_wrapper::DOUBLE_CLICK_MILLISECONDS;
use std::time::Duration;
pub(crate) const RESOURCE_SCHEME: &str = "resources";
@@ -18,5 +19,5 @@ pub(crate) const SCROLL_SPEED_Y: f32 = 1.0;
pub(crate) const PINCH_ZOOM_SPEED: f64 = 300.0;
pub(crate) const MULTICLICK_TIMEOUT: Duration = Duration::from_millis(500);
pub(crate) const MULTICLICK_TIMEOUT: Duration = Duration::from_millis(DOUBLE_CLICK_MILLISECONDS);
pub(crate) const MULTICLICK_ALLOWED_TRAVEL: usize = 4;
+16 -20
View File
@@ -4,15 +4,15 @@ use cef::{
App, BrowserSettings, CefString, Client, DictionaryValue, ImplCommandLine, ImplRequestContext, LogSeverity, RequestContextSettings, SchemeHandlerFactory, Settings, WindowInfo, api_hash,
browser_host_create_browser_sync, execute_process,
};
use std::path::{Path, PathBuf};
use std::path::Path;
use super::CefContext;
use super::singlethreaded::SingleThreadedCefContext;
use crate::cef::CefEventHandler;
use crate::cef::consts::{RESOURCE_DOMAIN, RESOURCE_SCHEME};
use crate::cef::dirs::{create_instance_dir, delete_instance_dirs};
use crate::cef::input::InputState;
use crate::cef::internal::{BrowserProcessAppImpl, BrowserProcessClientImpl, RenderProcessAppImpl, SchemeHandlerFactoryImpl};
use crate::dirs::TempDir;
pub(crate) struct CefContextBuilder<H: CefEventHandler> {
pub(crate) args: Args,
@@ -45,8 +45,7 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
let args = Args::new();
let cmd = args.as_cmd_line().unwrap();
let switch = CefString::from("type");
let is_sub_process = cmd.has_switch(Some(&switch)) == 1;
let is_sub_process = cmd.has_switch(Some(&"type".into())) == 1;
Self {
args,
@@ -61,8 +60,7 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
pub(crate) fn execute_sub_process(&self) -> SetupError {
let cmd = self.args.as_cmd_line().unwrap();
let switch = CefString::from("type");
let process_type = CefString::from(&cmd.switch_value(Some(&switch)));
let process_type = CefString::from(&cmd.switch_value(Some(&"type".into())));
let mut app = RenderProcessAppImpl::<H>::app();
let ret = execute_process(Some(self.args.as_main_args()), Some(&mut app), std::ptr::null_mut());
if ret >= 0 {
@@ -88,7 +86,7 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
Settings {
windowless_rendering_enabled: 1,
root_cache_path: instance_dir.to_str().map(CefString::from).unwrap(),
cache_path: CefString::from(""),
cache_path: "".into(),
disable_signal_handlers: 1,
log_severity,
..Default::default()
@@ -97,18 +95,17 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
#[cfg(target_os = "macos")]
pub(crate) fn initialize(self, event_handler: H, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
delete_instance_dirs();
let instance_dir = create_instance_dir();
let instance_dir = TempDir::new().expect("Failed to create temporary directory for CEF instance");
let exe = std::env::current_exe().expect("cannot get current exe path");
let app_root = exe.parent().and_then(|p| p.parent()).expect("bad path structure").parent().expect("bad path structure");
let settings = Settings {
main_bundle_path: CefString::from(app_root.to_str().unwrap()),
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)
..Self::common_settings(instance_dir.as_ref())
};
self.initialize_inner(&event_handler, settings)?;
@@ -118,14 +115,13 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
#[cfg(not(target_os = "macos"))]
pub(crate) fn initialize(self, event_handler: H, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
delete_instance_dirs();
let instance_dir = create_instance_dir();
let instance_dir = TempDir::new().expect("Failed to create temporary directory for CEF instance");
let settings = Settings {
multi_threaded_message_loop: 1,
#[cfg(target_os = "linux")]
no_sandbox: 1,
..Self::common_settings(&instance_dir)
..Self::common_settings(instance_dir.as_ref())
};
self.initialize_inner(&event_handler, settings)?;
@@ -157,7 +153,7 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
}
}
fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: PathBuf, disable_gpu_acceleration: 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")]
@@ -183,7 +179,7 @@ fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: PathBuf, d
let Some(mut incognito_request_context) = cef::request_context_create_context(
Some(&RequestContextSettings {
persist_session_cookies: 0,
cache_path: CefString::from(""),
cache_path: "".into(),
..Default::default()
}),
Option::<&mut cef::RequestContextHandler>::None,
@@ -193,14 +189,14 @@ fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: PathBuf, d
let mut scheme_handler_factory = SchemeHandlerFactory::new(SchemeHandlerFactoryImpl::new(event_handler.duplicate()));
incognito_request_context.clear_scheme_handler_factories();
incognito_request_context.register_scheme_handler_factory(Some(&CefString::from(RESOURCE_SCHEME)), Some(&CefString::from(RESOURCE_DOMAIN)), Some(&mut scheme_handler_factory));
incognito_request_context.register_scheme_handler_factory(Some(&RESOURCE_SCHEME.into()), Some(&RESOURCE_DOMAIN.into()), Some(&mut scheme_handler_factory));
let url = CefString::from(format!("{RESOURCE_SCHEME}://{RESOURCE_DOMAIN}/").as_str());
let url = format!("{RESOURCE_SCHEME}://{RESOURCE_DOMAIN}/");
let browser = browser_host_create_browser_sync(
Some(&window_info),
Some(&mut client),
Some(&url),
Some(&url.as_str().into()),
Some(&settings),
Option::<&mut DictionaryValue>::None,
Some(&mut incognito_request_context),
@@ -211,7 +207,7 @@ fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: PathBuf, d
event_handler: Box::new(event_handler),
browser,
input_state: InputState::default(),
instance_dir,
_instance_dir: instance_dir,
})
} else {
tracing::error!("Failed to create browser");
+6 -1
View File
@@ -54,7 +54,12 @@ impl CefContext for MultiThreadedCefContextProxy {
impl Drop for MultiThreadedCefContextProxy {
fn drop(&mut self) {
// Force dropping underlying context on the UI thread
run_on_ui_thread(move || drop(CONTEXT.take()));
let (sync_drop_tx, sync_drop_rx) = std::sync::mpsc::channel();
run_on_ui_thread(move || {
drop(CONTEXT.take());
let _ = sync_drop_tx.send(());
});
let _ = sync_drop_rx.recv();
}
}
+2 -15
View File
@@ -4,6 +4,7 @@ use winit::event::WindowEvent;
use crate::cef::input::InputState;
use crate::cef::ipc::{MessageType, SendMessage};
use crate::cef::{CefEventHandler, input};
use crate::dirs::TempDir;
use super::CefContext;
@@ -11,7 +12,7 @@ pub(super) struct SingleThreadedCefContext {
pub(super) event_handler: Box<dyn CefEventHandler>,
pub(super) browser: Browser,
pub(super) input_state: InputState,
pub(super) instance_dir: std::path::PathBuf,
pub(super) _instance_dir: TempDir,
}
impl CefContext for SingleThreadedCefContext {
@@ -46,19 +47,6 @@ impl Drop for SingleThreadedCefContext {
// CEF wants us to close the browser before shutting down, otherwise it may run longer that necessary.
self.browser.host().unwrap().close_browser(1);
cef::shutdown();
// Sometimes some CEF processes still linger at this point and hold file handles to the cache directory.
// To mitigate this, we try to remove the directory multiple times with some delay.
// TODO: find a better solution if possible.
for _ in 0..30 {
match std::fs::remove_dir_all(&self.instance_dir) {
Ok(_) => break,
Err(e) => {
tracing::warn!("Failed to remove CEF cache directory, retrying...: {e}");
std::thread::sleep(std::time::Duration::from_millis(100));
}
}
}
}
}
@@ -68,7 +56,6 @@ impl SendMessage for SingleThreadedCefContext {
tracing::error!("Main frame is not available, cannot send message");
return;
};
frame.send_message(message_type, message);
}
}
-24
View File
@@ -1,24 +0,0 @@
use std::path::PathBuf;
use crate::dirs::{app_data_dir, ensure_dir_exists};
static CEF_DIR_NAME: &str = "browser";
pub(crate) fn delete_instance_dirs() {
let cef_dir = app_data_dir().join(CEF_DIR_NAME);
if let Ok(entries) = std::fs::read_dir(&cef_dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
let _ = std::fs::remove_dir_all(&path);
}
}
}
}
pub(crate) fn create_instance_dir() -> PathBuf {
let instance_id: String = (0..32).map(|_| format!("{:x}", rand::random::<u8>() % 16)).collect();
let path = app_data_dir().join(CEF_DIR_NAME).join(instance_id);
ensure_dir_exists(&path);
path
}
+29 -32
View File
@@ -133,51 +133,46 @@ impl ClickTracker {
};
let Some(record) = record else {
*record = Some(ClickRecord { position, ..Default::default() });
*record = Some(ClickRecord {
down_position: position,
up_position: position,
..Default::default()
});
return ClickCount::Single;
};
let prev_time = record.time;
let prev_position = record.position;
let prev_count: ClickCount = record.down_count;
let now = Instant::now();
record.time = now;
record.position = position;
let within_time = now.saturating_duration_since(record.time) <= MULTICLICK_TIMEOUT;
match state {
ElementState::Pressed if record.down_count == ClickCount::Triple => {
*record = ClickRecord {
down_count: ClickCount::Double,
..*record
};
return ClickCount::Double;
}
ElementState::Released if record.up_count == ClickCount::Triple => {
*record = ClickRecord {
up_count: ClickCount::Double,
..*record
};
return ClickCount::Double;
}
_ => {}
}
let (prev_count, prev_position) = match state {
ElementState::Pressed => (record.down_count, record.down_position),
ElementState::Released => (record.up_count, record.up_position),
};
let dx = position.x.abs_diff(prev_position.x);
let dy = position.y.abs_diff(prev_position.y);
let within_dist = dx <= MULTICLICK_ALLOWED_TRAVEL && dy <= MULTICLICK_ALLOWED_TRAVEL;
let within_time = now.saturating_duration_since(prev_time) <= MULTICLICK_TIMEOUT;
let count = match (prev_count, within_time, within_dist) {
(ClickCount::Single, true, true) => ClickCount::Double,
(ClickCount::Double, true, true) => ClickCount::Triple,
(_, true, true) => ClickCount::Double,
(ClickCount::Triple, true, true) => ClickCount::Double,
_ => ClickCount::Single,
};
*record = match state {
ElementState::Pressed => ClickRecord { down_count: count, ..*record },
ElementState::Released => ClickRecord { up_count: count, ..*record },
};
record.time = now;
match state {
ElementState::Pressed => {
record.down_position = position;
record.down_count = count;
}
ElementState::Released => {
record.up_position = position;
record.up_count = count;
}
}
count
}
}
@@ -202,7 +197,8 @@ impl From<ClickCount> for i32 {
#[derive(Clone, Copy)]
struct ClickRecord {
time: Instant,
position: MousePosition,
down_position: MousePosition,
up_position: MousePosition,
down_count: ClickCount,
up_count: ClickCount,
}
@@ -211,7 +207,8 @@ impl Default for ClickRecord {
fn default() -> Self {
Self {
time: Instant::now(),
position: Default::default(),
down_position: Default::default(),
up_position: Default::default(),
down_count: Default::default(),
up_count: Default::default(),
}
+34 -47
View File
@@ -1,6 +1,3 @@
#[cfg(target_os = "linux")]
use std::env;
use cef::rc::{Rc, RcImpl};
use cef::sys::{_cef_app_t, cef_base_ref_counted_t};
use cef::{BrowserProcessHandler, CefString, ImplApp, ImplCommandLine, SchemeRegistrar, WrapApp};
@@ -33,81 +30,71 @@ impl<H: CefEventHandler> ImplApp for BrowserProcessAppImpl<H> {
fn on_before_command_line_processing(&self, _process_type: Option<&cef::CefString>, command_line: Option<&mut cef::CommandLine>) {
if let Some(cmd) = command_line {
cmd.append_switch_with_value(Some(&CefString::from("renderer-process-limit")), Some(&CefString::from("1")));
cmd.append_switch_with_value(Some(&CefString::from("password-store")), Some(&CefString::from("basic")));
cmd.append_switch_with_value(Some(&CefString::from("disk-cache-size")), Some(&CefString::from("0")));
cmd.append_switch(Some(&CefString::from("incognito")));
cmd.append_switch(Some(&CefString::from("no-first-run")));
cmd.append_switch(Some(&CefString::from("no-default-browser-check")));
cmd.append_switch(Some(&CefString::from("disable-component-update")));
cmd.append_switch(Some(&CefString::from("disable-geolocation")));
cmd.append_switch(Some(&CefString::from("disable-notifications")));
cmd.append_switch(Some(&CefString::from("disable-audio-input")));
cmd.append_switch(Some(&CefString::from("disable-audio-output")));
cmd.append_switch(Some(&CefString::from("disable-sync")));
cmd.append_switch(Some(&CefString::from("disable-file-system")));
cmd.append_switch(Some(&CefString::from("disable-local-storage")));
cmd.append_switch(Some(&CefString::from("disable-background-networking")));
cmd.append_switch(Some(&CefString::from("disable-default-apps")));
cmd.append_switch(Some(&CefString::from("disable-breakpad")));
cmd.append_switch_with_value(Some(&CefString::from("disable-blink-features")), Some(&CefString::from("WebBluetooth,WebUSB,Serial")));
cmd.append_switch_with_value(Some(&"renderer-process-limit".into()), Some(&"1".into()));
cmd.append_switch_with_value(Some(&"password-store".into()), Some(&"basic".into()));
cmd.append_switch_with_value(Some(&"disk-cache-size".into()), Some(&"0".into()));
cmd.append_switch(Some(&"no-sandbox".into()));
cmd.append_switch(Some(&"no-first-run".into()));
cmd.append_switch(Some(&"noerrdialogs".into()));
cmd.append_switch(Some(&"no-default-browser-check".into()));
cmd.append_switch(Some(&"mute-audio".into()));
cmd.append_switch(Some(&"use-fake-device-for-media-stream".into()));
cmd.append_switch(Some(&"incognito".into()));
cmd.append_switch(Some(&"disable-sync".into()));
cmd.append_switch(Some(&"disable-file-system".into()));
cmd.append_switch(Some(&"disable-component-update".into()));
cmd.append_switch(Some(&"disable-geolocation".into()));
cmd.append_switch(Some(&"disable-notifications".into()));
cmd.append_switch(Some(&"disable-background-networking".into()));
cmd.append_switch(Some(&"disable-default-apps".into()));
cmd.append_switch(Some(&"disable-breakpad".into()));
cmd.append_switch_with_value(Some(&"disable-blink-features".into()), Some(&"WebBluetooth,WebUSB,Serial".into()));
let extra_disabled_features = ["OptimizationHints", "OnDeviceModelService", "TranslateUI"];
let disabled_features_switch = Some(&CefString::from("disable-features"));
let disabled_features_switch = Some(&"disable-features".into());
let disabled_features: String = CefString::from(&cmd.switch_value(disabled_features_switch))
.to_string()
.split(',')
.chain(extra_disabled_features)
.collect::<Vec<_>>()
.join(",");
cmd.append_switch_with_value(disabled_features_switch, Some(&CefString::from(disabled_features.as_str())));
cmd.append_switch_with_value(disabled_features_switch, Some(&disabled_features.as_str().into()));
#[cfg(not(feature = "accelerated_paint"))]
{
// Disable GPU acceleration when accelerated_paint feature is not enabled
cmd.append_switch(Some(&CefString::from("disable-gpu")));
cmd.append_switch(Some(&CefString::from("disable-gpu-compositing")));
cmd.append_switch(Some(&"disable-gpu".into()));
cmd.append_switch(Some(&"disable-gpu-compositing".into()));
}
#[cfg(feature = "accelerated_paint")]
{
// Enable GPU acceleration switches for better performance
cmd.append_switch(Some(&CefString::from("enable-gpu-rasterization")));
cmd.append_switch(Some(&CefString::from("enable-accelerated-2d-canvas")));
// 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"))]
{
// Use Vulkan for accelerated painting
cmd.append_switch_with_value(Some(&CefString::from("use-angle")), Some(&CefString::from("vulkan")));
}
// Tell CEF to use Wayland if available
#[cfg(target_os = "linux")]
{
let use_wayland = env::var("WAYLAND_DISPLAY")
.ok()
.filter(|var| !var.is_empty())
.or_else(|| env::var("WAYLAND_SOCKET").ok())
.filter(|var| !var.is_empty())
.is_some();
if use_wayland {
cmd.append_switch_with_value(Some(&CefString::from("ozone-platform")), Some(&CefString::from("wayland")));
}
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
cmd.append_switch(Some(&CefString::from("use-mock-keychain")));
cmd.append_switch(Some(&"use-mock-keychain".into()));
}
// Enable browser debugging via environment variable
if let Some(env) = std::env::var("GRAPHITE_BROWSER_DEBUG_PORT").ok()
&& let Some(port) = env.parse::<u16>().ok()
{
cmd.append_switch_with_value(Some(&CefString::from("remote-debugging-port")), Some(&CefString::from(port.to_string().as_str())));
cmd.append_switch_with_value(Some(&CefString::from("remote-allow-origins")), Some(&CefString::from("*")));
cmd.append_switch_with_value(Some(&"remote-debugging-port".into()), Some(&port.to_string().as_str().into()));
cmd.append_switch_with_value(Some(&"remote-allow-origins".into()), Some(&"*".into()));
}
}
}
@@ -1,6 +1,6 @@
use cef::rc::{ConvertReturnValue, Rc, RcImpl};
use cef::sys::{_cef_render_process_handler_t, cef_base_ref_counted_t, cef_render_process_handler_t, cef_v8_propertyattribute_t, cef_v8_value_create_array_buffer_with_copy};
use cef::{CefString, ImplFrame, ImplRenderProcessHandler, ImplV8Context, ImplV8Value, V8Handler, V8Propertyattribute, V8Value, WrapRenderProcessHandler, v8_value_create_function};
use cef::{ImplFrame, ImplRenderProcessHandler, ImplV8Context, ImplV8Value, V8Handler, V8Propertyattribute, V8Value, WrapRenderProcessHandler, v8_value_create_function};
use crate::cef::ipc::{MessageType, UnpackMessage, UnpackedMessage};
@@ -53,13 +53,13 @@ impl ImplRenderProcessHandler for RenderProcessHandlerImpl {
let function_call = format!("window.{function_name}(window.{property_name})");
global.set_value_bykey(
Some(&CefString::from(property_name)),
Some(&property_name.into()),
Some(&mut value),
cef_v8_propertyattribute_t::V8_PROPERTY_ATTRIBUTE_READONLY.wrap_result(),
);
if global.value_bykey(Some(&CefString::from(function_name))).is_some() {
frame.execute_java_script(Some(&CefString::from(function_call.as_str())), None, 0);
if global.value_bykey(Some(&function_name.into())).is_some() {
frame.execute_java_script(Some(&function_call.as_str().into()), None, 0);
}
if context.exit() == 0 {
@@ -78,7 +78,7 @@ impl ImplRenderProcessHandler for RenderProcessHandlerImpl {
fn on_context_created(&self, _browser: Option<&mut cef::Browser>, _frame: Option<&mut cef::Frame>, context: Option<&mut cef::V8Context>) {
let register_js_function = |context: &mut cef::V8Context, name: &'static str| {
let mut v8_handler = V8Handler::new(RenderProcessV8HandlerImpl::new());
let Some(mut function) = v8_value_create_function(Some(&CefString::from(name)), Some(&mut v8_handler)) else {
let Some(mut function) = v8_value_create_function(Some(&name.into()), Some(&mut v8_handler)) else {
tracing::error!("Failed to create V8 function {name}");
return;
};
@@ -87,7 +87,7 @@ impl ImplRenderProcessHandler for RenderProcessHandlerImpl {
tracing::error!("Global object is not available in V8 context");
return;
};
global.set_value_bykey(Some(&CefString::from(name)), Some(&mut function), V8Propertyattribute::default());
global.set_value_bykey(Some(&name.into()), Some(&mut function), V8Propertyattribute::default());
};
let Some(context) = context else {
+2 -3
View File
@@ -46,15 +46,14 @@ impl ImplResourceHandler for ResourceHandlerImpl {
if let Some(response) = response {
if self.reader.is_some() {
if let Some(mimetype) = &self.mimetype {
let cef_mime = CefString::from(mimetype.as_str());
response.set_mime_type(Some(&cef_mime));
response.set_mime_type(Some(&mimetype.as_str().into()));
} else {
response.set_mime_type(None);
}
response.set_status(200);
} else {
response.set_status(404);
response.set_mime_type(Some(&CefString::from("text/plain")));
response.set_mime_type(Some(&"text/plain".into()));
}
}
}
@@ -25,7 +25,7 @@ impl<H: CefEventHandler> SchemeHandlerFactoryImpl<H> {
scheme_options |= cef_scheme_options_t::CEF_SCHEME_OPTION_FETCH_ENABLED as i32;
scheme_options |= cef_scheme_options_t::CEF_SCHEME_OPTION_SECURE as i32;
scheme_options |= cef_scheme_options_t::CEF_SCHEME_OPTION_CORS_ENABLED as i32;
registrar.add_custom_scheme(Some(&CefString::from(RESOURCE_SCHEME)), scheme_options);
registrar.add_custom_scheme(Some(&RESOURCE_SCHEME.into()), scheme_options);
}
}
}
+2 -2
View File
@@ -1,4 +1,4 @@
use cef::{CefString, Frame, ImplBinaryValue, ImplFrame, ImplListValue, ImplProcessMessage, ImplV8Context, ProcessId, V8Context, sys::cef_process_id_t};
use cef::{Frame, ImplBinaryValue, ImplFrame, ImplListValue, ImplProcessMessage, ImplV8Context, ProcessId, V8Context, sys::cef_process_id_t};
pub(crate) enum MessageType {
Initialized,
@@ -67,7 +67,7 @@ impl SendMessage for Frame {
fn send_message(&self, message_type: MessageType, message: &[u8]) {
let MessageInfo { name, target } = message_type.into();
let Some(mut process_message) = cef::process_message_create(Some(&CefString::from(name.as_str()))) else {
let Some(mut process_message) = cef::process_message_create(Some(&name.as_str().into())) else {
tracing::error!("Failed to create process message: {}", name);
return;
};
+75 -3
View File
@@ -1,11 +1,31 @@
use std::fs::create_dir_all;
use std::path::PathBuf;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use crate::consts::{APP_DIRECTORY_NAME, APP_DOCUMENTS_DIRECTORY_NAME};
pub(crate) fn ensure_dir_exists(path: &PathBuf) {
if !path.exists() {
create_dir_all(path).unwrap_or_else(|_| panic!("Failed to create directory at {path:?}"));
fs::create_dir_all(path).unwrap_or_else(|_| panic!("Failed to create directory at {path:?}"));
}
}
fn clear_dir(path: &PathBuf) {
let Ok(entries) = fs::read_dir(path) else {
tracing::error!("Failed to read directory at {path:?}");
return;
};
for entry in entries.flatten() {
let entry_path = entry.path();
if entry_path.is_dir() {
if let Err(e) = fs::remove_dir_all(&entry_path) {
tracing::error!("Failed to remove directory at {:?}: {}", entry_path, e);
}
} else if entry_path.is_file() {
if let Err(e) = fs::remove_file(&entry_path) {
tracing::error!("Failed to remove file at {:?}: {}", entry_path, e);
}
}
}
}
@@ -15,8 +35,60 @@ pub(crate) fn app_data_dir() -> PathBuf {
path
}
fn app_tmp_dir() -> PathBuf {
let path = std::env::temp_dir().join(APP_DIRECTORY_NAME);
ensure_dir_exists(&path);
path
}
pub(crate) fn app_tmp_dir_cleanup() {
clear_dir(&app_tmp_dir());
}
pub(crate) fn app_autosave_documents_dir() -> PathBuf {
let path = app_data_dir().join(APP_DOCUMENTS_DIRECTORY_NAME);
ensure_dir_exists(&path);
path
}
/// Temporary directory that is automatically deleted when dropped.
pub struct TempDir {
path: PathBuf,
}
impl TempDir {
pub fn new() -> io::Result<Self> {
Self::new_with_parent(app_tmp_dir())
}
pub fn new_with_parent(parent: impl AsRef<Path>) -> io::Result<Self> {
let random_suffix = format!("{:032x}", rand::random::<u128>());
let name = format!("{}_{}", std::process::id(), random_suffix);
let path = parent.as_ref().join(name);
fs::create_dir_all(&path)?;
Ok(Self { path })
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let result = fs::remove_dir_all(&self.path);
if let Err(e) = result {
tracing::error!("Failed to remove temporary directory at {:?}: {}", self.path, e);
}
}
}
impl AsRef<Path> for TempDir {
fn as_ref(&self) -> &Path {
&self.path
}
}
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory
pub(crate) fn delete_old_cef_browser_directory() {
let old_browser_dir = crate::dirs::app_data_dir().join("browser");
if old_browser_dir.is_dir() {
let _ = std::fs::remove_dir_all(&old_browser_dir);
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
use crate::wrapper::{WgpuContext, WgpuContextBuilder, WgpuFeatures};
pub(super) async fn create_wgpu_context() -> WgpuContext {
let wgpu_context_builder = WgpuContextBuilder::new().with_features(WgpuFeatures::PUSH_CONSTANTS);
let wgpu_context_builder = WgpuContextBuilder::new().with_features(WgpuFeatures::IMMEDIATES);
// TODO: add a cli flag to list adapters and exit instead of always printing
println!("\nAvailable WGPU adapters:\n{}", wgpu_context_builder.available_adapters_fmt().await);
+5
View File
@@ -62,6 +62,11 @@ pub fn start() {
}
};
dirs::app_tmp_dir_cleanup();
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory
dirs::delete_old_cef_browser_directory();
let prefs = preferences::read();
// Must be called before event loop initialization or native window integrations will break
+73 -173
View File
@@ -1,192 +1,92 @@
use crate::wrapper::messages::{Document, DocumentId};
use crate::wrapper::messages::{DocumentId, PersistedState};
#[derive(Default, serde::Serialize, serde::Deserialize)]
pub(crate) struct PersistentData {
documents: DocumentStore,
current_document: Option<DocumentId>,
#[serde(skip)]
document_order: Option<Vec<DocumentId>>,
pub(crate) fn read_state() -> PersistedState {
let path = state_file_path();
let data = match std::fs::read_to_string(&path) {
Ok(d) => d,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
tracing::info!("No persistent data file found at {path:?}, starting fresh");
return PersistedState::default();
}
Err(e) => {
tracing::error!("Failed to read persistent data from disk: {e}");
return PersistedState::default();
}
};
let loaded = match ron::from_str(&data) {
Ok(d) => d,
Err(e) => {
tracing::error!("Failed to deserialize persistent data: {e}");
return PersistedState::default();
}
};
garbage_collect_document_files(&loaded);
loaded
}
impl PersistentData {
pub(crate) fn write_document(&mut self, id: DocumentId, document: Document) {
self.documents.write(id, document);
if let Some(order) = &self.document_order {
self.documents.force_order(order);
pub(crate) fn write_state(state: PersistedState) {
let state: &PersistedState = &state;
let data = match ron::ser::to_string_pretty(state, Default::default()) {
Ok(d) => d,
Err(e) => {
tracing::error!("Failed to serialize persistent data: {e}");
return;
}
self.flush();
};
if let Err(e) = std::fs::write(state_file_path(), data) {
tracing::error!("Failed to write persistent data to disk: {e}");
}
garbage_collect_document_files(&state);
}
pub(crate) fn delete_document(&mut self, id: &DocumentId) {
if Some(*id) == self.current_document {
self.current_document = None;
}
self.documents.delete(id);
self.flush();
}
pub(crate) fn current_document_id(&self) -> Option<DocumentId> {
match self.current_document {
Some(id) => Some(id),
None => Some(*self.documents.document_ids().first()?),
}
}
pub(crate) fn current_document(&self) -> Option<(DocumentId, Document)> {
let current_id = self.current_document_id()?;
Some((current_id, self.documents.read(&current_id)?))
}
pub(crate) fn documents_before_current(&self) -> Vec<(DocumentId, Document)> {
let Some(current_id) = self.current_document_id() else {
return Vec::new();
};
self.documents
.document_ids()
.into_iter()
.take_while(|id| *id != current_id)
.filter_map(|id| Some((id, self.documents.read(&id)?)))
.collect()
}
pub(crate) fn documents_after_current(&self) -> Vec<(DocumentId, Document)> {
let Some(current_id) = self.current_document_id() else {
return Vec::new();
};
self.documents
.document_ids()
.into_iter()
.skip_while(|id| *id != current_id)
.skip(1)
.filter_map(|id| Some((id, self.documents.read(&id)?)))
.collect()
}
pub(crate) fn set_current_document(&mut self, id: DocumentId) {
self.current_document = Some(id);
self.flush();
}
pub(crate) fn set_document_order(&mut self, order: Vec<DocumentId>) {
self.document_order = Some(order);
self.flush();
}
fn flush(&self) {
let data = match ron::ser::to_string_pretty(self, Default::default()) {
Ok(d) => d,
Err(e) => {
tracing::error!("Failed to serialize persistent data: {e}");
return;
}
};
if let Err(e) = std::fs::write(Self::state_file_path(), data) {
tracing::error!("Failed to write persistent data to disk: {e}");
}
}
pub(crate) fn load_from_disk(&mut self) {
let path = Self::state_file_path();
let data = match std::fs::read_to_string(&path) {
Ok(d) => d,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
tracing::info!("No persistent data file found at {path:?}, starting fresh");
return;
}
Err(e) => {
tracing::error!("Failed to read persistent data from disk: {e}");
return;
}
};
let loaded = match ron::from_str(&data) {
Ok(d) => d,
Err(e) => {
tracing::error!("Failed to deserialize persistent data: {e}");
return;
}
};
*self = loaded;
}
fn state_file_path() -> std::path::PathBuf {
let mut path = crate::dirs::app_data_dir();
path.push(crate::consts::APP_STATE_FILE_NAME);
path
pub(crate) fn write_document_content(id: DocumentId, document_content: String) {
if let Err(e) = std::fs::write(document_content_path(&id), document_content) {
tracing::error!("Failed to write document {id:?} to disk: {e}");
}
}
#[derive(Default, serde::Serialize, serde::Deserialize)]
struct DocumentStore(Vec<DocumentInfo>);
impl DocumentStore {
fn write(&mut self, id: DocumentId, document: Document) {
let meta = DocumentInfo::new(id, &document);
if let Some(existing) = self.0.iter_mut().find(|meta| meta.id == id) {
*existing = meta;
} else {
self.0.push(meta);
}
if let Err(e) = std::fs::write(Self::document_path(&id), document.content) {
tracing::error!("Failed to write document {id:?} to disk: {e}");
}
}
pub(crate) fn read_document_content(id: &DocumentId) -> Option<String> {
std::fs::read_to_string(document_content_path(id)).ok()
}
fn delete(&mut self, id: &DocumentId) {
self.0.retain(|meta| meta.id != *id);
if let Err(e) = std::fs::remove_file(Self::document_path(id)) {
tracing::error!("Failed to delete document {id:?} from disk: {e}");
pub(crate) fn delete_document(id: &DocumentId) {
if let Err(e) = std::fs::remove_file(document_content_path(id)) {
tracing::error!("Failed to delete document {id:?} from disk: {e}");
}
}
fn garbage_collect_document_files(state: &PersistedState) {
let valid_paths: std::collections::HashSet<_> = state.documents.iter().map(|doc| document_content_path(&doc.id)).collect();
let directory = crate::dirs::app_autosave_documents_dir();
let entries = match std::fs::read_dir(&directory) {
Ok(entries) => entries,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
Err(e) => {
tracing::error!("Failed to read autosave documents directory: {e}");
return;
}
}
};
fn read(&self, id: &DocumentId) -> Option<Document> {
let meta = self.0.iter().find(|meta| meta.id == *id)?;
let content = std::fs::read_to_string(Self::document_path(id)).ok()?;
Some(Document {
content,
name: meta.name.clone(),
path: meta.path.clone(),
is_saved: meta.is_saved,
})
}
fn force_order(&mut self, desired_order: &Vec<DocumentId>) {
let mut ordered_prefix_len = 0;
for id in desired_order {
if let Some(offset) = self.0[ordered_prefix_len..].iter().position(|meta| meta.id == *id) {
let found_index = ordered_prefix_len + offset;
if found_index != ordered_prefix_len {
self.0[ordered_prefix_len..=found_index].rotate_right(1);
}
ordered_prefix_len += 1;
for entry in entries.flatten() {
let path = entry.path();
if path.is_file() && !valid_paths.contains(&path) {
if let Err(e) = std::fs::remove_file(&path) {
tracing::error!("Failed to remove orphaned document file {path:?}: {e}");
}
}
self.0.truncate(ordered_prefix_len);
}
fn document_ids(&self) -> Vec<DocumentId> {
self.0.iter().map(|meta| meta.id).collect()
}
fn document_path(id: &DocumentId) -> std::path::PathBuf {
let mut path = crate::dirs::app_autosave_documents_dir();
path.push(format!("{:x}.{}", id.0, graphite_desktop_wrapper::FILE_EXTENSION));
path
}
}
#[derive(serde::Serialize, serde::Deserialize)]
struct DocumentInfo {
id: DocumentId,
name: String,
path: Option<std::path::PathBuf>,
is_saved: bool,
fn state_file_path() -> std::path::PathBuf {
let mut path = crate::dirs::app_data_dir();
path.push(crate::consts::APP_STATE_FILE_NAME);
path
}
impl DocumentInfo {
fn new(id: DocumentId, Document { name, path, is_saved, .. }: &Document) -> Self {
Self {
id,
name: name.clone(),
path: path.clone(),
is_saved: *is_saved,
}
}
fn document_content_path(id: &DocumentId) -> std::path::PathBuf {
let mut path = crate::dirs::app_autosave_documents_dir();
path.push(format!("{:x}.{}", id.0, graphite_desktop_wrapper::FILE_EXTENSION));
path
}
+8 -8
View File
@@ -26,14 +26,14 @@ fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
// FRAGMENT SHADER
// ===============
struct Constants {
struct Immediates {
viewport_scale: vec2<f32>,
viewport_offset: vec2<f32>,
ui_scale: vec2<f32>,
background_color: vec4<f32>,
};
var<push_constant> constants: Constants;
var<immediate> immediates: Immediates;
@group(0) @binding(0)
var t_viewport: texture_2d<f32>;
@@ -46,10 +46,10 @@ var s_diffuse: sampler;
@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
let ui_coordinate = in.tex_coords * constants.ui_scale;
let ui_coordinate = in.tex_coords * immediates.ui_scale;
if (ui_coordinate.x < 0.0 || ui_coordinate.x > 1.0 ||
ui_coordinate.y < 0.0 || ui_coordinate.y > 1.0) {
return srgb_to_linear(constants.background_color);
return srgb_to_linear(immediates.background_color);
}
let ui_linear = srgb_to_linear(textureSample(t_ui, s_diffuse, ui_coordinate));
@@ -60,19 +60,19 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
// UI texture is premultiplied, we need to unpremultiply before blending
let ui_srgb = linear_to_srgb(unpremultiply(ui_linear));
let viewport_coordinate = (in.tex_coords - constants.viewport_offset) * constants.viewport_scale;
let viewport_coordinate = (in.tex_coords - immediates.viewport_offset) * immediates.viewport_scale;
if (viewport_coordinate.x < 0.0 || viewport_coordinate.x > 1.0 ||
viewport_coordinate.y < 0.0 || viewport_coordinate.y > 1.0) {
return srgb_to_linear(constants.background_color);
return srgb_to_linear(immediates.background_color);
}
let overlay_srgb = textureSample(t_overlays, s_diffuse, viewport_coordinate);
var viewport_srgb = textureSample(t_viewport, s_diffuse, viewport_coordinate);
if (viewport_srgb.a < 0.001) {
viewport_srgb = constants.background_color;
viewport_srgb = immediates.background_color;
} else if (viewport_srgb.a < 0.999) {
viewport_srgb = blend(viewport_srgb, constants.background_color);
viewport_srgb = blend(viewport_srgb, immediates.background_color);
}
if (overlay_srgb.a < 0.001) {
+8 -11
View File
@@ -73,7 +73,7 @@ impl RenderState {
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Nearest,
mipmap_filter: wgpu::FilterMode::Nearest,
mipmap_filter: wgpu::MipmapFilterMode::Nearest,
..Default::default()
});
@@ -122,10 +122,7 @@ impl RenderState {
let render_pipeline_layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Render Pipeline Layout"),
bind_group_layouts: &[&texture_bind_group_layout],
push_constant_ranges: &[wgpu::PushConstantRange {
stages: wgpu::ShaderStages::FRAGMENT,
range: 0..size_of::<Constants>() as u32,
}],
immediate_size: size_of::<Immediates>() as u32,
});
let render_pipeline = context.device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
@@ -162,7 +159,7 @@ impl RenderState {
mask: !0,
alpha_to_coverage_enabled: false,
},
multiview: None,
multiview_mask: None,
cache: None,
});
@@ -236,7 +233,7 @@ impl RenderState {
return;
};
let size = glam::UVec2::new(viewport_texture.width(), viewport_texture.height());
let result = futures::executor::block_on(self.executor.render_vello_scene_to_target_texture(&scene, size, &Default::default(), None, &mut self.overlays_texture));
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;
@@ -281,13 +278,13 @@ impl RenderState {
depth_stencil_attachment: None,
occlusion_query_set: None,
timestamp_writes: None,
multiview_mask: None,
});
render_pass.set_pipeline(&self.render_pipeline);
render_pass.set_push_constants(
wgpu::ShaderStages::FRAGMENT,
render_pass.set_immediates(
0,
bytemuck::bytes_of(&Constants {
bytemuck::bytes_of(&Immediates {
viewport_scale: self.viewport_scale,
viewport_offset: self.viewport_offset,
ui_scale: ui_scale.unwrap_or([1., 1.]),
@@ -358,7 +355,7 @@ pub(crate) enum RenderError {
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct Constants {
struct Immediates {
viewport_scale: [f32; 2],
viewport_offset: [f32; 2],
ui_scale: [f32; 2],
+1 -1
View File
@@ -72,7 +72,7 @@ impl NativeWindowHandle {
// Subclass the main window.
// https://learn.microsoft.com/windows/win32/api/winuser/nf-winuser-setwindowlongptra
let prev_window_message_handler = unsafe { SetWindowLongPtrW(main, GWLP_WNDPROC, main_window_handle_message as isize) };
let prev_window_message_handler = unsafe { SetWindowLongPtrW(main, GWLP_WNDPROC, main_window_handle_message as *const () as isize) };
if prev_window_message_handler == 0 {
let _ = unsafe { DestroyWindow(helper) };
panic!("SetWindowLongPtrW failed");
+1 -3
View File
@@ -13,9 +13,7 @@ gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
[dependencies]
# Local dependencies
graphite-editor = { path = "../../editor", features = [
"gpu",
] }
graphite-editor = { workspace = true }
graphene-std = { workspace = true }
graph-craft = { workspace = true }
wgpu-executor = { workspace = true }
@@ -49,26 +49,12 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
let message = FrontendMessage::UpdateFullscreen { fullscreen };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::LoadDocument {
id,
document,
to_front,
select_after_open,
} => {
let message = PortfolioMessage::OpenDocumentFileWithId {
document_id: id,
document_name: Some(document.name),
document_path: document.path,
document_serialized_content: document.content,
document_is_auto_saved: true,
document_is_saved: document.is_saved,
to_front,
select_after_open,
};
DesktopWrapperMessage::LoadDocumentContent { id, document } => {
let message = PersistentStateMessage::LoadDocument { document_id: id, document };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::SelectDocument { id } => {
let message = PortfolioMessage::SelectDocument { document_id: id };
DesktopWrapperMessage::LoadPersistedState { state } => {
let message = PersistentStateMessage::LoadState { state };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::LoadPreferences { preferences } => {
@@ -3,7 +3,7 @@ use graphite_editor::messages::layout::utility_types::layout_widget::LayoutTarge
use graphite_editor::messages::prelude::FrontendMessage;
use super::DesktopWrapperMessageDispatcher;
use super::messages::{DesktopFrontendMessage, Document, FileFilter, OpenFileDialogContext, SaveFileDialogContext};
use super::messages::{DesktopFrontendMessage, FileFilter, OpenFileDialogContext, SaveFileDialogContext};
pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: FrontendMessage) -> Option<FrontendMessage> {
match message {
@@ -67,39 +67,23 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
dispatcher.respond(DesktopFrontendMessage::UpdateUIScale { scale });
return Some(FrontendMessage::UpdateUIScale { scale });
}
FrontendMessage::TriggerPersistenceWriteDocument { document_id, document, details } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteDocument {
id: document_id,
document: Document {
name: details.name,
path: details.path,
content: document,
is_saved: details.is_saved,
},
});
FrontendMessage::TriggerPersistenceReadState => {
dispatcher.respond(DesktopFrontendMessage::PersistenceReadState);
}
FrontendMessage::TriggerPersistenceRemoveDocument { document_id } => {
FrontendMessage::TriggerPersistenceWriteState { state } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteState { state });
}
FrontendMessage::TriggerPersistenceReadDocument { document_id } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceReadDocument { id: document_id });
}
FrontendMessage::TriggerPersistenceDeleteDocument { document_id } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceDeleteDocument { id: document_id });
}
FrontendMessage::UpdateActiveDocument { document_id } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceUpdateCurrentDocument { id: document_id });
// Forward this to update the UI
return Some(FrontendMessage::UpdateActiveDocument { document_id });
}
FrontendMessage::UpdateOpenDocumentsList { open_documents } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceUpdateDocumentsList {
ids: open_documents.iter().map(|document| document.id).collect(),
FrontendMessage::TriggerPersistenceWriteDocument { document_id, document } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteDocument {
id: document_id,
document_serialized_content: document,
});
// Forward this to update the UI
return Some(FrontendMessage::UpdateOpenDocumentsList { open_documents });
}
FrontendMessage::TriggerLoadFirstAutoSaveDocument => {
dispatcher.respond(DesktopFrontendMessage::PersistenceLoadCurrentDocument);
}
FrontendMessage::TriggerLoadRestAutoSaveDocuments => {
dispatcher.respond(DesktopFrontendMessage::PersistenceLoadRemainingDocuments);
}
FrontendMessage::TriggerOpenLaunchDocuments => {
dispatcher.respond(DesktopFrontendMessage::OpenLaunchDocuments);
+4 -4
View File
@@ -1,10 +1,10 @@
use graph_craft::wasm_application_io::WasmApplicationIo;
use graph_craft::application_io::PlatformApplicationIo;
use graphite_editor::application::{Editor, Environment, Host, Platform};
use graphite_editor::messages::prelude::{FrontendMessage, Message};
use message_dispatcher::DesktopWrapperMessageDispatcher;
use messages::{DesktopFrontendMessage, DesktopWrapperMessage};
pub use graphite_editor::consts::FILE_EXTENSION;
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
pub use wgpu_executor::TargetTexture;
pub use wgpu_executor::WgpuContext;
pub use wgpu_executor::WgpuContextBuilder;
@@ -38,7 +38,7 @@ impl DesktopWrapper {
}
pub fn init(&self, wgpu_context: WgpuContext) {
let application_io = WasmApplicationIo::new_with_context(wgpu_context);
let application_io = PlatformApplicationIo::new_with_context(wgpu_context);
futures::executor::block_on(graphite_editor::node_graph_executor::replace_application_io(application_io));
}
@@ -51,7 +51,7 @@ impl DesktopWrapper {
pub async fn execute_node_graph() -> NodeGraphExecutionResult {
let result = graphite_editor::node_graph_executor::run_node_graph().await;
match result {
(true, texture) => NodeGraphExecutionResult::HasRun(texture.map(|t| t.texture)),
(true, texture) => NodeGraphExecutionResult::HasRun(texture.map(Into::into)),
(false, _) => NodeGraphExecutionResult::NotRun,
}
}
+22 -65
View File
@@ -3,6 +3,7 @@ use std::path::PathBuf;
pub(crate) use graphite_editor::messages::prelude::Message as EditorMessage;
pub use graphite_editor::messages::frontend::utility_types::{DocumentInfo, PersistedState};
pub use graphite_editor::messages::input_mapper::utility_types::input_keyboard::{Key, ModifierKeys};
pub use graphite_editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState as MouseState, EditorPosition as Position, MouseKeys};
pub use graphite_editor::messages::prelude::DocumentId;
@@ -41,23 +42,22 @@ pub enum DesktopFrontendMessage {
UpdateOverlays(vello::Scene),
PersistenceWriteDocument {
id: DocumentId,
document: Document,
document_serialized_content: String,
},
PersistenceDeleteDocument {
id: DocumentId,
},
PersistenceUpdateCurrentDocument {
id: DocumentId,
},
PersistenceLoadCurrentDocument,
PersistenceLoadRemainingDocuments,
PersistenceUpdateDocumentsList {
ids: Vec<DocumentId>,
},
PersistenceWritePreferences {
preferences: Preferences,
},
PersistenceLoadPreferences,
PersistenceWriteState {
state: PersistedState,
},
PersistenceReadState,
PersistenceReadDocument {
id: DocumentId,
},
UpdateMenu {
entries: Vec<MenuItem>,
},
@@ -81,63 +81,20 @@ pub enum DesktopFrontendMessage {
pub enum DesktopWrapperMessage {
FromWeb(Box<EditorMessage>),
Input(InputMessage),
FileDialogResult {
path: PathBuf,
content: Vec<u8>,
context: OpenFileDialogContext,
},
SaveFileDialogResult {
path: PathBuf,
context: SaveFileDialogContext,
},
OpenFile {
path: PathBuf,
content: Vec<u8>,
},
ImportFile {
path: PathBuf,
content: Vec<u8>,
},
FileDialogResult { path: PathBuf, content: Vec<u8>, context: OpenFileDialogContext },
SaveFileDialogResult { path: PathBuf, context: SaveFileDialogContext },
OpenFile { path: PathBuf, content: Vec<u8> },
ImportFile { path: PathBuf, content: Vec<u8> },
PollNodeGraphEvaluation,
UpdateMaximized {
maximized: bool,
},
UpdateFullscreen {
fullscreen: bool,
},
LoadDocument {
id: DocumentId,
document: Document,
to_front: bool,
select_after_open: bool,
},
SelectDocument {
id: DocumentId,
},
LoadPreferences {
preferences: Preferences,
},
MenuEvent {
id: String,
},
ClipboardReadResult {
content: Option<String>,
},
PointerLockMove {
x: f64,
y: f64,
},
LoadThirdPartyLicenses {
text: String,
},
}
#[derive(Clone, serde::Serialize, serde::Deserialize, Debug)]
pub struct Document {
pub content: String,
pub name: String,
pub path: Option<PathBuf>,
pub is_saved: bool,
UpdateMaximized { maximized: bool },
UpdateFullscreen { fullscreen: bool },
LoadDocumentContent { id: DocumentId, document: String },
LoadPersistedState { state: PersistedState },
LoadPreferences { preferences: Preferences },
MenuEvent { id: String },
ClipboardReadResult { content: Option<String> },
PointerLockMove { x: f64, y: f64 },
LoadThirdPartyLicenses { text: String },
}
pub struct FileFilter {
+3 -3
View File
@@ -11,9 +11,9 @@ repository = "https://github.com/GraphiteEditor/Graphite"
license = "Apache-2.0"
[features]
default = ["wasm", "gpu"]
wasm = ["wasm-bindgen", "graphene-std/wasm"]
gpu = ["interpreted-executor/gpu", "wgpu-executor"]
default = ["gpu"]
wasm = ["graphene-std/wasm", "interpreted-executor/wasm", "dep:wasm-bindgen"]
gpu = ["interpreted-executor/gpu", "dep:wgpu-executor"]
[dependencies]
# Local dependencies
+9
View File
@@ -4,6 +4,12 @@ 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;
pub const IMPORTS_TO_LEFT_EDGE_PIXEL_GAP: u32 = 120;
/// Vertical grid distance between adjacent stack siblings, or between a parent layer and its first stack child.
pub const STACK_VERTICAL_GAP: i32 = 3;
/// Horizontal grid indentation of a child layer relative to its parent layer.
pub const LAYER_INDENT_OFFSET: i32 = 8;
/// Horizontal grid width of a non-layer node in a chain.
pub const NODE_CHAIN_WIDTH: i32 = 7;
// VIEWPORT
pub const VIEWPORT_ZOOM_WHEEL_RATE: f64 = (1. / 600.) * 3.;
@@ -180,3 +186,6 @@ pub const DOUBLE_CLICK_MILLISECONDS: u64 = 500;
pub const UI_SCALE_DEFAULT: f64 = 1.;
pub const UI_SCALE_MIN: f64 = 0.5;
pub const UI_SCALE_MAX: f64 = 3.;
// ACTIONS
pub const BLEND_COUNT_PER_LAYER: usize = 10;
+7 -5
View File
@@ -2,6 +2,7 @@ use crate::messages::debug::utility_types::MessageLoggingVerbosity;
use crate::messages::defer::DeferMessageContext;
use crate::messages::dialog::DialogMessageContext;
use crate::messages::layout::layout_message_handler::LayoutMessageContext;
use crate::messages::portfolio::utility_types::PanelType;
use crate::messages::preferences::preferences_message_handler::PreferencesMessageContext;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::utility_functions::make_path_editable_is_allowed;
@@ -233,10 +234,11 @@ impl Dispatcher {
Message::MenuBar(message) => {
let menu_bar_message_handler = &mut self.message_handlers.menu_bar_message_handler;
menu_bar_message_handler.focus_document = self.message_handlers.portfolio_message_handler.focus_document;
menu_bar_message_handler.data_panel_open = self.message_handlers.portfolio_message_handler.data_panel_open;
menu_bar_message_handler.layers_panel_open = self.message_handlers.portfolio_message_handler.layers_panel_open;
menu_bar_message_handler.properties_panel_open = self.message_handlers.portfolio_message_handler.properties_panel_open;
menu_bar_message_handler.focus_document = self.message_handlers.portfolio_message_handler.workspace_panel_layout.focus_document;
let layout = &self.message_handlers.portfolio_message_handler.workspace_panel_layout;
menu_bar_message_handler.data_panel_open = layout.is_panel_present(PanelType::Data);
menu_bar_message_handler.layers_panel_open = layout.is_panel_present(PanelType::Layers);
menu_bar_message_handler.properties_panel_open = layout.is_panel_present(PanelType::Properties);
menu_bar_message_handler.message_logging_verbosity = self.message_handlers.debug_message_handler.message_logging_verbosity;
menu_bar_message_handler.reset_node_definitions_on_open = self.message_handlers.portfolio_message_handler.reset_node_definitions_on_open;
@@ -293,7 +295,7 @@ impl Dispatcher {
document_id,
document,
input: &self.message_handlers.input_preprocessor_message_handler,
persistent_data: &self.message_handlers.portfolio_message_handler.persistent_data,
cached_data: &self.message_handlers.portfolio_message_handler.cached_data,
node_graph: &self.message_handlers.portfolio_message_handler.executor,
preferences: &self.message_handlers.preferences_message_handler,
viewport: &self.message_handlers.viewport_message_handler,
@@ -6,7 +6,6 @@ use crate::messages::prelude::*;
pub enum ExportDialogMessage {
FileType { file_type: FileType },
ScaleFactor { factor: f64 },
TransparentBackground { transparent: bool },
ExportBounds { bounds: ExportBounds },
Submit,
@@ -14,7 +14,6 @@ pub struct ExportDialogMessageHandler {
pub file_type: FileType,
pub scale_factor: f64,
pub bounds: ExportBounds,
pub transparent_background: bool,
pub artboards: HashMap<LayerNodeIdentifier, String>,
pub has_selection: bool,
}
@@ -25,7 +24,6 @@ impl Default for ExportDialogMessageHandler {
file_type: Default::default(),
scale_factor: 1.,
bounds: Default::default(),
transparent_background: false,
artboards: Default::default(),
has_selection: false,
}
@@ -40,11 +38,17 @@ impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for Exp
match message {
ExportDialogMessage::FileType { file_type } => self.file_type = file_type,
ExportDialogMessage::ScaleFactor { factor } => self.scale_factor = factor,
ExportDialogMessage::TransparentBackground { transparent } => self.transparent_background = transparent,
ExportDialogMessage::ExportBounds { bounds } => self.bounds = bounds,
ExportDialogMessage::Submit => {
let artboard_name = match self.bounds {
// Fall back to "All Artwork" if "Selection" was chosen but nothing is currently selected
let bounds = if !self.has_selection && self.bounds == ExportBounds::Selection {
ExportBounds::AllArtwork
} else {
self.bounds
};
let artboard_name = match bounds {
ExportBounds::Artboard(layer) => self.artboards.get(&layer).cloned(),
_ => None,
};
@@ -52,8 +56,7 @@ impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for Exp
name: portfolio.active_document().map(|document| document.name.clone()).unwrap_or_default(),
file_type: self.file_type,
scale_factor: self.scale_factor,
bounds: self.bounds,
transparent_background: self.file_type != FileType::Jpg && self.transparent_background,
bounds,
artboard_name,
artboard_count: self.artboards.len(),
})
@@ -127,6 +130,7 @@ impl LayoutHolder for ExportDialogMessageHandler {
let artboards = self.artboards.iter().map(|(&layer, name)| (ExportBounds::Artboard(layer), name.to_string(), false)).collect();
let choices = [standard_bounds, artboards];
// Fall back to "All Artwork" if "Selection" was chosen but nothing is currently selected
let current_bounds = if !self.has_selection && self.bounds == ExportBounds::Selection {
ExportBounds::AllArtwork
} else {
@@ -159,22 +163,6 @@ impl LayoutHolder for ExportDialogMessageHandler {
DropdownInput::new(entries).selected_index(Some(index as u32)).widget_instance(),
];
let checkbox_id = CheckboxId::new();
let transparent_background = vec![
TextLabel::new("Transparency").table_align(true).min_width(100).for_checkbox(checkbox_id).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(self.transparent_background)
.disabled(self.file_type == FileType::Jpg)
.on_update(move |value: &CheckboxInput| ExportDialogMessage::TransparentBackground { transparent: value.checked }.into())
.for_label(checkbox_id)
.widget_instance(),
];
Layout(vec![
LayoutGroup::row(export_type),
LayoutGroup::row(resolution),
LayoutGroup::row(export_area),
LayoutGroup::row(transparent_background),
])
Layout(vec![LayoutGroup::row(export_type), LayoutGroup::row(resolution), LayoutGroup::row(export_area)])
}
}
@@ -1,7 +1,9 @@
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::prelude::*;
use glam::{IVec2, UVec2};
use graph_craft::document::NodeId;
use graphene_std::Color;
/// A dialog to allow users to set some initial options about a new document.
#[derive(Debug, Clone, Default, ExtractField)]
@@ -22,26 +24,40 @@ impl MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHa
NewDocumentDialogMessage::Submit => {
responses.add(PortfolioMessage::NewDocumentWithName { name: self.name.clone() });
let create_artboard = !self.infinite && self.dimensions.x > 0 && self.dimensions.y > 0;
if create_artboard {
if self.infinite {
// Infinite canvas: add a locked white background layer
let node_id = NodeId::new();
responses.add(GraphOperationMessage::NewColorFillLayer {
node_id,
color: Color::WHITE,
parent: LayerNodeIdentifier::ROOT_PARENT,
insert_index: 0,
});
responses.add(NodeGraphMessage::SetDisplayNameImpl {
node_id,
alias: "Background".to_string(),
});
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(),
artboard: graphene_std::Artboard::new(IVec2::ZERO, self.dimensions.as_ivec2()),
});
responses.add(NavigationMessage::CanvasPan { delta: self.dimensions.as_dvec2() });
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(ViewportMessage::RepropagateUpdate);
responses.add(DeferMessage::AfterNavigationReady {
messages: vec![
DocumentMessage::ZoomCanvasToFitAll.into(),
DocumentMessage::DeselectAllLayers.into(),
PortfolioMessage::AutoSaveActiveDocument.into(),
],
});
}
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(ViewportMessage::RepropagateUpdate);
responses.add(DeferMessage::AfterNavigationReady {
messages: vec![
DocumentMessage::ZoomCanvasToFitAll.into(),
DocumentMessage::DeselectAllLayers.into(),
PortfolioMessage::AutoSaveActiveDocument.into(),
],
});
responses.add(DocumentMessage::MarkAsSaved);
}
}
@@ -1,7 +1,7 @@
use super::IconName;
use super::utility_types::{DocumentDetails, MouseCursorIcon, OpenDocument};
use super::utility_types::{MouseCursorIcon, PersistedState};
use crate::messages::app_window::app_window_message_handler::AppWindowPlatform;
use crate::messages::frontend::utility_types::EyedropperPreviewImage;
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage};
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::utility_types::{
@@ -9,6 +9,7 @@ use crate::messages::portfolio::document::node_graph::utility_types::{
};
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
use crate::messages::portfolio::utility_types::WorkspacePanelLayout;
use crate::messages::prelude::*;
use crate::messages::tool::tool_messages::eyedropper_tool::PrimarySecondary;
use graph_craft::document::NodeId;
@@ -112,7 +113,15 @@ pub enum FrontendMessage {
font: Font,
url: String,
},
TriggerPersistenceRemoveDocument {
TriggerPersistenceReadState,
TriggerPersistenceReadDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
},
TriggerPersistenceWriteState {
state: PersistedState,
},
TriggerPersistenceDeleteDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
},
@@ -120,22 +129,15 @@ pub enum FrontendMessage {
#[serde(rename = "documentId")]
document_id: DocumentId,
document: String,
details: DocumentDetails,
},
TriggerLoadFirstAutoSaveDocument,
TriggerLoadRestAutoSaveDocuments,
TriggerOpenLaunchDocuments,
TriggerLoadPreferences,
TriggerOpen,
TriggerImport,
TriggerSavePreferences {
#[tsify(type = "unknown")]
#[cfg_attr(feature = "wasm", tsify(type = "unknown"))]
preferences: PreferencesMessageHandler,
},
TriggerSaveActiveDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
},
TriggerTextCommit,
TriggerVisitLink {
url: String,
@@ -194,14 +196,9 @@ pub enum FrontendMessage {
UpdateGraphViewOverlay {
open: bool,
},
UpdateDataPanelState {
open: bool,
},
UpdatePropertiesPanelState {
open: bool,
},
UpdateLayersPanelState {
open: bool,
UpdateWorkspacePanelLayout {
#[serde(rename = "panelLayout")]
panel_layout: WorkspacePanelLayout,
},
UpdateLayout {
#[serde(rename = "layoutTarget")]
@@ -291,7 +288,7 @@ pub enum FrontendMessage {
},
UpdateOpenDocumentsList {
#[serde(rename = "openDocuments")]
open_documents: Vec<OpenDocument>,
open_documents: Vec<DocumentInfo>,
},
UpdateWirePathInProgress {
#[serde(rename = "wirePath")]
+15 -13
View File
@@ -1,24 +1,26 @@
use std::path::PathBuf;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::utility_types::WorkspacePanelLayout;
use crate::messages::prelude::*;
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(PartialEq, Eq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct OpenDocument {
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct DocumentInfo {
pub id: DocumentId,
pub details: DocumentDetails,
pub name: String,
#[serde(default)]
pub path: Option<PathBuf>,
pub is_saved: bool,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(PartialEq, Eq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct DocumentDetails {
pub name: String,
pub path: Option<PathBuf>,
#[serde(rename = "isSaved")]
pub is_saved: bool,
#[serde(rename = "isAutoSaved")]
pub is_auto_saved: bool,
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct PersistedState {
pub documents: Vec<DocumentInfo>,
pub current_document: Option<DocumentId>,
#[serde(default)]
pub workspace_layout: Option<WorkspacePanelLayout>,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -357,6 +357,8 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
entry!(KeyDown(KeyS); modifiers=[Accel, Shift], action_dispatch=DocumentMessage::SaveDocumentAs),
entry!(KeyDown(KeyD); modifiers=[Accel], canonical, action_dispatch=DocumentMessage::DuplicateSelectedLayers),
entry!(KeyDown(KeyJ); modifiers=[Accel], action_dispatch=DocumentMessage::DuplicateSelectedLayers),
entry!(KeyDown(KeyB); modifiers=[Accel, Alt], action_dispatch=DocumentMessage::BlendSelectedLayers),
entry!(KeyDown(KeyM); modifiers=[Accel, Alt], action_dispatch=DocumentMessage::MorphSelectedLayers), // Might get eaten by the GeForce Experience overlay for some Windows users
entry!(KeyDown(KeyG); modifiers=[Accel], action_dispatch=DocumentMessage::GroupSelectedLayers { group_folder_type: GroupFolderType::Layer }),
entry!(KeyDown(KeyG); modifiers=[Accel, Shift], action_dispatch=DocumentMessage::UngroupSelectedLayers),
entry!(KeyDown(KeyN); modifiers=[Accel, Shift], action_dispatch=DocumentMessage::CreateEmptyFolder),
@@ -139,7 +139,8 @@ impl FrameTimeInfo {
}
pub fn advance_timestamp(&mut self, next_timestamp: Duration) {
debug_assert!(next_timestamp >= self.timestamp);
// Guard against non-monotonic timestamps from the browser (Keavon observed this once in Chrome)
let next_timestamp = next_timestamp.max(self.timestamp);
self.prev_timestamp = Some(self.timestamp);
self.timestamp = next_timestamp;
@@ -495,6 +495,18 @@ impl LayoutHolder for MenuBarMessageHandler {
})
.disabled(no_active_document || !has_selected_layers),
]]),
MenuListEntry::new("Blend")
.label("Blend")
.icon("InterpolationBlend")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::BlendSelectedLayers))
.on_commit(|_| DocumentMessage::BlendSelectedLayers.into())
.disabled(no_active_document || !has_selected_layers),
MenuListEntry::new("Morph")
.label("Morph")
.icon("InterpolationMorph")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::MorphSelectedLayers))
.on_commit(|_| DocumentMessage::MorphSelectedLayers.into())
.disabled(no_active_document || !has_selected_layers),
],
vec![
MenuListEntry::new("Make Path Editable")
@@ -635,6 +647,12 @@ impl LayoutHolder for MenuBarMessageHandler {
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::ToggleFocusDocument))
.on_commit(|_| PortfolioMessage::ToggleFocusDocument.into()),
],
vec![
MenuListEntry::new("Reset Workspace")
.label("Reset Workspace")
.icon("Reset")
.on_commit(|_| PortfolioMessage::ResetWorkspaceLayout.into()),
],
vec![
MenuListEntry::new("Properties")
.label("Properties")
@@ -9,7 +9,7 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, GridSnapping};
use crate::messages::portfolio::utility_types::PanelType;
use crate::messages::prelude::*;
use glam::DAffine2;
use glam::{DAffine2, IVec2};
use graph_craft::document::NodeId;
use graphene_std::Color;
use graphene_std::raster::BlendMode;
@@ -84,6 +84,8 @@ pub enum DocumentMessage {
GridVisibility {
visible: bool,
},
BlendSelectedLayers,
MorphSelectedLayers,
GroupSelectedLayers {
group_folder_type: GroupFolderType,
},
@@ -105,12 +107,18 @@ pub enum DocumentMessage {
image: Image<Color>,
mouse: Option<(f64, f64)>,
parent_and_insert_index: Option<(LayerNodeIdentifier, usize)>,
/// When true (file-open flow), place the image at the document origin so `WrapContentInArtboard`
/// can wrap it without a content Transform node. When false, place at the cursor or viewport center.
place_at_origin: bool,
},
PasteSvg {
name: Option<String>,
svg: String,
mouse: Option<(f64, f64)>,
parent_and_insert_index: Option<(LayerNodeIdentifier, usize)>,
/// When true (file-open flow), place the SVG at the document origin so `WrapContentInArtboard`
/// can wrap it without a content Transform node. When false, place at the cursor or viewport center.
place_at_origin: bool,
},
Redo,
RenameDocument {
@@ -191,7 +199,7 @@ pub enum DocumentMessage {
undo_count: usize,
},
ToggleLayerExpansion {
id: NodeId,
instance_path: Vec<NodeId>,
recursive: bool,
},
ToggleSelectedVisibility,
@@ -223,6 +231,9 @@ pub enum DocumentMessage {
SelectionStepForward,
WrapContentInArtboard {
place_artboard_at_origin: bool,
/// When `Some`, use this canvas (origin, dimensions) for the artboard instead of measuring the content bounding box.
/// The origin comes from the SVG viewBox's min-x/min-y values and the dimensions from its width/height.
artboard_canvas: Option<(IVec2, IVec2)>,
},
ZoomCanvasTo100Percent,
ZoomCanvasTo200Percent,
@@ -4,7 +4,10 @@ use super::utility_types::misc::{GroupFolderType, SNAP_FUNCTIONS_FOR_BOUNDING_BO
use super::utility_types::network_interface::{self, NodeNetworkInterface, TransactionStatus};
use super::utility_types::nodes::{CollapsedLayers, LayerStructureEntry, SelectedNodes};
use crate::application::{GRAPHITE_GIT_COMMIT_HASH, generate_uuid};
use crate::consts::{ASYMPTOTIC_EFFECT, COLOR_OVERLAY_GRAY, DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, SCALE_EFFECT, SCROLLBAR_SPACING, VIEWPORT_ROTATE_SNAP_INTERVAL};
use crate::consts::{
ASYMPTOTIC_EFFECT, BLEND_COUNT_PER_LAYER, COLOR_OVERLAY_GRAY, DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH, SCALE_EFFECT, SCROLLBAR_SPACING,
VIEWPORT_ROTATE_SNAP_INTERVAL,
};
use crate::messages::input_mapper::utility_types::macros::action_shortcut;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::data_panel::{DataPanelMessageContext, DataPanelMessageHandler};
@@ -18,7 +21,7 @@ use crate::messages::portfolio::document::properties_panel::properties_panel_mes
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, PTZ};
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate};
use crate::messages::portfolio::utility_types::{PanelType, PersistentData};
use crate::messages::portfolio::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;
@@ -40,6 +43,7 @@ use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
use graphene_std::vector::misc::dvec2_to_point;
use graphene_std::vector::style::RenderMode;
use kurbo::{Affine, BezPath, Line, PathSeg};
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
@@ -48,7 +52,7 @@ use std::time::Duration;
pub struct DocumentMessageContext<'a> {
pub document_id: DocumentId,
pub ipp: &'a InputPreprocessorMessageHandler,
pub persistent_data: &'a PersistentData,
pub cached_data: &'a CachedData,
pub executor: &'a mut NodeGraphExecutor,
pub current_tool: &'a ToolType,
pub preferences: &'a PreferencesMessageHandler,
@@ -82,8 +86,8 @@ pub struct DocumentMessageHandler {
//
// Contains the NodeNetwork and acts an an interface to manipulate the NodeNetwork with custom setters in order to keep NetworkMetadata in sync
pub network_interface: NodeNetworkInterface,
/// List of the [`LayerNodeIdentifier`]s that are currently collapsed by the user in the Layers panel.
/// Collapsed means that the expansion arrow isn't set to show the children of these layers.
/// Tracks which layer 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.
/// We save this to provide a hint about which version of the editor was used to create the document.
@@ -189,7 +193,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
let DocumentMessageContext {
document_id,
ipp,
persistent_data,
cached_data,
executor,
viewport,
current_tool,
@@ -227,7 +231,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
selection_network_path: &self.selection_network_path,
document_name: self.name.as_str(),
executor,
persistent_data,
cached_data,
properties_panel_open,
};
self.properties_panel_message_handler.process_message(message, responses, context);
@@ -315,7 +319,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
DocumentMessage::ClearLayersPanel => {
// Send an empty layer list
if layers_panel_open {
let layer_structure = Self::default().build_layer_structure(LayerNodeIdentifier::ROOT_PARENT);
let layer_structure = Self::default().build_layer_structure();
responses.add(FrontendMessage::UpdateDocumentLayerStructure { layer_structure });
}
@@ -378,7 +382,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
DocumentMessage::DocumentStructureChanged => {
if layers_panel_open {
self.network_interface.load_structure();
let layer_structure = self.build_layer_structure(LayerNodeIdentifier::ROOT_PARENT);
let layer_structure = self.build_layer_structure();
self.update_layers_panel_control_bar_widgets(layers_panel_open, responses);
self.update_layers_panel_bottom_bar_widgets(layers_panel_open, responses);
@@ -622,6 +626,12 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.snapping_state.grid_snapping = visible;
responses.add(OverlaysMessage::Draw);
}
DocumentMessage::BlendSelectedLayers => {
self.handle_group_selected_layers(GroupFolderType::Blend, responses);
}
DocumentMessage::MorphSelectedLayers => {
self.handle_group_selected_layers(GroupFolderType::Morph, responses);
}
DocumentMessage::GroupSelectedLayers { group_folder_type } => {
self.handle_group_selected_layers(group_folder_type, responses);
}
@@ -658,29 +668,35 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
image,
mouse,
parent_and_insert_index,
place_at_origin,
} => {
// All the image's pixels have been converted to 0..=1, linear, and premultiplied by `Color::from_rgba8_srgb`
let layer_parent = self.new_layer_parent(true);
let image_size = DVec2::new(image.width as f64, image.height as f64);
// Align the layer with the mouse or center of viewport
let viewport_location = mouse.map_or(viewport.center_in_viewport_space().into_dvec2() + viewport.offset().into_dvec2(), |pos| pos.into());
let document_to_viewport = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
let center_in_viewport = DAffine2::from_translation(document_to_viewport.inverse().transform_point2(viewport_location - viewport.offset().into_dvec2()));
let center_in_viewport_layerspace = center_in_viewport;
// Make layer the size of the image
let fit_image_size = DAffine2::from_scale_angle_translation(image_size, 0., image_size / -2.);
let transform = center_in_viewport_layerspace * fit_image_size;
let mut transform = if place_at_origin {
// File-open flow: place at document origin without centering so `WrapContentInArtboard` can wrap it
DAffine2::from_scale(image_size)
} else {
// Clipboard paste or drag-drop: center at cursor or viewport center.
// Convert the document-space cursor to the parent's local coordinate space so that
// an artboard at a non-zero position does not offset the placement.
let parent_to_document = {
let metadata = self.metadata();
metadata.document_to_viewport.inverse() * metadata.transform_to_viewport(layer_parent)
};
let cursor_in_parent = parent_to_document.inverse() * self.document_transform_from_mouse(mouse, viewport);
cursor_in_parent * DAffine2::from_scale_angle_translation(image_size, 0., image_size / -2.)
};
transform.translation = transform.translation.round();
let layer_node_id = NodeId::new();
let layer_id = LayerNodeIdentifier::new_unchecked(layer_node_id);
responses.add(DocumentMessage::AddTransaction);
let layer = graph_modification_utils::new_image_layer(Table::new_from_element(Raster::new_cpu(image)), layer_node_id, self.new_layer_parent(true), 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 {
@@ -715,17 +731,29 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
svg,
mouse,
parent_and_insert_index,
place_at_origin,
} => {
let document_to_viewport = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
let viewport_location = mouse.map_or(viewport.center_in_viewport_space().into_dvec2() + viewport.offset().into_dvec2(), |pos| pos.into());
let center_in_viewport = DAffine2::from_translation(document_to_viewport.inverse().transform_point2(viewport_location - viewport.offset().into_dvec2()));
let layer_parent = self.new_layer_parent(true);
let transform = if place_at_origin {
// File-open flow: place at document origin so `WrapContentInArtboard` can wrap it without extra Transform nodes
DAffine2::IDENTITY
} else {
// Clipboard paste or drag-drop: center at cursor or viewport center.
// Convert the document-space cursor to the parent's local coordinate space so that
// an artboard at a non-zero position does not offset the placement.
let parent_to_document = {
let metadata = self.metadata();
metadata.document_to_viewport.inverse() * metadata.transform_to_viewport(layer_parent)
};
parent_to_document.inverse() * self.document_transform_from_mouse(mouse, viewport)
};
let layer_node_id = NodeId::new();
let layer_id = LayerNodeIdentifier::new_unchecked(layer_node_id);
responses.add(DocumentMessage::AddTransaction);
let layer = graph_modification_utils::new_svg_layer(svg, center_in_viewport, layer_node_id, self.new_layer_parent(true), responses);
let layer = graph_modification_utils::new_svg_layer(svg, transform, !place_at_origin, layer_node_id, layer_parent, responses);
if let Some(name) = name {
responses.add(NodeGraphMessage::SetDisplayName {
@@ -993,8 +1021,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
}
}
}
DocumentMessage::SetActivePanel { active_panel: panel } => {
match panel {
DocumentMessage::SetActivePanel { active_panel } => {
match active_panel {
PanelType::Document => {
if self.graph_view_overlay_open {
self.selection_network_path.clone_from(&self.breadcrumb_network_path);
@@ -1147,25 +1175,27 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
responses.add(OverlaysMessage::Draw);
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
}
DocumentMessage::ToggleLayerExpansion { id, recursive } => {
let layer = LayerNodeIdentifier::new(id, &self.network_interface);
let metadata = self.metadata();
let is_collapsed = self.collapsed.0.contains(&layer);
DocumentMessage::ToggleLayerExpansion { instance_path, recursive } => {
let is_collapsed = self.collapsed.0.contains(&instance_path);
if is_collapsed {
if recursive {
let children: HashSet<_> = layer.descendants(metadata).collect();
self.collapsed.0.retain(|collapsed_layer| !children.contains(collapsed_layer) && collapsed_layer != &layer);
// Remove this path and all descendant paths (paths that start with this one)
self.collapsed.0.retain(|path| !path.starts_with(&instance_path));
} else {
self.collapsed.0.retain(|collapsed_layer| collapsed_layer != &layer);
self.collapsed.0.retain(|path| *path != instance_path);
}
} else {
if recursive {
let children_to_add: Vec<_> = layer.descendants(metadata).filter(|child| !self.collapsed.0.contains(child)).collect();
self.collapsed.0.extend(children_to_add);
// Collapse all expanded descendant 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(layer);
self.collapsed.0.push(instance_path);
}
responses.add(NodeGraphMessage::SendGraph);
@@ -1347,11 +1377,23 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.network_interface.selection_step_forward(&self.selection_network_path);
responses.add(EventMessage::SelectionChanged);
}
DocumentMessage::WrapContentInArtboard { place_artboard_at_origin } => {
// Get bounding box of all layers
DocumentMessage::WrapContentInArtboard {
place_artboard_at_origin,
artboard_canvas,
} => {
// Get bounding box of all layers (always needed to confirm there is content)
let bounds = self.network_interface.document_bounds_document_space(false);
let Some(bounds) = bounds else { return };
let bounds_rounded_dimensions = (bounds[1] - bounds[0]).round();
// When artboard_canvas is provided (SVG file-open flow), use the declared canvas origin and dimensions;
// no content-shift Transform node needed since the SVG was already placed at its natural coordinates.
let (artboard_location, artboard_dimensions, content_shift) = if let Some((origin, dimensions)) = artboard_canvas {
(origin, dimensions, DVec2::ZERO)
} else {
// No declared canvas (image or clipboard paste): derive location and dimensions from the content bounding box.
let location = if place_artboard_at_origin { IVec2::ZERO } else { bounds[0].round().as_ivec2() };
(location, (bounds[1] - bounds[0]).round().as_ivec2(), -bounds[0].round())
};
// Create an artboard and set its dimensions to the bounding box size and location
let node_id = NodeId::new();
@@ -1363,11 +1405,17 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
node_id,
node_template: Box::new(new_artboard_node),
});
responses.add(NodeGraphMessage::ShiftNodePosition { node_id, x: 15, y: -3 });
let needs_content_transform = !content_shift.abs_diff_eq(DVec2::ZERO, 1e-6);
// With a content Transform node: shift by the layer indent plus the node width. Without: use just the layer indent.
responses.add(NodeGraphMessage::ShiftNodePosition {
node_id,
x: if needs_content_transform { LAYER_INDENT_OFFSET + NODE_CHAIN_WIDTH } else { LAYER_INDENT_OFFSET },
y: -3,
});
responses.add(GraphOperationMessage::ResizeArtboard {
layer: LayerNodeIdentifier::new_unchecked(node_id),
location: if place_artboard_at_origin { IVec2::ZERO } else { bounds[0].round().as_ivec2() },
dimensions: bounds_rounded_dimensions.as_ivec2(),
location: artboard_location,
dimensions: artboard_dimensions,
});
// Connect the current output data to the artboard's input data, and the artboard's output to the document output
@@ -1377,10 +1425,10 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
insert_node_input_index: 1,
});
// Shift the content by half its width and height so it gets centered in the artboard
// Shift the content to align its top-left to the artboard's origin (no-op when content is already at origin)
responses.add(GraphOperationMessage::TransformChange {
layer: node_layer_id,
transform: DAffine2::from_translation(bounds_rounded_dimensions / 2.),
transform: DAffine2::from_translation(content_shift),
transform_in: TransformIn::Local,
skip_rerender: false,
});
@@ -1443,6 +1491,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
DeleteSelectedLayers,
DuplicateSelectedLayers,
GroupSelectedLayers,
BlendSelectedLayers,
MorphSelectedLayers,
SelectedLayersLower,
SelectedLayersLowerToBack,
SelectedLayersRaise,
@@ -1474,6 +1524,13 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
}
impl DocumentMessageHandler {
/// Translates a viewport mouse position to a document-space transform, or uses the viewport center if no mouse position is given.
fn document_transform_from_mouse(&self, mouse: Option<(f64, f64)>, viewport: &ViewportMessageHandler) -> DAffine2 {
let viewport_pos: DVec2 = mouse.map_or_else(|| viewport.center_in_viewport_space().into_dvec2() + viewport.offset().into_dvec2(), |pos| pos.into());
let document_to_viewport = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
DAffine2::from_translation(document_to_viewport.inverse().transform_point2(viewport_pos - viewport.offset().into_dvec2()))
}
/// Runs an intersection test with all layers and a viewport space quad
pub fn intersect_quad<'a>(&'a self, viewport_quad: graphene_std::renderer::Quad, viewport: &ViewportMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
let document_to_viewport = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
@@ -1694,22 +1751,218 @@ impl DocumentMessageHandler {
Ok(document_message_handler)
}
/// Recursively builds the layer structure tree for a folder.
fn build_layer_structure(&self, folder: LayerNodeIdentifier) -> Vec<LayerStructureEntry> {
folder
.children(self.metadata())
.map(|layer_node| {
let children = if layer_node.has_children(self.metadata()) && !self.collapsed.0.contains(&layer_node) {
self.build_layer_structure(layer_node)
} else {
Vec::new()
};
LayerStructureEntry {
layer_id: layer_node.to_node(),
children,
/// Builds the layer structure tree by traversing the node graph directly.
/// Unlike the canonical `structure` field of [`DocumentMetadata`] (which stores single-parent relationships), this allows
/// the same layer to appear under multiple parents when the graph feeds the same child content into separate parent layers.
fn build_layer_structure(&self) -> Vec<LayerStructureEntry> {
let network = &self.network_interface;
let Some(root_node) = network.root_node(&[]) else { return Vec::new() };
let Some(first_root_layer_id) = network
.upstream_flow_back_from_nodes(vec![root_node.node_id], &[], FlowType::PrimaryFlow)
.find(|node_id| network.is_layer(node_id, &[]))
else {
return Vec::new();
};
let selected_layers: HashSet<NodeId> = network.selected_nodes().selected_layers(self.metadata()).map(LayerNodeIdentifier::to_node).collect();
let ancestors = HashSet::new();
let 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, &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();
root_ancestors.insert(first_root_layer_id);
for sibling_id in network.upstream_flow_back_from_nodes(vec![first_root_layer_id], &[], FlowType::PrimaryFlow).skip(1) {
if network.is_layer(&sibling_id, &[]) && !root_ancestors.contains(&sibling_id) {
root_entries.push(self.build_layer_entry(sibling_id, &root_ancestors, &selected_layers, &instance_path));
}
}
root_entries
}
/// Builds a single `LayerStructureEntry` for the given layer, including its `children_present` flag,
/// `descendant_selected` flag, and (if expanded) its children collected from the graph.
fn build_layer_entry(&self, layer_id: NodeId, ancestors: &HashSet<NodeId>, selected_layers: &HashSet<NodeId>, parent_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(&instance_path);
let children = if children_present && !collapsed {
self.collect_layer_children(layer_id, &child_ancestors, selected_layers, &instance_path)
} else {
Vec::new()
};
// Compute whether any descendant is selected (checking expanded children and, if collapsed, via graph traversal)
let descendant_selected = if !children.is_empty() {
children.iter().any(|child| child.descendant_selected || selected_layers.contains(&child.layer_id))
} else if children_present {
// Layer is collapsed but has children, so check via graph traversal
self.has_selected_descendant_in_graph(layer_id, &child_ancestors, selected_layers)
} else {
false
};
LayerStructureEntry {
layer_id,
children,
children_present,
descendant_selected,
}
}
/// Checks whether a layer has any child layers reachable via horizontal flow in the graph.
fn has_layer_children_in_graph(&self, layer_id: NodeId, child_ancestors: &HashSet<NodeId>) -> bool {
let network = &self.network_interface;
network
.upstream_flow_back_from_nodes(vec![layer_id], &[], FlowType::HorizontalFlow)
.skip(1)
.any(|id| network.is_layer(&id, &[]) && !child_ancestors.contains(&id))
}
/// Checks whether any descendant layer in the graph (via horizontal + primary flow) is selected.
/// Used when a layer is collapsed to determine if the ancestor-of-selected indicator should show.
fn has_selected_descendant_in_graph(&self, layer_id: NodeId, ancestors: &HashSet<NodeId>, selected_layers: &HashSet<NodeId>) -> bool {
let network = &self.network_interface;
// Find child layers via horizontal flow
let mut stack: Vec<NodeId> = network
.upstream_flow_back_from_nodes(vec![layer_id], &[], FlowType::HorizontalFlow)
.skip(1)
.filter(|node_id| network.is_layer(node_id, &[]) && !ancestors.contains(node_id))
.collect();
let mut visited = ancestors.clone();
// Iteratively explore all descendant layers via a depth-first traversal
while let Some(current_id) = stack.pop() {
// Skip already-visited layers to avoid infinite loops from graph cycles
if !visited.insert(current_id) {
continue;
}
// Found a selected descendant, the ancestor indicator should be shown
if selected_layers.contains(&current_id) {
return true;
}
// Check this layer's children via horizontal flow
for node_id in network.upstream_flow_back_from_nodes(vec![current_id], &[], FlowType::HorizontalFlow).skip(1) {
if network.is_layer(&node_id, &[]) && !visited.contains(&node_id) {
stack.push(node_id);
}
})
.collect()
}
// Check stacked siblings via primary flow
for node_id in network.upstream_flow_back_from_nodes(vec![current_id], &[], FlowType::PrimaryFlow).skip(1) {
if network.is_layer(&node_id, &[]) && !visited.contains(&node_id) {
stack.push(node_id);
}
}
}
false
}
/// Collects the child entries for a given layer by traversing its horizontal and primary flows.
/// The horizontal flow (a layer's secondary input chain) finds nested content layers, and the
/// primary flow from those (their stack's top output) finds stacked siblings at the same depth.
/// `ancestors` contains layer IDs in the current path from root, used for cycle prevention.
fn collect_layer_children(&self, layer_id: NodeId, ancestors: &HashSet<NodeId>, selected_layers: &HashSet<NodeId>, instance_path: &[NodeId]) -> Vec<LayerStructureEntry> {
let network = &self.network_interface;
// Find the first nested layer via horizontal flow (content inside this layer)
let Some(nested_id) = network
.upstream_flow_back_from_nodes(vec![layer_id], &[], FlowType::HorizontalFlow)
.skip(1)
.find(|id| network.is_layer(id, &[]))
else {
return Vec::new();
};
// Cycle detected, this layer is already an ancestor in the current branch
if ancestors.contains(&nested_id) {
return Vec::new();
}
// The nested layer is the first child at this depth level
let mut children = vec![self.build_layer_entry(nested_id, ancestors, selected_layers, 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, instance_path));
}
}
children
}
/// 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_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();
let mut stack: Vec<(NodeId, Vec<NodeId>)> = Vec::new();
// Seed with child layers via horizontal flow
for node_id in network.upstream_flow_back_from_nodes(vec![layer_id], &[], FlowType::HorizontalFlow).skip(1) {
if network.is_layer(&node_id, &[]) {
let mut child_path = instance_path.to_vec();
child_path.push(node_id);
stack.push((node_id, child_path));
}
}
let mut visited = HashSet::new();
// Depth-first traversal collecting all unique descendant 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 instance path for collapsing
paths.push(current_path.clone());
// Add nested content layers found via horizontal flow
for node_id in network.upstream_flow_back_from_nodes(vec![current_id], &[], FlowType::HorizontalFlow).skip(1) {
if network.is_layer(&node_id, &[]) {
let mut child_path = current_path.clone();
child_path.push(node_id);
stack.push((node_id, child_path));
}
}
// Add stacked sibling layers found via primary flow
for node_id in network.upstream_flow_back_from_nodes(vec![current_id], &[], FlowType::PrimaryFlow).skip(1) {
if network.is_layer(&node_id, &[]) {
// Siblings share the same parent path (everything up to the last element of current_path)
let mut sibling_path = current_path[..current_path.len() - 1].to_vec();
sibling_path.push(node_id);
stack.push((node_id, sibling_path));
}
}
}
paths
}
pub fn undo_with_history(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) {
@@ -1915,6 +2168,57 @@ impl DocumentMessageHandler {
});
}
}
GroupFolderType::Blend | GroupFolderType::Morph => {
let control_path_id = NodeId(generate_uuid());
let all_layers_to_group = network_interface.shallowest_unique_layers_sorted(&[]);
let blend_count = matches!(group_folder_type, GroupFolderType::Blend).then(|| all_layers_to_group.len() * BLEND_COUNT_PER_LAYER);
responses.add(GraphOperationMessage::NewInterpolationLayer {
id: folder_id,
control_path_id,
parent,
insert_index,
blend_count,
});
let new_group_folder = LayerNodeIdentifier::new_unchecked(folder_id);
// Move selected layers into the group as children
for layer_to_group in all_layers_to_group.into_iter().rev() {
responses.add(NodeGraphMessage::MoveLayerToStack {
layer: layer_to_group,
parent: new_group_folder,
insert_index: 0,
});
}
// Connect the child stack to the control path layer as a co-parent
responses.add(GraphOperationMessage::ConnectInterpolationControlPathToChildren {
interpolation_layer_id: folder_id,
control_path_id,
});
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![folder_id] });
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(DocumentMessage::DocumentStructureChanged);
responses.add(NodeGraphMessage::SendGraph);
// The control path layer (Blend Path / Morph Path) should start collapsed.
let 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();
instance_path.reverse();
instance_path.push(control_path_id);
instance_path
};
responses.add(DocumentMessage::ToggleLayerExpansion { instance_path, recursive: false });
return folder_id;
}
}
let new_group_folder = LayerNodeIdentifier::new_unchecked(folder_id);
@@ -3175,6 +3479,16 @@ impl Iterator for ClickXRayIter<'_> {
}
}
/// Deserializes `CollapsedLayers` with backwards compatibility for the old format
/// (flat list of layer node IDs) by consuming the entire value first, then attempting
/// to interpret it as the new format. Falls back to an empty default for old documents.
fn deserialize_collapsed_layers<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<CollapsedLayers, D::Error> {
use serde::Deserialize;
// Buffer the entire value to avoid leaving the deserializer in a bad state on type mismatch
let value = serde_json::Value::deserialize(deserializer)?;
Ok(serde_json::from_value(value).unwrap_or_default())
}
#[cfg(test)]
mod document_message_handler_tests {
use super::*;
@@ -4,7 +4,6 @@ use crate::messages::portfolio::document::utility_types::network_interface::Node
use crate::messages::prelude::*;
use glam::{DAffine2, IVec2};
use graph_craft::document::NodeId;
use graphene_std::Artboard;
use graphene_std::brush::brush_stroke::BrushStroke;
use graphene_std::raster::BlendMode;
use graphene_std::raster_types::{CPU, Raster};
@@ -14,6 +13,7 @@ use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::PointId;
use graphene_std::vector::VectorModificationType;
use graphene_std::vector::style::{Fill, Stroke};
use graphene_std::{Artboard, Color};
#[impl_message(Message, DocumentMessage, GraphOperation)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
@@ -74,6 +74,17 @@ pub enum GraphOperationMessage {
parent: LayerNodeIdentifier,
insert_index: usize,
},
NewInterpolationLayer {
id: NodeId,
control_path_id: NodeId,
parent: LayerNodeIdentifier,
insert_index: usize,
blend_count: Option<usize>,
},
ConnectInterpolationControlPathToChildren {
interpolation_layer_id: NodeId,
control_path_id: NodeId,
},
NewBooleanOperationLayer {
id: NodeId,
operation: graphene_std::vector::misc::BooleanOperation,
@@ -86,6 +97,12 @@ pub enum GraphOperationMessage {
parent: LayerNodeIdentifier,
insert_index: usize,
},
NewColorFillLayer {
node_id: NodeId,
color: Color,
parent: LayerNodeIdentifier,
insert_index: usize,
},
NewVectorLayer {
id: NodeId,
subpaths: Vec<Subpath<PointId>>,
@@ -112,5 +129,7 @@ pub enum GraphOperationMessage {
transform: DAffine2,
parent: LayerNodeIdentifier,
insert_index: usize,
/// When true, centers the SVG at the transform origin (clipboard paste / drag-drop). When false, keeps natural SVG coordinates (file-open flow).
center: bool,
},
}
@@ -1,5 +1,6 @@
use super::transform_utils;
use super::utility_types::ModifyInputsContext;
use crate::consts::{LAYER_INDENT_OFFSET, STACK_VERTICAL_GAP};
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface, OutputConnector};
@@ -14,7 +15,7 @@ use graphene_std::renderer::Quad;
use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
use graphene_std::table::Table;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::style::{Fill, Gradient, GradientStop, GradientStops, GradientType, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::style::{Fill, Gradient, GradientSpreadMethod, GradientStop, GradientStops, GradientType, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
#[derive(ExtractField)]
pub struct GraphOperationMessageContext<'a> {
@@ -171,6 +172,77 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
responses.add(NodeGraphMessage::RunDocumentGraph);
}
GraphOperationMessage::NewInterpolationLayer {
id,
control_path_id,
parent,
insert_index,
blend_count,
} => {
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
let layer = modify_inputs.create_layer(id);
// Insert the main chain node (Blend or Morph) depending on whether a blend count is provided
let (chain_node_id, layer_alias, path_alias) = if let Some(count) = blend_count {
(modify_inputs.insert_blend_data(layer, count as f64), "Blend", "Blend Path")
} else {
(modify_inputs.insert_morph_data(layer), "Morph", "Morph Path")
};
// Create the control path layer (Path → Auto-Tangents → Origins to Polyline)
let control_path_layer = modify_inputs.create_layer(control_path_id);
let path_node_id = modify_inputs.insert_control_path_data(control_path_layer);
network_interface.move_layer_to_stack(control_path_layer, parent, insert_index, &[]);
network_interface.move_layer_to_stack(layer, parent, insert_index + 1, &[]);
// Connect the Path node's output to the chain node's path parameter input (input 4 for both Morph and Blend).
// Done after move_layer_to_stack so chain nodes have correct positions when converted to absolute.
network_interface.set_input(&InputConnector::node(chain_node_id, 4), NodeInput::node(path_node_id, 0), &[]);
responses.add(NodeGraphMessage::SetDisplayNameImpl {
node_id: id,
alias: layer_alias.to_string(),
});
responses.add(NodeGraphMessage::SetDisplayNameImpl {
node_id: control_path_id,
alias: path_alias.to_string(),
});
}
GraphOperationMessage::ConnectInterpolationControlPathToChildren {
interpolation_layer_id,
control_path_id,
} => {
// Find the chain node (Blend or Morph, first in chain of the layer)
let Some(OutputConnector::Node { node_id: chain_node, .. }) = network_interface.upstream_output_connector(&InputConnector::node(interpolation_layer_id, 1), &[]) else {
log::error!("Could not find chain node for layer {interpolation_layer_id}");
return;
};
// Get what feeds into the chain node's primary input (the children stack)
let Some(OutputConnector::Node { node_id: children_id, output_index }) = network_interface.upstream_output_connector(&InputConnector::node(chain_node, 0), &[]) else {
log::error!("Could not find children stack feeding chain node {chain_node}");
return;
};
// Find the deepest node in the control path layer's chain (Origins to Polyline)
let mut deepest_chain_node = None;
let mut current_connector = InputConnector::node(control_path_id, 1);
while let Some(OutputConnector::Node { node_id, .. }) = network_interface.upstream_output_connector(&current_connector, &[]) {
deepest_chain_node = Some(node_id);
current_connector = InputConnector::node(node_id, 0);
}
// Connect children to the deepest chain node's input 0 (or the layer's input 1 if no chain)
let target_connector = match deepest_chain_node {
Some(node_id) => InputConnector::node(node_id, 0),
None => InputConnector::node(control_path_id, 1),
};
network_interface.set_input(&target_connector, NodeInput::node(children_id, output_index), &[]);
// Shift the child stack (topmost child only, the rest follow) down 3 and left 10
network_interface.shift_node(&children_id, IVec2::new(-10, 3), &[]);
}
GraphOperationMessage::NewBooleanOperationLayer { id, operation, parent, insert_index } => {
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
let layer = modify_inputs.create_layer(id);
@@ -202,6 +274,13 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
responses.add(NodeGraphMessage::MoveLayerToStack { layer, parent, insert_index });
responses.add(NodeGraphMessage::RunDocumentGraph);
}
GraphOperationMessage::NewColorFillLayer { node_id, color, parent, insert_index } => {
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
let layer = modify_inputs.create_layer(node_id);
modify_inputs.insert_color_value(color, layer);
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
responses.add(NodeGraphMessage::RunDocumentGraph);
}
GraphOperationMessage::NewVectorLayer { id, subpaths, parent, insert_index } => {
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
let layer = modify_inputs.create_layer(id);
@@ -320,6 +399,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
transform,
parent,
insert_index,
center,
} => {
let tree = match usvg::Tree::from_str(&svg, &usvg::Options::default()) {
Ok(t) => t,
@@ -333,21 +413,38 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
};
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
let size = tree.size();
let offset_to_center = DVec2::new(size.width() as f64, size.height() as f64) / -2.;
let transform = transform * DAffine2::from_translation(offset_to_center);
// The placement transform positions the root group in document space.
// When centering (paste at cursor/viewport), shift so the SVG is centered at the transform origin.
// When not centering (file-open flow), content stays at viewport coordinates (usvg's viewBox mapping
// already places it in [0, width] × [0, height]); the artboard's X/Y handles the viewBox origin offset.
let mut placement_transform = if center {
// Center on the actual rendered content bounds rather than the viewbox size.
// An SVG may have a viewbox larger than its content, so using viewport_size/2 would place the cursor
// in that empty region instead of on the content.
let bounds = tree.root().abs_bounding_box();
let visual_center = DVec2::new((bounds.left() + bounds.right()) as f64 / 2., (bounds.top() + bounds.bottom()) as f64 / 2.);
transform * DAffine2::from_translation(-visual_center)
} else {
transform
};
placement_transform.translation = placement_transform.translation.round();
let graphite_gradient_stops = extract_graphite_gradient_stops(&svg);
// Pass identity so each leaf layer receives only its SVG-native transform from `abs_transform`.
// The placement offset is then applied once to the root group layer below.
import_usvg_node(
&mut modify_inputs,
&usvg::Node::Group(Box::new(tree.root().clone())),
transform,
id,
parent,
insert_index,
&graphite_gradient_stops,
);
// After import, `layer_node` is set to the root group. Apply the placement transform to it
// (skipped automatically when identity, so file-open with content at origin creates no Transform node).
modify_inputs.transform_set(placement_transform, TransformIn::Local, false);
}
}
}
@@ -442,48 +539,62 @@ fn parse_hex_stop_color(hex: &str, opacity: f32) -> Option<Color> {
Some(Color::from_rgbaf32_unchecked(r, g, b, opacity))
}
/// Import a usvg node as the root of an SVG import operation.
///
/// The root layer uses the full `move_layer_to_stack` (with push/collision logic) to correctly
/// interact with any existing layers in the parent stack. All descendant layers use a lightweight
/// O(n) import path that skips collision detection and instead calculates positions directly from
/// the known tree structure.
fn import_usvg_node(
modify_inputs: &mut ModifyInputsContext,
node: &usvg::Node,
transform: DAffine2,
id: NodeId,
parent: LayerNodeIdentifier,
insert_index: usize,
graphite_gradient_stops: &HashMap<String, GradientStops>,
) {
let layer = modify_inputs.create_layer(id);
modify_inputs.network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
modify_inputs.layer_node = Some(layer);
if let Some(upstream_layer) = layer.next_sibling(modify_inputs.network_interface.document_metadata()) {
modify_inputs.network_interface.shift_node(&upstream_layer.to_node(), IVec2::new(0, 3), &[]);
modify_inputs.network_interface.shift_node(&upstream_layer.to_node(), IVec2::new(0, STACK_VERTICAL_GAP), &[]);
}
match node {
usvg::Node::Group(group) => {
// Collect child extents for O(n) position calculation
let mut child_extents_svg_order: Vec<u32> = Vec::new();
let mut group_extents_map: HashMap<LayerNodeIdentifier, Vec<u32>> = HashMap::new();
// Enable import mode: skips expensive is_acyclic checks and per-node cache invalidation
// during wiring since we're building a known tree structure where cycles are impossible
modify_inputs.import = true;
for child in group.children() {
import_usvg_node(modify_inputs, child, transform, NodeId::new(), layer, 0, graphite_gradient_stops);
let extent = import_usvg_node_inner(modify_inputs, child, NodeId::new(), layer, 0, graphite_gradient_stops, &mut group_extents_map);
child_extents_svg_order.push(extent);
}
modify_inputs.import = false;
modify_inputs.layer_node = Some(layer);
// Rebuild the layer tree once now that all wiring is complete
modify_inputs.network_interface.load_structure();
// Set positions for all imported descendants in a single O(n) pass
let parent_pos = modify_inputs.network_interface.position(&layer.to_node(), &[]).unwrap_or(IVec2::ZERO);
set_import_child_positions(modify_inputs.network_interface, layer, parent_pos, &child_extents_svg_order, &group_extents_map);
// Invalidate caches once after all positions are set
modify_inputs.network_interface.unload_all_nodes_click_targets(&[]);
modify_inputs.network_interface.unload_all_nodes_bounding_box(&[]);
}
usvg::Node::Path(path) => {
let subpaths = convert_usvg_path(path);
let bounds = subpaths.iter().filter_map(|subpath| subpath.bounding_box()).reduce(Quad::combine_bounds).unwrap_or_default();
modify_inputs.insert_vector(subpaths, layer, true, path.fill().is_some(), path.stroke().is_some());
if let Some(transform_node_id) = modify_inputs.existing_network_node_id("Transform", true) {
transform_utils::update_transform(modify_inputs.network_interface, &transform_node_id, transform * usvg_transform(node.abs_transform()));
}
if let Some(fill) = path.fill() {
let bounds_transform = DAffine2::from_scale_angle_translation(bounds[1] - bounds[0], 0., bounds[0]);
apply_usvg_fill(fill, modify_inputs, bounds_transform, graphite_gradient_stops);
}
if let Some(stroke) = path.stroke() {
apply_usvg_stroke(stroke, modify_inputs, transform * usvg_transform(node.abs_transform()));
}
import_usvg_path(modify_inputs, node, path, layer, graphite_gradient_stops);
}
usvg::Node::Image(_image) => {
warn!("Skip image")
warn!("Skip image");
}
usvg::Node::Text(text) => {
let font = Font::new(graphene_std::consts::DEFAULT_FONT_FAMILY.to_string(), graphene_std::consts::DEFAULT_FONT_STYLE.to_string());
@@ -493,6 +604,141 @@ fn import_usvg_node(
}
}
/// Recursively import a usvg node as a descendant of the root import layer.
/// Uses lightweight wiring (no push/collision) and returns the subtree extent for position calculation.
///
/// The subtree extent represents the additional vertical grid units that this node's descendants
/// occupy below the node's position. This is used to calculate correct y_offsets between siblings.
fn import_usvg_node_inner(
modify_inputs: &mut ModifyInputsContext,
node: &usvg::Node,
id: NodeId,
parent: LayerNodeIdentifier,
insert_index: usize,
graphite_gradient_stops: &HashMap<String, GradientStops>,
group_extents_map: &mut HashMap<LayerNodeIdentifier, Vec<u32>>,
) -> u32 {
let layer = modify_inputs.create_layer(id);
modify_inputs.network_interface.move_layer_to_stack_for_import(layer, parent, insert_index, &[]);
modify_inputs.layer_node = Some(layer);
match node {
usvg::Node::Group(group) => {
let mut child_extents: Vec<u32> = Vec::new();
for child in group.children() {
let extent = import_usvg_node_inner(modify_inputs, child, NodeId::new(), layer, 0, graphite_gradient_stops, group_extents_map);
child_extents.push(extent);
}
modify_inputs.layer_node = Some(layer);
let n = child_extents.len();
let total_extent = if n == 0 {
0
} else {
(2 * STACK_VERTICAL_GAP as u32) * n as u32 - STACK_VERTICAL_GAP as u32 + child_extents.iter().sum::<u32>()
};
group_extents_map.insert(layer, child_extents);
total_extent
}
usvg::Node::Path(path) => {
import_usvg_path(modify_inputs, node, path, layer, graphite_gradient_stops);
0
}
usvg::Node::Image(_image) => {
warn!("Skip image");
0
}
usvg::Node::Text(text) => {
let font = Font::new(graphene_std::consts::DEFAULT_FONT_FAMILY.to_string(), graphene_std::consts::DEFAULT_FONT_STYLE.to_string());
modify_inputs.insert_text(text.chunks().iter().map(|chunk| chunk.text()).collect(), font, TypesettingConfig::default(), layer);
modify_inputs.fill_set(Fill::Solid(Color::BLACK));
0
}
}
}
/// Helper to apply path data (vector geometry, fill, stroke, transform) to a layer.
fn import_usvg_path(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node, path: &usvg::Path, layer: LayerNodeIdentifier, graphite_gradient_stops: &HashMap<String, GradientStops>) {
let subpaths = convert_usvg_path(path);
let bounds = subpaths.iter().filter_map(|subpath| subpath.bounding_box()).reduce(Quad::combine_bounds).unwrap_or_default();
// Skip creating a Transform node entirely when the SVG-native transform is identity.
let node_transform = usvg_transform(node.abs_transform());
let has_transform = node_transform != DAffine2::IDENTITY;
modify_inputs.insert_vector(subpaths, layer, has_transform, path.fill().is_some(), path.stroke().is_some());
if has_transform && let Some(transform_node_id) = modify_inputs.existing_network_node_id("Transform", false) {
transform_utils::update_transform(modify_inputs.network_interface, &transform_node_id, node_transform);
}
if let Some(fill) = path.fill() {
let bounds_transform = DAffine2::from_scale_angle_translation(bounds[1] - bounds[0], 0., bounds[0]);
apply_usvg_fill(fill, modify_inputs, bounds_transform, graphite_gradient_stops);
}
if let Some(stroke) = path.stroke() {
apply_usvg_stroke(stroke, modify_inputs, node_transform);
}
}
/// Set correct positions for all imported layers in a single top-down O(n) pass.
///
/// For each group's child stack:
/// - The top-of-stack child (last SVG child) gets an `Absolute` position at `(parent_x - LAYER_INDENT_OFFSET, parent_y + STACK_VERTICAL_GAP)`
/// - All other children get `Stack(y_offset)` where `y_offset` accounts for the subtree extent of the sibling above them in the stack, ensuring no overlap.
fn set_import_child_positions(
network_interface: &mut NodeNetworkInterface,
group: LayerNodeIdentifier,
group_pos: IVec2,
child_extents_svg_order: &[u32],
group_extents_map: &HashMap<LayerNodeIdentifier, Vec<u32>>,
) {
use crate::messages::portfolio::document::utility_types::network_interface::LayerPosition;
let layer_children: Vec<_> = group.children(network_interface.document_metadata()).collect();
let n = child_extents_svg_order.len();
if n == 0 || layer_children.is_empty() {
return;
}
// Children in the layer tree are in stack order (top to bottom), which is the REVERSE of SVG order.
// SVG order: [s_0, s_1, ..., s_{n-1}] with extents [e_0, e_1, ..., e_{n-1}]
// Stack order: [s_{n-1}, s_{n-2}, ..., s_0 ] (top to bottom)
//
// For stack child at index i:
// - SVG index = n - 1 - i
// - Previous stack sibling's SVG index = n - i
// - y_offset = extent_of_previous_sibling + STACK_VERTICAL_GAP
let child_x = group_pos.x - LAYER_INDENT_OFFSET;
let mut current_y = group_pos.y + STACK_VERTICAL_GAP;
for (i, child_layer) in layer_children.iter().enumerate() {
let child_pos = IVec2::new(child_x, current_y);
if i == 0 {
// 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
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), &[]);
}
// Recurse into group children to set their descendants' positions
if let Some(grandchild_extents) = group_extents_map.get(child_layer) {
set_import_child_positions(network_interface, *child_layer, child_pos, grandchild_extents, group_extents_map);
}
// Advance `current_y` for the next child: node height (STACK_VERTICAL_GAP) + gap (STACK_VERTICAL_GAP) + subtree extent
let child_svg_index = n - 1 - i;
let child_extent = child_extents_svg_order[child_svg_index];
current_y += 2 * STACK_VERTICAL_GAP + child_extent as i32;
}
}
fn apply_usvg_stroke(stroke: &usvg::Stroke, modify_inputs: &mut ModifyInputsContext, transform: DAffine2) {
if let usvg::Paint::Color(color) = &stroke.paint() {
modify_inputs.stroke_set(Stroke {
@@ -519,6 +765,14 @@ fn apply_usvg_stroke(stroke: &usvg::Stroke, modify_inputs: &mut ModifyInputsCont
}
}
fn convert_spread_method(spread_method: usvg::SpreadMethod) -> GradientSpreadMethod {
match spread_method {
usvg::SpreadMethod::Pad => GradientSpreadMethod::Pad,
usvg::SpreadMethod::Reflect => GradientSpreadMethod::Reflect,
usvg::SpreadMethod::Repeat => GradientSpreadMethod::Repeat,
}
}
fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, bounds_transform: DAffine2, graphite_gradient_stops: &HashMap<String, GradientStops>) {
modify_inputs.fill_set(match &fill.paint() {
usvg::Paint::Color(color) => Fill::solid(usvg_color(*color, fill.opacity().get())),
@@ -541,8 +795,15 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, b
GradientStops::new(stops)
}
};
let spread_method = convert_spread_method(linear.spread_method());
Fill::Gradient(Gradient { start, end, gradient_type, stops })
Fill::Gradient(Gradient {
start,
end,
gradient_type,
stops,
spread_method,
})
}
usvg::Paint::RadialGradient(radial) => {
let gradient_transform = usvg_transform(radial.transform());
@@ -564,8 +825,15 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, b
GradientStops::new(stops)
}
};
let spread_method = convert_spread_method(radial.spread_method());
Fill::Gradient(Gradient { start, end, gradient_type, stops })
Fill::Gradient(Gradient {
start,
end,
gradient_type,
stops,
spread_method,
})
}
usvg::Paint::Pattern(_) => {
warn!("SVG patterns are not currently supported");
@@ -3,44 +3,21 @@ use glam::{DAffine2, DVec2};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graphene_std::subpath::Subpath;
use graphene_std::transform::Transform;
use graphene_std::vector::PointId;
/// Convert an affine transform into the tuple `(scale, angle, translation, shear)` assuming `shear.y = 0`.
pub fn compute_scale_angle_translation_shear(transform: DAffine2) -> (DVec2, f64, DVec2, DVec2) {
let x_axis = transform.matrix2.x_axis;
let y_axis = transform.matrix2.y_axis;
// Assuming there is no vertical shear
let angle = x_axis.y.atan2(x_axis.x);
let (sin, cos) = angle.sin_cos();
let scale_x = if cos.abs() > 1e-10 { x_axis.x / cos } else { x_axis.y / sin };
let mut shear_x = (sin * y_axis.y + cos * y_axis.x) / (sin * sin * scale_x + cos * cos * scale_x);
if !shear_x.is_finite() {
shear_x = 0.;
}
let scale_y = if cos.abs() > 1e-10 {
(y_axis.y - scale_x * sin * shear_x) / cos
} else {
(scale_x * cos * shear_x - y_axis.x) / sin
};
let translation = transform.translation;
let scale = DVec2::new(scale_x, scale_y);
let shear = DVec2::new(shear_x, 0.);
(scale, angle, translation, shear)
}
/// Update the inputs of the transform node to match a new transform
pub fn update_transform(network_interface: &mut NodeNetworkInterface, node_id: &NodeId, transform: DAffine2) {
let (scale, rotation, translation, shear) = compute_scale_angle_translation_shear(transform);
let (rotation, scale, skew) = transform.decompose_rotation_scale_skew();
let translation = transform.translation;
let rotation = rotation.to_degrees();
let shear = DVec2::new(shear.x.atan().to_degrees(), shear.y.atan().to_degrees());
let skew = DVec2::new(skew.atan().to_degrees(), 0.);
network_interface.set_input(&InputConnector::node(*node_id, 1), NodeInput::value(TaggedValue::DVec2(translation), false), &[]);
network_interface.set_input(&InputConnector::node(*node_id, 2), NodeInput::value(TaggedValue::F64(rotation), false), &[]);
network_interface.set_input(&InputConnector::node(*node_id, 3), NodeInput::value(TaggedValue::DVec2(scale), false), &[]);
network_interface.set_input(&InputConnector::node(*node_id, 4), NodeInput::value(TaggedValue::DVec2(shear), false), &[]);
network_interface.set_input(&InputConnector::node(*node_id, 4), NodeInput::value(TaggedValue::DVec2(skew), false), &[]);
}
// TODO: This should be extracted from the graph at the location of the transform node.
@@ -81,12 +58,12 @@ pub fn get_current_transform(inputs: &[NodeInput]) -> DAffine2 {
};
let rotation = if let Some(&TaggedValue::F64(rotation)) = inputs[2].as_value() { rotation } else { 0. };
let scale = if let Some(&TaggedValue::DVec2(scale)) = inputs[3].as_value() { scale } else { DVec2::ONE };
let shear = if let Some(&TaggedValue::DVec2(shear)) = inputs[4].as_value() { shear } else { DVec2::ZERO };
let skew = if let Some(&TaggedValue::DVec2(skew)) = inputs[4].as_value() { skew } else { DVec2::ZERO };
let rotation = rotation.to_radians();
let shear = DVec2::new(shear.x.to_radians().tan(), shear.y.to_radians().tan());
let skew = DVec2::new(skew.x.to_radians().tan(), skew.y.to_radians().tan());
DAffine2::from_scale_angle_translation(scale, rotation, translation) * DAffine2::from_cols_array(&[1., shear.y, shear.x, 1., 0., 0.])
DAffine2::from_scale_angle_translation(scale, rotation, translation) * DAffine2::from_cols_array(&[1., skew.y, skew.x, 1., 0., 0.])
}
/// Extract the current normalized pivot from the layer
@@ -135,8 +112,8 @@ mod tests {
/// ```
#[test]
fn derive_transform() {
for shear_x in -10..=10 {
let shear_x = (shear_x as f64) / 2.;
for skew_x in -10..=10 {
let skew_x = (skew_x as f64) / 2.;
for angle in (0..=360).step_by(15) {
let angle = (angle as f64).to_radians();
for scale_x in 1..10 {
@@ -144,22 +121,23 @@ mod tests {
for scale_y in 1..10 {
let scale_y = (scale_y as f64) / 5.;
let shear = DVec2::new(shear_x, 0.);
let skew = DVec2::new(skew_x, 0.);
let scale = DVec2::new(scale_x, scale_y);
let translate = DVec2::new(5666., 644.);
let original_transform = DAffine2::from_cols(
DVec2::new(scale.x * angle.cos() - scale.y * angle.sin() * shear.y, scale.x * angle.sin() + scale.y * angle.cos() * shear.y),
DVec2::new(scale.x * angle.cos() * shear.x - scale.y * angle.sin(), scale.x * angle.sin() * shear.x + scale.y * angle.cos()),
DVec2::new(scale.x * angle.cos() - scale.y * angle.sin() * skew.y, scale.x * angle.sin() + scale.y * angle.cos() * skew.y),
DVec2::new(scale.x * angle.cos() * skew.x - scale.y * angle.sin(), scale.x * angle.sin() * skew.x + scale.y * angle.cos()),
translate,
);
let (new_scale, new_angle, new_translation, new_shear) = compute_scale_angle_translation_shear(original_transform);
let new_transform = DAffine2::from_scale_angle_translation(new_scale, new_angle, new_translation) * DAffine2::from_cols_array(&[1., new_shear.y, new_shear.x, 1., 0., 0.]);
let (new_angle, new_scale, new_skew) = original_transform.decompose_rotation_scale_skew();
let new_translation = original_transform.translation;
let new_transform = DAffine2::from_scale_angle_translation(new_scale, new_angle, new_translation) * DAffine2::from_cols_array(&[1., 0., new_skew, 1., 0., 0.]);
assert!(
new_transform.abs_diff_eq(original_transform, 1e-10),
"original_transform {original_transform} new_transform {new_transform} / scale {scale} new_scale {new_scale} / angle {angle} new_angle {new_angle} / shear {shear} / new_shear {new_shear}",
"original_transform {original_transform} new_transform {new_transform} / scale {scale} new_scale {new_scale} / angle {angle} new_angle {new_angle} / skew {skew} / new_skew {new_skew}",
);
}
}
@@ -7,7 +7,6 @@ use glam::{DAffine2, IVec2};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graph_craft::{ProtoNodeIdentifier, concrete};
use graphene_std::Artboard;
use graphene_std::brush::brush_stroke::BrushStroke;
use graphene_std::raster::BlendMode;
use graphene_std::raster_types::{CPU, Raster};
@@ -17,7 +16,7 @@ use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::Vector;
use graphene_std::vector::style::{Fill, Stroke};
use graphene_std::vector::{PointId, VectorModificationType};
use graphene_std::{Graphic, NodeInputDecleration};
use graphene_std::{Artboard, Color, Graphic, NodeInputDecleration};
#[derive(PartialEq, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub enum TransformIn {
@@ -33,6 +32,8 @@ pub struct ModifyInputsContext<'a> {
pub responses: &'a mut VecDeque<Message>,
// Cannot be LayerNodeIdentifier::ROOT_PARENT
pub layer_node: Option<LayerNodeIdentifier>,
/// When true, uses lightweight import paths that skip expensive checks during bulk import.
pub import: bool,
}
impl<'a> ModifyInputsContext<'a> {
@@ -42,6 +43,7 @@ impl<'a> ModifyInputsContext<'a> {
network_interface,
responses,
layer_node: None,
import: false,
}
}
@@ -150,7 +152,62 @@ impl<'a> ModifyInputsContext<'a> {
let boolean_id = NodeId::new();
self.network_interface.insert_node(boolean_id, boolean, &[]);
self.network_interface.move_node_to_chain_start(&boolean_id, layer, &[]);
self.network_interface.move_node_to_chain_start(&boolean_id, layer, &[], self.import);
}
pub fn insert_blend_data(&mut self, layer: LayerNodeIdentifier, count: f64) -> NodeId {
let blend = resolve_network_node_type("Blend").expect("Blend node does not exist").node_template_input_override([
Some(NodeInput::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, &[]);
self.network_interface.move_node_to_chain_start(&blend_id, layer, &[], self.import);
blend_id
}
pub fn insert_morph_data(&mut self, layer: LayerNodeIdentifier) -> NodeId {
let morph = resolve_proto_node_type(graphene_std::vector::morph::IDENTIFIER)
.expect("Morph node does not exist")
.node_template_input_override([
Some(NodeInput::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, &[]);
self.network_interface.move_node_to_chain_start(&morph_id, layer, &[], self.import);
morph_id
}
/// Returns the Path node ID (the node closest to the layer's merge node in the chain).
pub fn insert_control_path_data(&mut self, layer: LayerNodeIdentifier) -> NodeId {
// Add Origins to Polyline node first (will be pushed deepest in the chain)
let origins_to_polyline = resolve_network_node_type("Origins to Polyline")
.expect("Origins to Polyline node does not exist")
.default_node_template();
let origins_to_polyline_id = NodeId::new();
self.network_interface.insert_node(origins_to_polyline_id, origins_to_polyline, &[]);
self.network_interface.move_node_to_chain_start(&origins_to_polyline_id, layer, &[], self.import);
// Add Auto-Tangents node (between Origins to Polyline and Path), with spread=1 and preserve_existing=false
let auto_tangents = resolve_proto_node_type(graphene_std::vector::auto_tangents::IDENTIFIER)
.expect("Auto-Tangents node does not exist")
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(1.), false)), Some(NodeInput::value(TaggedValue::Bool(false), false))]);
let auto_tangents_id = NodeId::new();
self.network_interface.insert_node(auto_tangents_id, auto_tangents, &[]);
self.network_interface.move_node_to_chain_start(&auto_tangents_id, layer, &[], self.import);
// Add Path node to chain start (closest to the Merge node)
let path = resolve_network_node_type("Path").expect("Path node does not exist").default_node_template();
let path_id = NodeId::new();
self.network_interface.insert_node(path_id, path, &[]);
self.network_interface.move_node_to_chain_start(&path_id, layer, &[], self.import);
path_id
}
pub fn insert_vector(&mut self, subpaths: Vec<Subpath<PointId>>, layer: LayerNodeIdentifier, include_transform: bool, include_fill: bool, include_stroke: bool) {
@@ -161,13 +218,13 @@ impl<'a> ModifyInputsContext<'a> {
.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.network_interface.move_node_to_chain_start(&shape_id, layer, &[], self.import);
if include_transform {
let transform = resolve_network_node_type("Transform").expect("Transform node does not exist").default_node_template();
let transform_id = NodeId::new();
self.network_interface.insert_node(transform_id, transform, &[]);
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[]);
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[], self.import);
}
if include_stroke {
@@ -176,7 +233,7 @@ impl<'a> ModifyInputsContext<'a> {
.default_node_template();
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.network_interface.move_node_to_chain_start(&stroke_id, layer, &[], self.import);
}
if include_fill {
@@ -185,7 +242,7 @@ impl<'a> ModifyInputsContext<'a> {
.default_node_template();
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.network_interface.move_node_to_chain_start(&fill_id, layer, &[], self.import);
}
}
@@ -216,19 +273,32 @@ impl<'a> ModifyInputsContext<'a> {
let text_id = NodeId::new();
self.network_interface.insert_node(text_id, text, &[]);
self.network_interface.move_node_to_chain_start(&text_id, layer, &[]);
self.network_interface.move_node_to_chain_start(&text_id, layer, &[], self.import);
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.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.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.network_interface.move_node_to_chain_start(&fill_id, layer, &[], self.import);
}
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(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_frame: Table<Raster<CPU>>, layer: LayerNodeIdentifier) {
@@ -239,11 +309,11 @@ impl<'a> ModifyInputsContext<'a> {
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.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, &[]);
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[]);
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[], self.import);
}
fn get_output_layer(&self) -> Option<LayerNodeIdentifier> {
@@ -328,12 +398,12 @@ impl<'a> ModifyInputsContext<'a> {
};
let node_id = NodeId::new();
self.network_interface.insert_node(node_id, flatten_path_definition.default_node_template(), &[]);
self.network_interface.move_node_to_chain_start(&node_id, output_layer, &[]);
self.network_interface.move_node_to_chain_start(&node_id, output_layer, &[], self.import);
}
}
let node_id = NodeId::new();
self.network_interface.insert_node(node_id, node_definition.default_node_template(), &[]);
self.network_interface.move_node_to_chain_start(&node_id, output_layer, &[]);
self.network_interface.move_node_to_chain_start(&node_id, output_layer, &[], self.import);
Some(node_id)
}
@@ -343,8 +343,8 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
let (pos1, pos2) = (pos1.min(pos2), pos1.max(pos2));
let diagonal = pos2 - pos1;
if diagonal.length() < f64::EPSILON * 1000. || viewport.size().into_dvec2() == DVec2::ZERO {
warn!("Cannot center since the viewport size is 0");
if !diagonal.is_finite() || diagonal.length() < f64::EPSILON * 1000. || viewport.size().into_dvec2() == DVec2::ZERO {
warn!("Cannot center since the viewport size is 0 or the bounds are non-finite");
return;
}
@@ -8,7 +8,7 @@ use crate::messages::portfolio::document::utility_types::network_interface::{
DocumentNodeMetadata, DocumentNodePersistentMetadata, InputMetadata, NodeNetworkInterface, NodeNetworkMetadata, NodeNetworkPersistentMetadata, NodeTemplate, NodeTypePersistentMetadata,
NumberInputSettings, Vec2InputSettings, WidgetOverride,
};
use crate::messages::portfolio::utility_types::PersistentData;
use crate::messages::portfolio::utility_types::CachedData;
use crate::messages::prelude::Message;
use crate::node_graph_executor::NodeGraphExecutor;
use glam::DVec2;
@@ -29,7 +29,7 @@ use serde_json::Value;
use std::collections::{HashMap, VecDeque};
pub struct NodePropertiesContext<'a> {
pub persistent_data: &'a PersistentData,
pub cached_data: &'a CachedData,
pub responses: &'a mut VecDeque<Message>,
pub executor: &'a mut NodeGraphExecutor,
pub network_interface: &'a mut NodeNetworkInterface,
@@ -155,7 +155,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// TODO: Auto-generate this from its proto node macro
DocumentNodeDefinition {
identifier: "Monitor",
category: "Debug",
category: "",
node_template: NodeTemplate {
document_node: DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(memo::monitor::IDENTIFIER),
@@ -380,7 +380,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false),
NodeInput::value(TaggedValue::DVec2(DVec2::new(1920., 1080.)), false),
NodeInput::value(TaggedValue::Color(Table::new_from_element(Color::WHITE)), false),
NodeInput::value(TaggedValue::Bool(false), false),
NodeInput::value(TaggedValue::Bool(true), false),
],
..Default::default()
},
@@ -462,184 +462,131 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
properties: None,
},
DocumentNodeDefinition {
identifier: "Blend Shapes",
identifier: "Blend",
category: "Vector",
// [IMPORTS]2 -> 0[0:Floor]
// [0:Floor]0 -> 0[1:Subtract]
// "1: f64" -> 1[1:Subtract]
// "(): ()" -> 0[2:Read Index]
// "0: u32" -> 1[2:Read Index]
// [2:Read Index]0 -> 0[3:Divide]
// [1:Subtract]0 -> 1[3:Divide]
// [IMPORTS]1 -> 0[4:Position on Path]
// [3:Divide]0 -> 1[4:Position on Path]
// "false: bool" -> 2[4:Position on Path]
// "false: bool" -> 3[4:Position on Path]
// "(): ()" -> 0[5:Read Vector]
// [5:Read Vector]0 -> 0[6:Reset Transform]
// "true: bool" -> 1[6:Reset Transform]
// "false: bool" -> 2[6:Reset Transform]
// "false: bool" -> 3[6:Reset Transform]
// [12:Flatten Vector]0 -> 0[7:Map]
// [6:Reset Transform]0 -> 1[7:Map]
// [7:Map]0 -> 0[8:Morph]
// [15:Multiply]0 -> 1[8:Morph]
// [8:Morph]0 -> 0[9:Transform]
// [4:Position on Path]0 -> 1[9:Transform]
// "0: f64" -> 2[9:Transform]
// "(0, 0): DVec2" -> 3[9:Transform]
// "(0, 0): DVec2" -> 4[9:Transform]
// [IMPORTS]1 -> 0[10:Count Points]
// [10:Count Points]0 -> 0[11:Equals]
// [13:Count Elements]0 -> 1[11:Equals]
// [IMPORTS]0 -> 0[12:Flatten Vector]
// [12:Flatten Vector]0 -> 0[13:Count Elements]
// [13:Count Elements]0 -> 0[14:Subtract]
// "1: f64" -> 1[14:Subtract]
// [3:Divide]0 -> 0[15:Multiply]
// [14:Subtract]0 -> 1[15:Multiply]
// [12:Flatten Vector]0 -> 0[16:Morph]
// [15:Multiply]0 -> 1[16:Morph]
// [11:Equals]0 -> 0[17:Switch]
// [9:Transform]0 -> 1[17:Switch]
// [16:Morph]0 -> 2[17:Switch]
// [17:Switch]0 -> 0[18:Repeat]
// [0:Floor]0 -> 1[18:Repeat]
// [IMPORTS]3 -> 2[18:Repeat]
// [18:Repeat]0 -> 0[EXPORTS]
node_template: NodeTemplate {
document_node: DocumentNode {
implementation: DocumentNodeImplementation::Network(NodeNetwork {
exports: vec![NodeInput::node(NodeId(18), 0)],
exports: vec![NodeInput::node(NodeId(16), 0)],
nodes: [
// 0: Floor
// 0: Separate Subpaths (split path into individual subpaths)
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(vector::separate_subpaths::IDENTIFIER),
inputs: vec![NodeInput::import(generic!(T), 4)],
..Default::default()
},
// 1: Count Elements (number of subpaths)
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(vector::count_elements::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(0), 0)],
..Default::default()
},
// 2: Max (clamp subpath count to at least 1 for empty path case)
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::F64(1.), false)],
..Default::default()
},
// 3: Floor (integer count per subpath)
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
inputs: vec![NodeInput::import(concrete!(f64), 2)],
inputs: vec![NodeInput::import(concrete!(f64), 1)],
..Default::default()
},
// 1: Subtract
// 4: Multiply (total_instances = count × subpath_count)
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(2), 0)],
..Default::default()
},
// 5: Subtract (count - 1, open subpath denominator)
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(math_nodes::subtract::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(1.), false)],
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::F64(1.), false)],
..Default::default()
},
// 2: Read Index
// 6: Read Index (current repetition index)
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(context::read_index::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::U32(0), false)],
..Default::default()
},
// 3: Divide
// 7: Divide (index / count)
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(math_nodes::divide::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(2), 0), NodeInput::node(NodeId(1), 0)],
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::node(NodeId(17), 0)],
..Default::default()
},
// 4: Position on Path
// 8: Floor (floor(index / count) = subpath index)
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(vector_nodes::position_on_path::IDENTIFIER),
inputs: vec![
NodeInput::import(generic!(T), 1),
NodeInput::node(NodeId(3), 0),
NodeInput::value(TaggedValue::Bool(false), false),
NodeInput::value(TaggedValue::Bool(false), false),
],
implementation: DocumentNodeImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(7), 0)],
..Default::default()
},
// 5: Read Vector
// 9: Modulo (index % count = local index within subpath)
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(context::read_vector::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::None, false)],
implementation: DocumentNodeImplementation::ProtoNode(math_nodes::modulo::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Bool(true), false)],
..Default::default()
},
// 6: Reset Transform
// 10: Path Is Closed (check if current subpath is closed)
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(transform_nodes::reset_transform::IDENTIFIER),
inputs: vec![
NodeInput::node(NodeId(5), 0),
NodeInput::value(TaggedValue::Bool(true), false),
NodeInput::value(TaggedValue::Bool(false), false),
NodeInput::value(TaggedValue::Bool(false), false),
],
implementation: DocumentNodeImplementation::ProtoNode(vector::path_is_closed::IDENTIFIER),
inputs: vec![NodeInput::import(generic!(T), 4), NodeInput::node(NodeId(8), 0)],
..Default::default()
},
// 7: Map
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(graphic::map::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::node(NodeId(6), 0)],
..Default::default()
},
// 8: Morph
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(vector::morph::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(7), 0), NodeInput::node(NodeId(15), 0)],
..Default::default()
},
// 9: Transform
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(transform_nodes::transform::IDENTIFIER),
inputs: vec![
NodeInput::node(NodeId(8), 0),
NodeInput::node(NodeId(4), 0),
NodeInput::value(TaggedValue::F64(0.), false),
NodeInput::value(TaggedValue::DVec2(DVec2::ONE), false),
NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false),
],
..Default::default()
},
// 10: Count Points
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(vector_nodes::count_points::IDENTIFIER),
inputs: vec![NodeInput::import(generic!(T), 1)],
..Default::default()
},
// 11: Equals
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(math_nodes::equals::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(10), 0), NodeInput::node(NodeId(13), 0)],
..Default::default()
},
// 12: Flatten Vector
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(graphic_nodes::graphic::flatten_vector::IDENTIFIER),
inputs: vec![NodeInput::import(generic!(T), 0)],
..Default::default()
},
// 13: Count Elements
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(vector::count_elements::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(12), 0)],
..Default::default()
},
// 14: Subtract
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(math_nodes::subtract::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(13), 0), NodeInput::value(TaggedValue::F64(1.), false)],
..Default::default()
},
// 15: Multiply
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::node(NodeId(14), 0)],
..Default::default()
},
// 16: Morph
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(vector::morph::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::node(NodeId(15), 0)],
..Default::default()
},
// 17: Switch
// 11: Switch (closed → count, open → max(count - 1, 1) as denominator)
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(logic::switch::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(11), 0), NodeInput::node(NodeId(9), 0), NodeInput::node(NodeId(16), 0)],
inputs: vec![NodeInput::node(NodeId(10), 0), NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(18), 0)],
..Default::default()
},
// 18: Repeat
// 12: Divide (local_index / denominator = within-subpath fraction)
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(math_nodes::divide::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(9), 0), NodeInput::node(NodeId(11), 0)],
..Default::default()
},
// 13: Multiply (fraction × 0.9999999999 to avoid overflowing to the next subpath)
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::F64(0.9999999999), false)],
..Default::default()
},
// 14: Add (subpath_index + clamped fraction = progression)
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(math_nodes::add::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(8), 0), NodeInput::node(NodeId(13), 0)],
..Default::default()
},
// 15: Morph (content, progression, reverse, distribution, path)
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(vector::morph::IDENTIFIER),
inputs: vec![
NodeInput::import(generic!(T), 0),
NodeInput::node(NodeId(14), 0),
NodeInput::value(TaggedValue::Bool(false), false),
NodeInput::import(concrete!(vector::misc::InterpolationDistribution), 3),
NodeInput::import(generic!(T), 4),
],
..Default::default()
},
// 16: Repeat
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(repeat_nodes::repeat::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(0), 0), NodeInput::import(generic!(T), 3)],
inputs: vec![NodeInput::node(NodeId(15), 0), NodeInput::node(NodeId(4), 0), NodeInput::import(generic!(T), 2)],
..Default::default()
},
// 17: Max (clamp count to at least 1)
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::F64(1.), false)],
..Default::default()
},
// 18: Max (clamp open-path denominator to at least 1 to avoid division by zero when count = 1)
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::F64(1.), false)],
..Default::default()
},
]
@@ -650,168 +597,175 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
..Default::default()
}),
inputs: vec![
NodeInput::value(TaggedValue::Vector(Default::default()), true),
NodeInput::value(TaggedValue::Vector(Default::default()), true),
NodeInput::value(TaggedValue::F64(10.), false),
NodeInput::value(TaggedValue::Bool(Default::default()), false),
NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false),
NodeInput::value(TaggedValue::Vector(Default::default()), false),
],
..Default::default()
},
persistent_node_metadata: DocumentNodePersistentMetadata {
input_metadata: vec![("Content", "TODO").into(), ("Path", "TODO").into(), ("Count", "TODO").into(), ("Reverse", "TODO").into()],
input_metadata: vec![
("Content", "TODO").into(),
("Count", "TODO").into(),
("Reverse", "TODO").into(),
("Distribution", "TODO").into(),
("Path", "TODO").into(),
],
output_names: vec!["Out".to_string()],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
network_metadata: Some(NodeNetworkMetadata {
persistent_metadata: NodeNetworkPersistentMetadata {
node_metadata: [
// 0: Floor
// 0: Separate Subpaths
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 0)),
..Default::default()
},
..Default::default()
},
// 1: Subtract
// 1: Count Elements
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, -1)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 2)),
..Default::default()
},
..Default::default()
},
// 2: Read Index
// 2: Max (subpath count)
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, -2)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 2)),
..Default::default()
},
..Default::default()
},
// 3: Divide
// 3: Floor (count)
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, -2)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 13)),
..Default::default()
},
..Default::default()
},
// 4: Position on Path
// 4: Multiply (total instances)
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(28, -3)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 1)),
..Default::default()
},
..Default::default()
},
// 5: Read Vector
// 5: Subtract (count - 1)
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 2)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 14)),
..Default::default()
},
..Default::default()
},
// 6: Reset Transform
// 6: Read Index
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 2)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 7)),
..Default::default()
},
..Default::default()
},
// 7: Map
// 7: Divide (index / count)
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 1)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 10)),
..Default::default()
},
..Default::default()
},
// 8: Morph
// 8: Floor (subpath index)
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(28, 1)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 4)),
..Default::default()
},
..Default::default()
},
// 9: Transform
// 9: Modulo (local index)
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(35, 1)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 7)),
..Default::default()
},
..Default::default()
},
// 10: Count Points
// 10: Path Is Closed
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 4)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 2)),
..Default::default()
},
..Default::default()
},
// 11: Equals
// 11: Switch (denominator)
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 4)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 12)),
..Default::default()
},
..Default::default()
},
// 12: Flatten Vector
// 12: Divide (within-subpath fraction)
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 6)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 7)),
..Default::default()
},
..Default::default()
},
// 13: Count Elements
// 13: Multiply (clamp fraction)
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 8)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 7)),
..Default::default()
},
..Default::default()
},
// 14: Subtract
// 14: Add (progression)
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 8)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(37, 4)),
..Default::default()
},
..Default::default()
},
// 15: Multiply
// 15: Morph
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 7)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(44, 3)),
..Default::default()
},
..Default::default()
},
// 16: Morph
// 16: Repeat
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(28, 6)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(51, 0)),
..Default::default()
},
..Default::default()
},
// 17: Switch
// 17: Max (clamp count)
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(42, 4)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 13)),
..Default::default()
},
..Default::default()
},
// 18: Repeat
// 18: Max (clamp open-path denominator)
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(49, -1)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 14)),
..Default::default()
},
..Default::default()
@@ -834,17 +788,6 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
DocumentNodeDefinition {
identifier: "Origins to Polyline",
category: "Vector",
// "(): ()" -> 0[0:Read Vector]
// [0:Read Vector]0 -> 0[1:Extract Transform]
// [1:Extract Transform]0 -> 0[2:Decompose Translation]
// [2:Decompose Translation]0 -> 0[3:Vec2 to Point]
// [IMPORTS]0 -> 0[4:Flatten Vector]
// [4:Flatten Vector]0 -> 0[5:Map]
// [3:Vec2 to Point]0 -> 1[5:Map]
// [5:Map]0 -> 0[6: Flatten Path]
// [6:Flatten Path]0 -> 0[7:Points to Polyline]
// "false: bool" -> 1[7:Points to Polyline]
// [7:Points to Polyline]0 -> 0[EXPORTS]
node_template: NodeTemplate {
document_node: DocumentNode {
implementation: DocumentNodeImplementation::Network(NodeNetwork {
@@ -1004,12 +947,12 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
nodes: [
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::scope("editor-api"), NodeInput::import(concrete!(String), 1)],
implementation: DocumentNodeImplementation::ProtoNode(wasm_application_io::load_resource::IDENTIFIER),
implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER),
..Default::default()
},
DocumentNode {
inputs: vec![NodeInput::node(NodeId(0), 0)],
implementation: DocumentNodeImplementation::ProtoNode(wasm_application_io::decode_image::IDENTIFIER),
implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::decode_image::IDENTIFIER),
..Default::default()
},
]
@@ -1067,8 +1010,8 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
exports: vec![NodeInput::node(NodeId(2), 0)],
nodes: [
DocumentNode {
inputs: vec![NodeInput::scope("editor-api")],
implementation: DocumentNodeImplementation::ProtoNode(wasm_application_io::create_surface::IDENTIFIER),
inputs: vec![],
implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::create_canvas::IDENTIFIER),
skip_deduplication: true,
..Default::default()
},
@@ -1079,7 +1022,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
DocumentNode {
inputs: vec![NodeInput::import(generic!(T), 0), NodeInput::import(concrete!(Footprint), 1), NodeInput::node(NodeId(1), 0)],
implementation: DocumentNodeImplementation::ProtoNode(wasm_application_io::rasterize::IDENTIFIER),
implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::rasterize::IDENTIFIER),
..Default::default()
},
]
@@ -1530,7 +1473,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
DocumentNodeDefinition {
identifier: "Extract",
category: "Debug",
category: "",
node_template: NodeTemplate {
document_node: DocumentNode {
implementation: DocumentNodeImplementation::Extract,
@@ -189,7 +189,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
send: Box::new(NodeGraphMessage::SelectedNodesUpdated.into()),
});
network_interface.load_structure();
collapsed.0.retain(|&layer| network_interface.document_metadata().layer_exists(layer));
collapsed.0.retain(|path| path.iter().all(|&node_id| network_interface.document_network().nodes.contains_key(&node_id)));
}
NodeGraphMessage::SelectedNodesUpdated => {
let selected_layers = network_interface.selected_nodes().selected_layers(network_interface.document_metadata()).collect::<Vec<_>>();
@@ -717,7 +717,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
network_interface.move_layer_to_stack(layer, parent, insert_index, selection_network_path);
}
NodeGraphMessage::MoveNodeToChainStart { node_id, parent } => {
network_interface.move_node_to_chain_start(&node_id, parent, selection_network_path);
network_interface.move_node_to_chain_start(&node_id, parent, selection_network_path, false);
}
NodeGraphMessage::SetChainPosition { node_id } => {
network_interface.set_chain_position(&node_id, selection_network_path);
@@ -2047,7 +2047,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
NodeGraphMessage::UpdateLayerPanel => {
Self::update_layer_panel(network_interface, selection_network_path, collapsed, layers_panel_open, responses);
Self::update_layer_panel(network_interface, selection_network_path, layers_panel_open, responses);
}
NodeGraphMessage::UpdateEdges => {
// Update the import/export UI edges whenever the PTZ changes or the bounding box of all nodes changes
@@ -2684,7 +2684,7 @@ impl NodeGraphMessageHandler {
Some(NodeGraphErrorDiagnostic { position, error })
}
fn update_layer_panel(network_interface: &NodeNetworkInterface, selection_network_path: &[NodeId], collapsed: &CollapsedLayers, layers_panel_open: bool, responses: &mut VecDeque<Message>) {
fn update_layer_panel(network_interface: &NodeNetworkInterface, selection_network_path: &[NodeId], layers_panel_open: bool, responses: &mut VecDeque<Message>) {
if !layers_panel_open {
return;
}
@@ -2695,14 +2695,8 @@ impl NodeGraphMessageHandler {
.map(|layer| layer.to_node())
.collect::<HashSet<_>>();
let mut ancestors_of_selected = HashSet::new();
let mut descendants_of_selected = HashSet::new();
for selected_layer in &selected_layers {
for ancestor in LayerNodeIdentifier::new(*selected_layer, network_interface).ancestors(network_interface.document_metadata()) {
if ancestor != LayerNodeIdentifier::ROOT_PARENT && ancestor.to_node() != *selected_layer {
ancestors_of_selected.insert(ancestor.to_node());
}
}
for descendant in LayerNodeIdentifier::new(*selected_layer, network_interface).descendants(network_interface.document_metadata()) {
descendants_of_selected.insert(descendant.to_node());
}
@@ -2727,22 +2721,6 @@ impl NodeGraphMessageHandler {
}))
);
let parents_visible = layer.ancestors(network_interface.document_metadata()).filter(|&ancestor| ancestor != layer).all(|layer| {
if layer != LayerNodeIdentifier::ROOT_PARENT {
network_interface.document_node(&layer.to_node(), &[]).map(|node| node.visible).unwrap_or_default()
} else {
true
}
});
let parents_unlocked: bool = layer.ancestors(network_interface.document_metadata()).filter(|&ancestor| ancestor != layer).all(|layer| {
if layer != LayerNodeIdentifier::ROOT_PARENT {
!network_interface.is_locked(&layer.to_node(), &[])
} else {
true
}
});
let clippable = layer.can_be_clipped(network_interface.document_metadata());
let data = LayerPanelEntry {
@@ -2752,18 +2730,9 @@ impl NodeGraphMessageHandler {
alias: network_interface.display_name(&node_id, &[]),
in_selected_network: selection_network_path.is_empty(),
children_allowed,
children_present: layer.has_children(network_interface.document_metadata()),
expanded: layer.has_children(network_interface.document_metadata()) && !collapsed.0.contains(&layer),
depth: layer.ancestors(network_interface.document_metadata()).count() as u32 - 1,
visible: network_interface.is_visible(&node_id, &[]),
parents_visible,
unlocked: !network_interface.is_locked(&node_id, &[]),
parents_unlocked,
parent_id: layer
.parent(network_interface.document_metadata())
.and_then(|parent| if parent != LayerNodeIdentifier::ROOT_PARENT { Some(parent.to_node()) } else { None }),
selected: selected_layers.contains(&node_id),
ancestor_of_selected: ancestors_of_selected.contains(&node_id),
descendant_of_selected: descendants_of_selected.contains(&node_id),
clipped: get_clip_mode(layer, network_interface).unwrap_or(false) && clippable,
clippable,
@@ -5,7 +5,7 @@ use super::utility_types::FrontendGraphDataType;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
use crate::messages::portfolio::utility_types::{FontCatalogStyle, PersistentData};
use crate::messages::portfolio::utility_types::{CachedData, FontCatalogStyle};
use crate::messages::prelude::*;
use choice::enum_choice;
use dyn_any::DynAny;
@@ -23,11 +23,11 @@ use graphene_std::raster::{
};
use graphene_std::table::{Table, TableRow};
use graphene_std::text::{Font, TextAlign};
use graphene_std::transform::{Footprint, ReferencePoint, Transform};
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
use graphene_std::vector::QRCodeErrorCorrectionLevel;
use graphene_std::vector::misc::BooleanOperation;
use graphene_std::vector::misc::{ArcType, CentroidType, ExtrudeJoiningAlgorithm, GridType, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType};
use graphene_std::vector::style::{Fill, FillChoice, FillType, GradientStops, GradientType, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::misc::{ArcType, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType};
use graphene_std::vector::style::{Fill, FillChoice, FillType, GradientSpreadMethod, GradientStops, GradientType, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
pub(crate) fn string_properties(text: &str) -> Vec<LayoutGroup> {
let widget = TextLabel::new(text).widget_instance();
@@ -265,6 +265,8 @@ pub(crate) fn property_from_type(
Some(x) if x == TypeId::of::<CentroidType>() => enum_choice::<CentroidType>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<LuminanceCalculation>() => enum_choice::<LuminanceCalculation>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<QRCodeErrorCorrectionLevel>() => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<ScaleType>() => enum_choice::<ScaleType>().for_socket(default_info).property_row(),
Some(x) if x == TypeId::of::<InterpolationDistribution>() => enum_choice::<InterpolationDistribution>().for_socket(default_info).property_row(),
// =====
// OTHER
// =====
@@ -566,8 +568,8 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
let widgets = if let Some(&TaggedValue::DAffine2(transform)) = input.as_non_exposed_value() {
let translation = transform.translation;
let rotation = transform.decompose_rotation();
let scale = transform.decompose_scale();
let (rotation, scale, skew) = transform.decompose_rotation_scale_skew();
let skew_matrix = DAffine2::from_cols_array(&[1., 0., skew, 1., 0., 0.]);
location_widgets.extend_from_slice(&[
NumberInput::new(Some(translation.x))
@@ -608,7 +610,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
.range_max(Some(180.))
.on_update(update_value(
move |r: &NumberInput| {
let transform = DAffine2::from_scale_angle_translation(scale, r.value.map(|r| r.to_radians()).unwrap_or(rotation), translation);
let transform = DAffine2::from_scale_angle_translation(scale, r.value.map(|r| r.to_radians()).unwrap_or(rotation), translation) * skew_matrix;
TaggedValue::DAffine2(transform)
},
node_id,
@@ -623,7 +625,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
.unit("x")
.on_update(update_value(
move |w: &NumberInput| {
let transform = DAffine2::from_scale_angle_translation(DVec2::new(w.value.unwrap_or(scale.x), scale.y), rotation, translation);
let transform = DAffine2::from_scale_angle_translation(DVec2::new(w.value.unwrap_or(scale.x), scale.y), rotation, translation) * skew_matrix;
TaggedValue::DAffine2(transform)
},
node_id,
@@ -637,7 +639,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
.unit("x")
.on_update(update_value(
move |h: &NumberInput| {
let transform = DAffine2::from_scale_angle_translation(DVec2::new(scale.x, h.value.unwrap_or(scale.y)), rotation, translation);
let transform = DAffine2::from_scale_angle_translation(DVec2::new(scale.x, h.value.unwrap_or(scale.y)), rotation, translation) * skew_matrix;
TaggedValue::DAffine2(transform)
},
node_id,
@@ -791,7 +793,7 @@ pub fn array_of_vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, text_p
pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetInstance>, Option<Vec<WidgetInstance>>) {
let ParameterWidgetsInfo {
persistent_data,
cached_data,
document_node,
node_id,
index,
@@ -811,7 +813,7 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
first_widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
DropdownInput::new(vec![
persistent_data
cached_data
.font_catalog
.0
.iter()
@@ -864,7 +866,7 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
})
.collect::<Vec<_>>(),
])
.selected_index(persistent_data.font_catalog.0.iter().position(|family| family.name == font.font_family).map(|i| i as u32))
.selected_index(cached_data.font_catalog.0.iter().position(|family| family.name == font.font_family).map(|i| i as u32))
.virtual_scrolling(true)
.widget_instance(),
]);
@@ -874,7 +876,7 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
second_row.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
DropdownInput::new({
persistent_data
cached_data
.font_catalog
.0
.iter()
@@ -912,7 +914,7 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
.unwrap_or_default()
})
.selected_index(
persistent_data
cached_data
.font_catalog
.0
.iter()
@@ -2004,6 +2006,55 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
]);
widgets.push(LayoutGroup::row(row));
let mut spread_methods_row: Vec<WidgetInstance> = vec![TextLabel::new("").widget_instance(), Separator::new(SeparatorStyle::Unrelated).widget_instance()];
let spread_method_entries = [GradientSpreadMethod::Pad, GradientSpreadMethod::Reflect, GradientSpreadMethod::Repeat]
.iter()
.map(|&spread_method| {
let gradient_for_input = gradient_for_closure.clone();
let gradient_for_backup = gradient_for_closure.clone();
let set_input_value = update_value(
move |_: &()| {
let mut new_gradient = gradient_for_input.clone();
new_gradient.spread_method = spread_method;
TaggedValue::Fill(Fill::Gradient(new_gradient))
},
node_id,
FillInput::<Color>::INDEX,
);
let set_backup_value = update_value(
move |_: &()| {
let mut new_gradient = gradient_for_backup.clone();
new_gradient.spread_method = spread_method;
TaggedValue::Gradient(new_gradient)
},
node_id,
BackupGradientInput::INDEX,
);
RadioEntryData::new(format!("{:?}", spread_method))
.label(format!("{:?}", spread_method))
.on_update(move |_| Message::Batched {
messages: Box::new([
set_input_value(&()),
set_backup_value(&()),
GradientToolMessage::UpdateOptions {
options: GradientOptionsUpdate::SetSpreadMethod(spread_method),
}
.into(),
]),
})
.on_commit(commit_value)
})
.collect();
add_blank_assist(&mut spread_methods_row);
spread_methods_row.extend_from_slice(&[RadioInput::new(spread_method_entries).selected_index(Some(gradient.spread_method as u32)).widget_instance()]);
widgets.push(LayoutGroup::row(spread_methods_row));
}
widgets
@@ -2157,7 +2208,7 @@ pub fn math_properties(node_id: NodeId, context: &mut NodePropertiesContext) ->
}
pub struct ParameterWidgetsInfo<'a> {
persistent_data: &'a PersistentData,
cached_data: &'a CachedData,
network_interface: &'a NodeNetworkInterface,
selection_network_path: &'a [NodeId],
document_node: Option<&'a DocumentNode>,
@@ -2180,7 +2231,7 @@ impl<'a> ParameterWidgetsInfo<'a> {
let document_node = context.network_interface.document_node(&node_id, context.selection_network_path);
ParameterWidgetsInfo {
persistent_data: context.persistent_data,
cached_data: context.cached_data,
network_interface: context.network_interface,
selection_network_path: context.selection_network_path,
document_node,
@@ -11,8 +11,10 @@ use graphene_std::vector::misc::ManipulatorPointId;
use graphene_std::vector::{PointId, SegmentId, Vector};
use std::collections::HashMap;
use std::sync::{LazyLock, Mutex};
#[cfg(target_family = "wasm")]
use wasm_bindgen::JsCast;
#[cfg(target_family = "wasm")]
pub fn overlay_canvas_element() -> Option<web_sys::HtmlCanvasElement> {
let window = web_sys::window()?;
let document = window.document()?;
@@ -20,6 +22,7 @@ pub fn overlay_canvas_element() -> Option<web_sys::HtmlCanvasElement> {
canvas.dyn_into::<web_sys::HtmlCanvasElement>().ok()
}
#[cfg(target_family = "wasm")]
pub fn overlay_canvas_context() -> web_sys::CanvasRenderingContext2d {
let create_context = || {
let context = overlay_canvas_element()?.get_context("2d").ok().flatten()?;
@@ -3,7 +3,7 @@ use graphene_std::uuid::NodeId;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::NodePropertiesContext;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
use crate::messages::portfolio::utility_types::PersistentData;
use crate::messages::portfolio::utility_types::CachedData;
use crate::messages::prelude::*;
use crate::node_graph_executor::NodeGraphExecutor;
@@ -13,7 +13,7 @@ pub struct PropertiesPanelMessageContext<'a> {
pub selection_network_path: &'a [NodeId],
pub document_name: &'a str,
pub executor: &'a mut NodeGraphExecutor,
pub persistent_data: &'a PersistentData,
pub cached_data: &'a CachedData,
pub properties_panel_open: bool,
}
@@ -28,7 +28,7 @@ impl MessageHandler<PropertiesPanelMessage, PropertiesPanelMessageContext<'_>> f
selection_network_path,
document_name,
executor,
persistent_data,
cached_data,
properties_panel_open,
} = context;
@@ -46,7 +46,7 @@ impl MessageHandler<PropertiesPanelMessage, PropertiesPanelMessageContext<'_>> f
}
let mut node_properties_context = NodePropertiesContext {
persistent_data,
cached_data,
responses,
network_interface,
selection_network_path,
@@ -1,5 +1,6 @@
use crate::consts::COLOR_OVERLAY_GRAY;
use glam::DVec2;
use graphene_std::vector::misc::BooleanOperation;
use std::fmt;
#[repr(transparent)]
@@ -710,5 +711,7 @@ impl PTZ {
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum GroupFolderType {
Layer,
BooleanOperation(graphene_std::vector::misc::BooleanOperation),
BooleanOperation(BooleanOperation),
Blend,
Morph,
}
@@ -5,7 +5,9 @@ mod resolved_types;
use super::document_metadata::{DocumentMetadata, LayerNodeIdentifier, NodeRelations};
use super::misc::PTZ;
use super::nodes::SelectedNodes;
use crate::consts::{EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP, EXPORTS_TO_TOP_EDGE_PIXEL_GAP, GRID_SIZE, IMPORTS_TO_LEFT_EDGE_PIXEL_GAP, IMPORTS_TO_TOP_EDGE_PIXEL_GAP};
use crate::consts::{
EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP, EXPORTS_TO_TOP_EDGE_PIXEL_GAP, GRID_SIZE, IMPORTS_TO_LEFT_EDGE_PIXEL_GAP, IMPORTS_TO_TOP_EDGE_PIXEL_GAP, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH, STACK_VERTICAL_GAP,
};
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type};
use crate::messages::portfolio::document::node_graph::utility_types::{Direction, FrontendClickTargets, FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
@@ -241,7 +243,7 @@ impl NodeNetworkInterface {
pub fn chain_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> u32 {
if self.number_of_displayed_inputs(node_id, network_path) > 1 {
let mut last_chain_node_distance = 0u32;
let mut last_chain_node_distance = 0_u32;
// Iterate upstream from the layer, and get the number of nodes distance to the last node with Position::Chain
for (index, node_id) in self
.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::HorizontalPrimaryOutputFlow)
@@ -253,11 +255,11 @@ impl NodeNetworkInterface {
if self.is_chain(&node_id, network_path) {
last_chain_node_distance = (index as u32) + 1;
} else {
return last_chain_node_distance * 7 + 1;
return last_chain_node_distance * NODE_CHAIN_WIDTH as u32 + 1;
}
}
last_chain_node_distance * 7 + 1
last_chain_node_distance * NODE_CHAIN_WIDTH as u32 + 1
} else {
// Layer with no inputs has no chain
0
@@ -1207,6 +1209,8 @@ impl NodeNetworkInterface {
}
self.document_metadata.bounding_box_document(layer)
})
// Skip any layer bounds containing NaN to avoid poisoning the combined result
.filter(|[min, max]| min.is_finite() && max.is_finite())
.reduce(Quad::combine_bounds)
}
@@ -2065,6 +2069,30 @@ impl NodeNetworkInterface {
network_metadata.transient_metadata.outward_wires.unload();
}
/// Incrementally updates the outward_wires cache when a single input connector changes,
/// avoiding a full rebuild. If the cache is not loaded, this is a no-op (it will be fully
/// rebuilt on the next read via `outward_wires()`).
fn update_outward_wires(&mut self, network_path: &[NodeId], input_connector: &InputConnector, old_input: &NodeInput, new_input: &NodeInput) {
let Some(network_metadata) = self.network_metadata_mut(network_path) else {
return;
};
let TransientMetadata::Loaded(outward_wires) = &mut network_metadata.transient_metadata.outward_wires else {
return;
};
// Remove the input_connector from the old output's downstream list
if let Some(old_output) = OutputConnector::from_input(old_input)
&& let Some(connections) = outward_wires.get_mut(&old_output)
{
connections.retain(|c| c != input_connector);
}
// Add the input_connector to the new output's downstream list
if let Some(new_output) = OutputConnector::from_input(new_input) {
outward_wires.entry(new_output).or_default().push(*input_connector);
}
}
pub fn layer_width(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> Option<u32> {
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
log::error!("Could not get nested node_metadata in layer_width");
@@ -2669,7 +2697,7 @@ impl NodeNetworkInterface {
if downstream_node_metadata.persistent_metadata.is_layer() {
// Get the position of the layer
let layer_position = self.position(downstream_node_id, network_path)?;
return Some(layer_position + IVec2::new(-node_distance_from_layer * 7, 0));
return Some(layer_position + IVec2::new(-node_distance_from_layer * NODE_CHAIN_WIDTH, 0));
}
node_distance_from_layer += 1;
current_node_id = *downstream_node_id;
@@ -3831,6 +3859,46 @@ impl NodeNetworkInterface {
node.context_features = context_features;
}
/// Lightweight version of `set_input` for bulk import operations.
/// Directly sets the input without `is_acyclic` checks, `load_structure`, position conversions,
/// or per-node cache invalidation. Call `load_structure`, `unload_all_nodes_click_targets`, and
/// `unload_all_nodes_bounding_box` once after all import wiring is complete.
pub fn set_input_for_import(&mut self, input_connector: &InputConnector, new_input: NodeInput, network_path: &[NodeId]) {
if matches!(input_connector, InputConnector::Export(_)) && matches!(new_input, NodeInput::Import { .. }) {
log::error!("Cannot connect a network to an export, see https://github.com/GraphiteEditor/Graphite/issues/1762");
return;
}
let Some(network) = self.network_mut(network_path) else {
log::error!("Could not get nested network in set_input_for_import");
return;
};
let old_input = match input_connector {
InputConnector::Node { node_id, input_index } => {
let Some(node) = network.nodes.get_mut(node_id) else {
log::error!("Could not get node in set_input_for_import");
return;
};
let Some(input) = node.inputs.get_mut(*input_index) else {
log::error!("Could not get input in set_input_for_import");
return;
};
std::mem::replace(input, new_input.clone())
}
InputConnector::Export(export_index) => {
let Some(export) = network.exports.get_mut(*export_index) else {
log::error!("Could not get export in set_input_for_import");
return;
};
std::mem::replace(export, new_input.clone())
}
};
self.transaction_modified();
self.update_outward_wires(network_path, input_connector, &old_input, &new_input);
}
pub fn set_input(&mut self, input_connector: &InputConnector, new_input: NodeInput, network_path: &[NodeId]) {
if matches!(input_connector, InputConnector::Export(_)) && matches!(new_input, NodeInput::Import { .. }) {
// TODO: Add support for flattening NodeInput::Import exports in flatten_with_fns https://github.com/GraphiteEditor/Graphite/issues/1762
@@ -3892,8 +3960,8 @@ impl NodeNetworkInterface {
return;
};
// Ensure the network is not cyclic
if !network.is_acyclic() {
// Ensure the network is not cyclic (only Node connections can create cycles)
if matches!(new_input, NodeInput::Node { .. }) && !network.is_acyclic() {
self.set_input(input_connector, old_input, network_path);
return;
}
@@ -3928,10 +3996,12 @@ impl NodeNetworkInterface {
self.unload_upstream_node_click_targets(vec![*node_id], network_path);
self.unload_all_nodes_bounding_box(network_path);
// Unload the interior imports ports
let nested_path = [network_path, &[*node_id]].concat();
self.unload_import_export_ports(&nested_path);
self.unload_modify_import_export(&nested_path);
// Unload the interior import/export ports if this node has a nested network
if matches!(self.implementation(node_id, network_path), Some(DocumentNodeImplementation::Network(_))) {
let nested_path = [network_path, &[*node_id]].concat();
self.unload_import_export_ports(&nested_path);
self.unload_modify_import_export(&nested_path);
}
}
} else {
self.unload_import_export_ports(network_path);
@@ -3939,6 +4009,14 @@ impl NodeNetworkInterface {
}
}
(_, NodeInput::Node { node_id: upstream_node_id, .. }) => {
// If the old input wasn't exposed but the new one is (`Node` inputs are always exposed),
// the node's port count changed, so its click targets need to be recomputed
if !old_input.is_exposed()
&& let InputConnector::Node { node_id, .. } = input_connector
{
self.unload_node_click_targets(node_id, network_path);
}
// Load structure if the change is to the document network and to the first or second
if network_path.is_empty() {
if matches!(input_connector, InputConnector::Export(0)) {
@@ -3950,7 +4028,7 @@ impl NodeNetworkInterface {
}
}
}
self.unload_outward_wires(network_path);
self.update_outward_wires(network_path, input_connector, &old_input, &new_input);
// Layout system
let Some(current_node_position) = self.position(upstream_node_id, network_path) else {
log::error!("Could not get current node position in set_input for node {upstream_node_id}");
@@ -4005,17 +4083,17 @@ impl NodeNetworkInterface {
}
// If a connection is made to the imports
(NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Inline { .. }, NodeInput::Import { .. }) => {
self.unload_outward_wires(network_path);
self.update_outward_wires(network_path, input_connector, &old_input, &new_input);
self.unload_wire(input_connector, network_path);
}
// If a connection to the imports is disconnected
(NodeInput::Import { .. }, NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Inline { .. }) => {
self.unload_outward_wires(network_path);
self.update_outward_wires(network_path, input_connector, &old_input, &new_input);
self.unload_wire(input_connector, network_path);
}
// If a node is disconnected.
(NodeInput::Node { .. }, NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Inline { .. }) => {
self.unload_outward_wires(network_path);
self.update_outward_wires(network_path, input_connector, &old_input, &new_input);
self.unload_wire(input_connector, network_path);
if let Some((old_upstream_node_id, previous_position)) = previous_metadata {
@@ -4616,7 +4694,7 @@ impl NodeNetworkInterface {
// Set the position to stack if necessary
if let Some(downstream_position) = is_layer.then_some(single_downstream_layer_position).flatten() {
node_metadata.persistent_metadata.node_type_metadata = NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Stack((position.y - downstream_position.y - 3).max(0) as u32),
position: LayerPosition::Stack((position.y - downstream_position.y - STACK_VERTICAL_GAP).max(0) as u32),
owned_nodes: TransientMetadata::Unloaded,
})
}
@@ -4777,7 +4855,7 @@ impl NodeNetworkInterface {
return;
};
self.set_stack_position(node_id, (node_position.y - downstream_position.y - 3).max(0) as u32, network_path);
self.set_stack_position(node_id, (node_position.y - downstream_position.y - STACK_VERTICAL_GAP).max(0) as u32, network_path);
}
/// Sets the position of a node to a chain position
@@ -5417,6 +5495,61 @@ impl NodeNetworkInterface {
self.unload_all_nodes_bounding_box(network_path);
}
/// Lightweight version of `move_layer_to_stack` for SVG import. Performs only the wiring
/// (connecting the layer into the stack) without any position calculation or push/collision logic.
/// Positions should be set separately after the full import tree is built.
pub fn move_layer_to_stack_for_import(&mut self, layer: LayerNodeIdentifier, mut parent: LayerNodeIdentifier, mut insert_index: usize, network_path: &[NodeId]) {
// Artboard redirection: if a non-artboard layer targets ROOT_PARENT and an artboard exists, redirect into the artboard
if let Some(first_layer) = LayerNodeIdentifier::ROOT_PARENT.children(&self.document_metadata).next()
&& parent == LayerNodeIdentifier::ROOT_PARENT
&& self
.reference(&layer.to_node(), network_path)
.is_none_or(|reference| reference != DefinitionIdentifier::Network("Artboard".into()))
&& self.is_artboard(&first_layer.to_node(), network_path)
{
parent = first_layer;
insert_index = 0;
}
let post_node = ModifyInputsContext::get_post_node_with_index(self, parent, insert_index);
let Some(post_node_input) = self.input_from_connector(&post_node, network_path).cloned() else {
log::error!("Could not get previous input in move_layer_to_stack_for_import");
return;
};
let layer_output = NodeInput::node(layer.to_node(), 0);
match post_node_input {
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Inline(_) | NodeInput::Reflection(_) => {
// First child in the stack — wire layer output to the post_node input
self.set_input_for_import(&post_node, layer_output, network_path);
}
NodeInput::Node { .. } => {
// Subsequent child — insert layer between post_node and its current upstream:
// 1. Disconnect old upstream from post_node, wire layer output to post_node
self.set_input_for_import(&post_node, layer_output, network_path);
// 2. Wire old upstream into layer's primary (stack) input
self.set_input_for_import(&InputConnector::node(layer.to_node(), 0), post_node_input, network_path);
}
NodeInput::Import { .. } => {
log::error!("Cannot insert import layer into a parent that connects to the imports");
}
}
}
/// Sets a layer's position directly without triggering per-node cache invalidation.
/// Used for bulk import operations where caches are invalidated once at the end.
pub fn set_layer_position_for_import(&mut self, node_id: &NodeId, position: LayerPosition, network_path: &[NodeId]) {
let Some(node_metadata) = self.node_metadata_mut(node_id, network_path) else {
log::error!("Could not get node_metadata for node {node_id} in set_layer_position_for_import");
return;
};
if let NodeTypePersistentMetadata::Layer(layer_metadata) = &mut node_metadata.persistent_metadata.node_type_metadata {
layer_metadata.position = position;
self.transaction_modified();
}
}
/// Disconnect the layers primary output and the input to the last non layer node feeding into it through primary flow, reconnects, then moves the layer to the new layer and stack index
pub fn move_layer_to_stack(&mut self, layer: LayerNodeIdentifier, mut parent: LayerNodeIdentifier, mut insert_index: usize, network_path: &[NodeId]) {
// Prevent moving an artboard anywhere but to the ROOT_PARENT child stack
@@ -5482,7 +5615,7 @@ impl NodeNetworkInterface {
let after_move_post_layer_position = if let Some(post_node_id) = post_node.node_id() {
self.position(&post_node_id, network_path)
} else {
Some(IVec2::new(8, -3))
Some(IVec2::new(LAYER_INDENT_OFFSET, -STACK_VERTICAL_GAP))
};
let Some(after_move_post_layer_position) = after_move_post_layer_position else {
@@ -5499,15 +5632,15 @@ impl NodeNetworkInterface {
log::error!("Could not get downstream node position in move_layer_to_stack");
return;
};
let mut lowest_y_position = downstream_node_position.y + 3;
let mut lowest_y_position = downstream_node_position.y + STACK_VERTICAL_GAP;
for bottom_position in self.upstream_nodes_below_layer(&downstream_node, network_path).iter().filter_map(|node_id| {
let is_layer = self.is_layer(node_id, network_path);
self.position(node_id, network_path).map(|position| position.y + if is_layer { 3 } else { 2 })
self.position(node_id, network_path).map(|position| position.y + if is_layer { STACK_VERTICAL_GAP } else { 2 })
}) {
lowest_y_position = lowest_y_position.max(bottom_position);
}
downstream_height = lowest_y_position - (downstream_node_position.y + 3);
downstream_height = lowest_y_position - (downstream_node_position.y + STACK_VERTICAL_GAP);
}
let mut highest_y_position = layer_to_move_position.y;
@@ -5515,7 +5648,7 @@ impl NodeNetworkInterface {
for (bottom_position, top_position) in self.upstream_nodes_below_layer(&layer.to_node(), network_path).iter().filter_map(|node_id| {
let is_layer = self.is_layer(node_id, network_path);
let bottom_position = self.position(node_id, network_path).map(|position| position.y + if is_layer { 3 } else { 2 });
let bottom_position = self.position(node_id, network_path).map(|position| position.y + if is_layer { STACK_VERTICAL_GAP } else { 2 });
let top_position = self.position(node_id, network_path).map(|position| if is_layer { position.y - 1 } else { position.y });
bottom_position.zip(top_position)
}) {
@@ -5523,7 +5656,7 @@ impl NodeNetworkInterface {
lowest_y_position = lowest_y_position.max(bottom_position);
}
let height_above_layer = layer_to_move_position.y - highest_y_position + downstream_height;
let height_below_layer = lowest_y_position - layer_to_move_position.y - 3;
let height_below_layer = lowest_y_position - layer_to_move_position.y - STACK_VERTICAL_GAP;
// If there is an upstream node in the new location for the layer, create space for the moved layer by shifting the upstream node down
if let Some(upstream_node_id) = post_node_input.as_node() {
@@ -5535,7 +5668,7 @@ impl NodeNetworkInterface {
let old_selected_nodes = selected_nodes.replace_with(vec![upstream_node_id]);
// Create the minimum amount space for the moved layer
for _ in 0..3 {
for _ in 0..STACK_VERTICAL_GAP {
self.vertical_shift_with_push(&upstream_node_id, 1, &mut HashSet::new(), network_path);
}
@@ -5564,7 +5697,7 @@ impl NodeNetworkInterface {
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Inline(_) | NodeInput::Reflection(_) => {
self.create_wire(&OutputConnector::node(layer.to_node(), 0), &post_node, network_path);
let final_layer_position = after_move_post_layer_position + IVec2::new(-8, 3);
let final_layer_position = after_move_post_layer_position + IVec2::new(-LAYER_INDENT_OFFSET, STACK_VERTICAL_GAP);
let shift = final_layer_position - previous_layer_position;
self.shift_absolute_node_position(&layer.to_node(), shift, network_path);
}
@@ -5575,7 +5708,7 @@ impl NodeNetworkInterface {
return;
};
let final_layer_position = IVec2::new(stack_top_position.x, after_move_post_layer_position.y + 3 + height_above_layer);
let final_layer_position = IVec2::new(stack_top_position.x, after_move_post_layer_position.y + STACK_VERTICAL_GAP + height_above_layer);
let shift = final_layer_position - previous_layer_position;
self.shift_absolute_node_position(&layer.to_node(), shift, network_path);
insert_node_after_post = true;
@@ -5588,13 +5721,13 @@ impl NodeNetworkInterface {
match post_node_input {
// Move to the bottom of the stack
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Inline(_) | NodeInput::Reflection(_) => {
let offset = after_move_post_layer_position - previous_layer_position + IVec2::new(0, 3 + height_above_layer);
let offset = after_move_post_layer_position - previous_layer_position + IVec2::new(0, STACK_VERTICAL_GAP + height_above_layer);
self.shift_absolute_node_position(&layer.to_node(), offset, network_path);
self.create_wire(&OutputConnector::node(layer.to_node(), 0), &post_node, network_path);
}
// Insert into the stack
NodeInput::Node { .. } => {
let final_layer_position = after_move_post_layer_position + IVec2::new(0, 3 + height_above_layer);
let final_layer_position = after_move_post_layer_position + IVec2::new(0, STACK_VERTICAL_GAP + height_above_layer);
let shift = final_layer_position - previous_layer_position;
self.shift_absolute_node_position(&layer.to_node(), shift, network_path);
insert_node_after_post = true;
@@ -5653,18 +5786,38 @@ impl NodeNetworkInterface {
self.create_wire(&upstream_output, &InputConnector::node(*node_id, insert_node_input_index), network_path);
}
// Moves a node and to the start of a layer chain (feeding into the secondary input of the layer)
pub fn move_node_to_chain_start(&mut self, node_id: &NodeId, parent: LayerNodeIdentifier, network_path: &[NodeId]) {
let Some(current_input) = self.input_from_connector(&InputConnector::node(parent.to_node(), 1), network_path) else {
/// Moves a node to the start of a layer chain (feeding into the secondary input of the layer).
/// When `import` is true, uses lightweight wiring that skips `is_acyclic` checks and per-node cache invalidation.
pub fn move_node_to_chain_start(&mut self, node_id: &NodeId, parent: LayerNodeIdentifier, network_path: &[NodeId], import: bool) {
let parent_input = InputConnector::node(parent.to_node(), 1);
let Some(current_input) = self.input_from_connector(&parent_input, network_path).cloned() else {
log::error!("Could not get input for node {node_id}");
return;
};
// Chain is empty: wire the node as the first (and only) entry in the chain
if matches!(current_input, NodeInput::Value { .. }) {
self.create_wire(&OutputConnector::node(*node_id, 0), &InputConnector::node(parent.to_node(), 1), network_path);
// Wire: [parent] -> [new node]
if import {
self.set_input_for_import(&parent_input, NodeInput::node(*node_id, 0), network_path);
} else {
self.create_wire(&OutputConnector::node(*node_id, 0), &parent_input, network_path);
}
// Mark this lone node as chain-positioned
self.set_chain_position(node_id, network_path);
} else {
// Insert the node in the gap and set the upstream to a chain
self.insert_node_between(node_id, &InputConnector::node(parent.to_node(), 1), 0, network_path);
}
// Chain already has nodes: splice this node between the parent and the chain's existing final downstream node
else {
// Wire: [parent] -> [new node] -> [existing node]
if import {
self.set_input_for_import(&parent_input, NodeInput::node(*node_id, 0), network_path);
self.set_input_for_import(&InputConnector::node(*node_id, 0), current_input, network_path);
} else {
self.insert_node_between(node_id, &parent_input, 0, network_path);
}
// Ensure all upstream nodes from here are marked as chain-positioned
self.force_set_upstream_to_chain(node_id, network_path);
}
}
@@ -242,7 +242,10 @@ impl NodeNetworkInterface {
}
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => {
let Some(implementations) = NODE_REGISTRY.get(proto_node_identifier) else {
log::error!("Protonode {proto_node_identifier:?} not found in registry in potential_valid_input_types");
// The compiler removes the identity node, so it's expected to be absent from the registry
if proto_node_identifier != &graphene_std::ops::identity::IDENTIFIER {
log::error!("Proto node `{proto_node_identifier:?}` not found in the node registry, in potential_valid_input_types");
}
return Vec::new();
};
let number_of_inputs = self.number_of_inputs(node_id, network_path);
@@ -10,9 +10,17 @@ use graph_craft::document::{NodeId, NodeNetwork};
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct LayerStructureEntry {
/// The node ID of the layer this entry represents.
#[serde(rename = "layerId")]
pub layer_id: NodeId,
/// The expanded child entries nested within this layer. Empty when the layer is collapsed or has no children.
pub children: Vec<LayerStructureEntry>,
/// Whether this layer has children reachable in the graph, even when they are omitted from `children` because the layer is collapsed.
#[serde(rename = "childrenPresent")]
pub children_present: bool,
/// Whether any descendant layer in the graph is selected, including through collapsed subtrees not listed in `children`.
#[serde(rename = "descendantSelected")]
pub descendant_selected: bool,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -28,21 +36,9 @@ pub struct LayerPanelEntry {
pub in_selected_network: bool,
#[serde(rename = "childrenAllowed")]
pub children_allowed: bool,
#[serde(rename = "childrenPresent")]
pub children_present: bool,
pub expanded: bool,
pub depth: u32,
pub visible: bool,
#[serde(rename = "parentsVisible")]
pub parents_visible: bool,
pub unlocked: bool,
#[serde(rename = "parentsUnlocked")]
pub parents_unlocked: bool,
#[serde(rename = "parentId")]
pub parent_id: Option<NodeId>,
pub selected: bool,
#[serde(rename = "ancestorOfSelected")]
pub ancestor_of_selected: bool,
#[serde(rename = "descendantOfSelected")]
pub descendant_of_selected: bool,
pub clipped: bool,
@@ -163,4 +159,7 @@ impl SelectedNodes {
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct CollapsedLayers(pub Vec<LayerNodeIdentifier>);
/// Tracks which layer instances are collapsed in the Layers panel. Each entry is an "instance path":
/// the sequence of ancestor node IDs from the root down to the collapsed layer. This allows the same
/// layer appearing under multiple parents to have independent expand/collapse state per instance.
pub struct CollapsedLayers(pub Vec<Vec<NodeId>>);
@@ -12,6 +12,7 @@ use graphene_std::ProtoNodeIdentifier;
use graphene_std::subpath::Subpath;
use graphene_std::table::Table;
use graphene_std::text::{TextAlign, TypesettingConfig};
use graphene_std::transform::ScaleType;
use graphene_std::uuid::NodeId;
use graphene_std::vector::Vector;
use graphene_std::vector::style::{PaintOrder, StrokeAlign};
@@ -473,13 +474,14 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
],
},
NodeReplacement {
node: graphene_std::raster_nodes::blending_nodes::blend::IDENTIFIER,
node: graphene_std::raster_nodes::blending_nodes::mix::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::BlendNode",
"raster_nodes::adjustments::BlendNode",
"graphene_core::raster::adjustments::BlendNode",
"graphene_core::raster::BlendNode",
"graphene_raster_nodes::blending_nodes::BlendNode",
"raster_nodes::blending_nodes::BlendNode",
],
},
NodeReplacement {
@@ -1663,7 +1665,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
.set_input(&InputConnector::node(*node_id, 1), NodeInput::value(TaggedValue::U32(0), false), network_path);
}
// Migrate from the old source/target "Morph" node to the new vector table based "Morph" node.
// Migrate from the old source/target v1 "Morph" node to the new vector table based v2 "Morph" node.
// This doesn't produce exactly equivalent results in cases involving input vector tables with multiple rows.
// The old version would zip the source and target table rows, interpoleating each pair together.
// The migrated version will instead deeply flatten both merged tables and morph sequentially between all source vectors and all target vector elements.
@@ -1675,7 +1677,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
// 4 inputs - even older signature (commit 80b8df8d4298b6669f124b929ce61bfabfc44e41):
// async fn morph(_: impl Ctx, source: Table<Vector>, #[expose] target: Table<Vector>, #[default(0.5)] time: Fraction, #[min(0.)] start_index: IntegerCount) -> Table<Vector> { ... }
//
// New signature:
// v2 signature:
// async fn morph<I: IntoGraphicTable>(_: impl Ctx, #[implementations(Table<Graphic>, Table<Vector>)] content: I, progression: Progression) -> Table<Vector> { ... }
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
@@ -1711,6 +1713,84 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
.set_input(&InputConnector::node(*node_id, 0), NodeInput::node(merge_node_id, 0), network_path);
// Connect the old 'progression' input to the new 'progression' input of the Morph node
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[2].clone(), network_path);
inputs_count = 2;
}
// Migrate from the v2 "Morph" node (2 inputs: content, progression) to the v3 "Morph" node (5 inputs: content, progression, reverse, distribution, path).
// The old progression used integer part for pair selection (range 0..N-1 where N is the number of content objects).
// The new progression uses fractional 0..1 for euclidean traversal through all objects.
// We insert Count Elements → Subtract 1 → Divide to remap: new_progression = old_progression / (N - 1).
// For the common 2-object case (N=2), this divides by 1 which is a no-op, preserving identical behavior.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::morph::IDENTIFIER) && inputs_count == 2 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
// Reconnect content (input 0) and leave path (input 4) as default
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
let Some(morph_position) = document.network_interface.position_from_downstream_node(node_id, network_path) else {
log::error!("Could not get position for morph node {node_id}");
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
return None;
};
// Create Count Elements node: counts content table rows → N
let Some(count_elements_def) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::vector::count_elements::IDENTIFIER)) else {
log::error!("Could not get count_elements node from definition when upgrading morph");
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
return None;
};
let count_elements_template = count_elements_def.default_node_template();
let count_elements_id = NodeId::new();
// Create Subtract node: N → N-1
let Some(subtract_def) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::subtract::IDENTIFIER)) else {
log::error!("Could not get subtract node from definition when upgrading morph");
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
return None;
};
let mut subtract_template = subtract_def.default_node_template();
subtract_template.document_node.inputs[1] = NodeInput::value(TaggedValue::F64(1.), false);
let subtract_id = NodeId::new();
// Create Divide node: old_progression / (N-1) → new progression
let Some(divide_def) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::divide::IDENTIFIER)) else {
log::error!("Could not get divide node from definition when upgrading morph");
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
return None;
};
let divide_template = divide_def.default_node_template();
let divide_id = NodeId::new();
// Insert and position nodes
document.network_interface.insert_node(count_elements_id, count_elements_template, network_path);
document
.network_interface
.shift_absolute_node_position(&count_elements_id, morph_position + IVec2::new(-21, 2), network_path);
document.network_interface.insert_node(subtract_id, subtract_template, network_path);
document.network_interface.shift_absolute_node_position(&subtract_id, morph_position + IVec2::new(-14, 2), network_path);
document.network_interface.insert_node(divide_id, divide_template, network_path);
document.network_interface.shift_absolute_node_position(&divide_id, morph_position + IVec2::new(-7, 1), network_path);
// Wire: content source → Count Elements input 0
document.network_interface.set_input(&InputConnector::node(count_elements_id, 0), old_inputs[0].clone(), network_path);
// Wire: Count Elements output → Subtract input 0 (minuend)
document
.network_interface
.set_input(&InputConnector::node(subtract_id, 0), NodeInput::node(count_elements_id, 0), network_path);
// Wire: old progression → Divide input 0 (numerator)
document.network_interface.set_input(&InputConnector::node(divide_id, 0), old_inputs[1].clone(), network_path);
// Wire: Subtract output → Divide input 1 (denominator)
document.network_interface.set_input(&InputConnector::node(divide_id, 1), NodeInput::node(subtract_id, 0), network_path);
// Wire: Divide output → Morph progression input
document.network_interface.set_input(&InputConnector::node(*node_id, 1), NodeInput::node(divide_id, 0), network_path);
}
// Migrate old Arrow node from (start, end, shaft_width, head_width, head_length) to (arrow_to, shaft_width, head_width, head_length) with a Transform node for positioning
@@ -1848,6 +1928,30 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.set_context_features(node_id, network_path, context_features);
}
// Add the "Scale Type" parameter to the "Decompose Scale" node
if reference == DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::decompose_scale::IDENTIFIER) && inputs_count == 1 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
document
.network_interface
.set_input(&InputConnector::node(*node_id, 1), NodeInput::value(TaggedValue::ScaleType(ScaleType::Magnitude), false), network_path);
}
// Add the "Along Normals" parameter to the "Jitter Points" node
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::jitter_points::IDENTIFIER) && inputs_count == 3 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
document.network_interface.set_input(&InputConnector::node(*node_id, 2), old_inputs[2].clone(), network_path);
document
.network_interface
.set_input(&InputConnector::node(*node_id, 3), NodeInput::value(TaggedValue::Bool(false), false), network_path);
}
// ==================================
// PUT ALL MIGRATIONS ABOVE THIS LINE
// ==================================
+3
View File
@@ -3,8 +3,11 @@ mod portfolio_message_handler;
pub mod document;
pub mod document_migration;
pub mod persistent_state;
pub mod utility_types;
#[doc(inline)]
pub use persistent_state::{PersistentStateMessage, PersistentStateMessageContext, PersistentStateMessageHandler};
#[doc(inline)]
pub use portfolio_message::{PortfolioMessage, PortfolioMessageDiscriminant};
#[doc(inline)]
@@ -0,0 +1,7 @@
mod persistent_state_message;
mod persistent_state_message_handler;
#[doc(inline)]
pub use persistent_state_message::{PersistentStateMessage, PersistentStateMessageDiscriminant};
#[doc(inline)]
pub use persistent_state_message_handler::{PersistentStateMessageContext, PersistentStateMessageHandler};
@@ -0,0 +1,30 @@
use crate::messages::frontend::utility_types::PersistedState;
use crate::messages::prelude::*;
#[impl_message(Message, PortfolioMessage, PersistentState)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum PersistentStateMessage {
ReadState,
WriteState,
LoadState {
state: PersistedState,
},
ReadDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
},
WriteDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
document: String,
},
DeleteDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
},
LoadDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
document: String,
},
}
@@ -0,0 +1,54 @@
use crate::messages::frontend::utility_types::PersistedState;
use crate::messages::portfolio::utility_types::WorkspacePanelLayout;
use crate::messages::prelude::*;
#[derive(Default, Debug, Clone, ExtractField)]
pub struct PersistentStateMessageHandler {
loaded: bool,
}
#[derive(ExtractField)]
pub struct PersistentStateMessageContext {
pub persisted_state: PersistedState,
}
#[message_handler_data]
impl MessageHandler<PersistentStateMessage, PersistentStateMessageContext> for PersistentStateMessageHandler {
fn process_message(&mut self, message: PersistentStateMessage, responses: &mut VecDeque<Message>, context: PersistentStateMessageContext) {
let PersistentStateMessageContext { persisted_state: state } = context;
match message {
PersistentStateMessage::ReadState => {
responses.add(FrontendMessage::TriggerPersistenceReadState);
}
PersistentStateMessage::WriteState => {
if !self.loaded && (state.documents.is_empty() && (state.workspace_layout == Some(WorkspacePanelLayout::default()) || state.workspace_layout.is_none())) {
return;
}
self.loaded = true;
responses.add(FrontendMessage::TriggerPersistenceWriteState { state });
}
PersistentStateMessage::LoadState { state } => {
self.loaded = true;
responses.add(PortfolioMessage::LoadPersistedState { state });
}
PersistentStateMessage::ReadDocument { document_id } => {
responses.add(FrontendMessage::TriggerPersistenceReadDocument { document_id });
}
PersistentStateMessage::WriteDocument { document_id, document } => {
responses.add(FrontendMessage::TriggerPersistenceWriteDocument { document_id, document });
}
PersistentStateMessage::DeleteDocument { document_id } => {
responses.add(FrontendMessage::TriggerPersistenceDeleteDocument { document_id });
}
PersistentStateMessage::LoadDocument { document_id, document } => {
responses.add(PortfolioMessage::LoadDocumentContent {
document_id,
document_serialized_content: document,
});
}
}
}
advertise_actions!(PersistentStateMessageDiscriminant;);
}
@@ -1,6 +1,7 @@
use super::document::utility_types::document_metadata::LayerNodeIdentifier;
use super::utility_types::PanelType;
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use super::persistent_state::PersistentStateMessage;
use super::utility_types::{DockingSplitDirection, PanelGroupId, PanelType};
use crate::messages::frontend::utility_types::{ExportBounds, FileType, PersistedState};
use crate::messages::portfolio::document::utility_types::clipboards::Clipboard;
use crate::messages::portfolio::utility_types::FontCatalog;
use crate::messages::prelude::*;
@@ -15,6 +16,8 @@ pub enum PortfolioMessage {
// Sub-messages
#[child]
Document(DocumentMessage),
#[child]
PersistentState(PersistentStateMessage),
// Messages
Init,
@@ -61,6 +64,23 @@ pub enum PortfolioMessage {
LoadDocumentResources {
document_id: DocumentId,
},
LoadPersistedState {
state: PersistedState,
},
LoadDocumentContent {
document_id: DocumentId,
document_serialized_content: String,
},
MoveAllPanelTabs {
source_group: PanelGroupId,
target_group: PanelGroupId,
insert_index: usize,
},
MovePanelTab {
source_group: PanelGroupId,
target_group: PanelGroupId,
insert_index: usize,
},
NewDocumentWithName {
name: String,
},
@@ -80,15 +100,13 @@ pub enum PortfolioMessage {
document_path: Option<PathBuf>,
document_serialized_content: String,
},
OpenDocumentFileWithId {
LoadDocument {
document_id: DocumentId,
document_name: Option<String>,
document_path: Option<PathBuf>,
document_is_auto_saved: bool,
document_is_saved: bool,
document_serialized_content: String,
to_front: bool,
select_after_open: bool,
},
OpenImage {
name: Option<String>,
@@ -126,10 +144,26 @@ pub enum PortfolioMessage {
layers: Vec<LayerNodeIdentifier>,
},
PrevDocument,
ReorderDocument {
document_id: DocumentId,
new_index: usize,
},
ReorderPanelGroupTab {
group: PanelGroupId,
old_index: usize,
new_index: usize,
},
RequestWelcomeScreenButtonsLayout,
RequestStatusBarInfoLayout,
SetActivePanel {
panel: PanelType,
SetPanelGroupActiveTab {
group: PanelGroupId,
tab_index: usize,
},
SplitPanelGroup {
target_group: PanelGroupId,
direction: DockingSplitDirection,
tabs: Vec<PanelType>,
active_tab_index: usize,
},
SelectDocument {
document_id: DocumentId,
@@ -139,7 +173,6 @@ pub enum PortfolioMessage {
file_type: FileType,
scale_factor: f64,
bounds: ExportBounds,
transparent_background: bool,
artboard_name: Option<String>,
artboard_count: usize,
},
@@ -157,4 +190,16 @@ pub enum PortfolioMessage {
ToggleRulers,
UpdateDocumentWidgets,
UpdateOpenDocumentsList,
UpdateWorkspacePanelLayout,
ResetWorkspaceLayout,
ResetPanelGroupSizes {
/// Path of child indices from the root to the split node whose children's sizes should be reset to defaults.
split_path: Vec<usize>,
},
SetPanelGroupSizes {
/// Path of child indices from the root to the split node whose children's sizes are being set.
split_path: Vec<usize>,
/// New sizes for the children at that split node.
sizes: Vec<f64>,
},
}
File diff suppressed because it is too large. Load diff
+506 -7
View File
@@ -3,7 +3,7 @@ use graphene_std::raster::Image;
use graphene_std::text::{Font, FontCache};
#[derive(Debug, Default)]
pub struct PersistentData {
pub struct CachedData {
pub font_cache: FontCache,
pub font_catalog: FontCatalog,
}
@@ -83,29 +83,528 @@ impl FontCatalogStyle {
}
}
#[derive(PartialEq, Eq, Clone, Copy, Debug, Default, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub enum PanelType {
#[default]
Document,
Welcome,
Document,
Layers,
Properties,
DataPanel,
Data,
}
impl From<String> for PanelType {
fn from(value: String) -> Self {
match value.as_str() {
"Document" => PanelType::Document,
"Welcome" => PanelType::Welcome,
"Document" => PanelType::Document,
"Layers" => PanelType::Layers,
"Properties" => PanelType::Properties,
"Data" => PanelType::DataPanel,
"Data" => PanelType::Data,
_ => panic!("Unknown panel type: {value}"),
}
}
}
impl PanelType {
pub fn non_document_panels() -> &'static [PanelType] {
&[PanelType::Layers, PanelType::Properties, PanelType::Data]
}
}
/// Unique identifier for a panel group (a leaf subdivision in the layout tree that holds tabs).
#[repr(transparent)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct PanelGroupId(pub u64);
/// Which edge of a panel group to split on when docking a dragged panel.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum DockingSplitDirection {
Left,
Right,
Top,
Bottom,
}
/// State of a single panel group (leaf subdivision) in the workspace layout tree.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct PanelGroupState {
pub tabs: Vec<PanelType>,
pub active_tab_index: usize,
}
impl PanelGroupState {
pub fn active_panel_type(&self) -> Option<PanelType> {
self.tabs.get(self.active_tab_index).copied()
}
pub fn contains(&self, panel_type: PanelType) -> bool {
self.tabs.contains(&panel_type)
}
pub fn is_visible(&self, panel_type: PanelType) -> bool {
self.active_panel_type() == Some(panel_type)
}
}
/// A subdivision in the workspace layout tree. The root is always a row (horizontal).
/// Direction alternates at each depth: row, column, row, column, etc.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum PanelLayoutSubdivision {
/// A leaf subdivision: a panel group with tabbed panels.
PanelGroup { id: PanelGroupId, state: PanelGroupState },
/// A container subdivision that splits its space among children. Direction is implicit from depth (even = row, odd = column).
Split { children: Vec<SplitChild> },
}
impl Default for PanelLayoutSubdivision {
fn default() -> Self {
PanelLayoutSubdivision::Split { children: Vec::new() }
}
}
/// A child within a split container, with a proportional size weight.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct SplitChild {
pub subdivision: PanelLayoutSubdivision,
/// Flex-grow weight for proportional sizing.
pub size: f64,
}
/// The complete workspace panel layout as a tree of nested rows and columns.
/// The root subdivision is always a row (horizontal split). Direction alternates at each depth.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct WorkspacePanelLayout {
#[serde(default)]
pub root: PanelLayoutSubdivision,
/// Counter for generating unique panel group IDs.
#[serde(default)]
next_group_id: PanelGroupId,
/// Remembers where a panel was before being removed (panel type, group ID, and tab index), so it can be restored there.
#[serde(default)]
saved_positions: Vec<(PanelType, PanelGroupId, usize)>,
/// Whether Focus Document mode is active, hiding all non-document panels.
#[serde(default)]
pub focus_document: bool,
}
impl WorkspacePanelLayout {
/// Generate a new unique panel group ID.
pub fn next_id(&mut self) -> PanelGroupId {
let id = self.next_group_id;
self.next_group_id.0 += 1;
id
}
/// Find the panel group state for a given ID.
pub fn panel_group(&self, id: PanelGroupId) -> Option<&PanelGroupState> {
self.root.find_group(id)
}
/// Find the panel group state for a given ID (mutable).
pub fn panel_group_mut(&mut self, id: PanelGroupId) -> Option<&mut PanelGroupState> {
self.root.find_group_mut(id)
}
/// Find which panel group contains a given panel type, returning its ID.
pub fn find_panel(&self, panel_type: PanelType) -> Option<PanelGroupId> {
self.root.find_panel(panel_type)
}
/// Check if a panel type is the active (visible) tab in any panel group.
pub fn is_panel_visible(&self, panel_type: PanelType) -> bool {
self.find_panel(panel_type).and_then(|id| self.panel_group(id)).is_some_and(|group| group.is_visible(panel_type))
}
/// Check if a panel type is present (as any tab) in any panel group, whether or not it's the active tab.
pub fn is_panel_present(&self, panel_type: PanelType) -> bool {
self.find_panel(panel_type).is_some()
}
/// Remove empty panel groups and collapse unnecessary single-child splits.
pub fn prune(&mut self) {
self.root.prune();
}
/// Produce a filtered copy of this layout containing only the document panel, for use in Focus Document mode.
pub fn document_only_layout(&self) -> WorkspacePanelLayout {
let mut layout = self.clone();
layout.root.retain_only_document_panels();
layout.root.prune();
layout
}
/// Split a panel group by inserting a new panel group adjacent to it.
/// The direction determines where the new group goes relative to the target.
/// Left/Right creates a horizontal (row) split, Top/Bottom creates a vertical (column) split.
/// Returns the ID of the newly created panel group, or `None` if insertion failed.
pub fn split_panel_group(&mut self, target_group_id: PanelGroupId, direction: DockingSplitDirection, tabs: Vec<PanelType>, active_tab_index: usize) -> Option<PanelGroupId> {
let new_id = self.next_id();
let new_group = SplitChild {
subdivision: PanelLayoutSubdivision::PanelGroup {
id: new_id,
state: PanelGroupState { tabs, active_tab_index },
},
size: 50.,
};
let insert_before = matches!(direction, DockingSplitDirection::Left | DockingSplitDirection::Top);
let needs_horizontal = matches!(direction, DockingSplitDirection::Left | DockingSplitDirection::Right);
self.root.insert_split_adjacent(target_group_id, new_group, insert_before, needs_horizontal, 0).then_some(new_id)
}
/// Recalculate the default sizes for all splits in the tree based on document panel proximity.
pub fn recalculate_default_sizes(&mut self) {
self.root.recalculate_default_sizes();
}
/// Remember which panel group and tab index a panel was in before removal, so it can be restored there later.
pub fn save_panel_position(&mut self, panel_type: PanelType) {
if let Some(group_id) = self.find_panel(panel_type) {
let tab_index = self.panel_group(group_id).and_then(|g| g.tabs.iter().position(|&t| t == panel_type)).unwrap_or(0);
// Replace any existing saved position for this panel type
self.saved_positions.retain(|(pt, _, _)| *pt != panel_type);
self.saved_positions.push((panel_type, group_id, tab_index));
}
}
/// Restore a panel to its previous position if available, otherwise to its default position.
/// If the panel was previously in a group that still exists, it's added back as a tab at its original index.
/// Otherwise, it's placed at its default structural position in the tree.
pub fn restore_panel(&mut self, panel_type: PanelType) {
// Try to restore to the previously saved group and tab position
let saved = self.saved_positions.iter().find(|(pt, _, _)| *pt == panel_type).copied();
if let Some((_, saved_group_id, saved_tab_index)) = saved
&& let Some(group) = self.panel_group_mut(saved_group_id)
{
let insert_index = saved_tab_index.min(group.tabs.len());
group.tabs.insert(insert_index, panel_type);
group.active_tab_index = insert_index;
self.saved_positions.retain(|(pt, _, _)| *pt != panel_type);
return;
}
self.saved_positions.retain(|(pt, _, _)| *pt != panel_type);
self.restore_panel_to_default_position(panel_type);
}
/// Place a panel at its default structural position in the layout tree.
/// - Data: below the document in the left column (root child 0)
/// - Properties: top of the right column (root child 1)
/// - Layers: bottom of the right column (root child 1)
fn restore_panel_to_default_position(&mut self, panel_type: PanelType) {
let new_id = self.next_id();
let new_group = SplitChild {
subdivision: PanelLayoutSubdivision::PanelGroup {
id: new_id,
state: PanelGroupState {
tabs: vec![panel_type],
active_tab_index: 0,
},
},
size: match panel_type {
PanelType::Data => 30.,
PanelType::Properties => 45.,
PanelType::Layers => 55.,
_ => 50.,
},
};
// Determine which root child column to insert into and at which position
let (root_child_index, insert_at_end) = match panel_type {
PanelType::Data => (0, true), // Left column, after document
PanelType::Properties => (1, false), // Right column, at top
PanelType::Layers => (1, true), // Right column, at bottom
_ => (1, true),
};
// Ensure the root is a split
if !matches!(&self.root, PanelLayoutSubdivision::Split { .. }) {
let old_root = std::mem::replace(&mut self.root, PanelLayoutSubdivision::Split { children: vec![] });
if let PanelLayoutSubdivision::Split { children } = &mut self.root {
children.push(SplitChild { subdivision: old_root, size: 80. });
}
}
let PanelLayoutSubdivision::Split { children: root_children } = &mut self.root else { return };
// Ensure the target root child exists
while root_children.len() <= root_child_index {
root_children.push(SplitChild {
subdivision: PanelLayoutSubdivision::Split { children: vec![] },
size: 20.,
});
}
// The target should be a split (column at depth 1) so we can add children to it
let target = &mut root_children[root_child_index].subdivision;
if !matches!(target, PanelLayoutSubdivision::Split { .. }) {
let old_subdivision = std::mem::replace(target, PanelLayoutSubdivision::Split { children: vec![] });
if let PanelLayoutSubdivision::Split { children } = target {
children.push(SplitChild {
subdivision: old_subdivision,
size: 50.,
});
}
}
if let PanelLayoutSubdivision::Split { children } = target {
if insert_at_end {
children.push(new_group);
} else {
children.insert(0, new_group);
}
}
}
}
impl Default for WorkspacePanelLayout {
fn default() -> Self {
// Default layout (sizes are recalculated by `recalculate_default_sizes` before being sent to the frontend):
// Row [
// Column [Document]
// Column [Properties, Layers]
// ]
Self {
root: PanelLayoutSubdivision::Split {
children: vec![
SplitChild {
subdivision: PanelLayoutSubdivision::Split {
children: vec![SplitChild {
subdivision: PanelLayoutSubdivision::PanelGroup {
id: PanelGroupId(0),
state: PanelGroupState {
tabs: vec![PanelType::Document],
active_tab_index: 0,
},
},
size: 100.,
}],
},
size: 80.,
},
SplitChild {
subdivision: PanelLayoutSubdivision::Split {
children: vec![
SplitChild {
subdivision: PanelLayoutSubdivision::PanelGroup {
id: PanelGroupId(1),
state: PanelGroupState {
tabs: vec![PanelType::Properties],
active_tab_index: 0,
},
},
size: 50.,
},
SplitChild {
subdivision: PanelLayoutSubdivision::PanelGroup {
id: PanelGroupId(2),
state: PanelGroupState {
tabs: vec![PanelType::Layers],
active_tab_index: 0,
},
},
size: 50.,
},
],
},
size: 20.,
},
],
},
next_group_id: PanelGroupId(3),
saved_positions: Vec::new(),
focus_document: false,
}
}
}
impl PanelLayoutSubdivision {
/// Find the panel group state for a given ID.
pub fn find_group(&self, target_id: PanelGroupId) -> Option<&PanelGroupState> {
match self {
PanelLayoutSubdivision::PanelGroup { id, state } if *id == target_id => Some(state),
PanelLayoutSubdivision::PanelGroup { .. } => None,
PanelLayoutSubdivision::Split { children } => children.iter().find_map(|child| child.subdivision.find_group(target_id)),
}
}
/// Find the panel group state for a given ID (mutable).
pub fn find_group_mut(&mut self, target_id: PanelGroupId) -> Option<&mut PanelGroupState> {
match self {
PanelLayoutSubdivision::PanelGroup { id, state } if *id == target_id => Some(state),
PanelLayoutSubdivision::PanelGroup { .. } => None,
PanelLayoutSubdivision::Split { children } => children.iter_mut().find_map(|child| child.subdivision.find_group_mut(target_id)),
}
}
/// Find the panel group ID that contains a given panel type.
pub fn find_panel(&self, panel_type: PanelType) -> Option<PanelGroupId> {
match self {
PanelLayoutSubdivision::PanelGroup { id, state } if state.contains(panel_type) => Some(*id),
PanelLayoutSubdivision::PanelGroup { .. } => None,
PanelLayoutSubdivision::Split { children } => children.iter().find_map(|child| child.subdivision.find_panel(panel_type)),
}
}
/// Collect all panel group IDs in the tree.
pub fn all_group_ids(&self) -> Vec<PanelGroupId> {
match self {
PanelLayoutSubdivision::PanelGroup { id, .. } => vec![*id],
PanelLayoutSubdivision::Split { children } => children.iter().flat_map(|child| child.subdivision.all_group_ids()).collect(),
}
}
/// Remove empty panel groups and collapse unnecessary nesting.
/// Does NOT collapse single-child splits into their child, as that would change subdivision depths
/// and break the direction-by-depth alternation system.
pub fn prune(&mut self) {
let PanelLayoutSubdivision::Split { children } = self else { return };
// Recursively prune children
children.iter_mut().for_each(|child| child.subdivision.prune());
// Remove empty panel groups
children.retain(|child| !matches!(&child.subdivision, PanelLayoutSubdivision::PanelGroup { state, .. } if state.tabs.is_empty()));
// Remove empty splits (splits that lost all their children after pruning)
children.retain(|child| !matches!(&child.subdivision, PanelLayoutSubdivision::Split { children } if children.is_empty()));
}
/// Remove all non-document/non-welcome tabs from panel groups, leaving only document-related panels.
pub fn retain_only_document_panels(&mut self) {
match self {
PanelLayoutSubdivision::PanelGroup { state, .. } => {
state.tabs.retain(|t| matches!(t, PanelType::Document | PanelType::Welcome));
state.active_tab_index = state.active_tab_index.min(state.tabs.len().saturating_sub(1));
}
PanelLayoutSubdivision::Split { children } => {
children.iter_mut().for_each(|child| child.subdivision.retain_only_document_panels());
}
}
}
/// Check if this subtree contains a panel group with the given ID.
pub fn contains_group(&self, target_id: PanelGroupId) -> bool {
match self {
PanelLayoutSubdivision::PanelGroup { id, .. } => *id == target_id,
PanelLayoutSubdivision::Split { children } => children.iter().any(|child| child.subdivision.contains_group(target_id)),
}
}
/// Inserts a new split child adjacent to a target panel group and returns whether the insertion was successful.
/// Recurses to the deepest split closest to the target that matches the requested split direction.
/// If the target is a direct child of a mismatched-direction split, this wraps it in a new sub-split.
pub fn insert_split_adjacent(&mut self, target_id: PanelGroupId, new_child: SplitChild, insert_before: bool, needs_horizontal: bool, depth: usize) -> bool {
let PanelLayoutSubdivision::Split { children } = self else { return false };
let is_horizontal = depth.is_multiple_of(2);
let direction_matches = is_horizontal == needs_horizontal;
// Find which child subtree contains the target
let Some(containing_index) = children.iter().position(|child| child.subdivision.contains_group(target_id)) else {
return false;
};
// If the target is a direct child: we can certainly insert the new split, either as a sibling (if direction matches) or wrapping the target in a new split (if direction is mismatched)
let target_is_direct_child = matches!(&children[containing_index].subdivision, PanelLayoutSubdivision::PanelGroup { id, .. } if *id == target_id);
if target_is_direct_child {
// Direction matches and target is right here: insert as a sibling
if direction_matches {
let insert_index = if insert_before { containing_index } else { containing_index + 1 };
children.insert(insert_index, new_child);
}
// Direction mismatch: wrap the target in a new sub-split (at depth+1, which has the opposite direction of this and thus is the requested direction)
else {
let old_child_subdivision = std::mem::replace(&mut children[containing_index].subdivision, PanelLayoutSubdivision::Split { children: vec![] });
let old_child = SplitChild {
subdivision: old_child_subdivision,
size: 50.,
};
if let PanelLayoutSubdivision::Split { children: sub_children } = &mut children[containing_index].subdivision {
if insert_before {
sub_children.push(new_child);
sub_children.push(old_child);
} else {
sub_children.push(old_child);
sub_children.push(new_child);
}
}
}
return true;
}
// The target is deeper, so recurse into the containing child's subtree and return its insertion outcome
children[containing_index]
.subdivision
.insert_split_adjacent(target_id, new_child.clone(), insert_before, needs_horizontal, depth + 1)
}
/// Check if this subtree contains the document panel.
pub fn contains_document(&self) -> bool {
match self {
PanelLayoutSubdivision::PanelGroup { state, .. } => state.contains(PanelType::Document) || state.contains(PanelType::Welcome),
PanelLayoutSubdivision::Split { children } => children.iter().any(|child| child.subdivision.contains_document()),
}
}
/// Recalculate the default sizes for this subdivision's children based on proximity to the document panel.
/// Splits directly surrounding the document panel use 80-20 weighting.
/// All other splits use equal division.
pub fn recalculate_default_sizes(&mut self) {
if let PanelLayoutSubdivision::Split { children } = self {
let child_count = children.len();
if child_count == 0 {
return;
}
// Check if any child directly contains (or is) the document panel
let document_child_index = children.iter().position(|child| child.subdivision.contains_document());
if let Some(document_index) = document_child_index {
// This split directly surrounds the document panel, so use 80-20 weighting
let non_document_count = child_count - 1;
let document_share = if non_document_count > 0 { 80. } else { 100. };
let other_share = if non_document_count > 0 { 20. / non_document_count as f64 } else { 0. };
for (i, child) in children.iter_mut().enumerate() {
child.size = if i == document_index { document_share } else { other_share };
}
} else {
// This split doesn't directly contain the document, use equal division
let equal_share = 100. / child_count as f64;
for child in children.iter_mut() {
child.size = equal_share;
}
}
// Recurse into children
for child in children.iter_mut() {
child.subdivision.recalculate_default_sizes();
}
}
}
/// Remove a panel group by ID from the tree. Does not prune.
pub fn remove_group(&mut self, target_id: PanelGroupId) {
if let PanelLayoutSubdivision::Split { children } = self {
children.retain(|child| !matches!(&child.subdivision, PanelLayoutSubdivision::PanelGroup { id, .. } if *id == target_id));
children.iter_mut().for_each(|child| child.subdivision.remove_group(target_id));
}
}
}
pub enum FileContent {
/// A Graphite document.
Document(String),
@@ -4,7 +4,7 @@ use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use crate::messages::preferences::SelectionMode;
use crate::messages::prelude::*;
use crate::messages::tool::utility_types::ToolType;
use graph_craft::wasm_application_io::EditorPreferences;
use graph_craft::application_io::EditorPreferences;
#[derive(ExtractField)]
pub struct PreferencesMessageContext<'a> {
@@ -51,7 +51,7 @@ impl PreferencesMessageHandler {
}
pub fn supports_wgpu(&self) -> bool {
graph_craft::wasm_application_io::wgpu_available().unwrap_or_default()
graph_craft::application_io::wgpu_available().unwrap_or_default()
}
}
+1
View File
@@ -27,6 +27,7 @@ pub use crate::messages::portfolio::document::node_graph::{NodeGraphMessage, Nod
pub use crate::messages::portfolio::document::overlays::{OverlaysMessage, OverlaysMessageContext, OverlaysMessageDiscriminant, OverlaysMessageHandler};
pub use crate::messages::portfolio::document::properties_panel::{PropertiesPanelMessage, PropertiesPanelMessageDiscriminant, PropertiesPanelMessageHandler};
pub use crate::messages::portfolio::document::{DocumentMessage, DocumentMessageContext, DocumentMessageDiscriminant, DocumentMessageHandler};
pub use crate::messages::portfolio::persistent_state::{PersistentStateMessage, PersistentStateMessageContext, PersistentStateMessageDiscriminant, PersistentStateMessageHandler};
pub use crate::messages::portfolio::{PortfolioMessage, PortfolioMessageContext, PortfolioMessageDiscriminant, PortfolioMessageHandler};
pub use crate::messages::preferences::{PreferencesMessage, PreferencesMessageDiscriminant, PreferencesMessageHandler};
pub use crate::messages::tool::transform_layer::{TransformLayerMessage, TransformLayerMessageDiscriminant, TransformLayerMessageHandler};
@@ -230,7 +230,7 @@ pub fn new_image_layer(image_frame: Table<Raster<CPU>>, id: NodeId, parent: Laye
}
/// Create a new group layer from an SVG string.
pub fn new_svg_layer(svg: String, transform: glam::DAffine2, id: NodeId, parent: LayerNodeIdentifier, responses: &mut VecDeque<Message>) -> LayerNodeIdentifier {
pub fn new_svg_layer(svg: String, transform: glam::DAffine2, center: bool, id: NodeId, parent: LayerNodeIdentifier, responses: &mut VecDeque<Message>) -> LayerNodeIdentifier {
let insert_index = 0;
responses.add(GraphOperationMessage::NewSvg {
id,
@@ -238,6 +238,7 @@ pub fn new_svg_layer(svg: String, transform: glam::DAffine2, id: NodeId, parent:
transform,
parent,
insert_index,
center,
});
LayerNodeIdentifier::new_unchecked(id)
}
@@ -1822,7 +1822,7 @@ impl ShapeState {
/// Find the `t` value along the path segment we have clicked upon, together with that segment ID.
fn closest_segment(&self, network_interface: &NodeNetworkInterface, layer: LayerNodeIdentifier, position: glam::DVec2, tolerance: f64) -> Option<ClosestSegment> {
let transform = network_interface.document_metadata().transform_to_viewport_if_feeds(layer, network_interface);
let layer_pos = transform.inverse().transform_point2(position);
let layer_pos = (transform.matrix2.determinant().abs() >= f64::EPSILON).then(|| transform.inverse().transform_point2(position))?;
let tolerance = tolerance + 0.5;
@@ -212,16 +212,15 @@ impl SelectedEdges {
let original_from_pivot = updated - pivot; // The original vector from the point to the pivot
let mut scale_factor = new_from_pivot / original_from_pivot;
// Constrain should always scale by the same factor in x and y
// Constrain should always scale by the same factor in x and y.
// When one axis of `original_from_pivot` is near zero (e.g. for a line's degenerate bounding box),
// the scale factor for that axis is numerically unstable, so we copy from the more stable axis.
if constrain {
// When the point is on the pivot, we simply copy the other axis.
if original_from_pivot.x.abs() < 1e-5 {
if original_from_pivot.x.abs() < original_from_pivot.y.abs() {
scale_factor.x = scale_factor.y;
} else if original_from_pivot.y.abs() < 1e-5 {
} else {
scale_factor.y = scale_factor.x;
}
debug_assert!((scale_factor.x - scale_factor.y).abs() < 1e-5);
}
if !(self.left || self.right || constrain) {
@@ -4,7 +4,7 @@ use super::utility_types::{ToolActionMessageContext, ToolFsmState, tool_message_
use crate::application::generate_uuid;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::overlays::utility_types::OverlayProvider;
use crate::messages::portfolio::utility_types::PersistentData;
use crate::messages::portfolio::utility_types::CachedData;
use crate::messages::prelude::*;
use crate::messages::tool::transform_layer::transform_layer_message_handler::TransformLayerMessageContext;
use crate::messages::tool::utility_types::{HintData, ToolType};
@@ -18,7 +18,7 @@ pub struct ToolMessageContext<'a> {
pub document_id: DocumentId,
pub document: &'a mut DocumentMessageHandler,
pub input: &'a InputPreprocessorMessageHandler,
pub persistent_data: &'a PersistentData,
pub cached_data: &'a CachedData,
pub node_graph: &'a NodeGraphExecutor,
pub preferences: &'a PreferencesMessageHandler,
pub viewport: &'a ViewportMessageHandler,
@@ -39,7 +39,7 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
document_id,
document,
input,
persistent_data,
cached_data,
node_graph,
preferences,
viewport,
@@ -126,7 +126,7 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
node_graph,
preferences,
viewport,
persistent_data,
cached_data,
};
if let Some(tool_abort_message) = tool.event_to_message_map().tool_abort {
@@ -217,7 +217,7 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
tool_data.tools.get(active_tool).unwrap().activate(responses);
// Register initial properties
tool_data.tools.get(active_tool).unwrap().refresh_options(responses, persistent_data);
tool_data.tools.get(active_tool).unwrap().refresh_options(responses, cached_data);
// Notify the frontend about the initial active tool
tool_data.send_layout(responses, LayoutTarget::ToolShelf, preferences.brush_tool);
@@ -234,7 +234,7 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
node_graph,
preferences,
viewport,
persistent_data,
cached_data,
};
// Set initial hints and cursor
@@ -258,7 +258,7 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
ToolMessage::RefreshToolOptions => {
let tool_data = &mut self.tool_state.tool_data;
tool_data.tools.get(&tool_data.active_tool_type).unwrap().refresh_options(responses, persistent_data);
tool_data.tools.get(&tool_data.active_tool_type).unwrap().refresh_options(responses, cached_data);
}
ToolMessage::RefreshToolShelf => {
let tool_data = &mut self.tool_state.tool_data;
@@ -346,7 +346,7 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
node_graph,
preferences,
viewport,
persistent_data,
cached_data,
};
if matches!(tool_message, ToolMessage::UpdateHints) {
if graph_view_overlay_open {
@@ -395,7 +395,7 @@ impl Fsm for ArtboardToolFsmState {
location: start.min(end).round().as_ivec2(),
dimensions: (start.round() - end.round()).abs().as_ivec2(),
background: graphene_std::Color::WHITE,
clip: false,
clip: true,
},
})
}
@@ -9,7 +9,7 @@ use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
use crate::messages::tool::common_functionality::graph_modification_utils::{NodeGraphLayer, get_gradient};
use crate::messages::tool::common_functionality::snapping::{SnapCandidatePoint, SnapConstraint, SnapData, SnapManager, SnapTypeConfiguration};
use graphene_std::raster::color::Color;
use graphene_std::vector::style::{Fill, Gradient, GradientStops, GradientType};
use graphene_std::vector::style::{Fill, Gradient, GradientSpreadMethod, GradientStops, GradientType};
#[derive(Default, ExtractField)]
pub struct GradientTool {
@@ -21,6 +21,7 @@ pub struct GradientTool {
#[derive(Default)]
pub struct GradientOptions {
gradient_type: GradientType,
spread_method: GradientSpreadMethod,
}
#[impl_message(Message, ToolMessage, Gradient)]
@@ -53,6 +54,7 @@ pub enum GradientOptionsUpdate {
Type(GradientType),
ReverseStops,
ReverseDirection,
SetSpreadMethod(GradientSpreadMethod),
}
impl ToolMetadata for GradientTool {
@@ -84,6 +86,10 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Grad
GradientOptionsUpdate::ReverseDirection => {
apply_gradient_update(&mut self.data, context, responses, |_| true, |g| std::mem::swap(&mut g.start, &mut g.end));
}
GradientOptionsUpdate::SetSpreadMethod(spread_method) => {
self.options.spread_method = spread_method;
apply_gradient_update(&mut self.data, context, responses, |g| g.spread_method != spread_method, |g| g.spread_method = spread_method);
}
},
ToolMessage::Gradient(GradientToolMessage::StartTransactionForColorStop) => {
if self.data.color_picker_transaction_open {
@@ -123,6 +129,22 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Grad
self.data.has_selected_gradient = has_gradient;
responses.add(ToolMessage::RefreshToolOptions);
}
// Sync tool options with the selected layer's gradient
if has_gradient && let Some(gradient) = get_gradient_on_selected_layer(&context.document) {
let type_differs = self.options.gradient_type != gradient.gradient_type;
let spread_method_differs = self.options.spread_method != gradient.spread_method;
if type_differs {
self.options.gradient_type = gradient.gradient_type;
}
if spread_method_differs {
self.options.spread_method = gradient.spread_method;
}
if type_differs || spread_method_differs {
responses.add(ToolMessage::RefreshToolOptions);
}
};
}
}
}
@@ -168,7 +190,36 @@ impl LayoutHolder for GradientTool {
})
.widget_instance();
let mut widgets = vec![gradient_type, Separator::new(SeparatorStyle::Unrelated).widget_instance(), reverse_stops];
let spread_method = RadioInput::new(vec![
RadioEntryData::new("Pad").label("Pad").tooltip_label("Pad").on_update(move |_| {
GradientToolMessage::UpdateOptions {
options: GradientOptionsUpdate::SetSpreadMethod(GradientSpreadMethod::Pad),
}
.into()
}),
RadioEntryData::new("Reflect").label("Reflect").tooltip_label("Reflect").on_update(move |_| {
GradientToolMessage::UpdateOptions {
options: GradientOptionsUpdate::SetSpreadMethod(GradientSpreadMethod::Reflect),
}
.into()
}),
RadioEntryData::new("Repeat").label("Repeat").tooltip_label("Repeat").on_update(move |_| {
GradientToolMessage::UpdateOptions {
options: GradientOptionsUpdate::SetSpreadMethod(GradientSpreadMethod::Repeat),
}
.into()
}),
])
.selected_index(Some(self.options.spread_method as u32))
.widget_instance();
let mut widgets = vec![
gradient_type,
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
spread_method,
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
reverse_stops,
];
if self.options.gradient_type == GradientType::Radial {
let orientation = self
@@ -1149,7 +1200,14 @@ impl Fsm for GradientToolFsmState {
gradient.clone()
} else {
// Generate a new gradient
Gradient::new(DVec2::ZERO, global_tool_data.secondary_color, DVec2::ONE, global_tool_data.primary_color, tool_options.gradient_type)
Gradient::new(
DVec2::ZERO,
global_tool_data.secondary_color,
DVec2::ONE,
global_tool_data.primary_color,
tool_options.gradient_type,
tool_options.spread_method,
)
};
let mut selected_gradient = SelectedGradient::new(gradient, layer, document);
selected_gradient.dragging = GradientDragTarget::New;
@@ -1501,12 +1559,16 @@ fn apply_gradient_update(
responses.add(ToolMessage::RefreshToolOptions);
}
fn has_gradient_on_selected_layers(document: &DocumentMessageHandler) -> bool {
fn get_gradient_on_selected_layer(document: &DocumentMessageHandler) -> Option<Gradient> {
document
.network_interface
.selected_nodes()
.selected_visible_layers(&document.network_interface)
.any(|layer| get_gradient(layer, &document.network_interface).is_some())
.find_map(|layer| get_gradient(layer, &document.network_interface))
}
fn has_gradient_on_selected_layers(document: &DocumentMessageHandler) -> bool {
get_gradient_on_selected_layer(document).is_some()
}
#[inline(always)]
@@ -1941,4 +2003,38 @@ mod test_gradient {
// Additional verification that 0.75 stop is gone
assert!(!final_positions.iter().any(|pos| (pos - 0.75).abs() < 0.05), "Stop at position 0.75 should have been deleted");
}
#[tokio::test]
async fn change_spread_method() {
use graphene_std::vector::style::GradientSpreadMethod;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
editor.drag_tool(ToolType::Gradient, 10., 10., 90., 90., ModifierKeys::empty()).await;
// Verify default spread method is Pad
let (gradient, _) = get_gradient(&mut editor).await;
assert_eq!(gradient.spread_method, GradientSpreadMethod::Pad);
// Update spread method to Repeat
editor
.handle_message(GradientToolMessage::UpdateOptions {
options: GradientOptionsUpdate::SetSpreadMethod(GradientSpreadMethod::Repeat),
})
.await;
let (gradient, _) = get_gradient(&mut editor).await;
assert_eq!(gradient.spread_method, GradientSpreadMethod::Repeat);
// Update spread method to Reflect
editor
.handle_message(GradientToolMessage::UpdateOptions {
options: GradientOptionsUpdate::SetSpreadMethod(GradientSpreadMethod::Reflect),
})
.await;
let (gradient, _) = get_gradient(&mut editor).await;
assert_eq!(gradient.spread_method, GradientSpreadMethod::Reflect);
}
}
@@ -798,6 +798,11 @@ impl PathToolData {
self.saved_selection_before_handle_drag = old_selection;
}
if handle_drag_from_anchor && dragging_only_handles {
// Alt held at drag start on a handle: break colinearity (make the handle sharp)
shape_editor.disable_colinear_handles_state_on_selected(&document.network_interface, responses);
}
if handle_drag_from_anchor && let Some((layer, point)) = shape_editor.find_nearest_point_indices(&document.network_interface, input.mouse.position, SELECTION_THRESHOLD) {
// Check that selected point is an anchor
if let (Some(point_id), Some(vector)) = (point.as_anchor(), document.network_interface.compute_modified_vector(layer)) {
@@ -605,7 +605,7 @@ impl Fsm for SelectToolFsmState {
document,
input,
viewport,
persistent_data,
cached_data,
..
} = tool_action_data;
@@ -632,7 +632,7 @@ impl Fsm for SelectToolFsmState {
overlay_context.outline(document.metadata().layer_with_free_points_outline(layer), layer_to_viewport, None);
if is_layer_fed_by_node_of_name(layer, &document.network_interface, &DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER)) {
let transformed_quad = layer_to_viewport * text_bounding_box(layer, document, &persistent_data.font_cache);
let transformed_quad = layer_to_viewport * text_bounding_box(layer, document, &cached_data.font_cache);
overlay_context.dashed_quad(transformed_quad, None, None, Some(7.), Some(5.), None);
}
}
@@ -7,7 +7,7 @@ use crate::messages::portfolio::document::node_graph::document_node_definitions:
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
use crate::messages::portfolio::utility_types::{FontCatalog, FontCatalogStyle, PersistentData};
use crate::messages::portfolio::utility_types::{CachedData, FontCatalog, FontCatalogStyle};
use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
use crate::messages::tool::common_functionality::color_selector::{ToolColorOptions, ToolColorType};
use crate::messages::tool::common_functionality::graph_modification_utils::{self, is_layer_fed_by_node_of_name};
@@ -230,8 +230,8 @@ fn create_text_widgets(tool: &TextTool, font_catalog: &FontCatalog) -> Vec<Widge
}
impl ToolRefreshOptions for TextTool {
fn refresh_options(&self, responses: &mut VecDeque<Message>, persistent_data: &PersistentData) {
self.send_layout(responses, LayoutTarget::ToolOptions, &persistent_data.font_catalog);
fn refresh_options(&self, responses: &mut VecDeque<Message>, cached_data: &CachedData) {
self.send_layout(responses, LayoutTarget::ToolOptions, &cached_data.font_catalog);
}
}
@@ -302,7 +302,7 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Text
}
}
self.send_layout(responses, LayoutTarget::ToolOptions, &context.persistent_data.font_catalog);
self.send_layout(responses, LayoutTarget::ToolOptions, &context.cached_data.font_catalog);
}
fn actions(&self) -> ActionList {
@@ -573,11 +573,11 @@ impl Fsm for TextToolFsmState {
document,
global_tool_data,
input,
persistent_data,
cached_data,
viewport,
..
} = transition_data;
let font_cache = &persistent_data.font_cache;
let font_cache = &cached_data.font_cache;
let fill_color = COLOR_OVERLAY_BLUE_05;
let ToolMessage::Text(event) = event else { return self };
+4 -4
View File
@@ -9,7 +9,7 @@ use crate::messages::input_mapper::utility_types::macros::action_shortcut;
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::overlays::utility_types::OverlayProvider;
use crate::messages::portfolio::utility_types::PersistentData;
use crate::messages::portfolio::utility_types::CachedData;
use crate::messages::preferences::PreferencesMessageHandler;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::shapes::shape_utility::ShapeType;
@@ -24,7 +24,7 @@ pub struct ToolActionMessageContext<'a> {
pub document_id: DocumentId,
pub global_tool_data: &'a DocumentToolData,
pub input: &'a InputPreprocessorMessageHandler,
pub persistent_data: &'a PersistentData,
pub cached_data: &'a CachedData,
pub shape_editor: &'a mut ShapeState,
pub node_graph: &'a NodeGraphExecutor,
pub preferences: &'a PreferencesMessageHandler,
@@ -37,11 +37,11 @@ impl<T> ToolCommon for T where T: for<'a, 'b> MessageHandler<ToolMessage, &'b mu
type Tool = dyn ToolCommon + Send + Sync;
pub trait ToolRefreshOptions {
fn refresh_options(&self, responses: &mut VecDeque<Message>, _persistent_data: &PersistentData);
fn refresh_options(&self, responses: &mut VecDeque<Message>, _cached_data: &CachedData);
}
impl<T: LayoutHolder> ToolRefreshOptions for T {
fn refresh_options(&self, responses: &mut VecDeque<Message>, _persistent_data: &PersistentData) {
fn refresh_options(&self, responses: &mut VecDeque<Message>, _cached_data: &CachedData) {
self.send_layout(responses, LayoutTarget::ToolOptions);
}
}
+20 -16
View File
@@ -1,17 +1,16 @@
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use crate::messages::prelude::*;
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::document::value::{RenderOutput, TaggedValue};
use graph_craft::application_io::EditorPreferences;
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
use graph_craft::proto::GraphErrors;
use graph_craft::wasm_application_io::EditorPreferences;
use graphene_std::application_io::{NodeGraphUpdateMessage, RenderConfig, TimingInformation};
use graphene_std::raster::{CPU, Raster};
use graphene_std::renderer::{RenderMetadata, format_transform_matrix};
use graphene_std::renderer::RenderMetadata;
use graphene_std::text::FontCache;
use graphene_std::transform::Footprint;
use graphene_std::vector::Vector;
use graphene_std::wasm_application_io::RenderOutputType;
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
mod runtime_io;
@@ -154,7 +153,6 @@ impl NodeGraphExecutor {
pointer,
export_format: graphene_std::application_io::ExportFormat::Raster,
render_mode: document.render_mode,
hide_artboards: false,
for_export: false,
for_eyedropper: false,
};
@@ -219,7 +217,6 @@ impl NodeGraphExecutor {
pointer,
export_format: graphene_std::application_io::ExportFormat::Raster,
render_mode,
hide_artboards: false,
for_export: false,
for_eyedropper: true,
};
@@ -242,10 +239,10 @@ impl NodeGraphExecutor {
graphene_std::application_io::ExportFormat::Raster
};
// Calculate the bounding box of the region to be exported
// Calculate the bounding box of the region to be exported (artboard bounds always contribute)
let bounds = match export_config.bounds {
ExportBounds::AllArtwork => document.network_interface.document_bounds_document_space(!export_config.transparent_background),
ExportBounds::Selection => document.network_interface.selected_bounds_document_space(!export_config.transparent_background, &[]),
ExportBounds::AllArtwork => document.network_interface.document_bounds_document_space(true),
ExportBounds::Selection => document.network_interface.selected_bounds_document_space(true, &[]),
ExportBounds::Artboard(id) => document.metadata().bounding_box_document(id),
}
.ok_or_else(|| "No bounding box".to_string())?;
@@ -267,7 +264,6 @@ impl NodeGraphExecutor {
pointer: DVec2::ZERO,
export_format,
render_mode: document.render_mode,
hide_artboards: export_config.transparent_background,
for_export: true,
for_eyedropper: false,
};
@@ -380,6 +376,7 @@ impl NodeGraphExecutor {
let (data, width, height) = raster.to_flat_u8();
responses.add(EyedropperToolMessage::PreviewImage { data, width, height });
}
NodeGraphUpdate::NodeGraphUpdateMessage(_) => {}
}
}
@@ -397,12 +394,11 @@ impl NodeGraphExecutor {
responses.add(FrontendMessage::UpdateImageData { image_data });
responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
}
RenderOutputType::CanvasFrame(frame) => {
let matrix = format_transform_matrix(frame.transform);
let transform = if matrix.is_empty() { String::new() } else { format!(" transform=\"{matrix}\"") };
#[cfg(target_family = "wasm")]
RenderOutputType::CanvasFrame { canvas_id, resolution } => {
let svg = format!(
r#"<svg><foreignObject width="{}" height="{}"{transform}><div data-canvas-placeholder="{}" data-is-viewport="true"></div></foreignObject></svg>"#,
frame.resolution.x, frame.resolution.y, frame.surface_id.0,
r#"<svg><foreignObject width="{}" height="{}"><div data-canvas-placeholder="{}" data-is-viewport="true"></div></foreignObject></svg>"#,
resolution.x, resolution.y, canvas_id,
);
responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
}
@@ -482,7 +478,7 @@ impl NodeGraphExecutor {
use image::buffer::ConvertBuffer;
use image::{ImageFormat, RgbImage, RgbaImage};
let Some(image) = RgbaImage::from_raw(width, height, data) else {
let Some(mut image) = RgbaImage::from_raw(width, height, data) else {
return Err("Failed to create image buffer for export".to_string());
};
@@ -497,6 +493,14 @@ impl NodeGraphExecutor {
}
}
FileType::Jpg => {
// Composite onto a white background since JPG doesn't support transparency
for pixel in image.pixels_mut() {
let [r, g, b, a] = pixel.0;
let alpha = a as f32 / 255.;
let blend = |channel: u8| (channel as f32 * alpha + 255. * (1. - alpha)).round() as u8;
*pixel = image::Rgba([blend(r), blend(g), blend(b), 255]);
}
let image: RgbImage = image.convert();
let result = image.write_to(&mut cursor, ImageFormat::Jpeg);
if let Err(err) = result {
+29 -93
View File
@@ -1,25 +1,25 @@
use super::*;
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use glam::{DAffine2, UVec2};
use graph_craft::document::value::TaggedValue;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_craft::document::{NodeId, NodeNetwork};
use graph_craft::graphene_compiler::Compiler;
use graph_craft::proto::GraphErrors;
use graph_craft::wasm_application_io::EditorPreferences;
use graph_craft::{ProtoNodeIdentifier, concrete};
use graphene_std::application_io::{ApplicationIo, ExportFormat, ImageTexture, NodeGraphUpdateMessage, NodeGraphUpdateSender, RenderConfig};
use graphene_std::bounds::RenderBoundingBox;
use graphene_std::memo::IORecord;
use graphene_std::ops::Convert;
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle};
use graphene_std::raster_types::Raster;
use graphene_std::renderer::{Render, RenderParams, SvgRender};
use graphene_std::renderer::{RenderSvgSegmentList, SvgSegment};
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender, SvgSegment};
use graphene_std::table::{Table, TableRow};
use graphene_std::text::FontCache;
use graphene_std::transform::RenderQuality;
use graphene_std::vector::Vector;
use graphene_std::vector::style::RenderMode;
use graphene_std::wasm_application_io::{RenderOutputType, WasmApplicationIo, WasmEditorApi};
use graphene_std::{Artboard, Context, Graphic};
use interpreted_executor::dynamic_executor::{DynamicExecutor, IntrospectError, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::util::wrap_network_in_scope;
@@ -28,7 +28,7 @@ use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender};
/// Persistent data between graph executions. It's updated via message passing from the editor thread with [`GraphRuntimeRequest`]`.
/// Some of these fields are put into a [`WasmEditorApi`] which is passed to the final compiled graph network upon each execution.
/// Some of these fields are put into a [`PlatformEditorApi`] which is passed to the final compiled graph network upon each execution.
/// Once the implementation is finished, this will live in a separate thread. Right now it's part of the main JS thread, but its own separate JS stack frame independent from the editor.
pub struct NodeRuntime {
#[cfg(test)]
@@ -41,7 +41,7 @@ pub struct NodeRuntime {
old_graph: Option<NodeNetwork>,
update_thumbnails: bool,
editor_api: Arc<WasmEditorApi>,
editor_api: Arc<PlatformEditorApi>,
node_graph_errors: GraphErrors,
monitor_nodes: Vec<Vec<NodeId>>,
@@ -57,10 +57,10 @@ pub struct NodeRuntime {
vector_modify: HashMap<NodeId, Vector>,
/// Cached surface for Wasm viewport rendering (reused across frames)
#[cfg(all(target_family = "wasm", feature = "gpu"))]
wasm_viewport_surface: Option<wgpu_executor::WgpuSurface>,
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
wasm_canvas_cache: CanvasSurfaceHandle,
/// Currently displayed texture, the runtime keeps a reference to it to avoid the texture getting destroyed while it is still in use.
#[cfg(all(target_family = "wasm", feature = "gpu"))]
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
current_viewport_texture: Option<ImageTexture>,
}
@@ -86,7 +86,6 @@ pub struct ExportConfig {
pub file_type: FileType,
pub scale_factor: f64,
pub bounds: ExportBounds,
pub transparent_background: bool,
pub size: UVec2,
pub artboard_name: Option<String>,
pub artboard_count: usize,
@@ -128,7 +127,7 @@ impl NodeRuntime {
old_graph: None,
update_thumbnails: true,
editor_api: WasmEditorApi {
editor_api: PlatformEditorApi {
font_cache: FontCache::default(),
editor_preferences: Box::new(EditorPreferences::default()),
node_graph_message_sender: Box::new(InternalNodeGraphUpdateSender(sender)),
@@ -146,7 +145,7 @@ impl NodeRuntime {
vector_modify: Default::default(),
inspect_state: None,
#[cfg(all(target_family = "wasm", feature = "gpu"))]
wasm_viewport_surface: None,
wasm_canvas_cache: CanvasSurfaceHandle::new(),
#[cfg(all(target_family = "wasm", feature = "gpu"))]
current_viewport_texture: None,
}
@@ -154,11 +153,11 @@ impl NodeRuntime {
pub async fn run(&mut self) -> Option<ImageTexture> {
if self.editor_api.application_io.is_none() {
self.editor_api = WasmEditorApi {
self.editor_api = PlatformEditorApi {
#[cfg(all(not(test), target_family = "wasm"))]
application_io: Some(WasmApplicationIo::new().await.into()),
application_io: Some(PlatformApplicationIo::new().await.into()),
#[cfg(any(test, not(target_family = "wasm")))]
application_io: Some(WasmApplicationIo::new_offscreen().await.into()),
application_io: Some(PlatformApplicationIo::new().await.into()),
font_cache: self.editor_api.font_cache.clone(),
node_graph_message_sender: Box::new(self.sender.clone()),
editor_preferences: Box::new(self.editor_preferences.clone()),
@@ -208,7 +207,7 @@ impl NodeRuntime {
for request in requests {
match request {
GraphRuntimeRequest::FontCacheUpdate(font_cache) => {
self.editor_api = WasmEditorApi {
self.editor_api = PlatformEditorApi {
font_cache,
application_io: self.editor_api.application_io.clone(),
node_graph_message_sender: Box::new(self.sender.clone()),
@@ -222,7 +221,7 @@ impl NodeRuntime {
}
GraphRuntimeRequest::EditorPreferencesUpdate(preferences) => {
self.editor_preferences = preferences.clone();
self.editor_api = WasmEditorApi {
self.editor_api = PlatformEditorApi {
font_cache: self.editor_api.font_cache.clone(),
application_io: self.editor_api.application_io.clone(),
node_graph_message_sender: Box::new(self.sender.clone()),
@@ -280,7 +279,7 @@ impl NodeRuntime {
.gpu_executor()
.expect("GPU executor should be available when we receive a texture");
let raster_cpu = Raster::new_gpu(image_texture.texture.as_ref().clone()).convert(Footprint::BOUNDLESS, executor).await;
let raster_cpu = Raster::new_gpu(image_texture.as_ref().clone()).convert(Footprint::BOUNDLESS, executor).await;
let (data, width, height) = raster_cpu.to_flat_u8();
@@ -304,7 +303,7 @@ impl NodeRuntime {
.gpu_executor()
.expect("GPU executor should be available when we receive a texture");
let raster_cpu = Raster::new_gpu(image_texture.texture.as_ref().clone()).convert(Footprint::BOUNDLESS, executor).await;
let raster_cpu = Raster::new_gpu(image_texture.as_ref().clone()).convert(Footprint::BOUNDLESS, executor).await;
self.sender.send_eyedropper_preview(raster_cpu);
continue;
@@ -318,83 +317,20 @@ impl NodeRuntime {
data: RenderOutputType::Texture(image_texture),
metadata,
})) if !render_config.for_export => {
// On Wasm, for viewport rendering, blit the texture to a surface and return a CanvasFrame
self.current_viewport_texture = Some(image_texture.clone());
let app_io = self.editor_api.application_io.as_ref().unwrap();
let executor = app_io.gpu_executor().expect("GPU executor should be available when we receive a texture");
// Get or create the cached surface
if self.wasm_viewport_surface.is_none() {
let surface_handle = app_io.create_window();
let wasm_surface = executor
.create_surface(graphene_std::wasm_application_io::WasmSurfaceHandle {
surface: surface_handle.surface.clone(),
window_id: surface_handle.window_id,
})
.expect("Failed to create surface");
self.wasm_viewport_surface = Some(Arc::new(wasm_surface));
}
let surface = self.wasm_viewport_surface.as_ref().unwrap();
// Use logical resolution for CSS sizing, physical resolution for the actual surface/texture
let physical_resolution = render_config.viewport.resolution;
let logical_resolution = physical_resolution.as_dvec2() / render_config.scale;
// Blit the texture to the surface
let mut encoder = executor.context.device.create_command_encoder(&vello::wgpu::CommandEncoderDescriptor {
label: Some("Texture to Surface Blit"),
});
// Configure the surface at physical resolution (for HiDPI displays)
let surface_inner = &surface.surface.inner;
let surface_caps = surface_inner.get_capabilities(&executor.context.adapter);
surface_inner.configure(
&executor.context.device,
&vello::wgpu::SurfaceConfiguration {
usage: vello::wgpu::TextureUsages::RENDER_ATTACHMENT | vello::wgpu::TextureUsages::COPY_DST,
format: vello::wgpu::TextureFormat::Rgba8Unorm,
width: physical_resolution.x,
height: physical_resolution.y,
present_mode: surface_caps.present_modes[0],
alpha_mode: vello::wgpu::CompositeAlphaMode::PreMultiplied,
view_formats: vec![],
desired_maximum_frame_latency: 2,
},
);
let surface_texture = surface_inner.get_current_texture().expect("Failed to get surface texture");
self.current_viewport_texture = Some(image_texture.clone());
encoder.copy_texture_to_texture(
vello::wgpu::TexelCopyTextureInfoBase {
texture: image_texture.texture.as_ref(),
mip_level: 0,
origin: Default::default(),
aspect: Default::default(),
},
vello::wgpu::TexelCopyTextureInfoBase {
texture: &surface_texture.texture,
mip_level: 0,
origin: Default::default(),
aspect: Default::default(),
},
image_texture.texture.size(),
);
executor.context.queue.submit([encoder.finish()]);
surface_texture.present();
// TODO: Figure out if we can explicityl destroy the wgpu texture here to reduce the allocation pressure. We might also be able to use a texture allocation pool
let frame = graphene_std::application_io::SurfaceFrame {
surface_id: surface.window_id,
resolution: logical_resolution,
transform: glam::DAffine2::IDENTITY,
};
self.wasm_canvas_cache.present(&image_texture, executor);
let logical_resolution = render_config.viewport.resolution.as_dvec2() / render_config.scale;
(
Ok(TaggedValue::RenderOutput(RenderOutput {
data: RenderOutputType::CanvasFrame(frame),
data: RenderOutputType::CanvasFrame {
canvas_id: self.wasm_canvas_cache.id(),
resolution: logical_resolution,
},
metadata,
})),
None,
@@ -592,10 +528,10 @@ pub async fn replace_node_runtime(runtime: NodeRuntime) -> Option<NodeRuntime> {
let mut node_runtime = NODE_RUNTIME.lock();
node_runtime.replace(runtime)
}
pub async fn replace_application_io(application_io: WasmApplicationIo) {
pub async fn replace_application_io(application_io: PlatformApplicationIo) {
let mut node_runtime = NODE_RUNTIME.lock();
if let Some(node_runtime) = &mut *node_runtime {
node_runtime.editor_api = WasmEditorApi {
node_runtime.editor_api = PlatformEditorApi {
font_cache: node_runtime.editor_api.font_cache.clone(),
application_io: Some(application_io.into()),
node_graph_message_sender: Box::new(node_runtime.sender.clone()),
+4 -4
View File
@@ -36,15 +36,15 @@ impl EditorTestUtils {
async fn run<'a>(editor: &'a mut Editor, runtime: &'a mut NodeRuntime) -> Result<Instrumented, String> {
let portfolio = &mut editor.dispatcher.message_handlers.portfolio_message_handler;
let document_id = portfolio.active_document_id.unwrap();
let exector = &mut portfolio.executor;
let document = portfolio.documents.get_mut(&document_id).unwrap();
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap();
let instrumented = match exector.update_node_graph_instrumented(document) {
let instrumented = match executor.update_node_graph_instrumented(document) {
Ok(instrumented) => instrumented,
Err(e) => return Err(format!("update_node_graph_instrumented failed\n\n{e}")),
};
if let Err(e) = exector.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
return Err(format!("submit_current_node_graph_evaluation failed\n\n{e}"));
}
runtime.run().await;
Generated
+9 -9
View File
@@ -2,11 +2,11 @@
"nodes": {
"crane": {
"locked": {
"lastModified": 1770169865,
"narHash": "sha256-iPiy13xzDQ9GjpOez+NNIjh/qjl7i4RDf9dF2x5mF9I=",
"lastModified": 1776635034,
"narHash": "sha256-OEOJrT3ZfwbChzODfIH4GzlNTtOFuZFWPtW7jIeR8xU=",
"owner": "ipetkov",
"repo": "crane",
"rev": "8254ccf3b5b5131890ee073776f2e61c6d1e55d4",
"rev": "dc7496d8ea6e526b1254b55d09b966e94673750f",
"type": "github"
},
"original": {
@@ -17,11 +17,11 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1770197578,
"narHash": "sha256-AYqlWrX09+HvGs8zM6ebZ1pwUqjkfpnv8mewYwAo+iM=",
"lastModified": 1776548001,
"narHash": "sha256-ZSK0NL4a1BwVbbTBoSnWgbJy9HeZFXLYQizjb2DPF24=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "00c21e4c93d963c50d4c0c89bfa84ed6e0694df2",
"rev": "b12141ef619e0a9c1c84dc8c684040326f27cdcc",
"type": "github"
},
"original": {
@@ -45,11 +45,11 @@
]
},
"locked": {
"lastModified": 1770347142,
"narHash": "sha256-uz+ZSqXpXEPtdRPYwvgsum/CfNq7AUQ/0gZHqTigiPM=",
"lastModified": 1776741231,
"narHash": "sha256-k9G98qzn+7npROUaks8VqCFm7cFtEG8ulQLBBo5lItg=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "2859683cd9ef7858d324c5399b0d8d6652bf4044",
"rev": "02061303f7c4c964f7b4584dabd9e985b4cd442b",
"type": "github"
},
"original": {
+3 -1
View File
@@ -12,9 +12,11 @@
<meta name="apple-mobile-web-app-title" content="Graphite" />
<meta name="application-name" content="Graphite" />
<meta name="msapplication-TileColor" content="#ffffff" />
<meta name="theme-color" content="#ffffff" />
<meta name="theme-color" content="#222222" />
<meta name="color-scheme" content="dark only" />
<meta name="darkreader-lock" />
<meta name="description" content="Graphite is an open source vector graphics editor and procedural design engine. Create and animate with a nondestructive editing workflow that combines layer-based compositing with node-based generative design." />
<meta name="mobile-web-app-capable" content="yes">
<!-- INDEX_HTML_HEAD_REPLACEMENT -->
</head>
<body>
+267 -962
View File
File diff suppressed because it is too large. Load diff
+10 -11
View File
@@ -27,6 +27,7 @@
"wasm:watch-production": "cargo watch --postpone --watch-when-idle --workdir=wrapper --shell \"wasm-pack build . --release --target=web -- --color=always\""
},
"//": "NOTE: `source-sans-pro` is never to be upgraded to 3.x because that renders 1px above its intended position.",
"///": "Waiting on <https://github.com/import-js/eslint-plugin-import/issues/3227> before we can update @eslint/js and eslint to 10.x",
"dependencies": {
"source-code-pro": "2.42.0",
"source-sans-pro": "2.45.0"
@@ -34,26 +35,24 @@
"devDependencies": {
"@eslint/js": "^9.39.2",
"@sveltejs/vite-plugin-svelte": "^7.0.0",
"@types/node": "^25.5.0",
"@types/node": "^25.5.2",
"concurrently": "^9.2.1",
"eslint": "^9.39.2",
"eslint-import-resolver-typescript": "^4.4.4",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-prettier": "^5.5.5",
"eslint-plugin-svelte": "^3.16.0",
"eslint-plugin-svelte": "^3.17.0",
"globals": "^17.4.0",
"license-checker-rseidelsohn": "^4.4.2",
"prettier": "^3.8.1",
"prettier-plugin-svelte": "^3.5.1",
"sass": "^1.98.0",
"svelte": "^5.54.1",
"svelte-check": "^4.4.5",
"svelte-preprocess": "^6.0.3",
"tar": "^7.5.12",
"typescript": "^5.9.3",
"typescript-eslint": "^8.57.1",
"vite": "^8.0.1",
"vite-multiple-assets": "2.2.6"
"sass": "^1.99.0",
"svelte": "^5.55.1",
"svelte-check": "^4.4.6",
"tar": "^7.5.13",
"typescript": "^6.0.2",
"typescript-eslint": "^8.58.0",
"vite": "^8.0.3"
},
"homepage": "https://graphite.art",
"license": "Apache-2.0",
+1 -1
View File
@@ -75,7 +75,7 @@
<MainWindow />
<style lang="scss" global>
<style lang="scss">
// Disable the spinning loading indicator
body::before,
body::after {
@@ -28,7 +28,6 @@
colorEquals,
gradientFirstColor,
} from "/src/utility-functions/colors";
import { isPlatformNative } from "/wrapper/pkg/graphite_wasm_wrapper";
import type { FillChoice, MenuDirection, Color } from "/wrapper/pkg/graphite_wasm_wrapper";
type PresetColors = "None" | "Black" | "White" | "Red" | "Yellow" | "Green" | "Cyan" | "Blue" | "Magenta";
@@ -404,7 +403,7 @@
// TODO: Replace this temporary usage of the browser eyedropper API, that only works in Chromium-based browsers, with the custom color sampler system used by the Eyedropper tool
function eyedropperSupported(): boolean {
// TODO: Implement support in the desktop app for OS-level color picking
if (isPlatformNative()) return false;
if (import.meta.env.MODE === "native") return false;
return window.EyeDropper !== undefined;
}
@@ -733,7 +732,7 @@
</LayoutRow>
</FloatingMenu>
<style lang="scss" global>
<style lang="scss">
.color-picker {
--widget-height: 24px;
--picker-size: 256px;
@@ -73,7 +73,7 @@
</LayoutRow>
</FloatingMenu>
<style lang="scss" global>
<style lang="scss">
.dialog {
position: absolute;
pointer-events: none;
Loaded 100 of 225 files, more files were not shown because too many files have changed in this diff. Show more