Compare commits

..
225 changed files with 5510 additions and 8212 deletions

No files matched your search

+2 -2
View File
@@ -1,2 +1,2 @@
https://github.com/Keavon/graphite-branded-assets/archive/1509880500e32cb21235343ba865adcf0579133f.tar.gz
89b4c58aee186b0c1610a8778bd199c9bdaf1191b4006e6b007dc40a402f4aa7
https://github.com/Keavon/graphite-branded-assets/archive/8ae15dc9c51a3855475d8cab1d0f29d9d9bc622c.tar.gz
c19abe4ac848f3c835e43dc065c59e20e60233ae023ea0a064c5fed442be2d3d
+12 -19
View File
@@ -20,6 +20,9 @@ on:
linux:
description: "Linux"
type: boolean
push_to_nix_cache:
description: "Linux: push to Nix cache"
type: boolean
debug:
description: "Debug build"
type: boolean
@@ -33,6 +36,8 @@ on:
type: boolean
linux:
type: boolean
push_to_nix_cache:
type: boolean
debug:
type: boolean
checkout_repo:
@@ -157,7 +162,7 @@ jobs:
REF="master"
ENVIRONMENT="graphite-dev (Production)"
else
REF="$(git rev-parse HEAD)"
REF="${{ inputs.checkout_ref || github.head_ref || github.ref_name }}"
ENVIRONMENT="graphite-dev (Preview)"
fi
DEPLOY_ID=$(gh api \
@@ -634,35 +639,23 @@ 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 --print-build-logs
run: nix build .#graphite${{ inputs.debug && '-dev' || '' }} --no-link --print-out-paths
- name: 📤 Push to Nix cache
if: (github.event_name == 'push' || inputs.push_to_nix_cache) && !inputs.debug
env:
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' }}
NIX_CACHE_AUTH_TOKEN: ${{ secrets.NIX_CACHE_AUTH_TOKEN }}
run: |
nix run nixpkgs#cachix -- authtoken $NIX_CACHE_AUTH_TOKEN
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
nix build --no-link --print-out-paths | nix run nixpkgs#cachix -- push graphite
- name: 🏗 Build Linux bundle
run: nix build .#graphite-bundle${{ inputs.debug && '-dev' || '' }}.tar.xz && cp ./result ./graphite-linux-bundle.tar.xz
run: nix build .#graphite${{ inputs.debug && '-dev' || '' }}-bundle.tar.xz && cp ./result ./graphite-linux-bundle.tar.xz
- name: 📦 Upload Linux bundle
uses: actions/upload-artifact@v6
@@ -700,7 +693,7 @@ jobs:
- name: 🏗 Build Flatpak
run: |
nix build .#graphite-flatpak-manifest${{ inputs.debug && '-dev' || '' }}
nix build .#graphite${{ inputs.debug && '-dev' || '' }}-flatpak-manifest
rm -rf .flatpak
mkdir -p .flatpak
-51
View File
@@ -1,51 +0,0 @@
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
+3 -12
View File
@@ -17,10 +17,9 @@ 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: 💾 Set up Nix cache
uses: DeterminateSystems/magic-nix-cache-action@main
- name: 🏗 Build graphene raster nodes shaders
run: nix build .#graphite-raster-nodes-shaders && cp result raster_nodes_shaders_entrypoint.wgsl
@@ -35,11 +34,3 @@ 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
+6 -5
View File
@@ -31,6 +31,7 @@ let
deps = {
crane = lib.call ./deps/crane.nix;
cef = lib.call ./deps/cef.nix;
rustGPU = lib.call ./deps/rust-gpu.nix;
};
@@ -59,15 +60,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-bundle-dev = (lib.call ./pkgs/graphite-bundle.nix) { graphite = graphite-dev; };
graphite-dev-bundle = (lib.call ./pkgs/graphite-bundle.nix) { graphite = graphite-dev; };
graphite-flatpak-manifest = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { };
graphite-flatpak-manifest-dev = (lib.call ./pkgs/graphite-flatpak-manifest.nix) {
graphite-bundle = graphite-bundle-dev;
};
graphite-dev-flatpak-manifest = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { graphite-bundle = graphite-dev-bundle; };
# TODO: graphene-cli = lib.call ./pkgs/graphene-cli.nix;
graphite-cef = lib.call ./pkgs/graphite-cef/package.nix;
tools = {
third-party-licenses = lib.call ./pkgs/tools/third-party-licenses.nix;
};
}
);
+27
View File
@@ -0,0 +1,27 @@
{ 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;
}
+2 -25
View File
@@ -1,28 +1,5 @@
{
pkgs,
inputs,
...
}:
{ pkgs, inputs, ... }:
{
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;
});
};
lib = inputs.crane.mkLib pkgs;
}
+17 -14
View File
@@ -1,15 +1,16 @@
{ pkgs, ... }:
let
toolchain = pkgs.rust-bin.nightly."2026-04-11".default.override {
extensions = [
"rust-src"
"rust-analyzer"
"clippy"
"cargo"
"rustc-dev"
"llvm-tools"
];
extensions = [
"rust-src"
"rust-analyzer"
"clippy"
"cargo"
"rustc-dev"
"llvm-tools"
];
toolchain = pkgs.rust-bin.nightly."2025-06-23".default.override {
inherit extensions;
};
cargo = pkgs.writeShellScriptBin "cargo" ''
#!${pkgs.lib.getExe pkgs.bash}
@@ -31,12 +32,14 @@ let
}).buildRustPackage
(finalAttrs: {
pname = "rustc_codegen_spirv";
version = "0.10.0-alpha.1";
src = pkgs.fetchCrate {
inherit (finalAttrs) pname version;
sha256 = "sha256-zJEpExkPgYzwo7fR4ge4GxJNj7H5yo4bJ4eTOw36+7c=";
version = "0-unstable-2025-08-04";
src = pkgs.fetchFromGitHub {
owner = "Firestar99";
repo = "rust-gpu-new";
rev = "c12f216121820580731440ee79ebc7403d6ea04f";
hash = "sha256-rG1cZvOV0vYb1dETOzzbJ0asYdE039UZImobXZfKIno=";
};
cargoHash = "sha256-J1rtbfGqrL2NJ7Bu2pYfDwCdUmnECB/kzxrpYluA0kY=";
cargoHash = "sha256-AEigcEc5wiBd3zLqWN/2HSbkfOVFneAqNvg9HsouZf4=";
cargoBuildFlags = [
"-p"
"rustc_codegen_spirv"
+7 -12
View File
@@ -1,10 +1,4 @@
{
pkgs,
deps,
self,
system,
...
}:
{ pkgs, deps, ... }:
let
libs = [
@@ -28,6 +22,7 @@ pkgs.mkShell (
pkgs.lld
pkgs.nodejs
pkgs.nodePackages.npm
pkgs.binaryen
pkgs.wasm-bindgen-cli_0_2_100
pkgs.wasm-pack
@@ -57,13 +52,13 @@ pkgs.mkShell (
pkgs.graphviz
];
CEF_PATH = self.packages.${system}.graphite-cef;
LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libs}:${self.packages.${system}.graphite-cef}";
LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libs}:${deps.cef.env.CEF_PATH}";
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
)
+1 -2
View File
@@ -1,6 +1,5 @@
{
pkgs,
deps,
self,
system,
...
@@ -34,7 +33,7 @@ let
cp -r ${graphite}/share out/share
mkdir -p out/lib/cef
mkdir -p ./cef
tar -xvf ${self.packages.${system}.graphite-cef.src} -C ./cef --strip-components=1
tar -xvf ${pkgs.cef-binary.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
@@ -1,45 +0,0 @@
{ 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
@@ -1,7 +0,0 @@
{
"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,
self,
system,
...
}:
{ info, deps, ... }:
(deps.crane.lib.overrideToolchain (_: deps.rustGPU.toolchain)).buildPackage {
pname = "graphite-raster-nodes-shaders";
pname = "raster-nodes-shaders";
inherit (info) version src;
inherit (self.packages.${system}.graphite) cargoVendorDir cargoArtifacts;
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"
];
};
strictDeps = true;
+91 -79
View File
@@ -14,107 +14,125 @@
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;
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;
inherit cargoVendorDir;
strictDeps = true;
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";
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
// {
inherit cargoArtifacts;
cargoArtifacts = deps.crane.lib.buildDepsOnly common;
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
];
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";
};
npmDeps = pkgs.importNpmLock {
npmRoot = "${info.src}/frontend";
};
npmRoot = "frontend";
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
'';
nativeBuildInputs = [
pkgs.importNpmLock.npmConfigHook
pkgs.nodePackages.npm
]
++ common.nativeBuildInputs;
preBuild = ''
# 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"
${lib.getExe self.packages.${system}.tools.third-party-licenses}
''
+ (
if self ? rev then
@@ -125,10 +143,6 @@ 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
@@ -147,14 +161,12 @@ deps.crane.lib.buildPackage (
'';
postFixup = ''
remove-references-to -t "${common.cargoVendorDir}" $out/bin/graphite
remove-references-to -t "${cargoVendorDir}" $out/bin/graphite
patchelf \
--set-rpath "${pkgs.lib.makeLibraryPath libs}:${self.packages.${system}.graphite-cef}" \
--set-rpath "${pkgs.lib.makeLibraryPath libs}:${deps.cef.env.CEF_PATH}" \
--add-needed libGL.so \
$out/bin/graphite
'';
passthru.deps = cargoArtifacts;
}
)
+31
View File
@@ -0,0 +1,31 @@
{
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
+702 -239
View File
File diff suppressed because it is too large. Load diff
+12 -12
View File
@@ -89,8 +89,6 @@ 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"
@@ -115,7 +113,7 @@ quote = "1.0"
chrono = "0.4"
ron = "0.12"
fastnoise-lite = "1.1"
wgpu = { version = "28.0", features = [
wgpu = { version = "27.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",
@@ -149,8 +147,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.8"
vello_encoding = "0.8"
vello = "0.7"
vello_encoding = "0.7"
resvg = "0.47"
usvg = "0.47"
parley = "0.6"
@@ -159,7 +157,7 @@ polycool = "0.4"
# Linebender ecosystem (END)
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
rand_chacha = "0.9"
glam = { version = "0.32.1", default-features = false, features = [
glam = { version = "0.29", default-features = false, features = [
"nostd-libm",
"scalar-math",
"bytemuck",
@@ -197,17 +195,17 @@ iai-callgrind = { version = "0.16" }
ndarray = "0.16"
strum = { version = "0.27", features = ["derive"] }
dirs = "6.0"
cef = "146"
cef-dll-sys = "146"
cef = "142"
cef-dll-sys = "142"
include_dir = "0.7"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tracing = "0.1"
rfd = "0.17"
rfd = "0.15"
open = "5.3"
spin = "0.10"
clap = "4.5"
spirv-std = { version = "0.10.0-alpha.1", features = ["bytemuck"] }
cargo-gpu-install = { version = "0.10.0-alpha.1", default-features = false }
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 }
qrcodegen = "1.8"
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
scraper = "0.25"
@@ -238,4 +236,6 @@ debug = true
[patch.crates-io]
# Force cargo to use only one version of the dpi crate (vendoring breaks without this)
dpi = { git = "https://github.com/rust-windowing/winit.git" }
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
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" }
+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":[[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
{"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
+50 -17
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;
use crate::persist::PersistentData;
use crate::preferences;
use crate::render::{RenderError, RenderState};
use crate::window::Window;
@@ -45,6 +45,7 @@ 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,
@@ -91,6 +92,9 @@ impl App {
}
});
let mut persistent_data = PersistentData::default();
persistent_data.load_from_disk();
let desktop_wrapper = DesktopWrapper::new(rand::rng().random());
Self {
@@ -114,6 +118,7 @@ impl App {
start_render_sender,
web_communication_initialized: false,
web_communication_startup_buffer: Vec::new(),
persistent_data,
preferences,
cli,
startup_time: None,
@@ -279,24 +284,17 @@ impl App {
window.request_redraw();
}
}
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::PersistenceWriteDocument { id, document } => {
self.persistent_data.write_document(id, document);
}
DesktopFrontendMessage::PersistenceDeleteDocument { id } => {
persist::delete_document(&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);
}
DesktopFrontendMessage::PersistenceWritePreferences { preferences } => {
preferences::write(preferences);
@@ -306,6 +304,41 @@ 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;
+3 -34
View File
@@ -27,6 +27,7 @@ use crate::wrapper::{WgpuContext, deserialize_editor_message};
mod consts;
mod context;
mod dirs;
mod input;
mod internal;
mod ipc;
@@ -190,40 +191,8 @@ 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(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));
Ok(texture) => {
self.app_event_scheduler.schedule(AppEvent::UiUpdate(texture));
}
Err(e) => {
tracing::error!("Failed to import shared texture: {}", e);
+1 -2
View File
@@ -1,4 +1,3 @@
use graphite_desktop_wrapper::DOUBLE_CLICK_MILLISECONDS;
use std::time::Duration;
pub(crate) const RESOURCE_SCHEME: &str = "resources";
@@ -19,5 +18,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(DOUBLE_CLICK_MILLISECONDS);
pub(crate) const MULTICLICK_TIMEOUT: Duration = Duration::from_millis(500);
pub(crate) const MULTICLICK_ALLOWED_TRAVEL: usize = 4;
+20 -16
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;
use std::path::{Path, PathBuf};
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,7 +45,8 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
let args = Args::new();
let cmd = args.as_cmd_line().unwrap();
let is_sub_process = cmd.has_switch(Some(&"type".into())) == 1;
let switch = CefString::from("type");
let is_sub_process = cmd.has_switch(Some(&switch)) == 1;
Self {
args,
@@ -60,7 +61,8 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
pub(crate) fn execute_sub_process(&self) -> SetupError {
let cmd = self.args.as_cmd_line().unwrap();
let process_type = CefString::from(&cmd.switch_value(Some(&"type".into())));
let switch = CefString::from("type");
let process_type = CefString::from(&cmd.switch_value(Some(&switch)));
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 {
@@ -86,7 +88,7 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
Settings {
windowless_rendering_enabled: 1,
root_cache_path: instance_dir.to_str().map(CefString::from).unwrap(),
cache_path: "".into(),
cache_path: CefString::from(""),
disable_signal_handlers: 1,
log_severity,
..Default::default()
@@ -95,17 +97,18 @@ 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> {
let instance_dir = TempDir::new().expect("Failed to create temporary directory for CEF instance");
delete_instance_dirs();
let instance_dir = create_instance_dir();
let exe = std::env::current_exe().expect("cannot get current exe path");
let app_root = exe.parent().and_then(|p| p.parent()).expect("bad path structure").parent().expect("bad path structure");
let settings = Settings {
main_bundle_path: app_root.to_str().map(CefString::from).unwrap(),
main_bundle_path: CefString::from(app_root.to_str().unwrap()),
multi_threaded_message_loop: 0,
external_message_pump: 1,
no_sandbox: 1, // GPU helper crashes when running with sandbox
..Self::common_settings(instance_dir.as_ref())
..Self::common_settings(&instance_dir)
};
self.initialize_inner(&event_handler, settings)?;
@@ -115,13 +118,14 @@ 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> {
let instance_dir = TempDir::new().expect("Failed to create temporary directory for CEF instance");
delete_instance_dirs();
let instance_dir = create_instance_dir();
let settings = Settings {
multi_threaded_message_loop: 1,
#[cfg(target_os = "linux")]
no_sandbox: 1,
..Self::common_settings(instance_dir.as_ref())
..Self::common_settings(&instance_dir)
};
self.initialize_inner(&event_handler, settings)?;
@@ -153,7 +157,7 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
}
}
fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: TempDir, disable_gpu_acceleration: bool) -> Result<SingleThreadedCefContext, InitError> {
fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: PathBuf, disable_gpu_acceleration: bool) -> Result<SingleThreadedCefContext, InitError> {
let mut client = Client::new(BrowserProcessClientImpl::new(&event_handler));
#[cfg(feature = "accelerated_paint")]
@@ -179,7 +183,7 @@ fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: TempDir, d
let Some(mut incognito_request_context) = cef::request_context_create_context(
Some(&RequestContextSettings {
persist_session_cookies: 0,
cache_path: "".into(),
cache_path: CefString::from(""),
..Default::default()
}),
Option::<&mut cef::RequestContextHandler>::None,
@@ -189,14 +193,14 @@ fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: TempDir, 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(&RESOURCE_SCHEME.into()), Some(&RESOURCE_DOMAIN.into()), Some(&mut scheme_handler_factory));
incognito_request_context.register_scheme_handler_factory(Some(&CefString::from(RESOURCE_SCHEME)), Some(&CefString::from(RESOURCE_DOMAIN)), Some(&mut scheme_handler_factory));
let url = format!("{RESOURCE_SCHEME}://{RESOURCE_DOMAIN}/");
let url = CefString::from(format!("{RESOURCE_SCHEME}://{RESOURCE_DOMAIN}/").as_str());
let browser = browser_host_create_browser_sync(
Some(&window_info),
Some(&mut client),
Some(&url.as_str().into()),
Some(&url),
Some(&settings),
Option::<&mut DictionaryValue>::None,
Some(&mut incognito_request_context),
@@ -207,7 +211,7 @@ fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: TempDir, 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");
+1 -6
View File
@@ -54,12 +54,7 @@ impl CefContext for MultiThreadedCefContextProxy {
impl Drop for MultiThreadedCefContextProxy {
fn drop(&mut self) {
// Force dropping underlying context on the UI thread
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();
run_on_ui_thread(move || drop(CONTEXT.take()));
}
}
+15 -2
View File
@@ -4,7 +4,6 @@ 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;
@@ -12,7 +11,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: TempDir,
pub(super) instance_dir: std::path::PathBuf,
}
impl CefContext for SingleThreadedCefContext {
@@ -47,6 +46,19 @@ 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));
}
}
}
}
}
@@ -56,6 +68,7 @@ impl SendMessage for SingleThreadedCefContext {
tracing::error!("Main frame is not available, cannot send message");
return;
};
frame.send_message(message_type, message);
}
}
+24
View File
@@ -0,0 +1,24 @@
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
}
+33 -30
View File
@@ -133,46 +133,51 @@ impl ClickTracker {
};
let Some(record) = record else {
*record = Some(ClickRecord {
down_position: position,
up_position: position,
..Default::default()
});
*record = Some(ClickRecord { position, ..Default::default() });
return ClickCount::Single;
};
let now = Instant::now();
let within_time = now.saturating_duration_since(record.time) <= MULTICLICK_TIMEOUT;
let prev_time = record.time;
let prev_position = record.position;
let prev_count: ClickCount = record.down_count;
let (prev_count, prev_position) = match state {
ElementState::Pressed => (record.down_count, record.down_position),
ElementState::Released => (record.up_count, record.up_position),
};
let now = Instant::now();
record.time = now;
record.position = position;
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 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,
(ClickCount::Triple, true, true) => ClickCount::Double,
(_, true, true) => ClickCount::Double,
_ => ClickCount::Single,
};
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;
}
}
*record = match state {
ElementState::Pressed => ClickRecord { down_count: count, ..*record },
ElementState::Released => ClickRecord { up_count: count, ..*record },
};
count
}
}
@@ -197,8 +202,7 @@ impl From<ClickCount> for i32 {
#[derive(Clone, Copy)]
struct ClickRecord {
time: Instant,
down_position: MousePosition,
up_position: MousePosition,
position: MousePosition,
down_count: ClickCount,
up_count: ClickCount,
}
@@ -207,8 +211,7 @@ impl Default for ClickRecord {
fn default() -> Self {
Self {
time: Instant::now(),
down_position: Default::default(),
up_position: Default::default(),
position: Default::default(),
down_count: Default::default(),
up_count: Default::default(),
}
+47 -34
View File
@@ -1,3 +1,6 @@
#[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};
@@ -30,71 +33,81 @@ 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(&"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()));
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")));
let extra_disabled_features = ["OptimizationHints", "OnDeviceModelService", "TranslateUI"];
let disabled_features_switch = Some(&"disable-features".into());
let disabled_features_switch = Some(&CefString::from("disable-features"));
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(&disabled_features.as_str().into()));
cmd.append_switch_with_value(disabled_features_switch, Some(&CefString::from(disabled_features.as_str())));
#[cfg(not(feature = "accelerated_paint"))]
{
// Disable GPU acceleration when accelerated_paint feature is not enabled
cmd.append_switch(Some(&"disable-gpu".into()));
cmd.append_switch(Some(&"disable-gpu-compositing".into()));
cmd.append_switch(Some(&CefString::from("disable-gpu")));
cmd.append_switch(Some(&CefString::from("disable-gpu-compositing")));
}
#[cfg(feature = "accelerated_paint")]
{
// cmd.append_switch(Some(&"transparent-painting-enabled".into()));
cmd.append_switch(Some(&"enable-zero-copy".into()));
// cmd.append_switch(Some(&"off-screen-rendering-enabled".into()));
// cmd.append_switch(Some(&"use-views".into()));
cmd.append_switch(Some(&"enable-gpu-rasterization".into()));
cmd.append_switch(Some(&"enable-accelerated-2d-canvas".into()));
// Enable GPU acceleration switches for better performance
cmd.append_switch(Some(&CefString::from("enable-gpu-rasterization")));
cmd.append_switch(Some(&CefString::from("enable-accelerated-2d-canvas")));
}
#[cfg(all(feature = "accelerated_paint", target_os = "linux"))]
{
cmd.append_switch_with_value(Some(&"use-angle".into()), Some(&"gl-egl".into()));
cmd.append_switch_with_value(Some(&"ozone-platform".into()), Some(&"headless".into()));
// 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")));
}
}
#[cfg(target_os = "macos")]
{
// Hide user prompt asking for keychain access
cmd.append_switch(Some(&"use-mock-keychain".into()));
cmd.append_switch(Some(&CefString::from("use-mock-keychain")));
}
// 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(&"remote-debugging-port".into()), Some(&port.to_string().as_str().into()));
cmd.append_switch_with_value(Some(&"remote-allow-origins".into()), Some(&"*".into()));
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("*")));
}
}
}
@@ -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::{ImplFrame, ImplRenderProcessHandler, ImplV8Context, ImplV8Value, V8Handler, V8Propertyattribute, V8Value, WrapRenderProcessHandler, v8_value_create_function};
use cef::{CefString, 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(&property_name.into()),
Some(&CefString::from(property_name)),
Some(&mut value),
cef_v8_propertyattribute_t::V8_PROPERTY_ATTRIBUTE_READONLY.wrap_result(),
);
if global.value_bykey(Some(&function_name.into())).is_some() {
frame.execute_java_script(Some(&function_call.as_str().into()), None, 0);
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 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(&name.into()), Some(&mut v8_handler)) else {
let Some(mut function) = v8_value_create_function(Some(&CefString::from(name)), 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(&name.into()), Some(&mut function), V8Propertyattribute::default());
global.set_value_bykey(Some(&CefString::from(name)), Some(&mut function), V8Propertyattribute::default());
};
let Some(context) = context else {
+3 -2
View File
@@ -46,14 +46,15 @@ impl ImplResourceHandler for ResourceHandlerImpl {
if let Some(response) = response {
if self.reader.is_some() {
if let Some(mimetype) = &self.mimetype {
response.set_mime_type(Some(&mimetype.as_str().into()));
let cef_mime = CefString::from(mimetype.as_str());
response.set_mime_type(Some(&cef_mime));
} else {
response.set_mime_type(None);
}
response.set_status(200);
} else {
response.set_status(404);
response.set_mime_type(Some(&"text/plain".into()));
response.set_mime_type(Some(&CefString::from("text/plain")));
}
}
}
@@ -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(&RESOURCE_SCHEME.into()), scheme_options);
registrar.add_custom_scheme(Some(&CefString::from(RESOURCE_SCHEME)), scheme_options);
}
}
}
+2 -2
View File
@@ -1,4 +1,4 @@
use cef::{Frame, ImplBinaryValue, ImplFrame, ImplListValue, ImplProcessMessage, ImplV8Context, ProcessId, V8Context, sys::cef_process_id_t};
use cef::{CefString, 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(&name.as_str().into())) else {
let Some(mut process_message) = cef::process_message_create(Some(&CefString::from(name.as_str()))) else {
tracing::error!("Failed to create process message: {}", name);
return;
};
+3 -75
View File
@@ -1,31 +1,11 @@
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::fs::create_dir_all;
use std::path::PathBuf;
use crate::consts::{APP_DIRECTORY_NAME, APP_DOCUMENTS_DIRECTORY_NAME};
pub(crate) fn ensure_dir_exists(path: &PathBuf) {
if !path.exists() {
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);
}
}
create_dir_all(path).unwrap_or_else(|_| panic!("Failed to create directory at {path:?}"));
}
}
@@ -35,60 +15,8 @@ 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::IMMEDIATES);
let wgpu_context_builder = WgpuContextBuilder::new().with_features(WgpuFeatures::PUSH_CONSTANTS);
// 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,11 +62,6 @@ 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
+174 -74
View File
@@ -1,92 +1,192 @@
use crate::wrapper::messages::{DocumentId, PersistedState};
use crate::wrapper::messages::{Document, 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
#[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 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;
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);
}
};
if let Err(e) = std::fs::write(state_file_path(), data) {
tracing::error!("Failed to write persistent data to disk: {e}");
self.flush();
}
garbage_collect_document_files(&state);
}
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}");
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 read_document_content(id: &DocumentId) -> Option<String> {
std::fs::read_to_string(document_content_path(id)).ok()
}
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;
#[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}");
}
}
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}");
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}");
}
}
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;
}
}
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
}
}
fn state_file_path() -> std::path::PathBuf {
let mut path = crate::dirs::app_data_dir();
path.push(crate::consts::APP_STATE_FILE_NAME);
path
#[derive(serde::Serialize, serde::Deserialize)]
struct DocumentInfo {
id: DocumentId,
name: String,
path: Option<std::path::PathBuf>,
is_saved: bool,
}
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
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,
}
}
}
+8 -8
View File
@@ -26,14 +26,14 @@ fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
// FRAGMENT SHADER
// ===============
struct Immediates {
struct Constants {
viewport_scale: vec2<f32>,
viewport_offset: vec2<f32>,
ui_scale: vec2<f32>,
background_color: vec4<f32>,
};
var<immediate> immediates: Immediates;
var<push_constant> constants: Constants;
@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 * immediates.ui_scale;
let ui_coordinate = in.tex_coords * constants.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(immediates.background_color);
return srgb_to_linear(constants.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 - immediates.viewport_offset) * immediates.viewport_scale;
let viewport_coordinate = (in.tex_coords - constants.viewport_offset) * constants.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(immediates.background_color);
return srgb_to_linear(constants.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 = immediates.background_color;
viewport_srgb = constants.background_color;
} else if (viewport_srgb.a < 0.999) {
viewport_srgb = blend(viewport_srgb, immediates.background_color);
viewport_srgb = blend(viewport_srgb, constants.background_color);
}
if (overlay_srgb.a < 0.001) {
+11 -8
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::MipmapFilterMode::Nearest,
mipmap_filter: wgpu::FilterMode::Nearest,
..Default::default()
});
@@ -122,7 +122,10 @@ 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],
immediate_size: size_of::<Immediates>() as u32,
push_constant_ranges: &[wgpu::PushConstantRange {
stages: wgpu::ShaderStages::FRAGMENT,
range: 0..size_of::<Constants>() as u32,
}],
});
let render_pipeline = context.device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
@@ -159,7 +162,7 @@ impl RenderState {
mask: !0,
alpha_to_coverage_enabled: false,
},
multiview_mask: None,
multiview: None,
cache: None,
});
@@ -233,7 +236,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(), &mut self.overlays_texture));
let result = futures::executor::block_on(self.executor.render_vello_scene_to_target_texture(&scene, size, &Default::default(), None, &mut self.overlays_texture));
if let Err(e) = result {
tracing::error!("Error rendering overlays: {:?}", e);
return;
@@ -278,13 +281,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_immediates(
render_pass.set_push_constants(
wgpu::ShaderStages::FRAGMENT,
0,
bytemuck::bytes_of(&Immediates {
bytemuck::bytes_of(&Constants {
viewport_scale: self.viewport_scale,
viewport_offset: self.viewport_offset,
ui_scale: ui_scale.unwrap_or([1., 1.]),
@@ -355,7 +358,7 @@ pub(crate) enum RenderError {
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct Immediates {
struct Constants {
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 *const () as isize) };
let prev_window_message_handler = unsafe { SetWindowLongPtrW(main, GWLP_WNDPROC, main_window_handle_message as isize) };
if prev_window_message_handler == 0 {
let _ = unsafe { DestroyWindow(helper) };
panic!("SetWindowLongPtrW failed");
+3 -1
View File
@@ -13,7 +13,9 @@ gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
[dependencies]
# Local dependencies
graphite-editor = { workspace = true }
graphite-editor = { path = "../../editor", features = [
"gpu",
] }
graphene-std = { workspace = true }
graph-craft = { workspace = true }
wgpu-executor = { workspace = true }
@@ -49,12 +49,26 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
let message = FrontendMessage::UpdateFullscreen { fullscreen };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::LoadDocumentContent { id, document } => {
let message = PersistentStateMessage::LoadDocument { document_id: id, document };
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,
};
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::LoadPersistedState { state } => {
let message = PersistentStateMessage::LoadState { state };
DesktopWrapperMessage::SelectDocument { id } => {
let message = PortfolioMessage::SelectDocument { document_id: id };
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, FileFilter, OpenFileDialogContext, SaveFileDialogContext};
use super::messages::{DesktopFrontendMessage, Document, FileFilter, OpenFileDialogContext, SaveFileDialogContext};
pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: FrontendMessage) -> Option<FrontendMessage> {
match message {
@@ -67,24 +67,40 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
dispatcher.respond(DesktopFrontendMessage::UpdateUIScale { scale });
return Some(FrontendMessage::UpdateUIScale { scale });
}
FrontendMessage::TriggerPersistenceReadState => {
dispatcher.respond(DesktopFrontendMessage::PersistenceReadState);
}
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::TriggerPersistenceWriteDocument { document_id, document } => {
FrontendMessage::TriggerPersistenceWriteDocument { document_id, document, details } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteDocument {
id: document_id,
document_serialized_content: document,
document: Document {
name: details.name,
path: details.path,
content: document,
is_saved: details.is_saved,
},
});
}
FrontendMessage::TriggerPersistenceRemoveDocument { 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(),
});
// 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::application_io::PlatformApplicationIo;
use graph_craft::wasm_application_io::WasmApplicationIo;
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::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
pub use graphite_editor::consts::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 = PlatformApplicationIo::new_with_context(wgpu_context);
let application_io = WasmApplicationIo::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(Into::into)),
(true, texture) => NodeGraphExecutionResult::HasRun(texture.map(|t| t.texture)),
(false, _) => NodeGraphExecutionResult::NotRun,
}
}
+65 -22
View File
@@ -3,7 +3,6 @@ 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;
@@ -42,22 +41,23 @@ pub enum DesktopFrontendMessage {
UpdateOverlays(vello::Scene),
PersistenceWriteDocument {
id: DocumentId,
document_serialized_content: String,
document: Document,
},
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,20 +81,63 @@ 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 },
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 },
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,
}
pub struct FileFilter {
+3 -3
View File
@@ -11,9 +11,9 @@ repository = "https://github.com/GraphiteEditor/Graphite"
license = "Apache-2.0"
[features]
default = ["gpu"]
wasm = ["graphene-std/wasm", "interpreted-executor/wasm", "dep:wasm-bindgen"]
gpu = ["interpreted-executor/gpu", "dep:wgpu-executor"]
default = ["wasm", "gpu"]
wasm = ["wasm-bindgen", "graphene-std/wasm"]
gpu = ["interpreted-executor/gpu", "wgpu-executor"]
[dependencies]
# Local dependencies
-9
View File
@@ -4,12 +4,6 @@ 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.;
@@ -186,6 +180,3 @@ 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;
+5 -7
View File
@@ -2,7 +2,6 @@ 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;
@@ -234,11 +233,10 @@ 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.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.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.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;
@@ -295,7 +293,7 @@ impl Dispatcher {
document_id,
document,
input: &self.message_handlers.input_preprocessor_message_handler,
cached_data: &self.message_handlers.portfolio_message_handler.cached_data,
persistent_data: &self.message_handlers.portfolio_message_handler.persistent_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,6 +6,7 @@ use crate::messages::prelude::*;
pub enum ExportDialogMessage {
FileType { file_type: FileType },
ScaleFactor { factor: f64 },
TransparentBackground { transparent: bool },
ExportBounds { bounds: ExportBounds },
Submit,
@@ -14,6 +14,7 @@ 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,
}
@@ -24,6 +25,7 @@ impl Default for ExportDialogMessageHandler {
file_type: Default::default(),
scale_factor: 1.,
bounds: Default::default(),
transparent_background: false,
artboards: Default::default(),
has_selection: false,
}
@@ -38,17 +40,11 @@ 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 => {
// 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 {
let artboard_name = match self.bounds {
ExportBounds::Artboard(layer) => self.artboards.get(&layer).cloned(),
_ => None,
};
@@ -56,7 +52,8 @@ 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,
bounds: self.bounds,
transparent_background: self.file_type != FileType::Jpg && self.transparent_background,
artboard_name,
artboard_count: self.artboards.len(),
})
@@ -130,7 +127,6 @@ 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 {
@@ -163,6 +159,22 @@ impl LayoutHolder for ExportDialogMessageHandler {
DropdownInput::new(entries).selected_index(Some(index as u32)).widget_instance(),
];
Layout(vec![LayoutGroup::row(export_type), LayoutGroup::row(resolution), LayoutGroup::row(export_area)])
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),
])
}
}
@@ -1,9 +1,7 @@
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::prelude::*;
use glam::{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)]
@@ -24,40 +22,26 @@ impl MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHa
NewDocumentDialogMessage::Submit => {
responses.add(PortfolioMessage::NewDocumentWithName { name: self.name.clone() });
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
let create_artboard = !self.infinite && self.dimensions.x > 0 && self.dimensions.y > 0;
if create_artboard {
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::{MouseCursorIcon, PersistedState};
use super::utility_types::{DocumentDetails, MouseCursorIcon, OpenDocument};
use crate::messages::app_window::app_window_message_handler::AppWindowPlatform;
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage};
use crate::messages::frontend::utility_types::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,7 +9,6 @@ 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;
@@ -113,15 +112,7 @@ pub enum FrontendMessage {
font: Font,
url: String,
},
TriggerPersistenceReadState,
TriggerPersistenceReadDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
},
TriggerPersistenceWriteState {
state: PersistedState,
},
TriggerPersistenceDeleteDocument {
TriggerPersistenceRemoveDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
},
@@ -129,15 +120,22 @@ pub enum FrontendMessage {
#[serde(rename = "documentId")]
document_id: DocumentId,
document: String,
details: DocumentDetails,
},
TriggerLoadFirstAutoSaveDocument,
TriggerLoadRestAutoSaveDocuments,
TriggerOpenLaunchDocuments,
TriggerLoadPreferences,
TriggerOpen,
TriggerImport,
TriggerSavePreferences {
#[cfg_attr(feature = "wasm", tsify(type = "unknown"))]
#[tsify(type = "unknown")]
preferences: PreferencesMessageHandler,
},
TriggerSaveActiveDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
},
TriggerTextCommit,
TriggerVisitLink {
url: String,
@@ -196,9 +194,14 @@ pub enum FrontendMessage {
UpdateGraphViewOverlay {
open: bool,
},
UpdateWorkspacePanelLayout {
#[serde(rename = "panelLayout")]
panel_layout: WorkspacePanelLayout,
UpdateDataPanelState {
open: bool,
},
UpdatePropertiesPanelState {
open: bool,
},
UpdateLayersPanelState {
open: bool,
},
UpdateLayout {
#[serde(rename = "layoutTarget")]
@@ -288,7 +291,7 @@ pub enum FrontendMessage {
},
UpdateOpenDocumentsList {
#[serde(rename = "openDocuments")]
open_documents: Vec<DocumentInfo>,
open_documents: Vec<OpenDocument>,
},
UpdateWirePathInProgress {
#[serde(rename = "wirePath")]
+13 -15
View File
@@ -1,26 +1,24 @@
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), tsify(large_number_types_as_bigints))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct DocumentInfo {
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(PartialEq, Eq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct OpenDocument {
pub id: DocumentId,
pub name: String,
#[serde(default)]
pub path: Option<PathBuf>,
pub is_saved: bool,
pub details: DocumentDetails,
}
#[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))]
#[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))]
@@ -357,8 +357,6 @@ 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,8 +139,7 @@ impl FrameTimeInfo {
}
pub fn advance_timestamp(&mut self, next_timestamp: Duration) {
// Guard against non-monotonic timestamps from the browser (Keavon observed this once in Chrome)
let next_timestamp = next_timestamp.max(self.timestamp);
debug_assert!(next_timestamp >= self.timestamp);
self.prev_timestamp = Some(self.timestamp);
self.timestamp = next_timestamp;
@@ -495,18 +495,6 @@ 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")
@@ -647,12 +635,6 @@ 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, IVec2};
use glam::DAffine2;
use graph_craft::document::NodeId;
use graphene_std::Color;
use graphene_std::raster::BlendMode;
@@ -84,8 +84,6 @@ pub enum DocumentMessage {
GridVisibility {
visible: bool,
},
BlendSelectedLayers,
MorphSelectedLayers,
GroupSelectedLayers {
group_folder_type: GroupFolderType,
},
@@ -107,18 +105,12 @@ 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 {
@@ -199,7 +191,7 @@ pub enum DocumentMessage {
undo_count: usize,
},
ToggleLayerExpansion {
instance_path: Vec<NodeId>,
id: NodeId,
recursive: bool,
},
ToggleSelectedVisibility,
@@ -231,9 +223,6 @@ 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,10 +4,7 @@ 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, 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::consts::{ASYMPTOTIC_EFFECT, COLOR_OVERLAY_GRAY, DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, 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};
@@ -21,7 +18,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::{CachedData, PanelType};
use crate::messages::portfolio::utility_types::{PanelType, PersistentData};
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;
@@ -43,7 +40,6 @@ 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;
@@ -52,7 +48,7 @@ use std::time::Duration;
pub struct DocumentMessageContext<'a> {
pub document_id: DocumentId,
pub ipp: &'a InputPreprocessorMessageHandler,
pub cached_data: &'a CachedData,
pub persistent_data: &'a PersistentData,
pub executor: &'a mut NodeGraphExecutor,
pub current_tool: &'a ToolType,
pub preferences: &'a PreferencesMessageHandler,
@@ -86,8 +82,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,
/// Tracks which layer instances are collapsed in the Layers panel, keyed by instance path.
#[serde(deserialize_with = "deserialize_collapsed_layers", default)]
/// 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.
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.
@@ -193,7 +189,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
let DocumentMessageContext {
document_id,
ipp,
cached_data,
persistent_data,
executor,
viewport,
current_tool,
@@ -231,7 +227,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
selection_network_path: &self.selection_network_path,
document_name: self.name.as_str(),
executor,
cached_data,
persistent_data,
properties_panel_open,
};
self.properties_panel_message_handler.process_message(message, responses, context);
@@ -319,7 +315,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();
let layer_structure = Self::default().build_layer_structure(LayerNodeIdentifier::ROOT_PARENT);
responses.add(FrontendMessage::UpdateDocumentLayerStructure { layer_structure });
}
@@ -382,7 +378,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();
let layer_structure = self.build_layer_structure(LayerNodeIdentifier::ROOT_PARENT);
self.update_layers_panel_control_bar_widgets(layers_panel_open, responses);
self.update_layers_panel_bottom_bar_widgets(layers_panel_open, responses);
@@ -626,12 +622,6 @@ 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);
}
@@ -668,35 +658,29 @@ 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);
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();
// 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 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, layer_parent, responses);
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);
if let Some(name) = name {
responses.add(NodeGraphMessage::SetDisplayName {
@@ -731,29 +715,17 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
svg,
mouse,
parent_and_insert_index,
place_at_origin,
} => {
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 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_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, transform, !place_at_origin, layer_node_id, layer_parent, responses);
let layer = graph_modification_utils::new_svg_layer(svg, center_in_viewport, layer_node_id, self.new_layer_parent(true), responses);
if let Some(name) = name {
responses.add(NodeGraphMessage::SetDisplayName {
@@ -1021,8 +993,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
}
}
}
DocumentMessage::SetActivePanel { active_panel } => {
match active_panel {
DocumentMessage::SetActivePanel { active_panel: panel } => {
match panel {
PanelType::Document => {
if self.graph_view_overlay_open {
self.selection_network_path.clone_from(&self.breadcrumb_network_path);
@@ -1175,27 +1147,25 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
responses.add(OverlaysMessage::Draw);
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
}
DocumentMessage::ToggleLayerExpansion { instance_path, recursive } => {
let is_collapsed = self.collapsed.0.contains(&instance_path);
DocumentMessage::ToggleLayerExpansion { id, recursive } => {
let layer = LayerNodeIdentifier::new(id, &self.network_interface);
let metadata = self.metadata();
let is_collapsed = self.collapsed.0.contains(&layer);
if is_collapsed {
if recursive {
// Remove this path and all descendant paths (paths that start with this one)
self.collapsed.0.retain(|path| !path.starts_with(&instance_path));
let children: HashSet<_> = layer.descendants(metadata).collect();
self.collapsed.0.retain(|collapsed_layer| !children.contains(collapsed_layer) && collapsed_layer != &layer);
} else {
self.collapsed.0.retain(|path| *path != instance_path);
self.collapsed.0.retain(|collapsed_layer| collapsed_layer != &layer);
}
} else {
if recursive {
// 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);
}
}
let children_to_add: Vec<_> = layer.descendants(metadata).filter(|child| !self.collapsed.0.contains(child)).collect();
self.collapsed.0.extend(children_to_add);
}
self.collapsed.0.push(instance_path);
self.collapsed.0.push(layer);
}
responses.add(NodeGraphMessage::SendGraph);
@@ -1377,23 +1347,11 @@ 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,
artboard_canvas,
} => {
// Get bounding box of all layers (always needed to confirm there is content)
DocumentMessage::WrapContentInArtboard { place_artboard_at_origin } => {
// Get bounding box of all layers
let bounds = self.network_interface.document_bounds_document_space(false);
let Some(bounds) = bounds else { return };
// 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())
};
let bounds_rounded_dimensions = (bounds[1] - bounds[0]).round();
// Create an artboard and set its dimensions to the bounding box size and location
let node_id = NodeId::new();
@@ -1405,17 +1363,11 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
node_id,
node_template: Box::new(new_artboard_node),
});
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(NodeGraphMessage::ShiftNodePosition { node_id, x: 15, y: -3 });
responses.add(GraphOperationMessage::ResizeArtboard {
layer: LayerNodeIdentifier::new_unchecked(node_id),
location: artboard_location,
dimensions: artboard_dimensions,
location: if place_artboard_at_origin { IVec2::ZERO } else { bounds[0].round().as_ivec2() },
dimensions: bounds_rounded_dimensions.as_ivec2(),
});
// Connect the current output data to the artboard's input data, and the artboard's output to the document output
@@ -1425,10 +1377,10 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
insert_node_input_index: 1,
});
// Shift the content to align its top-left to the artboard's origin (no-op when content is already at origin)
// Shift the content by half its width and height so it gets centered in the artboard
responses.add(GraphOperationMessage::TransformChange {
layer: node_layer_id,
transform: DAffine2::from_translation(content_shift),
transform: DAffine2::from_translation(bounds_rounded_dimensions / 2.),
transform_in: TransformIn::Local,
skip_rerender: false,
});
@@ -1491,8 +1443,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
DeleteSelectedLayers,
DuplicateSelectedLayers,
GroupSelectedLayers,
BlendSelectedLayers,
MorphSelectedLayers,
SelectedLayersLower,
SelectedLayersLowerToBack,
SelectedLayersRaise,
@@ -1524,13 +1474,6 @@ 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);
@@ -1751,218 +1694,22 @@ impl DocumentMessageHandler {
Ok(document_message_handler)
}
/// 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);
/// 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,
}
}
// 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
})
.collect()
}
pub fn undo_with_history(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) {
@@ -2168,57 +1915,6 @@ 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);
@@ -3479,16 +3175,6 @@ 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,6 +4,7 @@ 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};
@@ -13,7 +14,6 @@ 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,17 +74,6 @@ 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,
@@ -97,12 +86,6 @@ 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>>,
@@ -129,7 +112,5 @@ 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,6 +1,5 @@
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};
@@ -15,7 +14,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, GradientSpreadMethod, GradientStop, GradientStops, GradientType, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::style::{Fill, Gradient, GradientStop, GradientStops, GradientType, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
#[derive(ExtractField)]
pub struct GraphOperationMessageContext<'a> {
@@ -172,77 +171,6 @@ 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);
@@ -274,13 +202,6 @@ 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);
@@ -399,7 +320,6 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
transform,
parent,
insert_index,
center,
} => {
let tree = match usvg::Tree::from_str(&svg, &usvg::Options::default()) {
Ok(t) => t,
@@ -413,38 +333,21 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
};
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
// 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 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);
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);
}
}
}
@@ -539,62 +442,48 @@ 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, STACK_VERTICAL_GAP), &[]);
modify_inputs.network_interface.shift_node(&upstream_layer.to_node(), IVec2::new(0, 3), &[]);
}
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() {
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);
import_usvg_node(modify_inputs, child, transform, NodeId::new(), layer, 0, graphite_gradient_stops);
}
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) => {
import_usvg_path(modify_inputs, node, path, layer, graphite_gradient_stops);
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()));
}
}
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());
@@ -604,141 +493,6 @@ 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 {
@@ -765,14 +519,6 @@ 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())),
@@ -795,15 +541,8 @@ 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,
spread_method,
})
Fill::Gradient(Gradient { start, end, gradient_type, stops })
}
usvg::Paint::RadialGradient(radial) => {
let gradient_transform = usvg_transform(radial.transform());
@@ -825,15 +564,8 @@ 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,
spread_method,
})
Fill::Gradient(Gradient { start, end, gradient_type, stops })
}
usvg::Paint::Pattern(_) => {
warn!("SVG patterns are not currently supported");
@@ -3,21 +3,44 @@ 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 (rotation, scale, skew) = transform.decompose_rotation_scale_skew();
let translation = transform.translation;
let (scale, rotation, translation, shear) = compute_scale_angle_translation_shear(transform);
let rotation = rotation.to_degrees();
let skew = DVec2::new(skew.atan().to_degrees(), 0.);
let shear = DVec2::new(shear.x.atan().to_degrees(), shear.y.atan().to_degrees());
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(skew), false), &[]);
network_interface.set_input(&InputConnector::node(*node_id, 4), NodeInput::value(TaggedValue::DVec2(shear), false), &[]);
}
// TODO: This should be extracted from the graph at the location of the transform node.
@@ -58,12 +81,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 skew = if let Some(&TaggedValue::DVec2(skew)) = inputs[4].as_value() { skew } else { DVec2::ZERO };
let shear = if let Some(&TaggedValue::DVec2(shear)) = inputs[4].as_value() { shear } else { DVec2::ZERO };
let rotation = rotation.to_radians();
let skew = DVec2::new(skew.x.to_radians().tan(), skew.y.to_radians().tan());
let shear = DVec2::new(shear.x.to_radians().tan(), shear.y.to_radians().tan());
DAffine2::from_scale_angle_translation(scale, rotation, translation) * DAffine2::from_cols_array(&[1., skew.y, skew.x, 1., 0., 0.])
DAffine2::from_scale_angle_translation(scale, rotation, translation) * DAffine2::from_cols_array(&[1., shear.y, shear.x, 1., 0., 0.])
}
/// Extract the current normalized pivot from the layer
@@ -112,8 +135,8 @@ mod tests {
/// ```
#[test]
fn derive_transform() {
for skew_x in -10..=10 {
let skew_x = (skew_x as f64) / 2.;
for shear_x in -10..=10 {
let shear_x = (shear_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 {
@@ -121,23 +144,22 @@ mod tests {
for scale_y in 1..10 {
let scale_y = (scale_y as f64) / 5.;
let skew = DVec2::new(skew_x, 0.);
let shear = DVec2::new(shear_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() * 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()),
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()),
translate,
);
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.]);
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.]);
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} / skew {skew} / new_skew {new_skew}",
"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}",
);
}
}
@@ -7,6 +7,7 @@ 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};
@@ -16,7 +17,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::{Artboard, Color, Graphic, NodeInputDecleration};
use graphene_std::{Graphic, NodeInputDecleration};
#[derive(PartialEq, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub enum TransformIn {
@@ -32,8 +33,6 @@ 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> {
@@ -43,7 +42,6 @@ impl<'a> ModifyInputsContext<'a> {
network_interface,
responses,
layer_node: None,
import: false,
}
}
@@ -152,62 +150,7 @@ 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.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
self.network_interface.move_node_to_chain_start(&boolean_id, layer, &[]);
}
pub fn insert_vector(&mut self, subpaths: Vec<Subpath<PointId>>, layer: LayerNodeIdentifier, include_transform: bool, include_fill: bool, include_stroke: bool) {
@@ -218,13 +161,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.import);
self.network_interface.move_node_to_chain_start(&shape_id, layer, &[]);
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.import);
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[]);
}
if include_stroke {
@@ -233,7 +176,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.import);
self.network_interface.move_node_to_chain_start(&stroke_id, layer, &[]);
}
if include_fill {
@@ -242,7 +185,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.import);
self.network_interface.move_node_to_chain_start(&fill_id, layer, &[]);
}
}
@@ -273,32 +216,19 @@ 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.import);
self.network_interface.move_node_to_chain_start(&text_id, layer, &[]);
let transform_id = NodeId::new();
self.network_interface.insert_node(transform_id, transform, &[]);
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[], self.import);
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[]);
let stroke_id = NodeId::new();
self.network_interface.insert_node(stroke_id, stroke, &[]);
self.network_interface.move_node_to_chain_start(&stroke_id, layer, &[], self.import);
self.network_interface.move_node_to_chain_start(&stroke_id, layer, &[]);
let fill_id = NodeId::new();
self.network_interface.insert_node(fill_id, fill, &[]);
self.network_interface.move_node_to_chain_start(&fill_id, layer, &[], self.import);
}
pub fn insert_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);
self.network_interface.move_node_to_chain_start(&fill_id, layer, &[]);
}
pub fn insert_image_data(&mut self, image_frame: Table<Raster<CPU>>, layer: LayerNodeIdentifier) {
@@ -309,11 +239,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.import);
self.network_interface.move_node_to_chain_start(&image_id, layer, &[]);
let transform_id = NodeId::new();
self.network_interface.insert_node(transform_id, transform, &[]);
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[], self.import);
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[]);
}
fn get_output_layer(&self) -> Option<LayerNodeIdentifier> {
@@ -398,12 +328,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.import);
self.network_interface.move_node_to_chain_start(&node_id, output_layer, &[]);
}
}
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.import);
self.network_interface.move_node_to_chain_start(&node_id, output_layer, &[]);
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.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");
if diagonal.length() < f64::EPSILON * 1000. || viewport.size().into_dvec2() == DVec2::ZERO {
warn!("Cannot center since the viewport size is 0");
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::CachedData;
use crate::messages::portfolio::utility_types::PersistentData;
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 cached_data: &'a CachedData,
pub persistent_data: &'a PersistentData,
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: "",
category: "Debug",
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(true), false),
NodeInput::value(TaggedValue::Bool(false), false),
],
..Default::default()
},
@@ -462,131 +462,184 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
properties: None,
},
DocumentNodeDefinition {
identifier: "Blend",
identifier: "Blend Shapes",
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(16), 0)],
exports: vec![NodeInput::node(NodeId(18), 0)],
nodes: [
// 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)
// 0: Floor
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
inputs: vec![NodeInput::import(concrete!(f64), 1)],
inputs: vec![NodeInput::import(concrete!(f64), 2)],
..Default::default()
},
// 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)
// 1: Subtract
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(math_nodes::subtract::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::F64(1.), false)],
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(1.), false)],
..Default::default()
},
// 6: Read Index (current repetition index)
// 2: Read Index
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(context::read_index::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::U32(0), false)],
..Default::default()
},
// 7: Divide (index / count)
// 3: Divide
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(math_nodes::divide::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::node(NodeId(17), 0)],
inputs: vec![NodeInput::node(NodeId(2), 0), NodeInput::node(NodeId(1), 0)],
..Default::default()
},
// 8: Floor (floor(index / count) = subpath index)
// 4: Position on Path
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(7), 0)],
..Default::default()
},
// 9: Modulo (index % count = local index within subpath)
DocumentNode {
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()
},
// 10: Path Is Closed (check if current subpath is closed)
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(vector::path_is_closed::IDENTIFIER),
inputs: vec![NodeInput::import(generic!(T), 4), NodeInput::node(NodeId(8), 0)],
..Default::default()
},
// 11: Switch (closed → count, open → max(count - 1, 1) as denominator)
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(logic::switch::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(10), 0), NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(18), 0)],
..Default::default()
},
// 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),
implementation: DocumentNodeImplementation::ProtoNode(vector_nodes::position_on_path::IDENTIFIER),
inputs: vec![
NodeInput::import(generic!(T), 0),
NodeInput::node(NodeId(14), 0),
NodeInput::import(generic!(T), 1),
NodeInput::node(NodeId(3), 0),
NodeInput::value(TaggedValue::Bool(false), false),
NodeInput::value(TaggedValue::Bool(false), false),
NodeInput::import(concrete!(vector::misc::InterpolationDistribution), 3),
NodeInput::import(generic!(T), 4),
],
..Default::default()
},
// 16: Repeat
// 5: Read Vector
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(context::read_vector::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::None, false)],
..Default::default()
},
// 6: Reset Transform
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),
],
..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
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(logic::switch::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(11), 0), NodeInput::node(NodeId(9), 0), NodeInput::node(NodeId(16), 0)],
..Default::default()
},
// 18: Repeat
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(repeat_nodes::repeat::IDENTIFIER),
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)],
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(0), 0), NodeInput::import(generic!(T), 3)],
..Default::default()
},
]
@@ -597,175 +650,168 @@ 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(),
("Count", "TODO").into(),
("Reverse", "TODO").into(),
("Distribution", "TODO").into(),
("Path", "TODO").into(),
],
input_metadata: vec![("Content", "TODO").into(), ("Path", "TODO").into(), ("Count", "TODO").into(), ("Reverse", "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: Separate Subpaths
// 0: Floor
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 0)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
..Default::default()
},
// 1: Count Elements
// 1: Subtract
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 2)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, -1)),
..Default::default()
},
..Default::default()
},
// 2: Max (subpath count)
// 2: Read Index
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 2)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, -2)),
..Default::default()
},
..Default::default()
},
// 3: Floor (count)
// 3: Divide
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 13)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, -2)),
..Default::default()
},
..Default::default()
},
// 4: Multiply (total instances)
// 4: Position on Path
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 1)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(28, -3)),
..Default::default()
},
..Default::default()
},
// 5: Subtract (count - 1)
// 5: Read Vector
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 14)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 2)),
..Default::default()
},
..Default::default()
},
// 6: Read Index
// 6: Reset Transform
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 7)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 2)),
..Default::default()
},
..Default::default()
},
// 7: Divide (index / count)
// 7: Map
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 10)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 1)),
..Default::default()
},
..Default::default()
},
// 8: Floor (subpath index)
// 8: Morph
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 4)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(28, 1)),
..Default::default()
},
..Default::default()
},
// 9: Modulo (local index)
// 9: Transform
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 7)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(35, 1)),
..Default::default()
},
..Default::default()
},
// 10: Path Is Closed
// 10: Count Points
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 2)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 4)),
..Default::default()
},
..Default::default()
},
// 11: Switch (denominator)
// 11: Equals
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 12)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 4)),
..Default::default()
},
..Default::default()
},
// 12: Divide (within-subpath fraction)
// 12: Flatten Vector
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 7)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 6)),
..Default::default()
},
..Default::default()
},
// 13: Multiply (clamp fraction)
// 13: Count Elements
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 7)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 8)),
..Default::default()
},
..Default::default()
},
// 14: Add (progression)
// 14: Subtract
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(37, 4)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 8)),
..Default::default()
},
..Default::default()
},
// 15: Morph
// 15: Multiply
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(44, 3)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 7)),
..Default::default()
},
..Default::default()
},
// 16: Repeat
// 16: Morph
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(51, 0)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(28, 6)),
..Default::default()
},
..Default::default()
},
// 17: Max (clamp count)
// 17: Switch
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 13)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(42, 4)),
..Default::default()
},
..Default::default()
},
// 18: Max (clamp open-path denominator)
// 18: Repeat
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 14)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(49, -1)),
..Default::default()
},
..Default::default()
@@ -788,6 +834,17 @@ 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 {
@@ -947,12 +1004,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(platform_application_io::load_resource::IDENTIFIER),
implementation: DocumentNodeImplementation::ProtoNode(wasm_application_io::load_resource::IDENTIFIER),
..Default::default()
},
DocumentNode {
inputs: vec![NodeInput::node(NodeId(0), 0)],
implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::decode_image::IDENTIFIER),
implementation: DocumentNodeImplementation::ProtoNode(wasm_application_io::decode_image::IDENTIFIER),
..Default::default()
},
]
@@ -1010,8 +1067,8 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
exports: vec![NodeInput::node(NodeId(2), 0)],
nodes: [
DocumentNode {
inputs: vec![],
implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::create_canvas::IDENTIFIER),
inputs: vec![NodeInput::scope("editor-api")],
implementation: DocumentNodeImplementation::ProtoNode(wasm_application_io::create_surface::IDENTIFIER),
skip_deduplication: true,
..Default::default()
},
@@ -1022,7 +1079,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(platform_application_io::rasterize::IDENTIFIER),
implementation: DocumentNodeImplementation::ProtoNode(wasm_application_io::rasterize::IDENTIFIER),
..Default::default()
},
]
@@ -1473,7 +1530,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
DocumentNodeDefinition {
identifier: "Extract",
category: "",
category: "Debug",
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(|path| path.iter().all(|&node_id| network_interface.document_network().nodes.contains_key(&node_id)));
collapsed.0.retain(|&layer| network_interface.document_metadata().layer_exists(layer));
}
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, false);
network_interface.move_node_to_chain_start(&node_id, parent, selection_network_path);
}
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, layers_panel_open, responses);
Self::update_layer_panel(network_interface, selection_network_path, collapsed, 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], layers_panel_open: bool, responses: &mut VecDeque<Message>) {
fn update_layer_panel(network_interface: &NodeNetworkInterface, selection_network_path: &[NodeId], collapsed: &CollapsedLayers, layers_panel_open: bool, responses: &mut VecDeque<Message>) {
if !layers_panel_open {
return;
}
@@ -2695,8 +2695,14 @@ 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());
}
@@ -2721,6 +2727,22 @@ 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 {
@@ -2730,9 +2752,18 @@ 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::{CachedData, FontCatalogStyle};
use crate::messages::portfolio::utility_types::{FontCatalogStyle, PersistentData};
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, ScaleType, Transform};
use graphene_std::transform::{Footprint, ReferencePoint, Transform};
use graphene_std::vector::QRCodeErrorCorrectionLevel;
use graphene_std::vector::misc::BooleanOperation;
use graphene_std::vector::misc::{ArcType, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType};
use graphene_std::vector::style::{Fill, FillChoice, FillType, GradientSpreadMethod, GradientStops, GradientType, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
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};
pub(crate) fn string_properties(text: &str) -> Vec<LayoutGroup> {
let widget = TextLabel::new(text).widget_instance();
@@ -265,8 +265,6 @@ 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
// =====
@@ -568,8 +566,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, scale, skew) = transform.decompose_rotation_scale_skew();
let skew_matrix = DAffine2::from_cols_array(&[1., 0., skew, 1., 0., 0.]);
let rotation = transform.decompose_rotation();
let scale = transform.decompose_scale();
location_widgets.extend_from_slice(&[
NumberInput::new(Some(translation.x))
@@ -610,7 +608,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) * skew_matrix;
let transform = DAffine2::from_scale_angle_translation(scale, r.value.map(|r| r.to_radians()).unwrap_or(rotation), translation);
TaggedValue::DAffine2(transform)
},
node_id,
@@ -625,7 +623,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) * skew_matrix;
let transform = DAffine2::from_scale_angle_translation(DVec2::new(w.value.unwrap_or(scale.x), scale.y), rotation, translation);
TaggedValue::DAffine2(transform)
},
node_id,
@@ -639,7 +637,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) * skew_matrix;
let transform = DAffine2::from_scale_angle_translation(DVec2::new(scale.x, h.value.unwrap_or(scale.y)), rotation, translation);
TaggedValue::DAffine2(transform)
},
node_id,
@@ -793,7 +791,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 {
cached_data,
persistent_data,
document_node,
node_id,
index,
@@ -813,7 +811,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![
cached_data
persistent_data
.font_catalog
.0
.iter()
@@ -866,7 +864,7 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
})
.collect::<Vec<_>>(),
])
.selected_index(cached_data.font_catalog.0.iter().position(|family| family.name == font.font_family).map(|i| i as u32))
.selected_index(persistent_data.font_catalog.0.iter().position(|family| family.name == font.font_family).map(|i| i as u32))
.virtual_scrolling(true)
.widget_instance(),
]);
@@ -876,7 +874,7 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
second_row.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
DropdownInput::new({
cached_data
persistent_data
.font_catalog
.0
.iter()
@@ -914,7 +912,7 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
.unwrap_or_default()
})
.selected_index(
cached_data
persistent_data
.font_catalog
.0
.iter()
@@ -2006,55 +2004,6 @@ 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
@@ -2208,7 +2157,7 @@ pub fn math_properties(node_id: NodeId, context: &mut NodePropertiesContext) ->
}
pub struct ParameterWidgetsInfo<'a> {
cached_data: &'a CachedData,
persistent_data: &'a PersistentData,
network_interface: &'a NodeNetworkInterface,
selection_network_path: &'a [NodeId],
document_node: Option<&'a DocumentNode>,
@@ -2231,7 +2180,7 @@ impl<'a> ParameterWidgetsInfo<'a> {
let document_node = context.network_interface.document_node(&node_id, context.selection_network_path);
ParameterWidgetsInfo {
cached_data: context.cached_data,
persistent_data: context.persistent_data,
network_interface: context.network_interface,
selection_network_path: context.selection_network_path,
document_node,
@@ -11,10 +11,8 @@ 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()?;
@@ -22,7 +20,6 @@ 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::CachedData;
use crate::messages::portfolio::utility_types::PersistentData;
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 cached_data: &'a CachedData,
pub persistent_data: &'a PersistentData,
pub properties_panel_open: bool,
}
@@ -28,7 +28,7 @@ impl MessageHandler<PropertiesPanelMessage, PropertiesPanelMessageContext<'_>> f
selection_network_path,
document_name,
executor,
cached_data,
persistent_data,
properties_panel_open,
} = context;
@@ -46,7 +46,7 @@ impl MessageHandler<PropertiesPanelMessage, PropertiesPanelMessageContext<'_>> f
}
let mut node_properties_context = NodePropertiesContext {
cached_data,
persistent_data,
responses,
network_interface,
selection_network_path,
@@ -1,6 +1,5 @@
use crate::consts::COLOR_OVERLAY_GRAY;
use glam::DVec2;
use graphene_std::vector::misc::BooleanOperation;
use std::fmt;
#[repr(transparent)]
@@ -711,7 +710,5 @@ impl PTZ {
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum GroupFolderType {
Layer,
BooleanOperation(BooleanOperation),
Blend,
Morph,
BooleanOperation(graphene_std::vector::misc::BooleanOperation),
}
@@ -5,9 +5,7 @@ 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, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH, STACK_VERTICAL_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};
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};
@@ -243,7 +241,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 = 0_u32;
let mut last_chain_node_distance = 0u32;
// 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)
@@ -255,11 +253,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 * NODE_CHAIN_WIDTH as u32 + 1;
return last_chain_node_distance * 7 + 1;
}
}
last_chain_node_distance * NODE_CHAIN_WIDTH as u32 + 1
last_chain_node_distance * 7 + 1
} else {
// Layer with no inputs has no chain
0
@@ -1209,8 +1207,6 @@ 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)
}
@@ -2069,30 +2065,6 @@ 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");
@@ -2697,7 +2669,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 * NODE_CHAIN_WIDTH, 0));
return Some(layer_position + IVec2::new(-node_distance_from_layer * 7, 0));
}
node_distance_from_layer += 1;
current_node_id = *downstream_node_id;
@@ -3859,46 +3831,6 @@ 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
@@ -3960,8 +3892,8 @@ impl NodeNetworkInterface {
return;
};
// Ensure the network is not cyclic (only Node connections can create cycles)
if matches!(new_input, NodeInput::Node { .. }) && !network.is_acyclic() {
// Ensure the network is not cyclic
if !network.is_acyclic() {
self.set_input(input_connector, old_input, network_path);
return;
}
@@ -3996,12 +3928,10 @@ impl NodeNetworkInterface {
self.unload_upstream_node_click_targets(vec![*node_id], network_path);
self.unload_all_nodes_bounding_box(network_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);
}
// 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);
}
} else {
self.unload_import_export_ports(network_path);
@@ -4009,14 +3939,6 @@ 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)) {
@@ -4028,7 +3950,7 @@ impl NodeNetworkInterface {
}
}
}
self.update_outward_wires(network_path, input_connector, &old_input, &new_input);
self.unload_outward_wires(network_path);
// 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}");
@@ -4083,17 +4005,17 @@ impl NodeNetworkInterface {
}
// If a connection is made to the imports
(NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Inline { .. }, NodeInput::Import { .. }) => {
self.update_outward_wires(network_path, input_connector, &old_input, &new_input);
self.unload_outward_wires(network_path);
self.unload_wire(input_connector, network_path);
}
// If a connection to the imports is disconnected
(NodeInput::Import { .. }, NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Inline { .. }) => {
self.update_outward_wires(network_path, input_connector, &old_input, &new_input);
self.unload_outward_wires(network_path);
self.unload_wire(input_connector, network_path);
}
// If a node is disconnected.
(NodeInput::Node { .. }, NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Inline { .. }) => {
self.update_outward_wires(network_path, input_connector, &old_input, &new_input);
self.unload_outward_wires(network_path);
self.unload_wire(input_connector, network_path);
if let Some((old_upstream_node_id, previous_position)) = previous_metadata {
@@ -4694,7 +4616,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 - STACK_VERTICAL_GAP).max(0) as u32),
position: LayerPosition::Stack((position.y - downstream_position.y - 3).max(0) as u32),
owned_nodes: TransientMetadata::Unloaded,
})
}
@@ -4855,7 +4777,7 @@ impl NodeNetworkInterface {
return;
};
self.set_stack_position(node_id, (node_position.y - downstream_position.y - STACK_VERTICAL_GAP).max(0) as u32, network_path);
self.set_stack_position(node_id, (node_position.y - downstream_position.y - 3).max(0) as u32, network_path);
}
/// Sets the position of a node to a chain position
@@ -5495,61 +5417,6 @@ 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
@@ -5615,7 +5482,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(LAYER_INDENT_OFFSET, -STACK_VERTICAL_GAP))
Some(IVec2::new(8, -3))
};
let Some(after_move_post_layer_position) = after_move_post_layer_position else {
@@ -5632,15 +5499,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 + STACK_VERTICAL_GAP;
let mut lowest_y_position = downstream_node_position.y + 3;
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 { STACK_VERTICAL_GAP } else { 2 })
self.position(node_id, network_path).map(|position| position.y + if is_layer { 3 } else { 2 })
}) {
lowest_y_position = lowest_y_position.max(bottom_position);
}
downstream_height = lowest_y_position - (downstream_node_position.y + STACK_VERTICAL_GAP);
downstream_height = lowest_y_position - (downstream_node_position.y + 3);
}
let mut highest_y_position = layer_to_move_position.y;
@@ -5648,7 +5515,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 { STACK_VERTICAL_GAP } else { 2 });
let bottom_position = self.position(node_id, network_path).map(|position| position.y + if is_layer { 3 } 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)
}) {
@@ -5656,7 +5523,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 - STACK_VERTICAL_GAP;
let height_below_layer = lowest_y_position - layer_to_move_position.y - 3;
// 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() {
@@ -5668,7 +5535,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..STACK_VERTICAL_GAP {
for _ in 0..3 {
self.vertical_shift_with_push(&upstream_node_id, 1, &mut HashSet::new(), network_path);
}
@@ -5697,7 +5564,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(-LAYER_INDENT_OFFSET, STACK_VERTICAL_GAP);
let final_layer_position = after_move_post_layer_position + IVec2::new(-8, 3);
let shift = final_layer_position - previous_layer_position;
self.shift_absolute_node_position(&layer.to_node(), shift, network_path);
}
@@ -5708,7 +5575,7 @@ impl NodeNetworkInterface {
return;
};
let final_layer_position = IVec2::new(stack_top_position.x, after_move_post_layer_position.y + STACK_VERTICAL_GAP + height_above_layer);
let final_layer_position = IVec2::new(stack_top_position.x, after_move_post_layer_position.y + 3 + 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;
@@ -5721,13 +5588,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, STACK_VERTICAL_GAP + height_above_layer);
let offset = after_move_post_layer_position - previous_layer_position + IVec2::new(0, 3 + 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, STACK_VERTICAL_GAP + height_above_layer);
let final_layer_position = after_move_post_layer_position + IVec2::new(0, 3 + 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;
@@ -5786,38 +5653,18 @@ impl NodeNetworkInterface {
self.create_wire(&upstream_output, &InputConnector::node(*node_id, insert_node_input_index), network_path);
}
/// 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 {
// 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 {
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 { .. }) {
// 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.create_wire(&OutputConnector::node(*node_id, 0), &InputConnector::node(parent.to_node(), 1), network_path);
self.set_chain_position(node_id, 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
} 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);
self.force_set_upstream_to_chain(node_id, network_path);
}
}
@@ -242,10 +242,7 @@ impl NodeNetworkInterface {
}
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => {
let Some(implementations) = NODE_REGISTRY.get(proto_node_identifier) else {
// 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");
}
log::error!("Protonode {proto_node_identifier:?} not found in registry in potential_valid_input_types");
return Vec::new();
};
let number_of_inputs = self.number_of_inputs(node_id, network_path);
@@ -10,17 +10,9 @@ 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))]
@@ -36,9 +28,21 @@ 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,
@@ -159,7 +163,4 @@ impl SelectedNodes {
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
/// 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>>);
pub struct CollapsedLayers(pub Vec<LayerNodeIdentifier>);
@@ -12,7 +12,6 @@ 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};
@@ -474,14 +473,13 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
],
},
NodeReplacement {
node: graphene_std::raster_nodes::blending_nodes::mix::IDENTIFIER,
node: graphene_std::raster_nodes::blending_nodes::blend::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 {
@@ -1665,7 +1663,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 v1 "Morph" node to the new vector table based v2 "Morph" node.
// Migrate from the old source/target "Morph" node to the new vector table based "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.
@@ -1677,7 +1675,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> { ... }
//
// v2 signature:
// New 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();
@@ -1713,84 +1711,6 @@ 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
@@ -1928,30 +1848,6 @@ 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,11 +3,8 @@ 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)]
@@ -1,7 +0,0 @@
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};
@@ -1,30 +0,0 @@
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,
},
}
@@ -1,54 +0,0 @@
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,7 +1,6 @@
use super::document::utility_types::document_metadata::LayerNodeIdentifier;
use super::persistent_state::PersistentStateMessage;
use super::utility_types::{DockingSplitDirection, PanelGroupId, PanelType};
use crate::messages::frontend::utility_types::{ExportBounds, FileType, PersistedState};
use super::utility_types::PanelType;
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use crate::messages::portfolio::document::utility_types::clipboards::Clipboard;
use crate::messages::portfolio::utility_types::FontCatalog;
use crate::messages::prelude::*;
@@ -16,8 +15,6 @@ pub enum PortfolioMessage {
// Sub-messages
#[child]
Document(DocumentMessage),
#[child]
PersistentState(PersistentStateMessage),
// Messages
Init,
@@ -64,23 +61,6 @@ 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,
},
@@ -100,13 +80,15 @@ pub enum PortfolioMessage {
document_path: Option<PathBuf>,
document_serialized_content: String,
},
LoadDocument {
OpenDocumentFileWithId {
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>,
@@ -144,26 +126,10 @@ 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,
SetPanelGroupActiveTab {
group: PanelGroupId,
tab_index: usize,
},
SplitPanelGroup {
target_group: PanelGroupId,
direction: DockingSplitDirection,
tabs: Vec<PanelType>,
active_tab_index: usize,
SetActivePanel {
panel: PanelType,
},
SelectDocument {
document_id: DocumentId,
@@ -173,6 +139,7 @@ pub enum PortfolioMessage {
file_type: FileType,
scale_factor: f64,
bounds: ExportBounds,
transparent_background: bool,
artboard_name: Option<String>,
artboard_count: usize,
},
@@ -190,16 +157,4 @@ 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
+7 -506
View File
@@ -3,7 +3,7 @@ use graphene_std::raster::Image;
use graphene_std::text::{Font, FontCache};
#[derive(Debug, Default)]
pub struct CachedData {
pub struct PersistentData {
pub font_cache: FontCache,
pub font_catalog: FontCatalog,
}
@@ -83,528 +83,29 @@ impl FontCatalogStyle {
}
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
#[derive(PartialEq, Eq, Clone, Copy, Debug, Default, serde::Serialize, serde::Deserialize)]
pub enum PanelType {
Welcome,
#[default]
Document,
Welcome,
Layers,
Properties,
Data,
DataPanel,
}
impl From<String> for PanelType {
fn from(value: String) -> Self {
match value.as_str() {
"Welcome" => PanelType::Welcome,
"Document" => PanelType::Document,
"Welcome" => PanelType::Welcome,
"Layers" => PanelType::Layers,
"Properties" => PanelType::Properties,
"Data" => PanelType::Data,
"Data" => PanelType::DataPanel,
_ => 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::application_io::EditorPreferences;
use graph_craft::wasm_application_io::EditorPreferences;
#[derive(ExtractField)]
pub struct PreferencesMessageContext<'a> {
@@ -51,7 +51,7 @@ impl PreferencesMessageHandler {
}
pub fn supports_wgpu(&self) -> bool {
graph_craft::application_io::wgpu_available().unwrap_or_default()
graph_craft::wasm_application_io::wgpu_available().unwrap_or_default()
}
}
-1
View File
@@ -27,7 +27,6 @@ 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, center: bool, id: NodeId, parent: LayerNodeIdentifier, responses: &mut VecDeque<Message>) -> LayerNodeIdentifier {
pub fn new_svg_layer(svg: String, transform: glam::DAffine2, id: NodeId, parent: LayerNodeIdentifier, responses: &mut VecDeque<Message>) -> LayerNodeIdentifier {
let insert_index = 0;
responses.add(GraphOperationMessage::NewSvg {
id,
@@ -238,7 +238,6 @@ pub fn new_svg_layer(svg: String, transform: glam::DAffine2, center: bool, id: N
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.matrix2.determinant().abs() >= f64::EPSILON).then(|| transform.inverse().transform_point2(position))?;
let layer_pos = transform.inverse().transform_point2(position);
let tolerance = tolerance + 0.5;
@@ -212,15 +212,16 @@ 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.
// 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.
// Constrain should always scale by the same factor in x and y
if constrain {
if original_from_pivot.x.abs() < original_from_pivot.y.abs() {
// When the point is on the pivot, we simply copy the other axis.
if original_from_pivot.x.abs() < 1e-5 {
scale_factor.x = scale_factor.y;
} else {
} else if original_from_pivot.y.abs() < 1e-5 {
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::CachedData;
use crate::messages::portfolio::utility_types::PersistentData;
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 cached_data: &'a CachedData,
pub persistent_data: &'a PersistentData,
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,
cached_data,
persistent_data,
node_graph,
preferences,
viewport,
@@ -126,7 +126,7 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
node_graph,
preferences,
viewport,
cached_data,
persistent_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, cached_data);
tool_data.tools.get(active_tool).unwrap().refresh_options(responses, persistent_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,
cached_data,
persistent_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, cached_data);
tool_data.tools.get(&tool_data.active_tool_type).unwrap().refresh_options(responses, persistent_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,
cached_data,
persistent_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: true,
clip: false,
},
})
}
@@ -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, GradientSpreadMethod, GradientStops, GradientType};
use graphene_std::vector::style::{Fill, Gradient, GradientStops, GradientType};
#[derive(Default, ExtractField)]
pub struct GradientTool {
@@ -21,7 +21,6 @@ pub struct GradientTool {
#[derive(Default)]
pub struct GradientOptions {
gradient_type: GradientType,
spread_method: GradientSpreadMethod,
}
#[impl_message(Message, ToolMessage, Gradient)]
@@ -54,7 +53,6 @@ pub enum GradientOptionsUpdate {
Type(GradientType),
ReverseStops,
ReverseDirection,
SetSpreadMethod(GradientSpreadMethod),
}
impl ToolMetadata for GradientTool {
@@ -86,10 +84,6 @@ 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 {
@@ -129,22 +123,6 @@ 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);
}
};
}
}
}
@@ -190,36 +168,7 @@ impl LayoutHolder for GradientTool {
})
.widget_instance();
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,
];
let mut widgets = vec![gradient_type, Separator::new(SeparatorStyle::Unrelated).widget_instance(), reverse_stops];
if self.options.gradient_type == GradientType::Radial {
let orientation = self
@@ -1200,14 +1149,7 @@ 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,
tool_options.spread_method,
)
Gradient::new(DVec2::ZERO, global_tool_data.secondary_color, DVec2::ONE, global_tool_data.primary_color, tool_options.gradient_type)
};
let mut selected_gradient = SelectedGradient::new(gradient, layer, document);
selected_gradient.dragging = GradientDragTarget::New;
@@ -1559,16 +1501,12 @@ fn apply_gradient_update(
responses.add(ToolMessage::RefreshToolOptions);
}
fn get_gradient_on_selected_layer(document: &DocumentMessageHandler) -> Option<Gradient> {
fn has_gradient_on_selected_layers(document: &DocumentMessageHandler) -> bool {
document
.network_interface
.selected_nodes()
.selected_visible_layers(&document.network_interface)
.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()
.any(|layer| get_gradient(layer, &document.network_interface).is_some())
}
#[inline(always)]
@@ -2003,38 +1941,4 @@ 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,11 +798,6 @@ 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,
cached_data,
persistent_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, &cached_data.font_cache);
let transformed_quad = layer_to_viewport * text_bounding_box(layer, document, &persistent_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::{CachedData, FontCatalog, FontCatalogStyle};
use crate::messages::portfolio::utility_types::{FontCatalog, FontCatalogStyle, PersistentData};
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>, cached_data: &CachedData) {
self.send_layout(responses, LayoutTarget::ToolOptions, &cached_data.font_catalog);
fn refresh_options(&self, responses: &mut VecDeque<Message>, persistent_data: &PersistentData) {
self.send_layout(responses, LayoutTarget::ToolOptions, &persistent_data.font_catalog);
}
}
@@ -302,7 +302,7 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Text
}
}
self.send_layout(responses, LayoutTarget::ToolOptions, &context.cached_data.font_catalog);
self.send_layout(responses, LayoutTarget::ToolOptions, &context.persistent_data.font_catalog);
}
fn actions(&self) -> ActionList {
@@ -573,11 +573,11 @@ impl Fsm for TextToolFsmState {
document,
global_tool_data,
input,
cached_data,
persistent_data,
viewport,
..
} = transition_data;
let font_cache = &cached_data.font_cache;
let font_cache = &persistent_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::CachedData;
use crate::messages::portfolio::utility_types::PersistentData;
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 cached_data: &'a CachedData,
pub persistent_data: &'a PersistentData,
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>, _cached_data: &CachedData);
fn refresh_options(&self, responses: &mut VecDeque<Message>, _persistent_data: &PersistentData);
}
impl<T: LayoutHolder> ToolRefreshOptions for T {
fn refresh_options(&self, responses: &mut VecDeque<Message>, _cached_data: &CachedData) {
fn refresh_options(&self, responses: &mut VecDeque<Message>, _persistent_data: &PersistentData) {
self.send_layout(responses, LayoutTarget::ToolOptions);
}
}
+16 -20
View File
@@ -1,16 +1,17 @@
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use crate::messages::prelude::*;
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::EditorPreferences;
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_craft::document::value::{RenderOutput, 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;
use graphene_std::renderer::{RenderMetadata, format_transform_matrix};
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;
@@ -153,6 +154,7 @@ 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,
};
@@ -217,6 +219,7 @@ impl NodeGraphExecutor {
pointer,
export_format: graphene_std::application_io::ExportFormat::Raster,
render_mode,
hide_artboards: false,
for_export: false,
for_eyedropper: true,
};
@@ -239,10 +242,10 @@ impl NodeGraphExecutor {
graphene_std::application_io::ExportFormat::Raster
};
// Calculate the bounding box of the region to be exported (artboard bounds always contribute)
// Calculate the bounding box of the region to be exported
let bounds = match export_config.bounds {
ExportBounds::AllArtwork => document.network_interface.document_bounds_document_space(true),
ExportBounds::Selection => document.network_interface.selected_bounds_document_space(true, &[]),
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::Artboard(id) => document.metadata().bounding_box_document(id),
}
.ok_or_else(|| "No bounding box".to_string())?;
@@ -264,6 +267,7 @@ impl NodeGraphExecutor {
pointer: DVec2::ZERO,
export_format,
render_mode: document.render_mode,
hide_artboards: export_config.transparent_background,
for_export: true,
for_eyedropper: false,
};
@@ -376,7 +380,6 @@ impl NodeGraphExecutor {
let (data, width, height) = raster.to_flat_u8();
responses.add(EyedropperToolMessage::PreviewImage { data, width, height });
}
NodeGraphUpdate::NodeGraphUpdateMessage(_) => {}
}
}
@@ -394,11 +397,12 @@ impl NodeGraphExecutor {
responses.add(FrontendMessage::UpdateImageData { image_data });
responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
}
#[cfg(target_family = "wasm")]
RenderOutputType::CanvasFrame { canvas_id, resolution } => {
RenderOutputType::CanvasFrame(frame) => {
let matrix = format_transform_matrix(frame.transform);
let transform = if matrix.is_empty() { String::new() } else { format!(" transform=\"{matrix}\"") };
let svg = format!(
r#"<svg><foreignObject width="{}" height="{}"><div data-canvas-placeholder="{}" data-is-viewport="true"></div></foreignObject></svg>"#,
resolution.x, resolution.y, canvas_id,
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,
);
responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
}
@@ -478,7 +482,7 @@ impl NodeGraphExecutor {
use image::buffer::ConvertBuffer;
use image::{ImageFormat, RgbImage, RgbaImage};
let Some(mut image) = RgbaImage::from_raw(width, height, data) else {
let Some(image) = RgbaImage::from_raw(width, height, data) else {
return Err("Failed to create image buffer for export".to_string());
};
@@ -493,14 +497,6 @@ 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 {
+93 -29
View File
@@ -1,25 +1,25 @@
use super::*;
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use glam::{DAffine2, UVec2};
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_craft::document::value::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, RenderSvgSegmentList, SvgRender, SvgSegment};
use graphene_std::renderer::{Render, RenderParams, SvgRender};
use graphene_std::renderer::{RenderSvgSegmentList, 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 [`PlatformEditorApi`] which is passed to the final compiled graph network upon each execution.
/// Some of these fields are put into a [`WasmEditorApi`] 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<PlatformEditorApi>,
editor_api: Arc<WasmEditorApi>,
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", feature = "wasm"))]
wasm_canvas_cache: CanvasSurfaceHandle,
#[cfg(all(target_family = "wasm", feature = "gpu"))]
wasm_viewport_surface: Option<wgpu_executor::WgpuSurface>,
/// 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", feature = "wasm"))]
#[cfg(all(target_family = "wasm", feature = "gpu"))]
current_viewport_texture: Option<ImageTexture>,
}
@@ -86,6 +86,7 @@ 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,
@@ -127,7 +128,7 @@ impl NodeRuntime {
old_graph: None,
update_thumbnails: true,
editor_api: PlatformEditorApi {
editor_api: WasmEditorApi {
font_cache: FontCache::default(),
editor_preferences: Box::new(EditorPreferences::default()),
node_graph_message_sender: Box::new(InternalNodeGraphUpdateSender(sender)),
@@ -145,7 +146,7 @@ impl NodeRuntime {
vector_modify: Default::default(),
inspect_state: None,
#[cfg(all(target_family = "wasm", feature = "gpu"))]
wasm_canvas_cache: CanvasSurfaceHandle::new(),
wasm_viewport_surface: None,
#[cfg(all(target_family = "wasm", feature = "gpu"))]
current_viewport_texture: None,
}
@@ -153,11 +154,11 @@ impl NodeRuntime {
pub async fn run(&mut self) -> Option<ImageTexture> {
if self.editor_api.application_io.is_none() {
self.editor_api = PlatformEditorApi {
self.editor_api = WasmEditorApi {
#[cfg(all(not(test), target_family = "wasm"))]
application_io: Some(PlatformApplicationIo::new().await.into()),
application_io: Some(WasmApplicationIo::new().await.into()),
#[cfg(any(test, not(target_family = "wasm")))]
application_io: Some(PlatformApplicationIo::new().await.into()),
application_io: Some(WasmApplicationIo::new_offscreen().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()),
@@ -207,7 +208,7 @@ impl NodeRuntime {
for request in requests {
match request {
GraphRuntimeRequest::FontCacheUpdate(font_cache) => {
self.editor_api = PlatformEditorApi {
self.editor_api = WasmEditorApi {
font_cache,
application_io: self.editor_api.application_io.clone(),
node_graph_message_sender: Box::new(self.sender.clone()),
@@ -221,7 +222,7 @@ impl NodeRuntime {
}
GraphRuntimeRequest::EditorPreferencesUpdate(preferences) => {
self.editor_preferences = preferences.clone();
self.editor_api = PlatformEditorApi {
self.editor_api = WasmEditorApi {
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()),
@@ -279,7 +280,7 @@ impl NodeRuntime {
.gpu_executor()
.expect("GPU executor should be available when we receive a texture");
let raster_cpu = Raster::new_gpu(image_texture.as_ref().clone()).convert(Footprint::BOUNDLESS, executor).await;
let raster_cpu = Raster::new_gpu(image_texture.texture.as_ref().clone()).convert(Footprint::BOUNDLESS, executor).await;
let (data, width, height) = raster_cpu.to_flat_u8();
@@ -303,7 +304,7 @@ impl NodeRuntime {
.gpu_executor()
.expect("GPU executor should be available when we receive a texture");
let raster_cpu = Raster::new_gpu(image_texture.as_ref().clone()).convert(Footprint::BOUNDLESS, executor).await;
let raster_cpu = Raster::new_gpu(image_texture.texture.as_ref().clone()).convert(Footprint::BOUNDLESS, executor).await;
self.sender.send_eyedropper_preview(raster_cpu);
continue;
@@ -317,20 +318,83 @@ impl NodeRuntime {
data: RenderOutputType::Texture(image_texture),
metadata,
})) if !render_config.for_export => {
self.current_viewport_texture = Some(image_texture.clone());
// On Wasm, for viewport rendering, blit the texture to a surface and return a CanvasFrame
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");
self.wasm_canvas_cache.present(&image_texture, executor);
// 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,
};
let logical_resolution = render_config.viewport.resolution.as_dvec2() / render_config.scale;
(
Ok(TaggedValue::RenderOutput(RenderOutput {
data: RenderOutputType::CanvasFrame {
canvas_id: self.wasm_canvas_cache.id(),
resolution: logical_resolution,
},
data: RenderOutputType::CanvasFrame(frame),
metadata,
})),
None,
@@ -528,10 +592,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: PlatformApplicationIo) {
pub async fn replace_application_io(application_io: WasmApplicationIo) {
let mut node_runtime = NODE_RUNTIME.lock();
if let Some(node_runtime) = &mut *node_runtime {
node_runtime.editor_api = PlatformEditorApi {
node_runtime.editor_api = WasmEditorApi {
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 (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap();
let exector = &mut portfolio.executor;
let document = portfolio.documents.get_mut(&document_id).unwrap();
let instrumented = match executor.update_node_graph_instrumented(document) {
let instrumented = match exector.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) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
if let Err(e) = exector.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": 1776635034,
"narHash": "sha256-OEOJrT3ZfwbChzODfIH4GzlNTtOFuZFWPtW7jIeR8xU=",
"lastModified": 1770169865,
"narHash": "sha256-iPiy13xzDQ9GjpOez+NNIjh/qjl7i4RDf9dF2x5mF9I=",
"owner": "ipetkov",
"repo": "crane",
"rev": "dc7496d8ea6e526b1254b55d09b966e94673750f",
"rev": "8254ccf3b5b5131890ee073776f2e61c6d1e55d4",
"type": "github"
},
"original": {
@@ -17,11 +17,11 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1776548001,
"narHash": "sha256-ZSK0NL4a1BwVbbTBoSnWgbJy9HeZFXLYQizjb2DPF24=",
"lastModified": 1770197578,
"narHash": "sha256-AYqlWrX09+HvGs8zM6ebZ1pwUqjkfpnv8mewYwAo+iM=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "b12141ef619e0a9c1c84dc8c684040326f27cdcc",
"rev": "00c21e4c93d963c50d4c0c89bfa84ed6e0694df2",
"type": "github"
},
"original": {
@@ -45,11 +45,11 @@
]
},
"locked": {
"lastModified": 1776741231,
"narHash": "sha256-k9G98qzn+7npROUaks8VqCFm7cFtEG8ulQLBBo5lItg=",
"lastModified": 1770347142,
"narHash": "sha256-uz+ZSqXpXEPtdRPYwvgsum/CfNq7AUQ/0gZHqTigiPM=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "02061303f7c4c964f7b4584dabd9e985b4cd442b",
"rev": "2859683cd9ef7858d324c5399b0d8d6652bf4044",
"type": "github"
},
"original": {
+1 -3
View File
@@ -12,11 +12,9 @@
<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="#222222" />
<meta name="theme-color" content="#ffffff" />
<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>
+962 -267
View File
File diff suppressed because it is too large. Load diff
+11 -10
View File
@@ -27,7 +27,6 @@
"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"
@@ -35,24 +34,26 @@
"devDependencies": {
"@eslint/js": "^9.39.2",
"@sveltejs/vite-plugin-svelte": "^7.0.0",
"@types/node": "^25.5.2",
"@types/node": "^25.5.0",
"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.17.0",
"eslint-plugin-svelte": "^3.16.0",
"globals": "^17.4.0",
"license-checker-rseidelsohn": "^4.4.2",
"prettier": "^3.8.1",
"prettier-plugin-svelte": "^3.5.1",
"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"
"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"
},
"homepage": "https://graphite.art",
"license": "Apache-2.0",
+1 -1
View File
@@ -75,7 +75,7 @@
<MainWindow />
<style lang="scss">
<style lang="scss" global>
// Disable the spinning loading indicator
body::before,
body::after {
@@ -28,6 +28,7 @@
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";
@@ -403,7 +404,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 (import.meta.env.MODE === "native") return false;
if (isPlatformNative()) return false;
return window.EyeDropper !== undefined;
}
@@ -732,7 +733,7 @@
</LayoutRow>
</FloatingMenu>
<style lang="scss">
<style lang="scss" global>
.color-picker {
--widget-height: 24px;
--picker-size: 256px;
@@ -73,7 +73,7 @@
</LayoutRow>
</FloatingMenu>
<style lang="scss">
<style lang="scss" global>
.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