mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
68362a7202 | ||
|
|
849760deb1 | ||
|
|
4cf7eb468e | ||
|
|
c7d91fe7f2 | ||
|
|
3114c57ec2 |
No files matched your search
@@ -2,25 +2,11 @@
|
||||
"image": "mcr.microsoft.com/devcontainers/base:debian",
|
||||
"features": {
|
||||
"ghcr.io/devcontainers/features/rust:1": {
|
||||
"profile": "default",
|
||||
"targets": "wasm32-unknown-unknown"
|
||||
"profile": "default"
|
||||
},
|
||||
"ghcr.io/devcontainers/features/node:1": {
|
||||
// NOTICE: keep in sync with `.nvmrc`
|
||||
"version": "24"
|
||||
}
|
||||
},
|
||||
// NOTICE: keep these tool versions in sync with `.github/workflows/build.yml`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
|
||||
"containerEnv": {
|
||||
"WASM_BINDGEN_CLI_VERSION": "0.2.121",
|
||||
"CARGO_ABOUT_VERSION": "0.9.2",
|
||||
"BINARYEN_VERSION": "130",
|
||||
"CARGO_BINSTALL_VERSION": "1.23.0"
|
||||
},
|
||||
"onCreateCommand": {
|
||||
"Install cargo-about and wasm-bindgen-cli": "curl -sSfL https://github.com/cargo-bins/cargo-binstall/releases/download/v$CARGO_BINSTALL_VERSION/cargo-binstall-$(uname -m)-unknown-linux-musl.tgz | tar xz -C $CARGO_HOME/bin && BINSTALL_DISABLE_TELEMETRY=true cargo binstall --no-confirm cargo-about@$CARGO_ABOUT_VERSION wasm-bindgen-cli@$WASM_BINDGEN_CLI_VERSION",
|
||||
"Install Binaryen wasm-opt": "curl -sSfL https://github.com/WebAssembly/binaryen/releases/download/version_$BINARYEN_VERSION/binaryen-version_$BINARYEN_VERSION-$(uname -m)-linux.tar.gz | tar xz -C $CARGO_HOME/bin --strip-components=2 binaryen-version_$BINARYEN_VERSION/bin/wasm-opt"
|
||||
"ghcr.io/devcontainers/features/node:1": {}
|
||||
},
|
||||
"onCreateCommand": "cargo install cargo-about && cargo install -f [email protected]",
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
// NOTE: Keep this in sync with `.vscode/extensions.json`
|
||||
@@ -30,16 +16,14 @@
|
||||
"tamasfe.even-better-toml",
|
||||
// Web
|
||||
"dbaeumer.vscode-eslint",
|
||||
"esbenp.prettier-vscode",
|
||||
"svelte.svelte-vscode",
|
||||
"vitaliymaz.vscode-svg-previewer",
|
||||
// Code quality
|
||||
"wayou.vscode-todo-highlight",
|
||||
"streetsidesoftware.code-spell-checker",
|
||||
// Git
|
||||
// Helpful
|
||||
"mhutchie.git-graph",
|
||||
"qezhu.gitlink",
|
||||
// Helpful
|
||||
"wmaurer.change-case"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
# Keavon Chambers (@Keavon [email protected])
|
||||
|
||||
|
||||
# Dennis Kobert (@TrueDoctor [email protected])
|
||||
|
||||
/document/format/ @TrueDoctor
|
||||
|
||||
/node-graph/graph-craft/ @TrueDoctor
|
||||
/node-graph/preprocessor/ @TrueDoctor
|
||||
/node-graph/node-macro/ @TrueDoctor
|
||||
/node-graph/interpreted-executor/ @TrueDoctor
|
||||
/node-graph/graphene-cli/ @TrueDoctor
|
||||
|
||||
# Timon Schelling (@timon-schelling [email protected])
|
||||
|
||||
/.nix/ @timon-schelling
|
||||
/flake.nix @timon-schelling
|
||||
/flake.lock @timon-schelling
|
||||
|
||||
/desktop/ @timon-schelling
|
||||
|
||||
/editor/src/messages/future/ @timon-schelling
|
||||
/editor/src/messages/resource_storage/ @timon-schelling
|
||||
/editor/src/messages/network/ @timon-schelling
|
||||
/editor/src/messages/app_window/ @timon-schelling
|
||||
/editor/src/messages/clipboard/ @timon-schelling
|
||||
/editor/src/messages/viewport/ @timon-schelling
|
||||
|
||||
/libraries/wgpu-sync/ @timon-schelling
|
||||
|
||||
/node-graph/libraries/canvas-utils/ @timon-schelling
|
||||
|
||||
/tools/cargo-run/ @timon-schelling
|
||||
/tools/third-party-licenses/ @timon-schelling
|
||||
+10
-24
@@ -58,7 +58,6 @@ jobs:
|
||||
RUSTC_WRAPPER: /usr/bin/sccache
|
||||
CARGO_INCREMENTAL: 0
|
||||
SCCACHE_DIR: /var/lib/github-actions/.cache
|
||||
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.121"
|
||||
BINARYEN_VERSION: "130"
|
||||
steps:
|
||||
@@ -303,11 +302,9 @@ jobs:
|
||||
pull-requests: write
|
||||
|
||||
env:
|
||||
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.121"
|
||||
BINARYEN_VERSION: "130"
|
||||
CARGO_ABOUT_VERSION: "0.9.2"
|
||||
CARGO_BINSTALL_VERSION: "1.23.0"
|
||||
CARGO_ABOUT_VERSION: "0.9.0"
|
||||
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
@@ -344,9 +341,7 @@ jobs:
|
||||
frontend/package-lock.json
|
||||
|
||||
- name: 📦 Install Cargo-binstall
|
||||
uses: cargo-bins/cargo-binstall@v1.23.0
|
||||
with:
|
||||
version: ${{ env.CARGO_BINSTALL_VERSION }}
|
||||
uses: cargo-bins/cargo-binstall@main
|
||||
|
||||
- name: 🚧 Install native dependencies
|
||||
shell: pwsh
|
||||
@@ -502,11 +497,9 @@ jobs:
|
||||
pull-requests: write
|
||||
|
||||
env:
|
||||
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.121"
|
||||
BINARYEN_VERSION: "130"
|
||||
CARGO_ABOUT_VERSION: "0.9.2"
|
||||
CARGO_BINSTALL_VERSION: "1.23.0"
|
||||
CARGO_ABOUT_VERSION: "0.9.0"
|
||||
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
@@ -542,11 +535,6 @@ jobs:
|
||||
package-lock.json
|
||||
frontend/package-lock.json
|
||||
|
||||
- name: 📦 Install Cargo-binstall
|
||||
uses: cargo-bins/[email protected]
|
||||
with:
|
||||
version: ${{ env.CARGO_BINSTALL_VERSION }}
|
||||
|
||||
- name: 🚧 Install native dependencies
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
@@ -556,7 +544,8 @@ jobs:
|
||||
brew install \
|
||||
pkg-config \
|
||||
openssl@3 \
|
||||
llvm
|
||||
llvm \
|
||||
cargo-binstall
|
||||
|
||||
echo "OPENSSL_DIR=$(brew --prefix openssl@3)" >> $GITHUB_ENV
|
||||
echo "PKG_CONFIG_PATH=$(brew --prefix openssl@3)/lib/pkgconfig" >> $GITHUB_ENV
|
||||
@@ -661,20 +650,17 @@ jobs:
|
||||
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Graphite Helper.app"
|
||||
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Graphite Helper (GPU).app"
|
||||
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Graphite Helper (Renderer).app"
|
||||
find "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries" -name "*.dylib" -exec codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" {} \;
|
||||
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework"
|
||||
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libcef_sandbox.dylib"
|
||||
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libEGL.dylib"
|
||||
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libGLESv2.dylib"
|
||||
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libvk_swiftshader.dylib"
|
||||
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH" --deep
|
||||
|
||||
codesign --verify --deep --strict --verbose=4 "$APP_PATH"
|
||||
|
||||
ditto -c -k --keepParent "$APP_PATH" "$ZIP_PATH"
|
||||
SUBMISSION_ID=$(xcrun notarytool submit "$ZIP_PATH" --wait --output-format json --apple-id "$APPLE_EMAIL" --team-id "$APPLE_TEAM_ID" --password "$APPLE_PASSWORD" | tee /dev/stderr | jq -r '.id')
|
||||
STATUS=$(xcrun notarytool info "$SUBMISSION_ID" --output-format json --apple-id "$APPLE_EMAIL" --team-id "$APPLE_TEAM_ID" --password "$APPLE_PASSWORD" | jq -r '.status')
|
||||
if [ "$STATUS" != "Accepted" ]; then
|
||||
echo "Notarization failed with status: $STATUS"
|
||||
xcrun notarytool log "$SUBMISSION_ID" --apple-id "$APPLE_EMAIL" --team-id "$APPLE_TEAM_ID" --password "$APPLE_PASSWORD"
|
||||
exit 1
|
||||
fi
|
||||
xcrun notarytool submit "$ZIP_PATH" --wait --apple-id "$APPLE_EMAIL" --team-id "$APPLE_TEAM_ID" --password "$APPLE_PASSWORD"
|
||||
rm "$ZIP_PATH"
|
||||
|
||||
xcrun stapler staple -v "$APP_PATH"
|
||||
|
||||
@@ -13,4 +13,3 @@ flamegraph.svg
|
||||
.direnv
|
||||
.DS_Store
|
||||
.nvim.lua
|
||||
/.devcontainer/devcontainer-lock.json
|
||||
+12
-14
@@ -1,10 +1,10 @@
|
||||
{ pkgs, ... }:
|
||||
|
||||
let
|
||||
version = "151.3.24+g2384915+chromium-151.0.7922.174";
|
||||
version = "149.0.5+g6770623+chromium-149.0.7827.197";
|
||||
hashes = {
|
||||
aarch64-linux = "sha256-R5ZbnDallYvdbW/bP+M2DzjRfWWRTvY2q63hSIHNxZs=";
|
||||
x86_64-linux = "sha256-21PEP9rOi37krw8AUSARbWlzqp2Ot3AsBhe635voaE4=";
|
||||
aarch64-linux = "sha256-cBAvcvs1rAg5EKJkCt81RZYupCWpUNIC/nLt3PJow7Q=";
|
||||
x86_64-linux = "sha256-OPGMBJmvvLiLdBDniBQwx7LmTGGI59AcesJdILSeqcs=";
|
||||
};
|
||||
|
||||
selectSystem =
|
||||
@@ -12,19 +12,17 @@ let
|
||||
attrs.${pkgs.stdenv.hostPlatform.system}
|
||||
or (throw "Unsupported system ${pkgs.stdenv.hostPlatform.system}");
|
||||
|
||||
url = "https://cef-builds.spotifycdn.com/cef_binary_${version}_${
|
||||
selectSystem {
|
||||
aarch64-linux = "linuxarm64";
|
||||
x86_64-linux = "linux64";
|
||||
}
|
||||
}_minimal.tar.bz2";
|
||||
|
||||
src = pkgs.fetchurl {
|
||||
inherit url;
|
||||
url = "https://cef-builds.spotifycdn.com/cef_binary_${version}_${
|
||||
selectSystem {
|
||||
aarch64-linux = "linuxarm64";
|
||||
x86_64-linux = "linux64";
|
||||
}
|
||||
}_minimal.tar.bz2";
|
||||
hash = selectSystem hashes;
|
||||
};
|
||||
in
|
||||
pkgs.cef-binary.overrideAttrs {
|
||||
pkgs.cef-binary.overrideAttrs (finalAttrs: {
|
||||
version = builtins.head (builtins.split "\\+" version);
|
||||
inherit src;
|
||||
postInstall = ''
|
||||
@@ -40,9 +38,9 @@ pkgs.cef-binary.overrideAttrs {
|
||||
echo '${
|
||||
builtins.toJSON {
|
||||
type = "minimal";
|
||||
name = builtins.baseNameOf url;
|
||||
name = builtins.baseNameOf finalAttrs.src.url;
|
||||
sha1 = "";
|
||||
}
|
||||
}' > $out/archive.json
|
||||
'';
|
||||
}
|
||||
})
|
||||
Vendored
-1
@@ -6,7 +6,6 @@
|
||||
"tamasfe.even-better-toml",
|
||||
// Web
|
||||
"dbaeumer.vscode-eslint",
|
||||
"esbenp.prettier-vscode",
|
||||
"svelte.svelte-vscode",
|
||||
"vitaliymaz.vscode-svg-previewer",
|
||||
// Code quality
|
||||
|
||||
Generated
+385
-329
File diff suppressed because it is too large.
Load diff
+12
-21
@@ -15,7 +15,6 @@ members = [
|
||||
"frontend/wrapper",
|
||||
"libraries/dyn-any",
|
||||
"libraries/math-parser",
|
||||
"libraries/ipsum",
|
||||
"libraries/wgpu-sync",
|
||||
"node-graph/libraries/graphene-hash",
|
||||
"node-graph/libraries/*",
|
||||
@@ -41,7 +40,6 @@ default-members = [
|
||||
"frontend/wrapper",
|
||||
"libraries/dyn-any",
|
||||
"libraries/math-parser",
|
||||
"libraries/ipsum",
|
||||
"node-graph/graph-craft",
|
||||
"node-graph/interpreted-executor",
|
||||
"node-graph/node-macro",
|
||||
@@ -58,7 +56,7 @@ edition = "2024"
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
homepage = "https://graphite.art"
|
||||
repository = "https://github.com/GraphiteEditor/Graphite"
|
||||
license = "MIT OR Apache-2.0"
|
||||
license = "Apache-2.0"
|
||||
version = "0.0.0"
|
||||
readme = "README.md"
|
||||
publish = false
|
||||
@@ -82,7 +80,6 @@ no-std-types = { path = "node-graph/libraries/no-std-types" }
|
||||
raster-types = { path = "node-graph/libraries/raster-types" }
|
||||
vector-types = { path = "node-graph/libraries/vector-types" }
|
||||
graphic-types = { path = "node-graph/libraries/graphic-types" }
|
||||
brush-types = { path = "node-graph/libraries/brush-types" }
|
||||
rendering = { path = "node-graph/libraries/rendering" }
|
||||
brush-nodes = { path = "node-graph/nodes/brush" }
|
||||
blending-nodes = { path = "node-graph/nodes/blending" }
|
||||
@@ -107,7 +104,6 @@ wgpu-sync = { path = "libraries/wgpu-sync" }
|
||||
graphite-proc-macros = { path = "proc-macros" }
|
||||
graphite-editor = { path = "editor" }
|
||||
graphene-canvas-utils = { path = "node-graph/libraries/canvas-utils" }
|
||||
ipsum = { path = "libraries/ipsum" }
|
||||
|
||||
# Workspace dependencies
|
||||
rustc-hash = "2.0"
|
||||
@@ -143,7 +139,7 @@ wgpu = { version = "29.0", features = [
|
||||
"strict_asserts",
|
||||
] }
|
||||
once_cell = "1.13" # Remove and replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>)
|
||||
wasm-bindgen = "=0.2.121" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned in `.github/workflows/build.yml`, `.devcontainer/devcontainer.json`, `.nix/dev.nix`, `.nix/pkgs/graphite.nix`, and `tools/cargo-run/src/requirements.rs`. We pin this version because wasm-bindgen upgrades may break various things.
|
||||
wasm-bindgen = "=0.2.121" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned across CI workflows, devcontainer, Nix, and the `cargo-run` tool. We pin this version because wasm-bindgen upgrades may break various things.
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "=0.3.98"
|
||||
web-sys = { version = "=0.3.98", features = [
|
||||
@@ -164,14 +160,15 @@ web-sys = { version = "=0.3.98", features = [
|
||||
"HtmlImageElement",
|
||||
"ImageBitmapRenderingContext",
|
||||
] }
|
||||
winit = "0.31.0-beta.2"
|
||||
winit = { git = "https://github.com/rust-windowing/winit.git" }
|
||||
keyboard-types = "0.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.10"
|
||||
vello_encoding = "0.10"
|
||||
# TODO: Return to crates.io versions once a release after 0.9 ships the ramp bake's `interpolation_alpha_space` support
|
||||
vello = { git = "https://github.com/linebender/vello.git", rev = "7073a85d61ee099d1d3595651ddf92302b074348" }
|
||||
vello_encoding = { git = "https://github.com/linebender/vello.git", rev = "7073a85d61ee099d1d3595651ddf92302b074348" }
|
||||
resvg = "0.47"
|
||||
usvg = "0.47"
|
||||
simplecss = "0.2"
|
||||
@@ -195,13 +192,6 @@ image = { version = "0.25", default-features = false, features = [
|
||||
"jpeg",
|
||||
"bmp",
|
||||
"gif",
|
||||
"webp",
|
||||
"tiff",
|
||||
"ico",
|
||||
"tga",
|
||||
"hdr",
|
||||
"exr",
|
||||
"serde",
|
||||
] }
|
||||
pretty_assertions = "1.4"
|
||||
fern = { version = "0.7", features = ["colored"] }
|
||||
@@ -230,8 +220,8 @@ gungraun = { version = "0.18" }
|
||||
ndarray = "0.16"
|
||||
strum = { version = "0.27", features = ["derive"] }
|
||||
dirs = "6.0"
|
||||
cef = "151"
|
||||
cef-dll-sys = "151"
|
||||
cef = "149"
|
||||
cef-dll-sys = "149"
|
||||
include_dir = "0.7"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
tracing = "0.1"
|
||||
@@ -270,7 +260,8 @@ lto = "thin"
|
||||
debug = true
|
||||
|
||||
[patch.crates-io]
|
||||
winit = { git = "https://github.com/timon-schelling/winit", branch = "graphite" }
|
||||
# Force cargo to use only one version of the dpi crate (vendoring breaks without this)
|
||||
dpi = { git = "https://github.com/rust-windowing/winit.git" }
|
||||
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
|
||||
cef = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-151" }
|
||||
cef-dll-sys = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-151" }
|
||||
cef = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-149" }
|
||||
cef-dll-sys = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-149" }
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
Copyright (c) Graphite contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
File renamed without changes.
@@ -80,6 +80,4 @@ Graphite is 100% community built and funded. Please become a part of keeping the
|
||||
|
||||
Are you a graphics programmer or Rust developer? Graphite aims to be one of the most approachable projects for putting your engineering skills to use in the world of open source. See [instructions here](https://graphite.art/volunteer/guide/) for setting up the project and getting started.
|
||||
|
||||
## License
|
||||
|
||||
Graphite's source code is dual-licensed under your choice of either the [MIT license](LICENSE-MIT) or the [Apache License 2.0](LICENSE-APACHE), at your option, unless otherwise noted within the repository. By submitting code for inclusion in the project, you agree to license your contributions under both licenses, and that you have the authority to do so.
|
||||
*By submitting code for inclusion in the project, you are agreeing to license your changes under the Apache 2.0 license, and that you have the authority to do so. Some directories may have other licenses, like dual-licensed MIT/Apache 2.0, and code submissions to those directories mean you agree to the applicable license(s).*
|
||||
@@ -22,6 +22,8 @@ accepted = [
|
||||
workarounds = ["ring"]
|
||||
ignore-build-dependencies = true
|
||||
ignore-dev-dependencies = true
|
||||
# Clearly Defined's API would occasionally (every few months) return errors for at least a full day (maybe some weird rate limiting?), but we can just disable to perform local checking (see #1653)
|
||||
no-clearly-defined = true
|
||||
|
||||
# https://raw.githubusercontent.com/briansmith/webpki/main/LICENSE
|
||||
# is the ISC license but test code within the repo is BSD-3-Clause, but is not compiled into the crate when we use it
|
||||
|
||||
+7
-7
@@ -1,12 +1,12 @@
|
||||
[package]
|
||||
name = "graphite-desktop"
|
||||
version = "0.1.0"
|
||||
description = "Graphite Desktop"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
|
||||
[[bin]]
|
||||
name = "graphite"
|
||||
@@ -44,12 +44,12 @@ rfd = { workspace = true }
|
||||
open = { workspace = true }
|
||||
lzma-rust2 = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
url = { workspace = true }
|
||||
rand = { workspace = true, features = ["thread_rng"] }
|
||||
clap = { workspace = true, features = ["derive"] }
|
||||
interprocess = "2.4.2"
|
||||
fd-lock = "4.0.4"
|
||||
ctrlc = "3.5.1"
|
||||
window_clipboard = "0.5"
|
||||
|
||||
# Windows-specific dependencies
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
[package]
|
||||
name = "graphite-desktop-bundle"
|
||||
version = "0.0.0"
|
||||
description = "Graphite Desktop Bundle"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
|
||||
[dependencies]
|
||||
cef-dll-sys = { workspace = true }
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
[package]
|
||||
name = "graphite-desktop-embedded-resources"
|
||||
version = "0.1.0"
|
||||
description = "Graphite Desktop Embedded Resources"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
|
||||
[dependencies]
|
||||
include_dir = { workspace = true }
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
[package]
|
||||
name = "graphite-desktop-platform-linux"
|
||||
version = "0.0.0"
|
||||
description = "Graphite Desktop Platform Linux"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
|
||||
[[bin]]
|
||||
name = "graphite"
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
[package]
|
||||
name = "graphite-desktop-platform-mac"
|
||||
version = "0.0.0"
|
||||
description = "Graphite Desktop Platform Mac"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
|
||||
[features]
|
||||
main = ["dep:graphite-desktop"]
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
[package]
|
||||
name = "graphite-desktop-platform-win"
|
||||
version = "0.0.0"
|
||||
description = "Graphite Desktop Platform Windows"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
|
||||
[[bin]]
|
||||
name = "graphite"
|
||||
|
||||
+90
-133
@@ -9,22 +9,19 @@ use std::sync::mpsc::{Receiver, SyncSender};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::data_transfer::{DataTransferSendBuilder, TypeHint};
|
||||
use winit::dpi::PhysicalSize;
|
||||
use winit::event::{ElementState, MouseButton, StartCause, WindowEvent};
|
||||
use winit::event_loop::run_on_demand::EventLoopExtRunOnDemand;
|
||||
use winit::event_loop::{ActiveEventLoop, AsyncRequestSerial, ControlFlow, DndAction, EventLoop};
|
||||
use winit::dpi::{PhysicalPosition, PhysicalSize};
|
||||
use winit::event::{ButtonSource, ElementState, MouseButton, StartCause, WindowEvent};
|
||||
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
|
||||
use winit::window::WindowId;
|
||||
|
||||
use crate::dirs;
|
||||
use crate::event::{AppEvent, AppEventScheduler};
|
||||
use crate::input::InputState;
|
||||
use crate::persist;
|
||||
use crate::preferences;
|
||||
use crate::render::{RenderError, RenderState};
|
||||
use crate::ui::{InputEvent, UiCommand, UiInstance};
|
||||
use crate::ui::{UiCommand, UiInstance};
|
||||
use crate::window::Window;
|
||||
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, IngestAction, Preferences};
|
||||
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, InputMessage, MouseKeys, MouseState, Preferences};
|
||||
use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
|
||||
|
||||
pub(crate) struct App {
|
||||
@@ -36,9 +33,8 @@ pub(crate) struct App {
|
||||
window_maximized: bool,
|
||||
window_fullscreen: bool,
|
||||
window_pending_drag: bool,
|
||||
pending_dnd_fetch: Option<AsyncRequestSerial>,
|
||||
pending_clipboard_fetch: Option<AsyncRequestSerial>,
|
||||
input_state: InputState,
|
||||
pointer_position: PhysicalPosition<f64>,
|
||||
pointer_lock_position: Option<PhysicalPosition<f64>>,
|
||||
ui_scale: f64,
|
||||
app_event_receiver: Receiver<AppEvent>,
|
||||
app_event_scheduler: AppEventScheduler,
|
||||
@@ -110,9 +106,8 @@ impl App {
|
||||
window_maximized: false,
|
||||
window_fullscreen: false,
|
||||
window_pending_drag: false,
|
||||
pending_dnd_fetch: None,
|
||||
pending_clipboard_fetch: None,
|
||||
input_state: InputState::new(),
|
||||
pointer_position: Default::default(),
|
||||
pointer_lock_position: Default::default(),
|
||||
ui_scale: 1.,
|
||||
app_event_receiver,
|
||||
app_event_scheduler,
|
||||
@@ -130,8 +125,8 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn run(mut self, mut event_loop: EventLoop) -> ExitReason {
|
||||
event_loop.run_app_on_demand(&mut self).unwrap();
|
||||
pub(crate) fn run(mut self, event_loop: EventLoop) -> ExitReason {
|
||||
event_loop.run_app(&mut self).unwrap();
|
||||
self.exit_reason
|
||||
}
|
||||
|
||||
@@ -205,15 +200,15 @@ impl App {
|
||||
};
|
||||
self.send_or_queue_web_message(bytes);
|
||||
}
|
||||
DesktopFrontendMessage::OpenFileDialog { title, options, action } => {
|
||||
DesktopFrontendMessage::OpenFileDialog { title, filters, multiple, context } => {
|
||||
let app_event_scheduler = self.app_event_scheduler.clone();
|
||||
let _ = thread::spawn(move || {
|
||||
let mut dialog = AsyncFileDialog::new().set_title(title);
|
||||
for filter in options.filters {
|
||||
for filter in filters {
|
||||
dialog = dialog.add_filter(filter.name, &filter.extensions);
|
||||
}
|
||||
|
||||
let handles = if options.multiple {
|
||||
let handles = if multiple {
|
||||
futures::executor::block_on(dialog.pick_files()).unwrap_or_default()
|
||||
} else {
|
||||
futures::executor::block_on(dialog.pick_file()).into_iter().collect()
|
||||
@@ -223,8 +218,7 @@ impl App {
|
||||
let path = handle.path().to_path_buf();
|
||||
match fs::read(&path) {
|
||||
Ok(content) => {
|
||||
let action = action.clone();
|
||||
let message = DesktopWrapperMessage::IngestFile { path, content, action };
|
||||
let message = DesktopWrapperMessage::FileDialogResult { path, content, context };
|
||||
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
Err(e) => tracing::error!("Failed to read file {}: {}", path.display(), e),
|
||||
@@ -270,8 +264,6 @@ impl App {
|
||||
});
|
||||
}
|
||||
DesktopFrontendMessage::UpdateViewportPhysicalBounds { x, y, width, height } => {
|
||||
self.input_state.set_viewport_info(x, y, width, height, self.window_scale);
|
||||
|
||||
if let Some(render_state) = &mut self.render_state
|
||||
&& let Some(window) = &self.window
|
||||
{
|
||||
@@ -286,9 +278,6 @@ impl App {
|
||||
render_state.set_viewport_scale([viewport_scale_x as f32, viewport_scale_y as f32]);
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::WindowUpdateDirectInput { enabled } => {
|
||||
self.input_state.set_direct_input(enabled);
|
||||
}
|
||||
DesktopFrontendMessage::UpdateUIScale { scale } => {
|
||||
self.ui_scale = scale;
|
||||
self.resize();
|
||||
@@ -341,13 +330,19 @@ impl App {
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::ClipboardRead => {
|
||||
self.app_event_scheduler.schedule(AppEvent::ClipboardRead);
|
||||
if let Some(window) = &self.window {
|
||||
let content = window.clipboard_read();
|
||||
let message = DesktopWrapperMessage::ClipboardReadResult { content };
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::ClipboardWrite { content } => {
|
||||
self.app_event_scheduler.schedule(AppEvent::ClipboardWrite { content });
|
||||
if let Some(window) = &mut self.window {
|
||||
window.clipboard_write(content);
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::PointerLock => {
|
||||
self.input_state.lock_pointer();
|
||||
self.pointer_lock_position = Some(self.pointer_position);
|
||||
if let Some(window) = &self.window {
|
||||
window.start_pointer_lock();
|
||||
}
|
||||
@@ -467,32 +462,6 @@ impl App {
|
||||
self.ui_frame_received = true;
|
||||
}
|
||||
}
|
||||
AppEvent::ClipboardRead => {
|
||||
let result = event_loop.clipboard().and_then(|id| {
|
||||
let Some(id) = id else { return Ok(None) };
|
||||
let data_transfer = event_loop.data_transfer(id)?;
|
||||
if !data_transfer.has_type(&TypeHint::Plaintext) {
|
||||
return Ok(None);
|
||||
}
|
||||
event_loop.fetch_data_transfer(id, &TypeHint::Plaintext).map(Some)
|
||||
});
|
||||
match result {
|
||||
Ok(Some(serial)) => self.pending_clipboard_fetch = Some(serial),
|
||||
Ok(None) => self.dispatch_desktop_wrapper_message(DesktopWrapperMessage::ClipboardReadResult { content: None }),
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to read from clipboard: {e}");
|
||||
self.dispatch_desktop_wrapper_message(DesktopWrapperMessage::ClipboardReadResult { content: None });
|
||||
}
|
||||
}
|
||||
}
|
||||
AppEvent::ClipboardWrite { content } => {
|
||||
let send_data = DataTransferSendBuilder::new(content)
|
||||
.with_type(TypeHint::Plaintext, |content: &String, _| Some(content.clone()))
|
||||
.build();
|
||||
if let Err(e) = event_loop.set_clipboard(send_data) {
|
||||
tracing::error!("Failed to write to clipboard: {e}");
|
||||
}
|
||||
}
|
||||
AppEvent::CursorChange(cursor) => {
|
||||
if let Some(window) = &mut self.window {
|
||||
window.set_cursor(event_loop, cursor);
|
||||
@@ -521,11 +490,7 @@ impl App {
|
||||
for path in paths {
|
||||
tracing::info!("Opening file: {}", path.display());
|
||||
if let Ok(content) = fs::read(&path) {
|
||||
let message = DesktopWrapperMessage::IngestFile {
|
||||
path,
|
||||
content,
|
||||
action: IngestAction::Open,
|
||||
};
|
||||
let message = DesktopWrapperMessage::OpenFile { path, content };
|
||||
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
} else {
|
||||
tracing::error!("Failed to read file: {}", path.display());
|
||||
@@ -568,28 +533,28 @@ impl ApplicationHandler for App {
|
||||
}
|
||||
}
|
||||
|
||||
fn window_event(&mut self, event_loop: &dyn ActiveEventLoop, _window_id: WindowId, event: WindowEvent) {
|
||||
fn window_event(&mut self, _event_loop: &dyn ActiveEventLoop, _window_id: WindowId, event: WindowEvent) {
|
||||
// Handle pointer lock release
|
||||
if let WindowEvent::PointerButton {
|
||||
state: ElementState::Released,
|
||||
button,
|
||||
..
|
||||
} = &event && button.clone().mouse_button() == Some(MouseButton::Left)
|
||||
&& let Some(pointer_lock_position) = self.input_state.unlock_pointer()
|
||||
if let Some(pointer_lock_position) = self.pointer_lock_position
|
||||
&& let WindowEvent::PointerButton {
|
||||
state: ElementState::Released,
|
||||
button: ButtonSource::Mouse(MouseButton::Left),
|
||||
..
|
||||
} = event
|
||||
{
|
||||
self.pointer_lock_position = None;
|
||||
if let Some(window) = &self.window {
|
||||
window.end_pointer_lock();
|
||||
}
|
||||
self.ui.send(UiCommand::Input(
|
||||
InputEvent::pointer().position(pointer_lock_position).moved().modifiers(self.input_state.modifiers()).build(),
|
||||
));
|
||||
self.ui.send(UiCommand::Input(WindowEvent::PointerMoved {
|
||||
device_id: None,
|
||||
position: pointer_lock_position,
|
||||
primary: true,
|
||||
source: winit::event::PointerSource::Mouse,
|
||||
}));
|
||||
}
|
||||
|
||||
self.input_state.process(
|
||||
&event,
|
||||
|message| self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Input(message))),
|
||||
|input| self.ui.send(UiCommand::Input(input)),
|
||||
);
|
||||
self.ui.send(UiCommand::Input(event.clone()));
|
||||
|
||||
match event {
|
||||
WindowEvent::CloseRequested => {
|
||||
@@ -631,73 +596,65 @@ impl ApplicationHandler for App {
|
||||
self.exit(Some(ExitReason::UiAccelerationFailure));
|
||||
}
|
||||
}
|
||||
WindowEvent::DragEntered { id, .. } => {
|
||||
let accepts = event_loop.data_transfer(id).is_ok_and(|data_transfer| data_transfer.has_type(&TypeHint::UriList));
|
||||
let actions: &[DndAction] = if accepts { &[DndAction::Copy] } else { &[] };
|
||||
if let Err(e) = event_loop.set_valid_dnd_actions(id, actions) {
|
||||
tracing::error!("Failed to set valid drag and drop actions: {e}");
|
||||
WindowEvent::DragDropped { paths, .. } => {
|
||||
for path in paths {
|
||||
match fs::read(&path) {
|
||||
Ok(content) => {
|
||||
let message = DesktopWrapperMessage::ImportFile { path, content };
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to read dropped file {}: {}", path.display(), e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
WindowEvent::DragDropped { id, .. } => match event_loop.fetch_data_transfer(id, &TypeHint::UriList) {
|
||||
Ok(serial) => self.pending_dnd_fetch = Some(serial),
|
||||
Err(e) => tracing::error!("Failed to fetch dropped data: {e}"),
|
||||
},
|
||||
WindowEvent::DataTransferReceived { serial, ref value, .. } if self.pending_clipboard_fetch == Some(serial) => match value.try_as_string() {
|
||||
Ok(content) => {
|
||||
self.pending_clipboard_fetch = None;
|
||||
let message = DesktopWrapperMessage::ClipboardReadResult { content: Some(content) };
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
|
||||
Err(e) => {
|
||||
self.pending_clipboard_fetch = None;
|
||||
tracing::error!("Failed to read from clipboard: {e}");
|
||||
let message = DesktopWrapperMessage::ClipboardReadResult { content: None };
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
},
|
||||
WindowEvent::DataTransferReceived { serial, ref value, .. } if self.pending_dnd_fetch == Some(serial) => match value.try_as_uris() {
|
||||
Ok(uris) => {
|
||||
self.pending_dnd_fetch = None;
|
||||
let paths = uris.iter().filter_map(|uri| url::Url::parse(uri).ok()?.to_file_path().ok());
|
||||
for path in paths {
|
||||
match fs::read(&path) {
|
||||
Ok(content) => {
|
||||
let message = DesktopWrapperMessage::IngestFile {
|
||||
path,
|
||||
content,
|
||||
action: IngestAction::Import,
|
||||
};
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to read dropped file {}: {}", path.display(), e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
|
||||
Err(e) => {
|
||||
self.pending_dnd_fetch = None;
|
||||
tracing::error!("Failed to read dropped data: {e}");
|
||||
}
|
||||
},
|
||||
|
||||
WindowEvent::PointerMoved { .. } | WindowEvent::PointerLeft { position: Some(_), .. } | WindowEvent::PointerEntered { .. }
|
||||
if !self.input_state.pointer_locked() && self.window_pending_drag =>
|
||||
// Forward and Back buttons are not supported by CEF and thus need to be directly forwarded the editor
|
||||
WindowEvent::PointerButton {
|
||||
button: ButtonSource::Mouse(button),
|
||||
state: ElementState::Pressed,
|
||||
..
|
||||
} => {
|
||||
let mouse_keys = match button {
|
||||
MouseButton::Back => Some(MouseKeys::BACK),
|
||||
MouseButton::Forward => Some(MouseKeys::FORWARD),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(mouse_keys) = mouse_keys {
|
||||
let message = DesktopWrapperMessage::Input(InputMessage::PointerDown {
|
||||
editor_mouse_state: MouseState { mouse_keys, ..Default::default() },
|
||||
modifier_keys: Default::default(),
|
||||
});
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
|
||||
let message = DesktopWrapperMessage::Input(InputMessage::PointerUp {
|
||||
editor_mouse_state: Default::default(),
|
||||
modifier_keys: Default::default(),
|
||||
});
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
}
|
||||
|
||||
WindowEvent::PointerMoved { position, .. } | WindowEvent::PointerLeft { position: Some(position), .. } | WindowEvent::PointerEntered { position, .. }
|
||||
if self.pointer_lock_position.is_none() =>
|
||||
{
|
||||
self.window_pending_drag = false;
|
||||
if let Some(window) = &self.window {
|
||||
window.start_drag();
|
||||
self.pointer_position = position;
|
||||
|
||||
if self.window_pending_drag {
|
||||
self.window_pending_drag = false;
|
||||
if let Some(window) = &self.window {
|
||||
window.start_drag();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
WindowEvent::PointerButton {
|
||||
button,
|
||||
button: ButtonSource::Mouse(MouseButton::Left),
|
||||
state: ElementState::Released,
|
||||
..
|
||||
} if button.clone().mouse_button() == Some(MouseButton::Left) => {
|
||||
} => {
|
||||
self.window_pending_drag = false;
|
||||
}
|
||||
|
||||
@@ -706,7 +663,7 @@ impl ApplicationHandler for App {
|
||||
}
|
||||
|
||||
fn device_event(&mut self, _event_loop: &dyn ActiveEventLoop, _device_id: Option<winit::event::DeviceId>, event: winit::event::DeviceEvent) {
|
||||
if self.input_state.pointer_locked()
|
||||
if self.pointer_lock_position.is_some()
|
||||
&& let winit::event::DeviceEvent::PointerMotion { delta: (x, y) } = event
|
||||
{
|
||||
let message = DesktopWrapperMessage::PointerLockMove { x, y };
|
||||
|
||||
+4
-4
@@ -20,10 +20,10 @@ pub(crate) fn clear_dir(path: &PathBuf) {
|
||||
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()
|
||||
&& let Err(e) = fs::remove_file(&entry_path)
|
||||
{
|
||||
tracing::error!("Failed to remove file 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,10 +8,6 @@ pub(crate) enum AppEvent {
|
||||
WebCommunicationInitialized,
|
||||
DesktopWrapperMessage(DesktopWrapperMessage),
|
||||
NodeGraphExecutionResult(NodeGraphExecutionResult),
|
||||
ClipboardRead,
|
||||
ClipboardWrite {
|
||||
content: String,
|
||||
},
|
||||
Exit,
|
||||
UiCrashed,
|
||||
OpenFiles(Vec<std::path::PathBuf>),
|
||||
|
||||
@@ -1,455 +0,0 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::time::{Duration, Instant};
|
||||
use winit::dpi::PhysicalPosition;
|
||||
use winit::event::{ButtonSource, ElementState, MouseButton, MouseScrollDelta, PointerSource, TabletToolData, TabletToolKind, WindowEvent};
|
||||
use winit::keyboard::ModifiersState;
|
||||
|
||||
use crate::ui::{InputEvent, MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT, PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
|
||||
use crate::wrapper::messages::{EditorPointerState, InputMessage, ModifierKeys, MouseKeys, ScrollDelta};
|
||||
|
||||
// Marks input event as observe-only, meaning it should not result in any input messages being send by the frontend.
|
||||
// And should instead be ignored by frontend input processing and only be used to update the UI state (hover, cursor).
|
||||
// TODO(Timon): Remove and find a less hacky solution
|
||||
trait ObserveOnlyExt {
|
||||
fn observe_only(self) -> Self;
|
||||
}
|
||||
impl ObserveOnlyExt for crate::ui::InputEventBuilder {
|
||||
fn observe_only(self) -> Self {
|
||||
self.num_lock(true)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct InputState {
|
||||
start: Instant,
|
||||
viewport_info: Option<ViewportInfo>,
|
||||
direct_input: bool,
|
||||
modifiers: ModifiersState,
|
||||
pointer_position: PhysicalPosition<f64>,
|
||||
pointer_state: PointerState,
|
||||
click_tracker: ClickTracker,
|
||||
shake_tracker: ShakeTracker,
|
||||
}
|
||||
|
||||
impl InputState {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
start: Instant::now(),
|
||||
viewport_info: None,
|
||||
direct_input: false,
|
||||
modifiers: ModifiersState::default(),
|
||||
pointer_position: PhysicalPosition::default(),
|
||||
pointer_state: PointerState::Hover { route: Route::Ui },
|
||||
click_tracker: ClickTracker::default(),
|
||||
shake_tracker: ShakeTracker::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_viewport_info(&mut self, x: f64, y: f64, width: f64, height: f64, scale: f64) {
|
||||
self.viewport_info = Some(ViewportInfo { x, y, width, height, scale });
|
||||
}
|
||||
|
||||
pub(crate) fn set_direct_input(&mut self, enabled: bool) {
|
||||
self.direct_input = enabled;
|
||||
}
|
||||
|
||||
pub(crate) fn lock_pointer(&mut self) {
|
||||
self.pointer_state = match self.pointer_state {
|
||||
PointerState::Hover { route } => PointerState::Locked {
|
||||
route,
|
||||
keys: MouseKeys::empty(),
|
||||
position: self.pointer_position,
|
||||
},
|
||||
PointerState::Stroke { route, keys } | PointerState::Locked { route, keys, .. } => PointerState::Locked {
|
||||
route,
|
||||
keys,
|
||||
position: self.pointer_position,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) fn unlock_pointer(&mut self) -> Option<PhysicalPosition<f64>> {
|
||||
let PointerState::Locked {
|
||||
route: resume,
|
||||
keys,
|
||||
position: restore,
|
||||
} = self.pointer_state
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
self.pointer_position = restore;
|
||||
self.pointer_state = match keys.is_empty() {
|
||||
true => PointerState::Hover { route: Route::Ui },
|
||||
false => PointerState::Stroke { route: resume, keys },
|
||||
};
|
||||
Some(restore)
|
||||
}
|
||||
|
||||
pub(crate) fn pointer_locked(&self) -> bool {
|
||||
matches!(self.pointer_state, PointerState::Locked { .. })
|
||||
}
|
||||
|
||||
pub(crate) fn modifiers(&self) -> ModifiersState {
|
||||
self.modifiers
|
||||
}
|
||||
|
||||
pub(crate) fn process(&mut self, event: &WindowEvent, mut editor_callback: impl FnMut(InputMessage), mut ui_callback: impl FnMut(InputEvent)) {
|
||||
match event {
|
||||
WindowEvent::PointerMoved { position, source, .. } => {
|
||||
self.pointer_position = *position;
|
||||
|
||||
let route = match self.pointer_state {
|
||||
PointerState::Hover { .. } => {
|
||||
let next = self.route(*position);
|
||||
self.pointer_state = PointerState::Hover { route: next };
|
||||
next
|
||||
}
|
||||
PointerState::Stroke { route, .. } => route,
|
||||
PointerState::Locked { keys, route: resume, .. } => match keys.is_empty() {
|
||||
true => Route::Ui,
|
||||
false => resume,
|
||||
},
|
||||
};
|
||||
match route {
|
||||
Route::Ui => ui_callback(InputEvent::pointer().position(*position).moved().modifiers(self.modifiers).build()),
|
||||
Route::Editor => {
|
||||
if !self.pointer_locked() {
|
||||
ui_callback(InputEvent::pointer().position(*position).moved().modifiers(self.modifiers).observe_only().build());
|
||||
}
|
||||
let editor_mouse_state = match source {
|
||||
PointerSource::TabletTool { kind, data } => self.tablet_pointer_state(kind, data),
|
||||
_ => self.pointer_state(),
|
||||
};
|
||||
let modifier_keys = self.modifier_keys();
|
||||
if self.shake_tracker.detect(*position, self.start.elapsed()) {
|
||||
editor_callback(InputMessage::PointerShake { editor_mouse_state, modifier_keys });
|
||||
}
|
||||
editor_callback(InputMessage::PointerMove { editor_mouse_state, modifier_keys });
|
||||
}
|
||||
}
|
||||
}
|
||||
WindowEvent::PointerEntered { position, .. } => {
|
||||
self.pointer_position = *position;
|
||||
ui_callback(InputEvent::pointer().position(*position).entered().modifiers(self.modifiers).build())
|
||||
}
|
||||
WindowEvent::PointerLeft { position: Some(position), .. } => {
|
||||
self.pointer_position = *position;
|
||||
ui_callback(InputEvent::pointer().position(*position).exited().modifiers(self.modifiers).build())
|
||||
}
|
||||
WindowEvent::PointerLeft { position: None, .. } => ui_callback(InputEvent::pointer().exited().modifiers(self.modifiers).build()),
|
||||
WindowEvent::PointerButton { state, button, position, .. } => {
|
||||
self.pointer_position = *position;
|
||||
|
||||
let mouse_button = button.clone().mouse_button();
|
||||
let keys = match mouse_button {
|
||||
Some(MouseButton::Left) => MouseKeys::LEFT,
|
||||
Some(MouseButton::Right) => MouseKeys::RIGHT,
|
||||
Some(MouseButton::Middle) => MouseKeys::MIDDLE,
|
||||
Some(MouseButton::Back) => MouseKeys::BACK,
|
||||
Some(MouseButton::Forward) => MouseKeys::FORWARD,
|
||||
_ => MouseKeys::NONE,
|
||||
};
|
||||
|
||||
let (pointer, route) = match self.pointer_state {
|
||||
PointerState::Hover { route } => match (state.is_pressed(), keys.is_empty()) {
|
||||
(true, false) => {
|
||||
let route = self.route(*position);
|
||||
(PointerState::Stroke { route, keys }, route)
|
||||
}
|
||||
(true, true) => (PointerState::Hover { route }, self.route(*position)),
|
||||
(false, _) => (PointerState::Hover { route }, route),
|
||||
},
|
||||
PointerState::Stroke { route, keys: mut held } => {
|
||||
match state.is_pressed() {
|
||||
true => held.insert(keys),
|
||||
false => held.remove(keys),
|
||||
}
|
||||
match held.is_empty() {
|
||||
true => (PointerState::Hover { route }, route),
|
||||
false => (PointerState::Stroke { route, keys: held }, route),
|
||||
}
|
||||
}
|
||||
PointerState::Locked { route, keys: mut held, position } => {
|
||||
let resume = if state.is_pressed() && held.is_empty() { Route::Ui } else { route };
|
||||
match state.is_pressed() {
|
||||
true => held.insert(keys),
|
||||
false => held.remove(keys),
|
||||
}
|
||||
(PointerState::Locked { route: resume, keys: held, position }, Route::Ui)
|
||||
}
|
||||
};
|
||||
self.pointer_state = pointer;
|
||||
|
||||
let count = mouse_button.map_or(1, |button| self.click_tracker.input(*position, button, *state));
|
||||
|
||||
let back_or_forward = matches!(mouse_button, Some(MouseButton::Back | MouseButton::Forward));
|
||||
let pointer = InputEvent::pointer().position(*position);
|
||||
let input = match state {
|
||||
ElementState::Pressed => pointer.pressed(button.clone(), count),
|
||||
ElementState::Released => pointer.released(button.clone(), count),
|
||||
}
|
||||
.modifiers(self.modifiers);
|
||||
if self.pointer_locked() || keys.is_empty() || !(back_or_forward || route == Route::Editor) {
|
||||
ui_callback(input.build());
|
||||
return;
|
||||
}
|
||||
if route == Route::Editor {
|
||||
ui_callback(input.observe_only().build());
|
||||
}
|
||||
|
||||
let editor_mouse_state = match button {
|
||||
ButtonSource::TabletTool { kind, data, .. } => self.tablet_pointer_state(kind, data),
|
||||
_ => self.pointer_state(),
|
||||
};
|
||||
let modifier_keys = self.modifier_keys();
|
||||
match state {
|
||||
ElementState::Pressed => editor_callback(InputMessage::PointerDown { editor_mouse_state, modifier_keys }),
|
||||
ElementState::Released if count % 2 == 0 => {
|
||||
editor_callback(InputMessage::PointerUp { editor_mouse_state, modifier_keys });
|
||||
editor_callback(InputMessage::DoubleClick {
|
||||
editor_mouse_state: EditorPointerState {
|
||||
mouse_keys: keys,
|
||||
..editor_mouse_state
|
||||
},
|
||||
modifier_keys,
|
||||
});
|
||||
}
|
||||
ElementState::Released => editor_callback(InputMessage::PointerUp { editor_mouse_state, modifier_keys }),
|
||||
}
|
||||
}
|
||||
WindowEvent::MouseWheel { delta, .. } => {
|
||||
if self.pointer_locked() || self.ui_captures(self.pointer_position) {
|
||||
let input = match delta {
|
||||
MouseScrollDelta::LineDelta(x, y) => InputEvent::pointer().scrolled_lines(f64::from(*x), f64::from(*y)),
|
||||
MouseScrollDelta::PixelDelta(position) => InputEvent::pointer().scrolled_pixels(position.x, position.y),
|
||||
_ => return,
|
||||
};
|
||||
ui_callback(input.modifiers(self.modifiers).build());
|
||||
return;
|
||||
}
|
||||
|
||||
let (x, y) = match delta {
|
||||
MouseScrollDelta::LineDelta(x, y) => (f64::from(*x) * SCROLL_LINE_WIDTH, f64::from(*y) * SCROLL_LINE_HEIGHT),
|
||||
MouseScrollDelta::PixelDelta(position) => (position.x, position.y),
|
||||
_ => return,
|
||||
};
|
||||
|
||||
let scroll_delta = ScrollDelta::new(-x * SCROLL_SPEED_X, -y * SCROLL_SPEED_Y, 0.);
|
||||
|
||||
editor_callback(InputMessage::WheelScroll {
|
||||
editor_mouse_state: EditorPointerState { scroll_delta, ..self.pointer_state() },
|
||||
modifier_keys: self.modifier_keys(),
|
||||
});
|
||||
}
|
||||
WindowEvent::PinchGesture { delta, .. } => {
|
||||
if self.pointer_locked() || self.ui_captures(self.pointer_position) || !delta.is_normal() {
|
||||
ui_callback(InputEvent::pointer().zoomed(*delta).modifiers(self.modifiers).build());
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO: This is a temporary solution to handle pinch gestures, we should handle pinch gestures editor-side instead.
|
||||
let scroll_delta = ScrollDelta::new(0., -delta * PINCH_ZOOM_SPEED, 0.);
|
||||
editor_callback(InputMessage::WheelScroll {
|
||||
editor_mouse_state: EditorPointerState { scroll_delta, ..self.pointer_state() },
|
||||
modifier_keys: self.modifier_keys() | ModifierKeys::CONTROL,
|
||||
});
|
||||
}
|
||||
WindowEvent::ModifiersChanged(modifiers) => {
|
||||
self.modifiers = modifiers.state();
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. } => ui_callback(InputEvent::key(event).modifiers(self.modifiers).build()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn scale(&self) -> f64 {
|
||||
self.viewport_info.as_ref().map_or(1., |info| info.scale)
|
||||
}
|
||||
|
||||
fn ui_captures(&self, position: PhysicalPosition<f64>) -> bool {
|
||||
!self.direct_input || !self.viewport_info.as_ref().is_some_and(|info| info.contains(position))
|
||||
}
|
||||
|
||||
fn route(&self, position: PhysicalPosition<f64>) -> Route {
|
||||
if self.ui_captures(position) { Route::Ui } else { Route::Editor }
|
||||
}
|
||||
|
||||
fn pointer_keys(&self) -> MouseKeys {
|
||||
match self.pointer_state {
|
||||
PointerState::Hover { .. } => MouseKeys::empty(),
|
||||
PointerState::Stroke { keys, .. } | PointerState::Locked { keys, .. } => keys,
|
||||
}
|
||||
}
|
||||
|
||||
fn pointer_state(&self) -> EditorPointerState {
|
||||
EditorPointerState {
|
||||
editor_position: (self.pointer_position.x / self.scale(), self.pointer_position.y / self.scale()).into(),
|
||||
mouse_keys: self.pointer_keys(),
|
||||
time: Some(self.start.elapsed().as_secs_f64() * 1000.),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn tablet_pointer_state(&self, kind: &TabletToolKind, data: &TabletToolData) -> EditorPointerState {
|
||||
EditorPointerState {
|
||||
pressure: data.force.map(|force| force.normalized(None)),
|
||||
tilt: data.clone().tilt().map(|tilt| (f64::from(tilt.x), f64::from(tilt.y)).into()),
|
||||
twist: data.twist.map(f64::from),
|
||||
wheel: data.tangential_force.map(f64::from),
|
||||
eraser: matches!(kind, TabletToolKind::Eraser),
|
||||
..self.pointer_state()
|
||||
}
|
||||
}
|
||||
|
||||
fn modifier_keys(&self) -> ModifierKeys {
|
||||
let mut keys = ModifierKeys::empty();
|
||||
keys.set(ModifierKeys::SHIFT, self.modifiers.shift_key());
|
||||
keys.set(ModifierKeys::CONTROL, self.modifiers.control_key());
|
||||
keys.set(ModifierKeys::ALT, self.modifiers.alt_key());
|
||||
keys.set(ModifierKeys::META_OR_COMMAND, self.modifiers.meta_key());
|
||||
keys
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum PointerState {
|
||||
Hover { route: Route },
|
||||
Stroke { route: Route, keys: MouseKeys },
|
||||
Locked { route: Route, keys: MouseKeys, position: PhysicalPosition<f64> },
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Route {
|
||||
Ui,
|
||||
Editor,
|
||||
}
|
||||
|
||||
struct ViewportInfo {
|
||||
x: f64,
|
||||
y: f64,
|
||||
width: f64,
|
||||
height: f64,
|
||||
scale: f64,
|
||||
}
|
||||
|
||||
impl ViewportInfo {
|
||||
fn contains(&self, position: PhysicalPosition<f64>) -> bool {
|
||||
position.x >= self.x && position.y >= self.y && position.x <= self.x + self.width && position.y <= self.y + self.height
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ClickTracker {
|
||||
left: ClickChains,
|
||||
right: ClickChains,
|
||||
middle: ClickChains,
|
||||
back: ClickChains,
|
||||
forward: ClickChains,
|
||||
}
|
||||
|
||||
impl ClickTracker {
|
||||
fn input(&mut self, position: PhysicalPosition<f64>, button: MouseButton, state: ElementState) -> u32 {
|
||||
let position = (position.x as i32, position.y as i32);
|
||||
let clicks = match button {
|
||||
MouseButton::Left => &mut self.left,
|
||||
MouseButton::Right => &mut self.right,
|
||||
MouseButton::Middle => &mut self.middle,
|
||||
MouseButton::Back => &mut self.back,
|
||||
MouseButton::Forward => &mut self.forward,
|
||||
_ => return 1,
|
||||
};
|
||||
let chain = match state {
|
||||
ElementState::Pressed => &mut clicks.down,
|
||||
ElementState::Released => &mut clicks.up,
|
||||
};
|
||||
|
||||
let now = Instant::now();
|
||||
let count = match chain {
|
||||
Some(previous) => {
|
||||
let within_time = now.saturating_duration_since(previous.time) <= MULTICLICK_TIMEOUT;
|
||||
let dx = position.0.abs_diff(previous.position.0) as usize;
|
||||
let dy = position.1.abs_diff(previous.position.1) as usize;
|
||||
let within_distance = dx <= MULTICLICK_ALLOWED_TRAVEL && dy <= MULTICLICK_ALLOWED_TRAVEL;
|
||||
if within_time && within_distance { previous.count.saturating_add(1) } else { 1 }
|
||||
}
|
||||
None => 1,
|
||||
};
|
||||
*chain = Some(Click { time: now, position, count });
|
||||
count
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ClickChains {
|
||||
down: Option<Click>,
|
||||
up: Option<Click>,
|
||||
}
|
||||
|
||||
struct Click {
|
||||
time: Instant,
|
||||
position: (i32, i32),
|
||||
count: u32,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ShakeTracker {
|
||||
samples: VecDeque<(PhysicalPosition<f64>, Duration)>,
|
||||
last: Option<Duration>,
|
||||
}
|
||||
|
||||
// Keep heuristic and constants in sync with `detectShake` in `frontend/src/utility-functions/input.ts`.
|
||||
impl ShakeTracker {
|
||||
const SENSITIVITY_DIRECTION_CHANGES: usize = 3;
|
||||
const SENSITIVITY_DISTANCE_TO_DISPLACEMENT_RATIO: f64 = 0.1;
|
||||
const DETECTION_WINDOW: Duration = Duration::from_millis(500);
|
||||
const DEBOUNCE: Duration = Duration::from_millis(1000);
|
||||
|
||||
fn detect(&mut self, position: PhysicalPosition<f64>, now: Duration) -> bool {
|
||||
self.samples.push_back((position, now));
|
||||
|
||||
while self.samples.front().is_some_and(|&(_, time)| now.saturating_sub(time) > Self::DETECTION_WINDOW) {
|
||||
self.samples.pop_front();
|
||||
}
|
||||
|
||||
if self.samples.len() <= 3 || self.last.is_some_and(|time| now.saturating_sub(time) <= Self::DEBOUNCE) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut total_distance_squared = 0.;
|
||||
for i in 1..self.samples.len() {
|
||||
let (p1, _) = self.samples[i - 1];
|
||||
let (p2, _) = self.samples[i];
|
||||
total_distance_squared += (p2.x - p1.x).powi(2) + (p2.y - p1.y).powi(2);
|
||||
}
|
||||
|
||||
let mut direction_changes = 0;
|
||||
let mut average = PhysicalPosition::new(0., 0.);
|
||||
let interior_count = self.samples.len() - 2;
|
||||
for i in 0..interior_count {
|
||||
let (p1, _) = self.samples[i];
|
||||
let (p2, _) = self.samples[i + 1];
|
||||
let (p3, _) = self.samples[i + 2];
|
||||
|
||||
let vector1 = (p2.x - p1.x, p2.y - p1.y);
|
||||
let vector2 = (p3.x - p2.x, p3.y - p2.y);
|
||||
if vector1.0 * vector2.0 + vector1.1 * vector2.1 < 0. {
|
||||
direction_changes += 1;
|
||||
}
|
||||
|
||||
average.x += p2.x;
|
||||
average.y += p2.y;
|
||||
}
|
||||
average.x /= interior_count as f64;
|
||||
average.y /= interior_count as f64;
|
||||
|
||||
let (last, _) = self.samples[self.samples.len() - 1];
|
||||
let displacement_squared = (last.x - average.x).powi(2) + (last.y - average.y).powi(2);
|
||||
|
||||
if Self::SENSITIVITY_DISTANCE_TO_DISPLACEMENT_RATIO * total_distance_squared >= displacement_squared && direction_changes >= Self::SENSITIVITY_DIRECTION_CHANGES {
|
||||
self.last = Some(now);
|
||||
self.samples.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,6 @@ mod cli;
|
||||
mod dirs;
|
||||
mod event;
|
||||
mod gpu_context;
|
||||
mod input;
|
||||
mod persist;
|
||||
mod preferences;
|
||||
mod render;
|
||||
|
||||
@@ -71,11 +71,10 @@ fn garbage_collect_document_files(state: &PersistedState) {
|
||||
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_file()
|
||||
&& !valid_paths.contains(&path)
|
||||
&& let Err(e) = std::fs::remove_file(&path)
|
||||
{
|
||||
tracing::error!("Failed to remove orphaned document file {path:?}: {e}");
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,12 +52,13 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
return srgb_to_linear(immediates.background_color);
|
||||
}
|
||||
|
||||
let ui_sample = textureSample(t_ui, s_diffuse, ui_coordinate);
|
||||
if (ui_sample.a >= 0.999) {
|
||||
return srgb_to_linear(ui_sample);
|
||||
let ui_linear = srgb_to_linear(textureSample(t_ui, s_diffuse, ui_coordinate));
|
||||
if (ui_linear.a >= 0.999) {
|
||||
return ui_linear;
|
||||
}
|
||||
|
||||
let ui_srgb = unpremultiply(ui_sample);
|
||||
// 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;
|
||||
if (viewport_coordinate.x < 0.0 || viewport_coordinate.x > 1.0 ||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use wgpu::PresentMode;
|
||||
|
||||
use crate::window::Window;
|
||||
use crate::wrapper::{Texture, WgpuContext, WgpuCurrentSurfaceTexture, WgpuExecutor, WgpuSurface};
|
||||
use crate::wrapper::{WgpuContext, WgpuCurrentSurfaceTexture, WgpuExecutor, WgpuSurface};
|
||||
|
||||
#[derive(derivative::Derivative)]
|
||||
#[derivative(Debug)]
|
||||
@@ -10,14 +10,14 @@ pub(crate) struct RenderState {
|
||||
executor: WgpuExecutor,
|
||||
config: wgpu::SurfaceConfiguration,
|
||||
render_pipeline: wgpu::RenderPipeline,
|
||||
transparent_texture: Texture,
|
||||
transparent_texture: std::sync::Arc<wgpu::Texture>,
|
||||
sampler: wgpu::Sampler,
|
||||
desired_width: u32,
|
||||
desired_height: u32,
|
||||
viewport_scale: [f32; 2],
|
||||
viewport_offset: [f32; 2],
|
||||
viewport_texture: Option<Texture>,
|
||||
overlays_texture: Option<Texture>,
|
||||
viewport_texture: Option<std::sync::Arc<wgpu::Texture>>,
|
||||
overlays_texture: Option<std::sync::Arc<wgpu::Texture>>,
|
||||
ui_texture: Option<wgpu::Texture>,
|
||||
bind_group: Option<wgpu::BindGroup>,
|
||||
#[derivative(Debug = "ignore")]
|
||||
@@ -46,8 +46,8 @@ impl RenderState {
|
||||
|
||||
surface.configure(&context.device, &config);
|
||||
|
||||
let transparent_texture = Texture::from(context.device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("transparent_fallback"),
|
||||
let transparent_texture = std::sync::Arc::new(context.device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("Transparent Texture"),
|
||||
size: wgpu::Extent3d {
|
||||
width: 1,
|
||||
height: 1,
|
||||
@@ -193,7 +193,7 @@ impl RenderState {
|
||||
self.surface_outdated = true;
|
||||
}
|
||||
|
||||
pub(crate) fn bind_viewport_texture(&mut self, viewport_texture: Texture) {
|
||||
pub(crate) fn bind_viewport_texture(&mut self, viewport_texture: std::sync::Arc<wgpu::Texture>) {
|
||||
self.viewport_texture = Some(viewport_texture);
|
||||
self.update_bindgroup();
|
||||
}
|
||||
@@ -231,7 +231,7 @@ impl RenderState {
|
||||
let result = futures::executor::block_on(self.executor.render_vello_scene(&scene, size, &Default::default(), None));
|
||||
match result {
|
||||
Ok(texture) => {
|
||||
self.overlays_texture = Some(texture);
|
||||
self.overlays_texture = Some(texture.into());
|
||||
}
|
||||
Err(e) => {
|
||||
self.overlays_texture = None;
|
||||
|
||||
@@ -43,6 +43,13 @@ pub(crate) struct Window {
|
||||
#[allow(dead_code)]
|
||||
native_handle: native::NativeWindowImpl,
|
||||
custom_cursors: HashMap<CustomCursorSource, CustomCursor>,
|
||||
clipboard: Option<window_clipboard::Clipboard>,
|
||||
}
|
||||
impl Drop for Window {
|
||||
fn drop(&mut self) {
|
||||
// Clipboard must be dropped before `winit_window`
|
||||
drop(self.clipboard.take());
|
||||
}
|
||||
}
|
||||
|
||||
impl Window {
|
||||
@@ -63,10 +70,12 @@ impl Window {
|
||||
|
||||
let winit_window = event_loop.create_window(attributes).unwrap();
|
||||
let native_handle = native::NativeWindowImpl::new(winit_window.as_ref(), app_event_scheduler);
|
||||
let clipboard = unsafe { window_clipboard::Clipboard::connect(&winit_window) }.ok();
|
||||
Self {
|
||||
winit_window: winit_window.into(),
|
||||
native_handle,
|
||||
custom_cursors: HashMap::new(),
|
||||
clipboard,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,4 +208,28 @@ impl Window {
|
||||
pub(crate) fn update_menu(&self, entries: Vec<MenuItem>) {
|
||||
self.native_handle.update_menu(entries);
|
||||
}
|
||||
|
||||
pub(crate) fn clipboard_read(&self) -> Option<String> {
|
||||
let Some(clipboard) = &self.clipboard else {
|
||||
tracing::error!("Clipboard not available");
|
||||
return None;
|
||||
};
|
||||
match clipboard.read() {
|
||||
Ok(data) => Some(data),
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to read from clipboard: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn clipboard_write(&mut self, data: String) {
|
||||
let Some(clipboard) = &mut self.clipboard else {
|
||||
tracing::error!("Clipboard not available");
|
||||
return;
|
||||
};
|
||||
if let Err(e) = clipboard.write(data) {
|
||||
tracing::error!("Failed to write to clipboard: {e}")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -344,14 +344,6 @@ unsafe fn position_helper(main: HWND, helper: HWND) {
|
||||
let h = (r.bottom - r.top) + RESIZE_BAND_THICKNESS * 2;
|
||||
|
||||
let _ = unsafe { SetWindowPos(helper, Some(main), x, y, w, h, SWP_NOACTIVATE | SWP_NOSENDCHANGING) };
|
||||
|
||||
let outer = unsafe { CreateRectRgn(0, 0, w, h) };
|
||||
let inner = unsafe { CreateRectRgn(RESIZE_BAND_THICKNESS, RESIZE_BAND_THICKNESS, w - RESIZE_BAND_THICKNESS, h - RESIZE_BAND_THICKNESS) };
|
||||
let _ = unsafe { CombineRgn(Some(outer), Some(outer), Some(inner), RGN_DIFF) };
|
||||
let _ = unsafe { DeleteObject(inner.into()) };
|
||||
if unsafe { SetWindowRgn(helper, Some(outer), false) } == 0 {
|
||||
let _ = unsafe { DeleteObject(outer.into()) };
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn calculate_hit(helper: HWND, lparam: LPARAM) -> u32 {
|
||||
|
||||
@@ -2,11 +2,9 @@
|
||||
name = "graphite-desktop-ui"
|
||||
description = "Renders the Graphite editor frontend UI into wgpu textures"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
|
||||
+18
-18
@@ -1,23 +1,5 @@
|
||||
use std::time::Duration;
|
||||
|
||||
pub const MULTICLICK_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
pub const MULTICLICK_ALLOWED_TRAVEL: usize = 4;
|
||||
|
||||
pub const SCROLL_LINE_HEIGHT: f64 = 40.;
|
||||
pub const SCROLL_LINE_WIDTH: f64 = 40.;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const SCROLL_SPEED_X: f64 = 3.;
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const SCROLL_SPEED_Y: f64 = 3.;
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub const SCROLL_SPEED_X: f64 = 1.;
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub const SCROLL_SPEED_Y: f64 = 1.;
|
||||
|
||||
pub const PINCH_ZOOM_SPEED: f64 = 300.;
|
||||
|
||||
pub(crate) const RESOURCE_SCHEME: &str = "resources";
|
||||
pub(crate) const RESOURCE_DOMAIN: &str = "resources";
|
||||
|
||||
@@ -35,3 +17,21 @@ pub(crate) const HOST_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) const IPC_BOOTSTRAP_PREFIX: &str = "art.graphite.Graphite.ipc.";
|
||||
|
||||
pub(crate) const SCROLL_LINE_HEIGHT: usize = 40;
|
||||
pub(crate) const SCROLL_LINE_WIDTH: usize = 40;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) const SCROLL_SPEED_X: f32 = 3.;
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) const SCROLL_SPEED_Y: f32 = 3.;
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub(crate) const SCROLL_SPEED_X: f32 = 1.;
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub(crate) const SCROLL_SPEED_Y: f32 = 1.;
|
||||
|
||||
pub(crate) const PINCH_ZOOM_SPEED: f64 = 300.;
|
||||
|
||||
pub(crate) const MULTICLICK_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
pub(crate) const MULTICLICK_ALLOWED_TRAVEL: usize = 4;
|
||||
@@ -223,7 +223,6 @@ fn create_browser(delegate: BrowserDelegate, frames: FrameStreamer, view_info_se
|
||||
.map(|browser| BrowserContext {
|
||||
delegate,
|
||||
browser,
|
||||
input: input::InputState::default(),
|
||||
view_info_sender,
|
||||
_instance_dir: instance_dir,
|
||||
})
|
||||
@@ -253,8 +252,12 @@ pub(crate) enum InitError {
|
||||
pub(crate) struct CefContextHandle;
|
||||
|
||||
impl CefContextHandle {
|
||||
pub(crate) fn process_input(&self, event: InputEvent) {
|
||||
with_context(move |context| input::process(&mut context.input, &context.browser, &event));
|
||||
pub(crate) fn apply_input(&self, events: Vec<InputEvent>) {
|
||||
with_context(move |context| {
|
||||
for event in &events {
|
||||
input::apply(&context.browser, event);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn update_view_info(&self, update: ViewInfoUpdate) {
|
||||
@@ -273,7 +276,6 @@ impl CefContextHandle {
|
||||
struct BrowserContext {
|
||||
delegate: BrowserDelegate,
|
||||
browser: Browser,
|
||||
input: input::InputState,
|
||||
view_info_sender: Sender<ViewInfoUpdate>,
|
||||
_instance_dir: TempDir,
|
||||
}
|
||||
|
||||
+207
-191
@@ -1,235 +1,251 @@
|
||||
pub(crate) mod event;
|
||||
pub(crate) use event::InputEvent;
|
||||
use cef::sys::{cef_key_event_type_t, cef_mouse_button_type_t};
|
||||
use cef::{Browser, ImplBrowser, ImplBrowserHost, KeyEvent, MouseEvent};
|
||||
use winit::event::{ButtonSource, ElementState, MouseButton, MouseScrollDelta, WindowEvent};
|
||||
|
||||
mod keymap;
|
||||
use keymap::{ToCharRepresentation, ToNativeKeycode, ToVKBits};
|
||||
|
||||
use cef::sys::{cef_event_flags_t, cef_key_event_type_t, cef_mouse_button_type_t};
|
||||
use cef::{Browser, ImplBrowser, ImplBrowserHost, KeyEvent, MouseEvent};
|
||||
use winit::dpi::PhysicalPosition;
|
||||
use winit::keyboard::{Key, KeyLocation, NamedKey};
|
||||
mod state;
|
||||
pub(crate) use state::{CefModifiers, InputState};
|
||||
|
||||
use super::consts::{PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
|
||||
use event::{InputEventKind, KeyAction, Modifiers, MouseButton, PointerAction};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct InputState {
|
||||
position: PhysicalPosition<f64>,
|
||||
buttons: ButtonStates,
|
||||
/// A window input translated into the plain data CEF consumes — no winit types, so it can
|
||||
/// be applied to a browser living in another process.
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) enum InputEvent {
|
||||
MouseMove { data: MouseData, leave: bool },
|
||||
MouseClick { data: MouseData, button: MouseButtonKind, up: bool, click_count: i32 },
|
||||
MouseWheel { data: MouseData, delta_x: i32, delta_y: i32 },
|
||||
Key(KeyData),
|
||||
}
|
||||
|
||||
impl InputState {
|
||||
fn pointer_move(&mut self, position: PhysicalPosition<f64>) -> bool {
|
||||
let moved = (position.x as i32, position.y as i32) != (self.position.x as i32, self.position.y as i32);
|
||||
self.position = position;
|
||||
moved
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) struct MouseData {
|
||||
pub(crate) x: i32,
|
||||
pub(crate) y: i32,
|
||||
pub(crate) modifiers: u32,
|
||||
}
|
||||
|
||||
pub(crate) fn process(state: &mut InputState, browser: &Browser, event: &InputEvent) {
|
||||
let Some(host) = browser.host() else { return };
|
||||
match &event.kind {
|
||||
InputEventKind::Pointer { position, action } => {
|
||||
let position = position.unwrap_or(state.position);
|
||||
match *action {
|
||||
PointerAction::Move => {
|
||||
if !state.pointer_move(position) {
|
||||
return;
|
||||
}
|
||||
let flags = event_flags(&event.modifiers, &state.buttons);
|
||||
host.send_mouse_move_event(Some(&mouse_event(position, flags)), 0);
|
||||
}
|
||||
PointerAction::Enter => {
|
||||
state.pointer_move(position);
|
||||
let flags = event_flags(&event.modifiers, &state.buttons);
|
||||
host.send_mouse_move_event(Some(&mouse_event(position, flags)), 0);
|
||||
}
|
||||
PointerAction::Exit => {
|
||||
state.pointer_move(position);
|
||||
let flags = event_flags(&event.modifiers, &state.buttons);
|
||||
host.send_mouse_move_event(Some(&mouse_event(position, flags)), 1);
|
||||
}
|
||||
PointerAction::Press { button, count } | PointerAction::Release { button, count } => {
|
||||
state.pointer_move(position);
|
||||
let cef_button = match button {
|
||||
MouseButton::Left => cef_mouse_button_type_t::MBT_LEFT,
|
||||
MouseButton::Right => cef_mouse_button_type_t::MBT_RIGHT,
|
||||
MouseButton::Middle => cef_mouse_button_type_t::MBT_MIDDLE,
|
||||
MouseButton::Unknown => return,
|
||||
};
|
||||
let up = matches!(action, PointerAction::Release { .. });
|
||||
state.buttons.update(button, !up);
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) enum MouseButtonKind {
|
||||
Left,
|
||||
Right,
|
||||
Middle,
|
||||
}
|
||||
|
||||
// CEF only understands single, double and triple clicks; further clicks alternate between double and triple.
|
||||
let count = match count {
|
||||
0 | 1 => 1,
|
||||
count if count % 2 == 0 => 2,
|
||||
_ => 3,
|
||||
};
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) enum KeyEventKind {
|
||||
RawKeyDown,
|
||||
KeyUp,
|
||||
Char,
|
||||
}
|
||||
|
||||
let flags = event_flags(&event.modifiers, &state.buttons);
|
||||
host.send_mouse_click_event(Some(&mouse_event(position, flags)), cef::MouseButtonType::from(cef_button), up as i32, count);
|
||||
}
|
||||
PointerAction::ScrollLines { x, y } => {
|
||||
let flags = event_flags(&event.modifiers, &state.buttons);
|
||||
let delta_x = (x * SCROLL_LINE_WIDTH * SCROLL_SPEED_X) as i32;
|
||||
let delta_y = (y * SCROLL_LINE_HEIGHT * SCROLL_SPEED_Y) as i32;
|
||||
host.send_mouse_wheel_event(Some(&mouse_event(position, flags)), delta_x, delta_y);
|
||||
}
|
||||
PointerAction::ScrollPixels { x, y } => {
|
||||
let flags = event_flags(&event.modifiers, &state.buttons) | PRECISION_SCROLLING_DELTA;
|
||||
host.send_mouse_wheel_event(Some(&mouse_event(position, flags)), (x * SCROLL_SPEED_X) as i32, (y * SCROLL_SPEED_Y) as i32);
|
||||
}
|
||||
PointerAction::Zoom(delta) => {
|
||||
if !delta.is_normal() {
|
||||
return;
|
||||
}
|
||||
let flags = CONTROL_DOWN | PRECISION_SCROLLING_DELTA;
|
||||
host.send_mouse_wheel_event(Some(&mouse_event(position, flags)), 0, (delta * PINCH_ZOOM_SPEED).round() as i32);
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) struct KeyData {
|
||||
pub(crate) kind: KeyEventKind,
|
||||
pub(crate) modifiers: u32,
|
||||
pub(crate) windows_key_code: i32,
|
||||
pub(crate) native_key_code: i32,
|
||||
pub(crate) character: u16,
|
||||
pub(crate) unmodified_character: u16,
|
||||
}
|
||||
|
||||
/// Turns a winit event into zero or more [`InputEvent`]s, updating the tracked input state
|
||||
/// (cursor position, click counting, modifiers) along the way.
|
||||
pub(crate) fn translate(input_state: &mut InputState, event: &WindowEvent) -> Vec<InputEvent> {
|
||||
match event {
|
||||
WindowEvent::PointerMoved { position, .. } => {
|
||||
if !input_state.cursor_move(position) {
|
||||
return Vec::new();
|
||||
}
|
||||
vec![InputEvent::MouseMove {
|
||||
data: input_state.mouse_data(),
|
||||
leave: false,
|
||||
}]
|
||||
}
|
||||
InputEventKind::Key {
|
||||
key,
|
||||
key_without_modifiers,
|
||||
physical_key,
|
||||
location,
|
||||
text,
|
||||
action,
|
||||
} => {
|
||||
let mut flags = event_flags(&event.modifiers, &state.buttons);
|
||||
WindowEvent::PointerEntered { position, .. } => {
|
||||
let _ = input_state.cursor_move(position);
|
||||
vec![InputEvent::MouseMove {
|
||||
data: input_state.mouse_data(),
|
||||
leave: false,
|
||||
}]
|
||||
}
|
||||
WindowEvent::PointerLeft { position, .. } => {
|
||||
if let Some(position) = position {
|
||||
let _ = input_state.cursor_move(position);
|
||||
}
|
||||
vec![InputEvent::MouseMove {
|
||||
data: input_state.mouse_data(),
|
||||
leave: true,
|
||||
}]
|
||||
}
|
||||
WindowEvent::PointerButton { state, button, position, .. } => {
|
||||
let mouse_button = match button {
|
||||
ButtonSource::Mouse(mouse_button) => mouse_button,
|
||||
_ => {
|
||||
return Vec::new(); // TODO: Handle touch input
|
||||
}
|
||||
};
|
||||
|
||||
let own_flag = match key {
|
||||
Key::Named(NamedKey::Shift) => SHIFT_DOWN,
|
||||
Key::Named(NamedKey::Control) => CONTROL_DOWN,
|
||||
Key::Named(NamedKey::Alt) => ALT_DOWN,
|
||||
Key::Named(NamedKey::AltGraph) => ALTGR_DOWN,
|
||||
Key::Named(NamedKey::Meta) => COMMAND_DOWN,
|
||||
let _ = input_state.cursor_move(position);
|
||||
let click_count = input_state.mouse_input(mouse_button, state).into();
|
||||
let up = matches!(state, ElementState::Released);
|
||||
let button = match mouse_button {
|
||||
MouseButton::Left => MouseButtonKind::Left,
|
||||
MouseButton::Right => MouseButtonKind::Right,
|
||||
MouseButton::Middle => MouseButtonKind::Middle,
|
||||
_ => return Vec::new(),
|
||||
};
|
||||
|
||||
vec![InputEvent::MouseClick {
|
||||
data: input_state.mouse_data(),
|
||||
button,
|
||||
up,
|
||||
click_count,
|
||||
}]
|
||||
}
|
||||
WindowEvent::MouseWheel { delta, phase: _, device_id: _, .. } => {
|
||||
let (mut delta_x, mut delta_y) = match delta {
|
||||
MouseScrollDelta::LineDelta(x, y) => (x * SCROLL_LINE_WIDTH as f32, y * SCROLL_LINE_HEIGHT as f32),
|
||||
MouseScrollDelta::PixelDelta(physical_position) => (physical_position.x as f32, physical_position.y as f32),
|
||||
};
|
||||
delta_x *= SCROLL_SPEED_X;
|
||||
delta_y *= SCROLL_SPEED_Y;
|
||||
|
||||
vec![InputEvent::MouseWheel {
|
||||
data: input_state.mouse_data(),
|
||||
delta_x: delta_x as i32,
|
||||
delta_y: delta_y as i32,
|
||||
}]
|
||||
}
|
||||
WindowEvent::ModifiersChanged(modifiers) => {
|
||||
input_state.modifiers_changed(&modifiers.state());
|
||||
Vec::new()
|
||||
}
|
||||
WindowEvent::KeyboardInput { device_id: _, event, is_synthetic: _ } => {
|
||||
input_state.modifiers_apply_key_event(&event.logical_key, &event.state);
|
||||
|
||||
let mut kind = match (event.state, &event.logical_key) {
|
||||
(ElementState::Pressed, winit::keyboard::Key::Character(_)) => KeyEventKind::Char,
|
||||
(ElementState::Pressed, _) => KeyEventKind::RawKeyDown,
|
||||
(ElementState::Released, _) => KeyEventKind::KeyUp,
|
||||
};
|
||||
|
||||
let modifiers = input_state.cef_modifiers(&event.location, event.repeat).into();
|
||||
|
||||
let windows_key_code = match &event.logical_key {
|
||||
winit::keyboard::Key::Named(named) => named.to_vk_bits(),
|
||||
winit::keyboard::Key::Character(char) => char.chars().next().unwrap_or_default().to_vk_bits(),
|
||||
_ => 0,
|
||||
};
|
||||
match action {
|
||||
KeyAction::Press | KeyAction::Repeat => flags |= own_flag,
|
||||
KeyAction::Release => flags &= !own_flag,
|
||||
}
|
||||
|
||||
flags |= match location {
|
||||
KeyLocation::Left => IS_LEFT,
|
||||
KeyLocation::Right => IS_RIGHT,
|
||||
KeyLocation::Numpad => IS_KEY_PAD,
|
||||
KeyLocation::Standard => 0,
|
||||
};
|
||||
if *action == KeyAction::Repeat {
|
||||
flags |= IS_REPEAT;
|
||||
}
|
||||
let native_key_code = event.physical_key.to_native_keycode();
|
||||
|
||||
let windows_key_code = match key {
|
||||
Key::Named(named) => named.to_vk_bits(),
|
||||
Key::Character(char) => char.chars().next().unwrap_or_default().to_vk_bits(),
|
||||
_ => 0,
|
||||
};
|
||||
let native_key_code = physical_key.to_native_keycode();
|
||||
|
||||
let char_representation = key.to_char_representation();
|
||||
let char_representation = event.logical_key.to_char_representation();
|
||||
#[allow(unused_mut)]
|
||||
let mut character = char_representation as u16;
|
||||
let unmodified_character = key_without_modifiers.to_char_representation() as u16;
|
||||
|
||||
if event.state == ElementState::Pressed && character != 0 {
|
||||
kind = KeyEventKind::Char;
|
||||
}
|
||||
|
||||
let unmodified_character = event.key_without_modifiers.to_char_representation() as u16;
|
||||
|
||||
#[cfg(target_os = "macos")] // See https://www.magpcss.org/ceforum/viewtopic.php?start=10&t=11650
|
||||
if character == 0 && unmodified_character == 0 && text.is_some() {
|
||||
if character == 0 && unmodified_character == 0 && event.text_with_all_modifiers.is_some() {
|
||||
character = 1;
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let _ = text;
|
||||
|
||||
let key_event = |kind: cef_key_event_type_t, windows_key_code: i32| KeyEvent {
|
||||
type_: kind.into(),
|
||||
modifiers: flags,
|
||||
let key = KeyData {
|
||||
kind,
|
||||
modifiers,
|
||||
windows_key_code,
|
||||
native_key_code,
|
||||
character,
|
||||
unmodified_character,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
match action {
|
||||
KeyAction::Press | KeyAction::Repeat if char_representation != '\0' => {
|
||||
host.send_key_event(Some(&key_event(cef_key_event_type_t::KEYEVENT_RAWKEYDOWN, windows_key_code)));
|
||||
host.send_key_event(Some(&key_event(cef_key_event_type_t::KEYEVENT_CHAR, char_representation as i32)));
|
||||
}
|
||||
KeyAction::Press | KeyAction::Repeat => {
|
||||
host.send_key_event(Some(&key_event(cef_key_event_type_t::KEYEVENT_RAWKEYDOWN, windows_key_code)));
|
||||
}
|
||||
KeyAction::Release => {
|
||||
host.send_key_event(Some(&key_event(cef_key_event_type_t::KEYEVENT_KEYUP, windows_key_code)));
|
||||
}
|
||||
if kind == KeyEventKind::Char {
|
||||
// CEF expects a raw key-down before the character event it produces.
|
||||
vec![
|
||||
InputEvent::Key(KeyData {
|
||||
kind: KeyEventKind::RawKeyDown,
|
||||
..key
|
||||
}),
|
||||
InputEvent::Key(KeyData {
|
||||
windows_key_code: char_representation as i32,
|
||||
..key
|
||||
}),
|
||||
]
|
||||
} else {
|
||||
vec![InputEvent::Key(key)]
|
||||
}
|
||||
}
|
||||
WindowEvent::PinchGesture { delta, .. } => {
|
||||
if !delta.is_normal() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let data = MouseData {
|
||||
modifiers: CefModifiers::PINCH_MODIFIERS.into(),
|
||||
..input_state.mouse_data()
|
||||
};
|
||||
|
||||
vec![InputEvent::MouseWheel {
|
||||
data,
|
||||
delta_x: 0,
|
||||
delta_y: (delta * PINCH_ZOOM_SPEED).round() as i32,
|
||||
}]
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ButtonStates {
|
||||
left: bool,
|
||||
right: bool,
|
||||
middle: bool,
|
||||
}
|
||||
|
||||
impl ButtonStates {
|
||||
fn update(&mut self, button: MouseButton, held: bool) {
|
||||
match button {
|
||||
MouseButton::Left => self.left = held,
|
||||
MouseButton::Right => self.right = held,
|
||||
MouseButton::Middle => self.middle = held,
|
||||
MouseButton::Unknown => {}
|
||||
/// Sends a translated [`InputEvent`] to the browser. Must run on the thread owning the browser.
|
||||
pub(crate) fn apply(browser: &Browser, event: &InputEvent) {
|
||||
let Some(host) = browser.host() else { return };
|
||||
match event {
|
||||
InputEvent::MouseMove { data, leave } => {
|
||||
host.send_mouse_move_event(Some(&data.into()), *leave as i32);
|
||||
}
|
||||
InputEvent::MouseClick { data, button, up, click_count } => {
|
||||
let cef_button = cef::MouseButtonType::from(match button {
|
||||
MouseButtonKind::Left => cef_mouse_button_type_t::MBT_LEFT,
|
||||
MouseButtonKind::Right => cef_mouse_button_type_t::MBT_RIGHT,
|
||||
MouseButtonKind::Middle => cef_mouse_button_type_t::MBT_MIDDLE,
|
||||
});
|
||||
host.send_mouse_click_event(Some(&data.into()), cef_button, *up as i32, *click_count);
|
||||
}
|
||||
InputEvent::MouseWheel { data, delta_x, delta_y } => {
|
||||
host.send_mouse_wheel_event(Some(&data.into()), *delta_x, *delta_y);
|
||||
}
|
||||
InputEvent::Key(key) => {
|
||||
let key_event = KeyEvent {
|
||||
type_: match key.kind {
|
||||
KeyEventKind::RawKeyDown => cef_key_event_type_t::KEYEVENT_RAWKEYDOWN,
|
||||
KeyEventKind::KeyUp => cef_key_event_type_t::KEYEVENT_KEYUP,
|
||||
KeyEventKind::Char => cef_key_event_type_t::KEYEVENT_CHAR,
|
||||
}
|
||||
.into(),
|
||||
modifiers: key.modifiers,
|
||||
windows_key_code: key.windows_key_code,
|
||||
native_key_code: key.native_key_code,
|
||||
character: key.character,
|
||||
unmodified_character: key.unmodified_character,
|
||||
..Default::default()
|
||||
};
|
||||
host.send_key_event(Some(&key_event));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn mouse_event(position: PhysicalPosition<f64>, flags: u32) -> MouseEvent {
|
||||
MouseEvent {
|
||||
x: position.x as i32,
|
||||
y: position.y as i32,
|
||||
modifiers: flags,
|
||||
impl From<&MouseData> for MouseEvent {
|
||||
fn from(data: &MouseData) -> Self {
|
||||
MouseEvent {
|
||||
x: data.x,
|
||||
y: data.y,
|
||||
modifiers: data.modifiers,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn event_flags(modifiers: &Modifiers, buttons: &ButtonStates) -> u32 {
|
||||
let bit = |condition: bool, flag: u32| if condition { flag } else { 0 };
|
||||
bit(modifiers.shift, SHIFT_DOWN)
|
||||
| bit(modifiers.control, CONTROL_DOWN)
|
||||
| bit(modifiers.alt, ALT_DOWN)
|
||||
| bit(modifiers.alt_graph, ALTGR_DOWN)
|
||||
| bit(modifiers.meta, COMMAND_DOWN)
|
||||
| bit(modifiers.caps_lock, CAPS_LOCK_ON)
|
||||
| bit(modifiers.num_lock, NUM_LOCK_ON)
|
||||
| bit(buttons.left, LEFT_MOUSE_BUTTON)
|
||||
| bit(buttons.right, RIGHT_MOUSE_BUTTON)
|
||||
| bit(buttons.middle, MIDDLE_MOUSE_BUTTON)
|
||||
}
|
||||
|
||||
const fn flag(flag: cef_event_flags_t) -> u32 {
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
{
|
||||
flag.0
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
flag.0 as u32
|
||||
}
|
||||
}
|
||||
|
||||
const SHIFT_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_SHIFT_DOWN);
|
||||
const CONTROL_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_CONTROL_DOWN);
|
||||
const ALT_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_ALT_DOWN);
|
||||
const ALTGR_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_ALTGR_DOWN);
|
||||
const COMMAND_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_COMMAND_DOWN);
|
||||
const CAPS_LOCK_ON: u32 = flag(cef_event_flags_t::EVENTFLAG_CAPS_LOCK_ON);
|
||||
const NUM_LOCK_ON: u32 = flag(cef_event_flags_t::EVENTFLAG_NUM_LOCK_ON);
|
||||
const LEFT_MOUSE_BUTTON: u32 = flag(cef_event_flags_t::EVENTFLAG_LEFT_MOUSE_BUTTON);
|
||||
const MIDDLE_MOUSE_BUTTON: u32 = flag(cef_event_flags_t::EVENTFLAG_MIDDLE_MOUSE_BUTTON);
|
||||
const RIGHT_MOUSE_BUTTON: u32 = flag(cef_event_flags_t::EVENTFLAG_RIGHT_MOUSE_BUTTON);
|
||||
const IS_LEFT: u32 = flag(cef_event_flags_t::EVENTFLAG_IS_LEFT);
|
||||
const IS_RIGHT: u32 = flag(cef_event_flags_t::EVENTFLAG_IS_RIGHT);
|
||||
const IS_KEY_PAD: u32 = flag(cef_event_flags_t::EVENTFLAG_IS_KEY_PAD);
|
||||
const IS_REPEAT: u32 = flag(cef_event_flags_t::EVENTFLAG_IS_REPEAT);
|
||||
const PRECISION_SCROLLING_DELTA: u32 = flag(cef_event_flags_t::EVENTFLAG_PRECISION_SCROLLING_DELTA);
|
||||
@@ -1,245 +0,0 @@
|
||||
use winit::dpi::PhysicalPosition;
|
||||
use winit::event::{ElementState, KeyEvent};
|
||||
use winit::keyboard::{Key, KeyLocation, ModifiersState, PhysicalKey, SmolStr};
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct InputEvent {
|
||||
pub(crate) kind: InputEventKind,
|
||||
pub(crate) modifiers: Modifiers,
|
||||
}
|
||||
|
||||
impl InputEvent {
|
||||
pub fn pointer() -> PointerInputEventBuilder {
|
||||
PointerInputEventBuilder { position: UnknownPosition }
|
||||
}
|
||||
|
||||
pub fn key(event: &KeyEvent) -> InputEventBuilder {
|
||||
let action = match (event.state, event.repeat) {
|
||||
(ElementState::Pressed, false) => KeyAction::Press,
|
||||
(ElementState::Pressed, true) => KeyAction::Repeat,
|
||||
(ElementState::Released, _) => KeyAction::Release,
|
||||
};
|
||||
InputEventBuilder::new(InputEventKind::Key {
|
||||
key: event.logical_key.clone(),
|
||||
key_without_modifiers: event.key_without_modifiers.clone(),
|
||||
physical_key: event.physical_key,
|
||||
location: event.location,
|
||||
text: event.text_with_all_modifiers.clone(),
|
||||
action,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum MouseButton {
|
||||
Left,
|
||||
Right,
|
||||
Middle,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl From<winit::event::MouseButton> for MouseButton {
|
||||
fn from(button: winit::event::MouseButton) -> Self {
|
||||
match button {
|
||||
winit::event::MouseButton::Left => Self::Left,
|
||||
winit::event::MouseButton::Right => Self::Right,
|
||||
winit::event::MouseButton::Middle => Self::Middle,
|
||||
_ => Self::Unknown,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<winit::event::ButtonSource> for MouseButton {
|
||||
fn from(button: winit::event::ButtonSource) -> Self {
|
||||
button.mouse_button().map_or(Self::Unknown, Self::from)
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PointerInputEventBuilder<P = UnknownPosition> {
|
||||
position: P,
|
||||
}
|
||||
|
||||
impl PointerInputEventBuilder<UnknownPosition> {
|
||||
pub fn position(self, position: PhysicalPosition<f64>) -> PointerInputEventBuilder<PhysicalPosition<f64>> {
|
||||
PointerInputEventBuilder { position }
|
||||
}
|
||||
}
|
||||
|
||||
impl PointerInputEventBuilder<PhysicalPosition<f64>> {
|
||||
pub fn moved(self) -> InputEventBuilder {
|
||||
self.finish(PointerAction::Move)
|
||||
}
|
||||
|
||||
pub fn entered(self) -> InputEventBuilder {
|
||||
self.finish(PointerAction::Enter)
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: PointerPosition> PointerInputEventBuilder<P> {
|
||||
pub fn exited(self) -> InputEventBuilder {
|
||||
self.finish(PointerAction::Exit)
|
||||
}
|
||||
|
||||
pub fn pressed(self, button: impl Into<MouseButton>, count: u32) -> InputEventBuilder {
|
||||
self.finish(PointerAction::Press { button: button.into(), count })
|
||||
}
|
||||
|
||||
pub fn released(self, button: impl Into<MouseButton>, count: u32) -> InputEventBuilder {
|
||||
self.finish(PointerAction::Release { button: button.into(), count })
|
||||
}
|
||||
|
||||
pub fn scrolled_lines(self, x: f64, y: f64) -> InputEventBuilder {
|
||||
self.finish(PointerAction::ScrollLines { x, y })
|
||||
}
|
||||
|
||||
pub fn scrolled_pixels(self, x: f64, y: f64) -> InputEventBuilder {
|
||||
self.finish(PointerAction::ScrollPixels { x, y })
|
||||
}
|
||||
|
||||
pub fn zoomed(self, delta: f64) -> InputEventBuilder {
|
||||
self.finish(PointerAction::Zoom(delta))
|
||||
}
|
||||
|
||||
fn finish(self, action: PointerAction) -> InputEventBuilder {
|
||||
InputEventBuilder::new(InputEventKind::Pointer {
|
||||
position: self.position.position(),
|
||||
action,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct InputEventBuilder {
|
||||
kind: InputEventKind,
|
||||
modifiers: Modifiers,
|
||||
}
|
||||
|
||||
impl InputEventBuilder {
|
||||
fn new(kind: InputEventKind) -> Self {
|
||||
Self {
|
||||
kind,
|
||||
modifiers: Modifiers::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn shift(mut self, on: bool) -> Self {
|
||||
self.modifiers.shift = on;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn control(mut self, on: bool) -> Self {
|
||||
self.modifiers.control = on;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn alt(mut self, on: bool) -> Self {
|
||||
self.modifiers.alt = on;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn alt_graph(mut self, on: bool) -> Self {
|
||||
self.modifiers.alt_graph = on;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn meta(mut self, on: bool) -> Self {
|
||||
self.modifiers.meta = on;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn caps_lock(mut self, on: bool) -> Self {
|
||||
self.modifiers.caps_lock = on;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn num_lock(mut self, on: bool) -> Self {
|
||||
self.modifiers.num_lock = on;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn modifiers(mut self, modifiers: ModifiersState) -> Self {
|
||||
self.modifiers.shift = modifiers.shift_key();
|
||||
self.modifiers.control = modifiers.control_key();
|
||||
self.modifiers.alt = modifiers.alt_key();
|
||||
self.modifiers.meta = modifiers.meta_key();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn build(self) -> InputEvent {
|
||||
InputEvent {
|
||||
kind: self.kind,
|
||||
modifiers: self.modifiers,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(private_bounds)]
|
||||
pub trait PointerPosition: OptionalPosition {}
|
||||
impl PointerPosition for UnknownPosition {}
|
||||
impl PointerPosition for PhysicalPosition<f64> {}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct UnknownPosition;
|
||||
|
||||
trait OptionalPosition {
|
||||
fn position(self) -> Option<PhysicalPosition<f64>>;
|
||||
}
|
||||
impl OptionalPosition for UnknownPosition {
|
||||
fn position(self) -> Option<PhysicalPosition<f64>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
impl OptionalPosition for PhysicalPosition<f64> {
|
||||
fn position(self) -> Option<PhysicalPosition<f64>> {
|
||||
Some(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) enum InputEventKind {
|
||||
Pointer {
|
||||
position: Option<PhysicalPosition<f64>>,
|
||||
action: PointerAction,
|
||||
},
|
||||
Key {
|
||||
key: Key,
|
||||
key_without_modifiers: Key,
|
||||
physical_key: PhysicalKey,
|
||||
location: KeyLocation,
|
||||
text: Option<SmolStr>,
|
||||
action: KeyAction,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) enum PointerAction {
|
||||
Move,
|
||||
Enter,
|
||||
Exit,
|
||||
Press { button: MouseButton, count: u32 },
|
||||
Release { button: MouseButton, count: u32 },
|
||||
ScrollLines { x: f64, y: f64 },
|
||||
ScrollPixels { x: f64, y: f64 },
|
||||
Zoom(f64),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) enum KeyAction {
|
||||
Press,
|
||||
Repeat,
|
||||
Release,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) struct Modifiers {
|
||||
pub(crate) shift: bool,
|
||||
pub(crate) control: bool,
|
||||
pub(crate) alt: bool,
|
||||
pub(crate) alt_graph: bool,
|
||||
pub(crate) meta: bool,
|
||||
pub(crate) caps_lock: bool,
|
||||
pub(crate) num_lock: bool,
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
use cef::sys::cef_event_flags_t;
|
||||
use std::time::Instant;
|
||||
use winit::dpi::PhysicalPosition;
|
||||
use winit::event::{ElementState, MouseButton};
|
||||
use winit::keyboard::{Key, KeyLocation, ModifiersState, NamedKey};
|
||||
|
||||
use super::MouseData;
|
||||
use crate::consts::{MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct InputState {
|
||||
modifiers: ModifiersState,
|
||||
mouse_position: MousePosition,
|
||||
mouse_state: MouseState,
|
||||
mouse_click_tracker: ClickTracker,
|
||||
}
|
||||
impl InputState {
|
||||
pub(crate) fn modifiers_changed(&mut self, modifiers: &ModifiersState) {
|
||||
self.modifiers = *modifiers;
|
||||
}
|
||||
|
||||
pub(crate) fn modifiers_apply_key_event(&mut self, key: &Key, state: &ElementState) {
|
||||
let bits = match key {
|
||||
Key::Named(NamedKey::Shift) => ModifiersState::SHIFT,
|
||||
Key::Named(NamedKey::Control) => ModifiersState::CONTROL,
|
||||
Key::Named(NamedKey::Alt) => ModifiersState::ALT,
|
||||
Key::Named(NamedKey::Meta) => ModifiersState::META,
|
||||
_ => return,
|
||||
};
|
||||
let is_pressed = matches!(state, ElementState::Pressed);
|
||||
self.modifiers.set(bits, is_pressed);
|
||||
}
|
||||
|
||||
pub(crate) fn cursor_move(&mut self, position: &PhysicalPosition<f64>) -> bool {
|
||||
let new = position.into();
|
||||
if self.mouse_position == new {
|
||||
return false;
|
||||
}
|
||||
self.mouse_position = new;
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn mouse_input(&mut self, button: &MouseButton, state: &ElementState) -> ClickCount {
|
||||
self.mouse_state.update(button, state);
|
||||
self.mouse_click_tracker.input(button, state, self.mouse_position)
|
||||
}
|
||||
|
||||
pub(crate) fn cef_modifiers(&self, location: &KeyLocation, is_repeat: bool) -> CefModifiers {
|
||||
CefModifiers::new(self, location, is_repeat)
|
||||
}
|
||||
|
||||
pub(crate) fn cef_mouse_modifiers(&self) -> CefModifiers {
|
||||
self.cef_modifiers(&KeyLocation::Standard, false)
|
||||
}
|
||||
|
||||
pub(crate) fn mouse_data(&self) -> MouseData {
|
||||
MouseData {
|
||||
x: self.mouse_position.x,
|
||||
y: self.mouse_position.y,
|
||||
modifiers: self.cef_mouse_modifiers().into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, Copy, Eq, PartialEq)]
|
||||
pub(crate) struct MousePosition {
|
||||
x: i32,
|
||||
y: i32,
|
||||
}
|
||||
impl From<&PhysicalPosition<f64>> for MousePosition {
|
||||
fn from(position: &PhysicalPosition<f64>) -> Self {
|
||||
Self {
|
||||
x: position.x as i32,
|
||||
y: position.y as i32,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
pub(crate) struct MouseState {
|
||||
left: bool,
|
||||
right: bool,
|
||||
middle: bool,
|
||||
}
|
||||
impl MouseState {
|
||||
pub(crate) fn update(&mut self, button: &MouseButton, state: &ElementState) {
|
||||
match state {
|
||||
ElementState::Pressed => match button {
|
||||
MouseButton::Left => self.left = true,
|
||||
MouseButton::Right => self.right = true,
|
||||
MouseButton::Middle => self.middle = true,
|
||||
_ => {}
|
||||
},
|
||||
ElementState::Released => match button {
|
||||
MouseButton::Left => self.left = false,
|
||||
MouseButton::Right => self.right = false,
|
||||
MouseButton::Middle => self.middle = false,
|
||||
_ => {}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ClickTracker {
|
||||
left: Option<ClickRecord>,
|
||||
middle: Option<ClickRecord>,
|
||||
right: Option<ClickRecord>,
|
||||
}
|
||||
impl ClickTracker {
|
||||
fn input(&mut self, button: &MouseButton, state: &ElementState, position: MousePosition) -> ClickCount {
|
||||
let record = match button {
|
||||
MouseButton::Left => &mut self.left,
|
||||
MouseButton::Right => &mut self.right,
|
||||
MouseButton::Middle => &mut self.middle,
|
||||
_ => return ClickCount::Single,
|
||||
};
|
||||
|
||||
let Some(record) = record else {
|
||||
*record = Some(ClickRecord {
|
||||
down_position: position,
|
||||
up_position: position,
|
||||
..Default::default()
|
||||
});
|
||||
return ClickCount::Single;
|
||||
};
|
||||
|
||||
let now = Instant::now();
|
||||
let within_time = now.saturating_duration_since(record.time) <= MULTICLICK_TIMEOUT;
|
||||
|
||||
let (prev_count, prev_position) = match state {
|
||||
ElementState::Pressed => (record.down_count, record.down_position),
|
||||
ElementState::Released => (record.up_count, record.up_position),
|
||||
};
|
||||
|
||||
let dx = position.x.abs_diff(prev_position.x) as usize;
|
||||
let dy = position.y.abs_diff(prev_position.y) as usize;
|
||||
let within_dist = dx <= MULTICLICK_ALLOWED_TRAVEL && dy <= MULTICLICK_ALLOWED_TRAVEL;
|
||||
|
||||
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,
|
||||
_ => 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;
|
||||
}
|
||||
}
|
||||
|
||||
count
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Default)]
|
||||
pub(crate) enum ClickCount {
|
||||
#[default]
|
||||
Single,
|
||||
Double,
|
||||
Triple,
|
||||
}
|
||||
impl From<ClickCount> for i32 {
|
||||
fn from(count: ClickCount) -> i32 {
|
||||
match count {
|
||||
ClickCount::Single => 1,
|
||||
ClickCount::Double => 2,
|
||||
ClickCount::Triple => 3,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct ClickRecord {
|
||||
time: Instant,
|
||||
down_position: MousePosition,
|
||||
up_position: MousePosition,
|
||||
down_count: ClickCount,
|
||||
up_count: ClickCount,
|
||||
}
|
||||
|
||||
impl Default for ClickRecord {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
time: Instant::now(),
|
||||
down_position: Default::default(),
|
||||
up_position: Default::default(),
|
||||
down_count: Default::default(),
|
||||
up_count: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct CefModifiers(cef_event_flags_t);
|
||||
impl CefModifiers {
|
||||
fn new(input_state: &InputState, location: &KeyLocation, is_repeat: bool) -> Self {
|
||||
let mut inner = cef_event_flags_t::EVENTFLAG_NONE;
|
||||
|
||||
if input_state.modifiers.shift_key() {
|
||||
inner |= cef_event_flags_t::EVENTFLAG_SHIFT_DOWN;
|
||||
}
|
||||
if input_state.modifiers.control_key() {
|
||||
inner |= cef_event_flags_t::EVENTFLAG_CONTROL_DOWN;
|
||||
}
|
||||
if input_state.modifiers.alt_key() {
|
||||
inner |= cef_event_flags_t::EVENTFLAG_ALT_DOWN;
|
||||
}
|
||||
if input_state.modifiers.meta_key() {
|
||||
inner |= cef_event_flags_t::EVENTFLAG_COMMAND_DOWN;
|
||||
}
|
||||
|
||||
if input_state.mouse_state.left {
|
||||
inner |= cef_event_flags_t::EVENTFLAG_LEFT_MOUSE_BUTTON;
|
||||
}
|
||||
if input_state.mouse_state.right {
|
||||
inner |= cef_event_flags_t::EVENTFLAG_RIGHT_MOUSE_BUTTON;
|
||||
}
|
||||
if input_state.mouse_state.middle {
|
||||
inner |= cef_event_flags_t::EVENTFLAG_MIDDLE_MOUSE_BUTTON;
|
||||
}
|
||||
|
||||
if is_repeat {
|
||||
inner |= cef_event_flags_t::EVENTFLAG_IS_REPEAT;
|
||||
}
|
||||
|
||||
inner |= match location {
|
||||
KeyLocation::Left => cef_event_flags_t::EVENTFLAG_IS_LEFT,
|
||||
KeyLocation::Right => cef_event_flags_t::EVENTFLAG_IS_RIGHT,
|
||||
KeyLocation::Numpad => cef_event_flags_t::EVENTFLAG_IS_KEY_PAD,
|
||||
KeyLocation::Standard => cef_event_flags_t::EVENTFLAG_NONE,
|
||||
};
|
||||
|
||||
Self(inner)
|
||||
}
|
||||
|
||||
pub(super) const PINCH_MODIFIERS: Self = Self(cef_event_flags_t(
|
||||
cef_event_flags_t::EVENTFLAG_CONTROL_DOWN.0 | cef_event_flags_t::EVENTFLAG_PRECISION_SCROLLING_DELTA.0,
|
||||
));
|
||||
}
|
||||
|
||||
impl From<CefModifiers> for u32 {
|
||||
fn from(val: CefModifiers) -> Self {
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
return val.0.0;
|
||||
#[cfg(target_os = "windows")]
|
||||
return val.0.0 as u32;
|
||||
}
|
||||
}
|
||||
+15
-5
@@ -22,9 +22,6 @@ mod resources;
|
||||
mod utility;
|
||||
mod view;
|
||||
|
||||
pub use consts::{MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT, PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
|
||||
pub use input::event::{InputEvent, InputEventBuilder, MouseButton, PointerInputEventBuilder, PointerPosition, UnknownPosition};
|
||||
|
||||
pub struct UiContext<S: Stage = Started> {
|
||||
inner: S::ContextData,
|
||||
}
|
||||
@@ -70,6 +67,7 @@ impl UiContext<Started> {
|
||||
Ok(UiInstance {
|
||||
inner: Arc::new(UiInstanceInner {
|
||||
host: self.inner.clone(),
|
||||
input: Mutex::new(input::InputState::default()),
|
||||
events: Mutex::new(events),
|
||||
queue,
|
||||
shutdown_complete: Mutex::new(shutdown_complete),
|
||||
@@ -143,6 +141,7 @@ pub struct UiInstance {
|
||||
|
||||
pub(crate) struct UiInstanceInner {
|
||||
host: Arc<HostHandle>,
|
||||
input: Mutex<input::InputState>,
|
||||
events: Mutex<Receiver<UiEvent>>,
|
||||
queue: events::EventQueue,
|
||||
shutdown_complete: Mutex<Receiver<()>>,
|
||||
@@ -153,7 +152,18 @@ impl UiInstance {
|
||||
pub fn send(&self, command: UiCommand) {
|
||||
let shared = &self.inner;
|
||||
match command {
|
||||
UiCommand::Input(event) => shared.host.send(HostControlMessage::Input(event)),
|
||||
UiCommand::Input(event) => {
|
||||
let events = {
|
||||
let Ok(mut input) = shared.input.lock() else {
|
||||
tracing::error!("Failed to lock the input state");
|
||||
return;
|
||||
};
|
||||
input::translate(&mut input, &event)
|
||||
};
|
||||
if !events.is_empty() {
|
||||
shared.host.send(HostControlMessage::Input(events));
|
||||
}
|
||||
}
|
||||
UiCommand::Resized { width, height } => shared.host.send(HostControlMessage::UpdateViewInfo(view::ViewInfoUpdate::Size { width, height })),
|
||||
UiCommand::ScaleChanged(scale) => shared.host.send(HostControlMessage::UpdateViewInfo(view::ViewInfoUpdate::Scale(scale))),
|
||||
UiCommand::Refresh => shared.host.send(HostControlMessage::RefreshViewInfo),
|
||||
@@ -210,7 +220,7 @@ impl Drop for UiInstanceInner {
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum UiCommand {
|
||||
Input(InputEvent),
|
||||
Input(winit::event::WindowEvent),
|
||||
Resized { width: u32, height: u32 },
|
||||
ScaleChanged(f64),
|
||||
Refresh,
|
||||
|
||||
@@ -99,7 +99,7 @@ enum ControlOutcome {
|
||||
fn control_loop(receiver: &IpcReceiver<HostControlMessage>, context: &CefContextHandle, sequence: &SequenceState) -> ControlOutcome {
|
||||
loop {
|
||||
match receiver.recv() {
|
||||
Ok(HostControlMessage::Input(event)) => context.process_input(event),
|
||||
Ok(HostControlMessage::Input(events)) => context.apply_input(events),
|
||||
Ok(HostControlMessage::UpdateViewInfo(update)) => context.update_view_info(update),
|
||||
Ok(HostControlMessage::RefreshViewInfo) => context.refresh_view_info(),
|
||||
Ok(HostControlMessage::SendWebMessage(message)) => context.send_web_message(message),
|
||||
|
||||
@@ -8,7 +8,7 @@ use crate::view::ViewInfoUpdate;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(crate) enum HostControlMessage {
|
||||
Input(InputEvent),
|
||||
Input(Vec<InputEvent>),
|
||||
UpdateViewInfo(ViewInfoUpdate),
|
||||
RefreshViewInfo,
|
||||
SendWebMessage(Vec<u8>),
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
[package]
|
||||
name = "graphite-desktop-wrapper"
|
||||
version = "0.1.0"
|
||||
description = "Graphite Desktop Wrapper"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
|
||||
[features]
|
||||
gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
|
||||
|
||||
@@ -2,7 +2,7 @@ use graphite_editor::messages::clipboard::utility_types::ClipboardContentRaw;
|
||||
use graphite_editor::messages::prelude::*;
|
||||
|
||||
use super::DesktopWrapperMessageDispatcher;
|
||||
use super::messages::{DesktopFrontendMessage, DesktopWrapperMessage, EditorMessage, SaveFileDialogContext};
|
||||
use super::messages::{DesktopFrontendMessage, DesktopWrapperMessage, EditorMessage, OpenFileDialogContext, SaveFileDialogContext};
|
||||
|
||||
pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: DesktopWrapperMessage) {
|
||||
match message {
|
||||
@@ -15,14 +15,14 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
||||
DesktopWrapperMessage::Input(message) => {
|
||||
dispatcher.queue_editor_message(EditorMessage::InputPreprocessor(message));
|
||||
}
|
||||
DesktopWrapperMessage::IngestFile { path, content, action } => {
|
||||
dispatcher.queue_editor_message(IngestMessage::Ingest {
|
||||
data: content,
|
||||
action,
|
||||
mime_type: String::new(),
|
||||
path: Some(path),
|
||||
});
|
||||
}
|
||||
DesktopWrapperMessage::FileDialogResult { path, content, context } => match context {
|
||||
OpenFileDialogContext::Open => {
|
||||
dispatcher.queue_desktop_wrapper_message(DesktopWrapperMessage::OpenFile { path, content });
|
||||
}
|
||||
OpenFileDialogContext::Import => {
|
||||
dispatcher.queue_desktop_wrapper_message(DesktopWrapperMessage::ImportFile { path, content });
|
||||
}
|
||||
},
|
||||
DesktopWrapperMessage::SaveFileDialogResult { path, context } => match context {
|
||||
SaveFileDialogContext::Document { document_id, content } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::WriteFile { path: path.clone(), content });
|
||||
@@ -35,6 +35,14 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
||||
dispatcher.respond(DesktopFrontendMessage::WriteFile { path, content });
|
||||
}
|
||||
},
|
||||
DesktopWrapperMessage::OpenFile { path, content } => {
|
||||
let message = PortfolioMessage::OpenFile { path, content };
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
DesktopWrapperMessage::ImportFile { path, content } => {
|
||||
let message = PortfolioMessage::ImportFile { path, content };
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
DesktopWrapperMessage::PollNodeGraphEvaluation => dispatcher.poll_node_graph_evaluation(),
|
||||
DesktopWrapperMessage::UpdateMaximized { maximized } => {
|
||||
let message = FrontendMessage::UpdateMaximized { maximized };
|
||||
|
||||
@@ -3,23 +3,27 @@ use graphite_editor::messages::layout::utility_types::layout_widget::LayoutTarge
|
||||
use graphite_editor::messages::prelude::FrontendMessage;
|
||||
|
||||
use super::DesktopWrapperMessageDispatcher;
|
||||
use super::messages::{DesktopFrontendMessage, IngestAction, SaveFileDialogContext};
|
||||
use super::messages::{DesktopFrontendMessage, FileFilter, OpenFileDialogContext, SaveFileDialogContext};
|
||||
|
||||
pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: FrontendMessage) -> Option<FrontendMessage> {
|
||||
match message {
|
||||
FrontendMessage::RenderOverlays { context } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::UpdateOverlays(context.take_scene()));
|
||||
}
|
||||
FrontendMessage::TriggerBrowse { options, action } => {
|
||||
let title = match action {
|
||||
IngestAction::Open => "Open Document",
|
||||
IngestAction::Import => "Import File",
|
||||
_ => "Select File",
|
||||
};
|
||||
FrontendMessage::TriggerOpen => {
|
||||
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
|
||||
title: title.to_string(),
|
||||
options,
|
||||
action,
|
||||
title: "Open Document".to_string(),
|
||||
filters: vec![],
|
||||
multiple: true,
|
||||
context: OpenFileDialogContext::Open,
|
||||
});
|
||||
}
|
||||
FrontendMessage::TriggerImport => {
|
||||
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
|
||||
title: "Import File".to_string(),
|
||||
filters: vec![],
|
||||
multiple: false,
|
||||
context: OpenFileDialogContext::Import,
|
||||
});
|
||||
}
|
||||
FrontendMessage::TriggerSaveDocument {
|
||||
@@ -27,29 +31,32 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
name,
|
||||
path,
|
||||
folder,
|
||||
filters,
|
||||
content,
|
||||
} => {
|
||||
let content = content.into_vec();
|
||||
if let Some(path) = path {
|
||||
dispatcher.respond(DesktopFrontendMessage::WriteFile { path, content });
|
||||
} else {
|
||||
let extension = std::path::Path::new(&name).extension().and_then(|extension| extension.to_str()).unwrap_or("*").to_string();
|
||||
dispatcher.respond(DesktopFrontendMessage::SaveFileDialog {
|
||||
title: "Save Document".to_string(),
|
||||
default_filename: name,
|
||||
default_folder: folder,
|
||||
filters,
|
||||
filters: vec![FileFilter {
|
||||
name: "Graphite Document".to_string(),
|
||||
extensions: vec![extension],
|
||||
}],
|
||||
context: SaveFileDialogContext::Document { document_id, content },
|
||||
});
|
||||
}
|
||||
}
|
||||
FrontendMessage::TriggerSaveFile { name, folder, filters, content } => {
|
||||
FrontendMessage::TriggerSaveFile { name, folder, content } => {
|
||||
let content = content.into_vec();
|
||||
dispatcher.respond(DesktopFrontendMessage::SaveFileDialog {
|
||||
title: "Save File".to_string(),
|
||||
default_filename: name,
|
||||
default_folder: folder,
|
||||
filters,
|
||||
filters: Vec::new(),
|
||||
context: SaveFileDialogContext::File { content },
|
||||
});
|
||||
}
|
||||
@@ -118,9 +125,6 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
FrontendMessage::WindowPointerLock => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PointerLock);
|
||||
}
|
||||
FrontendMessage::WindowUpdateDirectInput { enabled } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::WindowUpdateDirectInput { enabled });
|
||||
}
|
||||
FrontendMessage::WindowClose => {
|
||||
dispatcher.respond(DesktopFrontendMessage::WindowClose);
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ use std::sync::Arc;
|
||||
|
||||
pub use graph_craft::application_io::resource::MmapResourceStorage;
|
||||
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
|
||||
pub use wgpu_executor::Texture;
|
||||
pub use wgpu_executor::WgpuBackends;
|
||||
pub use wgpu_executor::WgpuContext;
|
||||
pub use wgpu_executor::WgpuContextBuilder;
|
||||
@@ -56,14 +55,14 @@ 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),
|
||||
(true, texture) => NodeGraphExecutionResult::HasRun(texture.map(Into::into)),
|
||||
(false, _) => NodeGraphExecutionResult::NotRun,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum NodeGraphExecutionResult {
|
||||
HasRun(Option<Texture>),
|
||||
HasRun(Option<std::sync::Arc<wgpu::Texture>>),
|
||||
NotRun,
|
||||
}
|
||||
|
||||
|
||||
@@ -44,10 +44,10 @@ impl<'a> DesktopWrapperMessageDispatcher<'a> {
|
||||
|
||||
pub(super) fn poll_node_graph_evaluation(&mut self) {
|
||||
let mut responses = VecDeque::new();
|
||||
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses)
|
||||
&& e != "No active document"
|
||||
{
|
||||
tracing::error!("Error poling node graph: {}", e);
|
||||
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses) {
|
||||
if e != "No active document" {
|
||||
tracing::error!("Error poling node graph: {}", e);
|
||||
}
|
||||
}
|
||||
while let Some(message) = responses.pop_front() {
|
||||
self.queue_editor_message(message);
|
||||
|
||||
@@ -3,10 +3,9 @@ use std::path::PathBuf;
|
||||
|
||||
pub(crate) use graphite_editor::messages::prelude::Message as EditorMessage;
|
||||
|
||||
pub use graphite_editor::messages::frontend::utility_types::{DocumentInfo, FileDialogOptions, FileFilter, PersistedState};
|
||||
pub use graphite_editor::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
|
||||
pub use graphite_editor::messages::input_mapper::utility_types::pointer::{EditorPointerState, MouseKeys, ScrollDelta};
|
||||
pub use graphite_editor::messages::portfolio::ingest::utility_types::IngestAction;
|
||||
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;
|
||||
pub use graphite_editor::messages::prelude::InputPreprocessorMessage as InputMessage;
|
||||
pub use graphite_editor::messages::prelude::PreferencesMessageHandler as Preferences;
|
||||
@@ -16,8 +15,9 @@ pub enum DesktopFrontendMessage {
|
||||
OpenLaunchDocuments,
|
||||
OpenFileDialog {
|
||||
title: String,
|
||||
options: FileDialogOptions,
|
||||
action: IngestAction,
|
||||
filters: Vec<FileFilter>,
|
||||
multiple: bool,
|
||||
context: OpenFileDialogContext,
|
||||
},
|
||||
SaveFileDialog {
|
||||
title: String,
|
||||
@@ -40,9 +40,6 @@ pub enum DesktopFrontendMessage {
|
||||
UpdateUIScale {
|
||||
scale: f64,
|
||||
},
|
||||
WindowUpdateDirectInput {
|
||||
enabled: bool,
|
||||
},
|
||||
UpdateOverlays(vello::Scene),
|
||||
PersistenceWriteDocument {
|
||||
id: DocumentId,
|
||||
@@ -87,8 +84,10 @@ pub enum DesktopWrapperMessage {
|
||||
FromWeb(Box<EditorMessage>),
|
||||
Wake,
|
||||
Input(InputMessage),
|
||||
IngestFile { path: PathBuf, content: Vec<u8>, action: IngestAction },
|
||||
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 },
|
||||
@@ -101,6 +100,17 @@ pub enum DesktopWrapperMessage {
|
||||
LoadThirdPartyLicenses { text: String },
|
||||
}
|
||||
|
||||
pub struct FileFilter {
|
||||
pub name: String,
|
||||
pub extensions: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum OpenFileDialogContext {
|
||||
Open,
|
||||
Import,
|
||||
}
|
||||
|
||||
pub enum SaveFileDialogContext {
|
||||
Document { document_id: DocumentId, content: Vec<u8> },
|
||||
File { content: Vec<u8> },
|
||||
|
||||
@@ -3,7 +3,7 @@ pub(crate) mod menu {
|
||||
use base64::engine::Engine;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64;
|
||||
|
||||
use graphite_editor::messages::input_mapper::utility_types::keyboard::{Key, LabeledKeyOrMouseMotion, LabeledShortcut};
|
||||
use graphite_editor::messages::input_mapper::utility_types::input_keyboard::{Key, LabeledKeyOrMouseMotion, LabeledShortcut};
|
||||
use graphite_editor::messages::input_mapper::utility_types::misc::ActionShortcut;
|
||||
use graphite_editor::messages::layout::LayoutMessage;
|
||||
use graphite_editor::messages::tool::tool_messages::tool_prelude::{Layout, LayoutGroup, LayoutTarget, MenuListEntry, Widget, WidgetId, WidgetRow};
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
[package]
|
||||
name = "document-container"
|
||||
description = "Container abstraction for the on-disk side of the .gdd document format"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
[package]
|
||||
name = "document-format"
|
||||
description = "Typed handle for the .gdd document format, sitting over document-graph-storage and document-container"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[features]
|
||||
# Runtime bridge: the editor <-> storage conversion methods (stage/commit from a `NodeNetwork`,
|
||||
|
||||
@@ -76,29 +76,6 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stage ops the caller built from what the editor recorded, rather than deriving them by converting
|
||||
/// the whole document and diffing it against the working registry.
|
||||
///
|
||||
/// Otherwise identical to [`stage_runtime_snapshot`](Self::stage_runtime_snapshot): each op becomes a
|
||||
/// hot frame, and the proto-node declaration bytes go to the byte store.
|
||||
#[cfg(feature = "conversion")]
|
||||
pub fn stage_constructed_ops(
|
||||
&mut self,
|
||||
ops: Vec<document_graph_storage::RegistryDelta>,
|
||||
declaration_bytes: &document_graph_storage::from_runtime::DeclarationBytes,
|
||||
byte_store: &dyn ResourceStorage,
|
||||
) -> Result<(), Error> {
|
||||
let hot_ops = self.session.stage_computed_ops(ops)?;
|
||||
|
||||
for hot_op in &hot_ops {
|
||||
self.append_hot_frame(hot_op)?;
|
||||
}
|
||||
for bytes in declaration_bytes.values() {
|
||||
byte_store.store(bytes);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Retire every pending hot op into durable history as a single interaction (marking the batch's last
|
||||
/// delta as the interaction boundary), then re-snapshot the registry. One interaction is one undo unit,
|
||||
/// so the caller invokes this at each undo-step boundary and before any undo/redo. A no-op when there
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
[package]
|
||||
name = "document-graph-storage"
|
||||
description = "Provides a delta based graph representation used in the Graphite file format"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[features]
|
||||
conversion = ["dep:graph-craft", "dep:core-types"]
|
||||
|
||||
@@ -31,6 +31,8 @@ pub mod node {
|
||||
|
||||
pub mod session {
|
||||
pub mod network {
|
||||
pub const PREVIEWING: &str = "ui::previewing";
|
||||
|
||||
// TODO: Remove these graph ui nav-specific attributes
|
||||
pub const NAV_PTZ: &str = "ui::nav::ptz";
|
||||
pub const NAV_TRANSFORM: &str = "ui::nav::transform";
|
||||
@@ -58,11 +60,6 @@ pub mod network {
|
||||
/// serialized blob so its shape can evolve (e.g. dropping the `Type`) without a model change. The
|
||||
/// node references use stable storage IDs, resolved back to runtime-local IDs on conversion.
|
||||
pub const SCOPE_INJECTIONS: &str = "scope_injections";
|
||||
|
||||
/// Whole-vec LWW of the display order of the network's pinned nodes, as stable storage IDs.
|
||||
/// Concurrent reorders do not merge, but the pinned set is already shared, and a shared set with
|
||||
/// per-peer ordering would diverge with no way to reconcile.
|
||||
pub const PINNED_ORDER: &str = "ui::pinned_order";
|
||||
}
|
||||
|
||||
pub mod delta {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::{Attributes, AttributesWrite, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev};
|
||||
use crate::{Attributes, AttributesWrite, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev};
|
||||
use graphene_resource::ResourceHash;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -109,16 +109,6 @@ pub enum RegistryDelta {
|
||||
index: u32,
|
||||
new_input: NodeInput,
|
||||
},
|
||||
/// A node's whole input list, for a change to the number or order of its slots that the
|
||||
/// index-addressed `ChangeNodeInput` cannot express. Assigns rather than merging: concurrent
|
||||
/// per-slot edits are lost, which is inherent to the indices themselves moving.
|
||||
///
|
||||
/// Touches only the inputs, leaving the node's attributes and implementation alone, so it composes
|
||||
/// with attribute ops on the same node instead of reverting them.
|
||||
SetNodeInputs {
|
||||
id: NodeId,
|
||||
inputs: Vec<InputSlot>,
|
||||
},
|
||||
ChangeNodeAttribute {
|
||||
id: NodeId,
|
||||
delta: AttributeDelta,
|
||||
|
||||
@@ -194,10 +194,6 @@ impl Document {
|
||||
RegistryDelta::RemoveNode { id, .. } => {
|
||||
registry.node_instances.remove(&id);
|
||||
}
|
||||
RegistryDelta::SetNodeInputs { id, inputs } => {
|
||||
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
node.inputs = inputs;
|
||||
}
|
||||
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
|
||||
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
let input = node.inputs.get_mut(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
|
||||
@@ -309,14 +305,6 @@ impl Document {
|
||||
}
|
||||
self.ensure_node_exists(target, *id)?;
|
||||
}
|
||||
RegistryDelta::SetNodeInputs { id, inputs } => {
|
||||
for slot in inputs {
|
||||
if let NodeInput::Node { id: referenced, .. } = slot.input {
|
||||
self.ensure_node_exists(target, referenced)?;
|
||||
}
|
||||
}
|
||||
self.ensure_node_exists(target, *id)?;
|
||||
}
|
||||
RegistryDelta::ChangeNodeAttribute { id, .. } | RegistryDelta::ChangeNodeInputAttribute { id, .. } => self.ensure_node_exists(target, *id)?,
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: network, export: export_target, ..
|
||||
@@ -354,10 +342,6 @@ impl Document {
|
||||
Ok(match delta {
|
||||
RegistryDelta::AddNode { id, node } => RegistryDelta::RemoveNode { id: *id, snapshot: node.clone() },
|
||||
RegistryDelta::RemoveNode { id, snapshot } => RegistryDelta::AddNode { id: *id, node: snapshot.clone() },
|
||||
&RegistryDelta::SetNodeInputs { id, .. } => {
|
||||
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
RegistryDelta::SetNodeInputs { id, inputs: node.inputs.clone() }
|
||||
}
|
||||
&RegistryDelta::ChangeNodeInput { id, index: input_idx, .. } => {
|
||||
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
let slot = node.inputs().get(input_idx as usize).ok_or(CrdtError::InputIndexOutOfBounds(input_idx as usize))?;
|
||||
|
||||
@@ -60,34 +60,6 @@ impl NodePath {
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves a node's storage identity: the identity the metadata source holds for it where there is
|
||||
/// one, and a hash of its location otherwise. Every place a node is named goes through here, so a
|
||||
/// node's own registry key and every reference to it agree.
|
||||
///
|
||||
/// A held identity travels with the node, so moving it between networks keeps it. A hashed one is
|
||||
/// derived from the node's place in the tree, so it changes when the node moves; it stands in for a
|
||||
/// node no source names, such as one in a network that has never been stored.
|
||||
pub(crate) struct NodeIds<'a, M: NodeMetadataSource + ?Sized> {
|
||||
pub(crate) metadata: Option<&'a M>,
|
||||
pub(crate) metadata_path: &'a [RuntimeNodeId],
|
||||
pub(crate) peer: PeerId,
|
||||
}
|
||||
|
||||
impl<M: NodeMetadataSource + ?Sized> Clone for NodeIds<'_, M> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
impl<M: NodeMetadataSource + ?Sized> Copy for NodeIds<'_, M> {}
|
||||
|
||||
impl<M: NodeMetadataSource + ?Sized> NodeIds<'_, M> {
|
||||
fn resolve(&self, path: &NodePath, local_id: RuntimeNodeId) -> NodeId {
|
||||
self.metadata
|
||||
.and_then(|metadata| metadata.storage_node_id(self.metadata_path, local_id))
|
||||
.unwrap_or_else(|| path.to_global_id(self.peer))
|
||||
}
|
||||
}
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ConversionError {
|
||||
#[error("Failed to serialize value: {0}")]
|
||||
@@ -296,20 +268,6 @@ struct ConversionContext<'m, M: NodeMetadataSource + ?Sized> {
|
||||
peer: PeerId,
|
||||
}
|
||||
|
||||
impl<'m, M: NodeMetadataSource + ?Sized> ConversionContext<'m, M> {
|
||||
/// The identity resolver for nodes addressed inside the network at `metadata_path`.
|
||||
fn ids<'a>(&self, metadata_path: &'a [RuntimeNodeId]) -> NodeIds<'a, M>
|
||||
where
|
||||
'm: 'a,
|
||||
{
|
||||
NodeIds {
|
||||
metadata: Some(self.metadata),
|
||||
metadata_path,
|
||||
peer: self.peer,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_network<M: NodeMetadataSource + ?Sized>(
|
||||
node_network: &NodeNetwork,
|
||||
network_id: NetworkId,
|
||||
@@ -320,7 +278,7 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
|
||||
) -> Result<(), ConversionError> {
|
||||
for (runtime_node_id, doc_node) in &node_network.nodes {
|
||||
let node_path = child_path(parent_path, network_id, *runtime_node_id);
|
||||
let global_id = ctx.ids(metadata_path).resolve(&node_path, *runtime_node_id);
|
||||
let global_id = node_path.to_global_id(ctx.peer);
|
||||
|
||||
let location = NodeLocation {
|
||||
network_id,
|
||||
@@ -338,15 +296,15 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
|
||||
.iter()
|
||||
.map(|export| {
|
||||
Ok(ExportSlot {
|
||||
target: Some(convert_input(export, parent_path, network_id, ctx.ids(metadata_path))?),
|
||||
target: Some(convert_input(export, parent_path, network_id, ctx.peer)?),
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>, ConversionError>>()?;
|
||||
|
||||
let mut attributes = crate::Attributes::new();
|
||||
write_ui_network_attributes(&mut attributes, ctx.metadata, metadata_path, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
|
||||
write_scope_injections(&mut attributes, node_network, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
|
||||
write_ui_network_attributes(&mut attributes, ctx.metadata, metadata_path, TimeStamp::ORIGIN)?;
|
||||
write_scope_injections(&mut attributes, node_network, parent_path, network_id, ctx.peer, TimeStamp::ORIGIN)?;
|
||||
|
||||
registry.networks.insert(network_id, Network { exports, attributes });
|
||||
ctx.network_ids.insert(metadata_path.to_vec(), network_id);
|
||||
@@ -357,12 +315,12 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
|
||||
/// Serialize a network's `scope_injections` onto its attributes as one whole-map LWW blob, remapping
|
||||
/// each runtime-local node reference to its stable storage global ID so the reference survives a
|
||||
/// round trip even if runtime IDs are later reshuffled.
|
||||
fn write_scope_injections<M: NodeMetadataSource + ?Sized>(
|
||||
fn write_scope_injections(
|
||||
attributes: &mut crate::Attributes,
|
||||
node_network: &NodeNetwork,
|
||||
parent_path: Option<&NodePath>,
|
||||
network_id: NetworkId,
|
||||
ids: NodeIds<'_, M>,
|
||||
peer: PeerId,
|
||||
timestamp: TimeStamp,
|
||||
) -> Result<(), ConversionError> {
|
||||
if node_network.scope_injections.is_empty() {
|
||||
@@ -373,7 +331,7 @@ fn write_scope_injections<M: NodeMetadataSource + ?Sized>(
|
||||
.scope_injections
|
||||
.iter()
|
||||
.map(|(key, (runtime_id, ty))| {
|
||||
let storage_id = ids.resolve(&child_path(parent_path, network_id, *runtime_id), *runtime_id);
|
||||
let storage_id = child_path(parent_path, network_id, *runtime_id).to_global_id(peer);
|
||||
(key.clone(), (storage_id, ty.clone()))
|
||||
})
|
||||
.collect();
|
||||
@@ -423,7 +381,7 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
|
||||
write_ui_input_attributes(&mut input_attrs, ctx.metadata, metadata_path, runtime_node_id, input_index, timestamp)?;
|
||||
|
||||
inputs.push(InputSlot {
|
||||
input: convert_input(input, parent_path, network_id, ctx.ids(metadata_path))?,
|
||||
input: convert_input(input, parent_path, network_id, ctx.peer)?,
|
||||
timestamp,
|
||||
attributes: input_attrs,
|
||||
});
|
||||
@@ -465,27 +423,6 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
|
||||
})
|
||||
}
|
||||
|
||||
/// The `call_argument` attribute write for a node, cleared when the value is the default that
|
||||
/// `to_runtime` rehydrates an absent key from. For staging paths that encode this field alone.
|
||||
pub fn encode_call_argument(call_argument: &core_types::Type) -> Result<crate::AttributeDelta, ConversionError> {
|
||||
encode_if_not_default(node::CALL_ARGUMENT, call_argument, &concrete!(Context))
|
||||
}
|
||||
|
||||
/// The `context_features` attribute write, cleared at its default like [`encode_call_argument`].
|
||||
pub fn encode_context_features(context_features: &ContextDependencies) -> Result<crate::AttributeDelta, ConversionError> {
|
||||
encode_if_not_default(node::CONTEXT_FEATURES, context_features, &ContextDependencies::default())
|
||||
}
|
||||
|
||||
fn encode_if_not_default<T: Serialize + PartialEq>(key: &str, value: &T, default: &T) -> Result<crate::AttributeDelta, ConversionError> {
|
||||
let value = if value == default {
|
||||
None
|
||||
} else {
|
||||
Some(serde_json::to_value(value).map_err(map_serialization_error(key))?)
|
||||
};
|
||||
|
||||
Ok(crate::AttributeDelta { key: key.to_string(), value })
|
||||
}
|
||||
|
||||
/// Public form of the node ui-attribute encoding, for staging paths that encode single nodes.
|
||||
pub fn encode_node_ui_attributes<M: NodeMetadataSource + ?Sized>(
|
||||
attributes: &mut crate::Attributes,
|
||||
@@ -550,31 +487,11 @@ fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Node references here are remapped to stable storage IDs for the same reason `write_scope_injections`
|
||||
/// does it: a runtime ID is not stable across a round trip.
|
||||
fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
|
||||
attributes: &mut crate::Attributes,
|
||||
metadata: &M,
|
||||
network_path: &[RuntimeNodeId],
|
||||
parent_path: Option<&NodePath>,
|
||||
network_id: NetworkId,
|
||||
ids: NodeIds<'_, M>,
|
||||
timestamp: TimeStamp,
|
||||
) -> Result<(), ConversionError> {
|
||||
fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(attributes: &mut crate::Attributes, metadata: &M, network_path: &[RuntimeNodeId], timestamp: TimeStamp) -> Result<(), ConversionError> {
|
||||
if let Some(reference) = metadata.reference(network_path) {
|
||||
attributes.set(node::ui::REFERENCE, serde_json::Value::String(reference.to_string()), timestamp);
|
||||
}
|
||||
|
||||
let to_storage_id = |runtime_id: RuntimeNodeId| ids.resolve(&child_path(parent_path, network_id, runtime_id), runtime_id);
|
||||
|
||||
let pinned_order = metadata.pinned_order(network_path);
|
||||
if !pinned_order.is_empty() {
|
||||
let stored: Vec<NodeId> = pinned_order.into_iter().map(to_storage_id).collect();
|
||||
attributes
|
||||
.set_serialized(network::PINNED_ORDER, &stored, timestamp)
|
||||
.map_err(map_serialization_error(network::PINNED_ORDER))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -605,10 +522,10 @@ fn write_ui_input_attributes<M: NodeMetadataSource + ?Sized>(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn convert_input<M: NodeMetadataSource + ?Sized>(input: &GraphCraftNodeInput, parent_path: Option<&NodePath>, network_id: NetworkId, ids: NodeIds<'_, M>) -> Result<NodeInput, ConversionError> {
|
||||
fn convert_input(input: &GraphCraftNodeInput, parent_path: Option<&NodePath>, network_id: NetworkId, peer: PeerId) -> Result<NodeInput, ConversionError> {
|
||||
Ok(match input {
|
||||
GraphCraftNodeInput::Node { node_id, output_index } => NodeInput::Node {
|
||||
id: ids.resolve(&child_path(parent_path, network_id, *node_id), *node_id),
|
||||
id: child_path(parent_path, network_id, *node_id).to_global_id(peer),
|
||||
index: (*output_index).try_into().map_err(|_| ConversionError::IndexOverflow(*output_index))?,
|
||||
},
|
||||
GraphCraftNodeInput::Value { tagged_value, exposed } => {
|
||||
@@ -625,9 +542,7 @@ fn convert_input<M: NodeMetadataSource + ?Sized>(input: &GraphCraftNodeInput, pa
|
||||
})
|
||||
}
|
||||
|
||||
/// The non-ui attributes a slot carries, derived from the input itself: the declared type of an
|
||||
/// import, and a reflection node.s metadata. Public for staging paths that rebuild a node.s slots.
|
||||
pub fn convert_input_attributes(input: &GraphCraftNodeInput) -> Result<crate::Attributes, ConversionError> {
|
||||
fn convert_input_attributes(input: &GraphCraftNodeInput) -> Result<crate::Attributes, ConversionError> {
|
||||
let mut attributes = crate::Attributes::new();
|
||||
let timestamp = TimeStamp::ORIGIN;
|
||||
|
||||
@@ -696,18 +611,15 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
|
||||
})
|
||||
}
|
||||
|
||||
/// Derives the storage IDs for entities addressed by runtime network paths, resolving each through
|
||||
/// the same [`NodeIds`] a whole-document conversion uses so scoped and whole-document conversions agree.
|
||||
pub struct PathResolver<'m> {
|
||||
metadata: Option<&'m dyn NodeMetadataSource>,
|
||||
/// Derives the stable storage IDs for entities addressed by runtime network paths, walking the
|
||||
/// same path-hash chain as a full conversion so scoped and whole-document conversions agree.
|
||||
pub struct PathResolver {
|
||||
peer: PeerId,
|
||||
}
|
||||
|
||||
impl<'m> PathResolver<'m> {
|
||||
/// Without a metadata source every node falls back to a hash of its location, which only matches a
|
||||
/// whole-document conversion while no node has a stored identity.
|
||||
pub fn new(metadata: Option<&'m dyn NodeMetadataSource>, peer: PeerId) -> Self {
|
||||
Self { metadata, peer }
|
||||
impl PathResolver {
|
||||
pub fn new(peer: PeerId) -> Self {
|
||||
Self { peer }
|
||||
}
|
||||
|
||||
/// The storage `NetworkId` of the network at `local_path` (`ROOT_NETWORK` for the empty path).
|
||||
@@ -721,26 +633,14 @@ impl<'m> PathResolver<'m> {
|
||||
/// The storage `NodeId` of the node with `local_id` inside the network at `local_path`.
|
||||
pub fn node_id(&self, local_path: &[RuntimeNodeId], local_id: RuntimeNodeId) -> NodeId {
|
||||
let owner = self.owner_path(local_path);
|
||||
self.ids(local_path).resolve(&child_path(owner.as_ref(), self.network_id(local_path), local_id), local_id)
|
||||
child_path(owner.as_ref(), self.network_id(local_path), local_id).to_global_id(self.peer)
|
||||
}
|
||||
|
||||
/// Converts one runtime input inside the network at `local_path` to its storage form, resolving
|
||||
/// node references to their storage IDs.
|
||||
/// node references to their stable global IDs.
|
||||
pub fn convert_input_at(&self, input: &GraphCraftNodeInput, local_path: &[RuntimeNodeId]) -> Result<NodeInput, ConversionError> {
|
||||
let owner = self.owner_path(local_path);
|
||||
convert_input(input, owner.as_ref(), self.network_id(local_path), self.ids(local_path))
|
||||
}
|
||||
|
||||
/// The identity resolver for nodes addressed inside the network at `local_path`.
|
||||
fn ids<'a>(&self, local_path: &'a [RuntimeNodeId]) -> NodeIds<'a, dyn NodeMetadataSource + 'm>
|
||||
where
|
||||
'm: 'a,
|
||||
{
|
||||
NodeIds {
|
||||
metadata: self.metadata,
|
||||
metadata_path: local_path,
|
||||
peer: self.peer,
|
||||
}
|
||||
convert_input(input, owner.as_ref(), self.network_id(local_path), self.peer)
|
||||
}
|
||||
|
||||
/// The `NodePath` of the node owning the network at `local_path`, or `None` for the root network.
|
||||
@@ -759,13 +659,13 @@ impl<'m> PathResolver<'m> {
|
||||
|
||||
/// Converts a chosen subset of runtime entities into a scratch [`Registry`] through the same
|
||||
/// encoders as a whole-document conversion, so staging can derive deltas for just those entities.
|
||||
pub struct ScopedConversion<'m> {
|
||||
ctx: ConversionContext<'m, dyn NodeMetadataSource + 'm>,
|
||||
resolver: PathResolver<'m>,
|
||||
pub struct ScopedConversion<'m, M: NodeMetadataSource + ?Sized> {
|
||||
ctx: ConversionContext<'m, M>,
|
||||
resolver: PathResolver,
|
||||
}
|
||||
|
||||
impl<'m> ScopedConversion<'m> {
|
||||
pub fn new(metadata: &'m dyn NodeMetadataSource, peer: PeerId) -> Self {
|
||||
impl<'m, M: NodeMetadataSource + ?Sized> ScopedConversion<'m, M> {
|
||||
pub fn new(metadata: &'m M, peer: PeerId) -> Self {
|
||||
Self {
|
||||
ctx: ConversionContext {
|
||||
declaration_ids: HashMap::new(),
|
||||
@@ -774,7 +674,7 @@ impl<'m> ScopedConversion<'m> {
|
||||
metadata,
|
||||
peer,
|
||||
},
|
||||
resolver: PathResolver::new(Some(metadata), peer),
|
||||
resolver: PathResolver::new(peer),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -807,23 +707,15 @@ impl<'m> ScopedConversion<'m> {
|
||||
.iter()
|
||||
.map(|export| {
|
||||
Ok(ExportSlot {
|
||||
target: Some(convert_input(export, owner_path.as_ref(), network_id, self.ctx.ids(local_path))?),
|
||||
target: Some(convert_input(export, owner_path.as_ref(), network_id, self.ctx.peer)?),
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>, ConversionError>>()?;
|
||||
|
||||
let mut attributes = crate::Attributes::new();
|
||||
write_ui_network_attributes(
|
||||
&mut attributes,
|
||||
self.ctx.metadata,
|
||||
local_path,
|
||||
owner_path.as_ref(),
|
||||
network_id,
|
||||
self.ctx.ids(local_path),
|
||||
TimeStamp::ORIGIN,
|
||||
)?;
|
||||
write_scope_injections(&mut attributes, node_network, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
|
||||
write_ui_network_attributes(&mut attributes, self.ctx.metadata, local_path, TimeStamp::ORIGIN)?;
|
||||
write_scope_injections(&mut attributes, node_network, owner_path.as_ref(), network_id, self.ctx.peer, TimeStamp::ORIGIN)?;
|
||||
|
||||
registry.networks.insert(network_id, Network { exports, attributes });
|
||||
Ok(())
|
||||
|
||||
@@ -30,8 +30,8 @@ pub use session::*;
|
||||
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub use from_runtime::{
|
||||
PathResolver, RuntimeConversion, ScopedConversion, convert_input_attributes, convert_resource_entry, decode_declaration, encode_declaration, encode_input_ui_attributes, encode_node_ui_attributes,
|
||||
node_value_resource_refs, value_resource_ref,
|
||||
PathResolver, RuntimeConversion, ScopedConversion, convert_resource_entry, decode_declaration, encode_declaration, encode_input_ui_attributes, encode_node_ui_attributes, node_value_resource_refs,
|
||||
value_resource_ref,
|
||||
};
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position};
|
||||
|
||||
@@ -8,15 +8,11 @@ use std::collections::HashMap;
|
||||
|
||||
use core_types::uuid::NodeId as RuntimeNodeId;
|
||||
|
||||
/// One node's editor-side metadata, produced by `Registry::to_runtime_with_metadata`. One entry per
|
||||
/// node, since every node carries an identity to restore even when it carries no `ui::*` attribute.
|
||||
/// One node's editor-side metadata, produced by `Registry::to_runtime_with_metadata`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct NodeMetadataEntry {
|
||||
pub network_path: Vec<RuntimeNodeId>,
|
||||
pub local_id: RuntimeNodeId,
|
||||
/// The node's storage identity. Restoring it pins the node to this identity, so a later conversion
|
||||
/// keeps it instead of re-deriving one from the node's location.
|
||||
pub storage_id: crate::NodeId,
|
||||
pub position: Option<Position>,
|
||||
pub is_layer: bool,
|
||||
pub display_name: Option<String>,
|
||||
@@ -28,7 +24,19 @@ pub struct NodeMetadataEntry {
|
||||
pub output_names: Vec<String>,
|
||||
}
|
||||
|
||||
/// Per-network metadata. Separate from `NodeMetadataEntry` since these are
|
||||
impl NodeMetadataEntry {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.position.is_none()
|
||||
&& !self.is_layer
|
||||
&& self.display_name.is_none()
|
||||
&& !self.locked
|
||||
&& !self.pinned
|
||||
&& self.output_names.is_empty()
|
||||
&& self.input_metadata.iter().all(InputMetadataEntry::is_empty)
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-network metadata (navigation, previewing). Separate from `NodeMetadataEntry` since these are
|
||||
/// properties of a network, not of any node.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct NetworkMetadataEntry {
|
||||
@@ -36,13 +44,16 @@ pub struct NetworkMetadataEntry {
|
||||
/// Empty = root network.
|
||||
pub network_path: Vec<RuntimeNodeId>,
|
||||
/// Stable storage id of this network. Lets the editor associate per-network, per-peer view state
|
||||
/// (the node-graph nav, in `session.json`) with a network across reparenting.
|
||||
/// (node-graph nav + previewing, in `session.json`) with a network across reparenting.
|
||||
pub network_id: crate::NetworkId,
|
||||
/// Matches the runtime's `NodeNetworkPersistentMetadata::reference` — definition lineage tag.
|
||||
pub reference: Option<String>,
|
||||
/// The display order of the network's pinned nodes. Shared for the same reason the pinned flag is:
|
||||
/// a shared set with per-peer ordering could never reconcile.
|
||||
pub pinned_order: Vec<RuntimeNodeId>,
|
||||
}
|
||||
|
||||
impl NetworkMetadataEntry {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.reference.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-input editor metadata. Mirrors `InputPersistentMetadata` but wraps strings in `Option` so
|
||||
@@ -56,6 +67,12 @@ pub struct InputMetadataEntry {
|
||||
pub input_data: HashMap<String, serde_json::Value>,
|
||||
}
|
||||
|
||||
impl InputMetadataEntry {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.input_name.is_none() && self.input_description.is_none() && self.widget_override.is_none() && self.input_data.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Editor-side metadata source. Methods default to "no data" so implementors only override what
|
||||
/// they carry. Returns are JSON-shaped where the underlying types live editor-side (PTZ, etc.).
|
||||
pub trait NodeMetadataSource {
|
||||
@@ -93,18 +110,9 @@ pub trait NodeMetadataSource {
|
||||
HashMap::new()
|
||||
}
|
||||
|
||||
/// The storage identity this node is pinned to, if it has one. A node the source does not name
|
||||
/// falls back to a hash of its location.
|
||||
fn storage_node_id(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Option<crate::NodeId> {
|
||||
None
|
||||
}
|
||||
fn reference(&self, _network_path: &[RuntimeNodeId]) -> Option<&str> {
|
||||
None
|
||||
}
|
||||
/// The display order of the network's pinned nodes.
|
||||
fn pinned_order(&self, _network_path: &[RuntimeNodeId]) -> Vec<RuntimeNodeId> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// No-op metadata source. Use when there's nothing to attach (synthetic networks, CLI tools).
|
||||
|
||||
@@ -168,7 +168,7 @@ fn convert_network(
|
||||
let network = context.registry.networks.get(&network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
|
||||
|
||||
if let Some(collector) = network_collector.as_mut() {
|
||||
collector.push(extract_network_metadata(context.registry, &network.attributes, metadata_path, network_id));
|
||||
collector.push(extract_network_metadata(&network.attributes, metadata_path, network_id));
|
||||
}
|
||||
|
||||
let mut nodes: FxHashMap<RuntimeNodeId, DocumentNode> = FxHashMap::default();
|
||||
@@ -176,8 +176,10 @@ fn convert_network(
|
||||
let local_id = node.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(global_id.0);
|
||||
let runtime_id = RuntimeNodeId(local_id);
|
||||
|
||||
if let Some(collector) = node_collector.as_mut() {
|
||||
collector.push(extract_ui_metadata(node, global_id, metadata_path, runtime_id));
|
||||
if let Some(collector) = node_collector.as_mut()
|
||||
&& let Some(entry) = extract_ui_metadata(node, metadata_path, runtime_id)
|
||||
{
|
||||
collector.push(entry);
|
||||
}
|
||||
|
||||
let doc_node = convert_node(context, node, metadata_path, runtime_id, node_collector, network_collector)?;
|
||||
@@ -237,10 +239,10 @@ fn read_scope_injections(registry: &Registry, network_id: NetworkId, attributes:
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Emitted for every node, since `storage_id` is worth restoring even where no `ui::*` attribute is.
|
||||
/// `input_metadata` is always sized to match `node.inputs.len()` for a strict slot-by-slot rebuild;
|
||||
/// empty slots use `InputMetadataEntry::default()`.
|
||||
fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[RuntimeNodeId], local_id: RuntimeNodeId) -> NodeMetadataEntry {
|
||||
/// Returns `None` when the node has no `ui::*` attributes at all so callers don't end up with
|
||||
/// empty entries for unconverted-from-runtime nodes. `input_metadata` is always sized to match
|
||||
/// `node.inputs.len()` for a strict slot-by-slot rebuild; empty slots use `InputMetadataEntry::default()`.
|
||||
fn extract_ui_metadata(node: &crate::Node, network_path: &[RuntimeNodeId], local_id: RuntimeNodeId) -> Option<NodeMetadataEntry> {
|
||||
let position: Option<Position> = node.attributes.get_typed(node::ui::POSITION);
|
||||
let is_layer = node.attributes.get_or(node::ui::IS_LAYER, false);
|
||||
let display_name: Option<String> = node.attributes.get_typed(node::ui::DISPLAY_NAME);
|
||||
@@ -250,10 +252,9 @@ fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[R
|
||||
|
||||
let input_metadata: Vec<InputMetadataEntry> = node.inputs.iter().map(|slot| &slot.attributes).map(extract_input_metadata).collect();
|
||||
|
||||
NodeMetadataEntry {
|
||||
let entry = NodeMetadataEntry {
|
||||
network_path: network_path.to_vec(),
|
||||
local_id,
|
||||
storage_id,
|
||||
position,
|
||||
is_layer,
|
||||
display_name,
|
||||
@@ -261,31 +262,15 @@ fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[R
|
||||
pinned,
|
||||
input_metadata,
|
||||
output_names,
|
||||
}
|
||||
};
|
||||
(!entry.is_empty()).then_some(entry)
|
||||
}
|
||||
|
||||
/// Node references stored here are storage IDs, resolved back to runtime-local IDs the way
|
||||
/// `read_scope_injections` does. A reference to a node that is no longer in this network is dropped
|
||||
/// rather than failing the conversion: the preview target or a pinned node can have been deleted.
|
||||
fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes, network_path: &[RuntimeNodeId], network_id: NetworkId) -> NetworkMetadataEntry {
|
||||
let to_runtime_id = |storage_id: NodeId| {
|
||||
let node = registry.node_instances.get(&storage_id).filter(|node| node.network == network_id)?;
|
||||
let local_id = node.attributes.get(node::ORIGINAL_NODE_ID).and_then(|value| value.value.as_u64()).unwrap_or(storage_id.0);
|
||||
Some(RuntimeNodeId(local_id))
|
||||
};
|
||||
|
||||
let pinned_order = attributes
|
||||
.get_typed::<Vec<NodeId>>(network::PINNED_ORDER)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter_map(to_runtime_id)
|
||||
.collect();
|
||||
|
||||
fn extract_network_metadata(attributes: &crate::Attributes, network_path: &[RuntimeNodeId], network_id: NetworkId) -> NetworkMetadataEntry {
|
||||
NetworkMetadataEntry {
|
||||
network_path: network_path.to_vec(),
|
||||
network_id,
|
||||
reference: attributes.get_typed(node::ui::REFERENCE),
|
||||
pinned_order,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+9
-8
@@ -1,11 +1,14 @@
|
||||
[package]
|
||||
name = "graphite-editor"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
publish = false
|
||||
version = "0.0.0"
|
||||
rust-version = "1.88"
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
edition = "2024"
|
||||
readme = "../README.md"
|
||||
homepage = "https://graphite.art"
|
||||
repository = "https://github.com/GraphiteEditor/Graphite"
|
||||
license = "Apache-2.0"
|
||||
|
||||
[features]
|
||||
default = ["gpu"]
|
||||
@@ -69,5 +72,3 @@ wasm-bindgen-futures = { workspace = true }
|
||||
# Workspace dependencies
|
||||
env_logger = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
core-types = { workspace = true }
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
use std::env;
|
||||
use std::process::Command;
|
||||
|
||||
const GRAPHITE_RELEASE_SERIES: &str = "Alpha 5";
|
||||
const GRAPHITE_RELEASE_SERIES: &str = "Alpha 4";
|
||||
|
||||
fn main() {
|
||||
// Instruct Cargo to rerun this build script if any of these environment variables change.
|
||||
|
||||
@@ -135,9 +135,7 @@ pub const LINE_ROTATE_SNAP_ANGLE: f64 = 15.;
|
||||
|
||||
// BRUSH TOOL
|
||||
pub const BRUSH_SIZE_CHANGE_KEYBOARD: f64 = 5.;
|
||||
pub const BRUSH_SIZE_DEFAULT: f64 = 40.;
|
||||
pub const BRUSH_HARDNESS_DEFAULT: f64 = 0.;
|
||||
pub const BRUSH_FLOW_DEFAULT: f64 = 100.;
|
||||
pub const DEFAULT_BRUSH_SIZE: f64 = 20.;
|
||||
|
||||
// EYEDROPPER TOOL
|
||||
pub const EYEDROPPER_PREVIEW_AREA_RESOLUTION: u32 = 11;
|
||||
|
||||
+15
-15
@@ -36,7 +36,7 @@ pub struct DispatcherMessageHandlers {
|
||||
pub(crate) portfolio_message_handler: PortfolioMessageHandler,
|
||||
preferences_message_handler: PreferencesMessageHandler,
|
||||
pub(crate) resource_storage_message_handler: ResourceStorageMessageHandler,
|
||||
pub(crate) tool_message_handler: ToolMessageHandler,
|
||||
tool_message_handler: ToolMessageHandler,
|
||||
viewport_message_handler: ViewportMessageHandler,
|
||||
}
|
||||
|
||||
@@ -96,9 +96,8 @@ impl Dispatcher {
|
||||
s
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self {
|
||||
let mut s = Self::new(Arc::new(graph_craft::application_io::resource::HashMapResourceStorage::new()), None);
|
||||
let mut s = Self::default();
|
||||
s.message_handlers.portfolio_message_handler = PortfolioMessageHandler::with_executor(executor);
|
||||
s
|
||||
}
|
||||
@@ -266,8 +265,8 @@ 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.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);
|
||||
@@ -427,7 +426,6 @@ impl Dispatcher {
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::messages::portfolio::ingest::utility_types::IngestAction;
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
|
||||
#[tokio::test]
|
||||
@@ -479,11 +477,9 @@ mod test {
|
||||
"Demo artwork '{document_name}' has more than 1 line (remember to open and re-save it in Graphite)",
|
||||
);
|
||||
|
||||
let responses = editor.editor.handle_message(IngestMessage::Ingest {
|
||||
data: document_serialized_content.into_bytes(),
|
||||
action: IngestAction::Open,
|
||||
mime_type: String::new(),
|
||||
path: Some(file_name.into()),
|
||||
let responses = editor.editor.handle_message(PortfolioMessage::OpenFile {
|
||||
path: file_name.into(),
|
||||
content: document_serialized_content.bytes().collect(),
|
||||
});
|
||||
|
||||
// Check if the graph renders
|
||||
@@ -496,11 +492,15 @@ mod test {
|
||||
if let FrontendMessage::UpdateLayout {
|
||||
layout_target: LayoutTarget::DialogColumn1,
|
||||
diff,
|
||||
} = response && let DiffUpdate::Layout(sub_layout) = &diff[0].new_value
|
||||
&& let LayoutGroup::Row(WidgetRow { widgets }) = &sub_layout.0[0]
|
||||
&& let Widget::TextLabel(TextLabel { value, .. }) = &*widgets[0].widget
|
||||
} = response
|
||||
{
|
||||
print_problem_to_terminal_on_failure(value);
|
||||
if let DiffUpdate::Layout(sub_layout) = &diff[0].new_value {
|
||||
if let LayoutGroup::Row(WidgetRow { widgets }) = &sub_layout.0[0] {
|
||||
if let Widget::TextLabel(TextLabel { value, .. }) = &*widgets[0].widget {
|
||||
print_problem_to_terminal_on_failure(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ use crate::messages::prelude::*;
|
||||
pub enum AppWindowMessage {
|
||||
PointerLock,
|
||||
PointerLockMove { x: f64, y: f64 },
|
||||
DirectInput { enabled: bool },
|
||||
Restart,
|
||||
Close,
|
||||
Minimize,
|
||||
|
||||
@@ -17,12 +17,6 @@ impl MessageHandler<AppWindowMessage, ()> for AppWindowMessageHandler {
|
||||
AppWindowMessage::PointerLockMove { x, y } => {
|
||||
responses.add(FrontendMessage::WindowPointerLockMove { position: (x, y) });
|
||||
}
|
||||
AppWindowMessage::DirectInput { enabled } => {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
responses.add(FrontendMessage::WindowUpdateDirectInput { enabled });
|
||||
#[cfg(target_family = "wasm")]
|
||||
let _ = enabled;
|
||||
}
|
||||
AppWindowMessage::Close => {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
responses.add(FrontendMessage::WindowClose);
|
||||
|
||||
@@ -11,10 +11,11 @@ use crate::messages::tool::utility_types::ToolType;
|
||||
use graph_craft::application_io::resource::{DataSource, ResourceHash};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::vector::misc::{BezierHandles, HandleId, point_to_dvec2, segment_to_handles};
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::subpath::BezierHandles;
|
||||
use graphene_std::vector::misc::HandleId;
|
||||
use graphene_std::vector::{PointId, SegmentId, VectorModificationType};
|
||||
use graphite_proc_macros::{ExtractField, message_handler_data};
|
||||
use kurbo::ParamCurve;
|
||||
use std::sync::Arc;
|
||||
|
||||
const CLIPBOARD_PREFIX: &str = "graphite: ";
|
||||
@@ -50,6 +51,22 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
responses.add(FrontendMessage::TriggerSelectionWrite { content: text });
|
||||
}
|
||||
}
|
||||
ClipboardContentRaw::Svg(svg) => {
|
||||
responses.add(PortfolioMessage::InsertSvg {
|
||||
svg,
|
||||
name: None,
|
||||
mouse: None,
|
||||
parent_and_insert_index: None,
|
||||
});
|
||||
}
|
||||
ClipboardContentRaw::Image { data, width, height } => {
|
||||
responses.add(PortfolioMessage::InsertImage {
|
||||
image: Image::from_image_data(&data, width, height),
|
||||
name: None,
|
||||
mouse: None,
|
||||
parent_and_insert_index: None,
|
||||
});
|
||||
}
|
||||
},
|
||||
ClipboardMessage::ReadSelection { content, cut } => {
|
||||
if let Some(text) = content {
|
||||
@@ -408,7 +425,7 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
|
||||
// Create new segment ids and add the segments into the existing Vector path
|
||||
let mut segments_map = HashMap::new();
|
||||
for (segment_id, segment, start, end) in new_vector.segment_iter() {
|
||||
for (segment_id, bezier, start, end) in new_vector.segment_bezier_iter() {
|
||||
let (Some(&start_point), Some(&end_point)) = (points_map.get(&start), points_map.get(&end)) else {
|
||||
warn!("Skipping pasted vector segment with an unknown endpoint");
|
||||
continue;
|
||||
@@ -417,12 +434,10 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
let new_segment_id = SegmentId::generate();
|
||||
segments_map.insert(segment_id, new_segment_id);
|
||||
|
||||
let segment_start = point_to_dvec2(segment.start());
|
||||
let segment_end = point_to_dvec2(segment.end());
|
||||
let handles = match segment_to_handles(&segment) {
|
||||
let handles = match bezier.handles {
|
||||
BezierHandles::Linear => [None, None],
|
||||
BezierHandles::Quadratic { handle } => [Some(handle - segment_start), None],
|
||||
BezierHandles::Cubic { handle_start, handle_end } => [Some(handle_start - segment_start), Some(handle_end - segment_end)],
|
||||
BezierHandles::Quadratic { handle } => [Some(handle - bezier.start), None],
|
||||
BezierHandles::Cubic { handle_start, handle_end } => [Some(handle_start - bezier.start), Some(handle_end - bezier.end)],
|
||||
};
|
||||
|
||||
let points = [start_point, end_point];
|
||||
|
||||
@@ -10,6 +10,8 @@ use graphene_std::vector::Vector;
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ClipboardContentRaw {
|
||||
Text(String),
|
||||
Svg(String),
|
||||
Image { data: Vec<u8>, width: u32, height: u32 },
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::messages::layout::utility_types::widgets::input_widgets::{SliderInputUpdate, VisualColorPickersInputUpdate};
|
||||
use crate::messages::layout::utility_types::widgets::input_widgets::{SpectrumInputUpdate, VisualColorPickersInputUpdate};
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_std::vector::style::{FillChoice, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread};
|
||||
|
||||
@@ -45,8 +45,8 @@ pub enum ColorPickerMessage {
|
||||
/// Swap the current "new" color with the captured "old" color.
|
||||
SwapNewWithOld,
|
||||
|
||||
/// `SliderInput` change: marker move/insert/delete, midpoint move/reset, or active marker selection changed.
|
||||
GradientUpdate { update: SliderInputUpdate },
|
||||
/// `SpectrumInput` change: marker move/insert/delete, midpoint move/reset, or active marker selection changed.
|
||||
GradientUpdate { update: SpectrumInputUpdate },
|
||||
/// Gradient spread choice from the gradient "Ends" selection.
|
||||
SetGradientSpread { gradient_spread: GradientSpread },
|
||||
/// Gradient cyclic choice: whether the stops wrap as a cycle, from the "Cyclic" checkbox.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::messages::color_picker::color_picker_message::{HsvChannel, RgbChannel};
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::layout::utility_types::widgets::input_widgets::{ColorPresetsInputUpdate, SliderInputUpdate, SliderMarker, VisualColorPickersInputUpdate};
|
||||
use crate::messages::layout::utility_types::widgets::input_widgets::{ColorPresetsInputUpdate, SpectrumInputUpdate, SpectrumMarker, VisualColorPickersInputUpdate};
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::color::SRGBA8;
|
||||
@@ -377,10 +377,10 @@ impl ColorPickerMessageHandler {
|
||||
});
|
||||
}
|
||||
|
||||
/// Apply an incoming `SliderInput` intent to the gradient state and broadcast the result.
|
||||
fn apply_gradient_update(&mut self, update: SliderInputUpdate, responses: &mut VecDeque<Message>) {
|
||||
/// Apply an incoming `SpectrumInput` intent to the gradient state and broadcast the result.
|
||||
fn apply_gradient_update(&mut self, update: SpectrumInputUpdate, responses: &mut VecDeque<Message>) {
|
||||
// Active marker selection is the one update that doesn't mutate the gradient
|
||||
if let SliderInputUpdate::ActiveMarker {
|
||||
if let SpectrumInputUpdate::ActiveMarker {
|
||||
active_marker_index,
|
||||
active_marker_is_midpoint,
|
||||
} = update
|
||||
@@ -401,19 +401,19 @@ impl ColorPickerMessageHandler {
|
||||
let Some(mut gradient) = self.gradient.clone() else { return };
|
||||
|
||||
match update {
|
||||
SliderInputUpdate::MoveMarker { index, position } => {
|
||||
SpectrumInputUpdate::MoveMarker { index, position } => {
|
||||
let new_index = gradient.move_stop(index as usize, position, self.gradient_cyclic);
|
||||
if Some(index) == self.active_marker_index {
|
||||
self.active_marker_index = Some(new_index as u32);
|
||||
}
|
||||
}
|
||||
SliderInputUpdate::MoveMidpoint { index, position } => {
|
||||
SpectrumInputUpdate::MoveMidpoint { index, position } => {
|
||||
if (index as usize) >= gradient.len() {
|
||||
return;
|
||||
}
|
||||
gradient.set_midpoint(index as usize, position.clamp(MIN_MIDPOINT, MAX_MIDPOINT));
|
||||
}
|
||||
SliderInputUpdate::InsertMarker { position } => {
|
||||
SpectrumInputUpdate::InsertMarker { position } => {
|
||||
let new_index = gradient.insert_stop(position, self.gradient_settings());
|
||||
self.active_marker_index = Some(new_index as u32);
|
||||
self.active_marker_is_midpoint = false;
|
||||
@@ -422,7 +422,7 @@ impl ColorPickerMessageHandler {
|
||||
self.snapshot_old();
|
||||
}
|
||||
}
|
||||
SliderInputUpdate::InsertDuplicate { index, position } => {
|
||||
SpectrumInputUpdate::InsertDuplicate { index, position } => {
|
||||
let source = index as usize;
|
||||
let Some(insert_index) = gradient.duplicate_stop(source, position, self.gradient_cyclic) else {
|
||||
return;
|
||||
@@ -432,7 +432,7 @@ impl ColorPickerMessageHandler {
|
||||
self.active_marker_index = Some(dragged_index as u32);
|
||||
self.active_marker_is_midpoint = false;
|
||||
}
|
||||
SliderInputUpdate::RemoveDuplicate { index } => {
|
||||
SpectrumInputUpdate::RemoveDuplicate { index } => {
|
||||
let anchor = index as usize;
|
||||
if anchor >= gradient.len() || gradient.len() <= 2 {
|
||||
return;
|
||||
@@ -449,7 +449,7 @@ impl ColorPickerMessageHandler {
|
||||
self.active_marker_index = Some(active - 1);
|
||||
}
|
||||
}
|
||||
SliderInputUpdate::DeleteMarker { index } => {
|
||||
SpectrumInputUpdate::DeleteMarker { index } => {
|
||||
// Enforce minimum stop count. The gradient editor needs at least 2 stops to remain meaningful.
|
||||
if gradient.len() <= 2 || (index as usize) >= gradient.len() {
|
||||
return;
|
||||
@@ -463,10 +463,10 @@ impl ColorPickerMessageHandler {
|
||||
self.snapshot_old();
|
||||
}
|
||||
}
|
||||
SliderInputUpdate::ResetMidpoint { index } => {
|
||||
SpectrumInputUpdate::ResetMidpoint { index } => {
|
||||
gradient.reset_midpoint(index as usize);
|
||||
}
|
||||
SliderInputUpdate::ResetMarker { index } => {
|
||||
SpectrumInputUpdate::ResetMarker { index } => {
|
||||
let i = index as usize;
|
||||
let count = gradient.len();
|
||||
if i >= count {
|
||||
@@ -483,7 +483,7 @@ impl ColorPickerMessageHandler {
|
||||
self.active_marker_index = Some(new_index as u32);
|
||||
}
|
||||
}
|
||||
SliderInputUpdate::ActiveMarker { .. } => unreachable!("handled above"),
|
||||
SpectrumInputUpdate::ActiveMarker { .. } => unreachable!("handled above"),
|
||||
}
|
||||
|
||||
responses.add(FrontendMessage::ColorPickerColorChanged {
|
||||
@@ -514,10 +514,10 @@ impl ColorPickerMessageHandler {
|
||||
if let Some(gradient) = &self.gradient {
|
||||
// For gradient editing, the markers' handle colors mirror their gradient stop colors
|
||||
let markers = (0..gradient.len())
|
||||
.filter_map(|i| Some(SliderMarker::new(gradient.position(i, self.gradient_cyclic), gradient.midpoint(i), gradient.color(i)?)))
|
||||
.filter_map(|i| Some(SpectrumMarker::new(gradient.position(i, self.gradient_cyclic), gradient.midpoint(i), gradient.color(i)?)))
|
||||
.collect();
|
||||
let mut row_widgets = vec![
|
||||
SliderInput::new(GradientStops::from(gradient))
|
||||
SpectrumInput::new(GradientStops::from(gradient))
|
||||
.track_space(self.gradient_space)
|
||||
.track_cyclic(self.gradient_cyclic)
|
||||
.track_hue_direction(self.gradient_hue_direction)
|
||||
@@ -529,9 +529,8 @@ impl ColorPickerMessageHandler {
|
||||
.allow_insert(!self.disabled)
|
||||
.allow_delete(!self.disabled)
|
||||
.allow_reorder(true)
|
||||
.allow_select(true)
|
||||
.disabled(self.disabled)
|
||||
.on_update(|update: &SliderInputUpdate| ColorPickerMessage::GradientUpdate { update: update.clone() }.into())
|
||||
.on_update(|update: &SpectrumInputUpdate| ColorPickerMessage::GradientUpdate { update: update.clone() }.into())
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
@@ -556,12 +555,12 @@ impl ColorPickerMessageHandler {
|
||||
return Message::NoOp;
|
||||
};
|
||||
let update = if is_midpoint {
|
||||
SliderInputUpdate::MoveMidpoint {
|
||||
SpectrumInputUpdate::MoveMidpoint {
|
||||
index: captured_index,
|
||||
position: new_value / 100.,
|
||||
}
|
||||
} else {
|
||||
SliderInputUpdate::MoveMarker {
|
||||
SpectrumInputUpdate::MoveMarker {
|
||||
index: captured_index,
|
||||
position: new_value / 100.,
|
||||
}
|
||||
|
||||
@@ -95,7 +95,7 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
||||
.network_interface
|
||||
.node_metadata(&layer.to_node(), &[])
|
||||
.map(|node| node.persistent_metadata.display_name.clone())
|
||||
.filter(|name| !name.is_empty())
|
||||
.and_then(|name| if name.is_empty() { None } else { Some(name) })
|
||||
.unwrap_or_else(|| "Artboard".to_string());
|
||||
(layer, name)
|
||||
})
|
||||
|
||||
@@ -94,38 +94,19 @@ impl DialogLayoutHolder for ExportDialogMessageHandler {
|
||||
|
||||
impl LayoutHolder for ExportDialogMessageHandler {
|
||||
fn layout(&self) -> Layout {
|
||||
// The vector type, then the raster ones
|
||||
let file_types = [
|
||||
vec![(FileType::Svg, "SVG")],
|
||||
vec![
|
||||
(FileType::Png, "PNG"),
|
||||
(FileType::Jpg, "JPG"),
|
||||
(FileType::Webp, "WEBP"),
|
||||
(FileType::Tiff, "TIFF"),
|
||||
(FileType::Bmp, "BMP"),
|
||||
(FileType::Tga, "TGA"),
|
||||
(FileType::Ico, "ICO"),
|
||||
],
|
||||
];
|
||||
let selected_index = file_types.iter().flatten().position(|(file_type, _)| *file_type == self.file_type);
|
||||
let entries = file_types
|
||||
let entries = [(FileType::Png, "PNG"), (FileType::Jpg, "JPG"), (FileType::Svg, "SVG")]
|
||||
.into_iter()
|
||||
.map(|section| {
|
||||
section
|
||||
.into_iter()
|
||||
.map(|(file_type, name)| {
|
||||
MenuListEntry::new(format!("{file_type:?}"))
|
||||
.label(name)
|
||||
.on_commit(move |_| ExportDialogMessage::FileType { file_type }.into())
|
||||
})
|
||||
.collect()
|
||||
.map(|(file_type, name)| {
|
||||
RadioEntryData::new(format!("{file_type:?}"))
|
||||
.label(name)
|
||||
.on_update(move |_| ExportDialogMessage::FileType { file_type }.into())
|
||||
})
|
||||
.collect();
|
||||
|
||||
let export_type = vec![
|
||||
TextLabel::new("File Type").table_align(true).min_width(100).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
DropdownInput::new(entries).selected_index(selected_index.map(|index| index as u32)).min_width(200).widget_instance(),
|
||||
RadioInput::new(entries).selected_index(Some(self.file_type as u32)).widget_instance(),
|
||||
];
|
||||
|
||||
let resolution = vec![
|
||||
|
||||
@@ -275,7 +275,11 @@ impl PreferencesDialogMessageHandler {
|
||||
|
||||
let checkbox_id = CheckboxId::new();
|
||||
let brush_tool_description = "
|
||||
Enable the Brush tool to support basic layer painting.\n\
|
||||
Enable the Brush tool to support basic raster-based layer painting.\n\
|
||||
\n\
|
||||
This legacy experimental tool has performance and quality limitations and is slated for replacement in future versions of Graphite that will have a renewed focus on raster graphics editing.\n\
|
||||
\n\
|
||||
Content created with the Brush tool may not be compatible with future versions of Graphite.\n\
|
||||
\n\
|
||||
*Default: Off.*
|
||||
"
|
||||
|
||||
@@ -18,7 +18,7 @@ impl DialogLayoutHolder for FailedToLoadDocumentsDialog {
|
||||
.tooltip_description("Save the raw document data to disk so it can be recovered later.")
|
||||
.on_update(|_| {
|
||||
DialogMessage::CloseAndThen {
|
||||
followups: vec![FailedDocumentsMessage::DownloadFailedToLoadDocuments.into()],
|
||||
followups: vec![PortfolioMessage::DownloadFailedToLoadDocuments.into()],
|
||||
}
|
||||
.into()
|
||||
})
|
||||
@@ -27,7 +27,7 @@ impl DialogLayoutHolder for FailedToLoadDocumentsDialog {
|
||||
.tooltip_description("Permanently delete the autosaved data for these documents.")
|
||||
.on_update(|_| {
|
||||
DialogMessage::CloseAndThen {
|
||||
followups: vec![FailedDocumentsMessage::DiscardFailedToLoadDocuments.into()],
|
||||
followups: vec![PortfolioMessage::DiscardFailedToLoadDocuments.into()],
|
||||
}
|
||||
.into()
|
||||
})
|
||||
|
||||
@@ -46,15 +46,11 @@ impl LayoutHolder for LicensesDialog {
|
||||
let year = &self.localized_commit_year;
|
||||
let description = format!(
|
||||
"
|
||||
Graphite source code is copyright © {year} Graphite contrib-\n\
|
||||
utors and is available under both the MIT and Apache 2.0\n\
|
||||
licenses. See \"Source Code License\" for details.\n\
|
||||
Graphite source code is copyright © {year} Graphite contrib-\nutors and is available under the Apache License 2.0. See\n\"Source Code License\" for details.\n\
|
||||
\n\
|
||||
The Graphite logo, icons, and visual identity are copyright ©\n\
|
||||
{year} Graphite Labs, LLC. See \"Branding License\" for details.\n\
|
||||
The Graphite logo, icons, and visual identity are copyright ©\n{year} Graphite Labs, LLC. See \"Branding License\" for details.\n\
|
||||
\n\
|
||||
Graphite is distributed with third-party open source code\n\
|
||||
dependencies. See \"Dependency Licenses\" for details.
|
||||
Graphite is distributed with third-party open source code\ndependencies. See \"Dependency Licenses\" for details.
|
||||
"
|
||||
);
|
||||
let description = description.trim();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::IconName;
|
||||
use super::utility_types::{MouseCursorIcon, PersistedState};
|
||||
use crate::messages::app_window::app_window_message_handler::AppWindowPlatform;
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage, FileDialogOptions, FileFilter, FileType, RasterizedImage};
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage, RasterizedImage};
|
||||
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::ingest::utility_types::IngestAction;
|
||||
use crate::messages::portfolio::utility_types::WorkspacePanelLayout;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::tool_messages::eyedropper_tool::PrimarySecondary;
|
||||
@@ -88,29 +87,22 @@ pub enum FrontendMessage {
|
||||
commit_date: String,
|
||||
},
|
||||
TriggerDisplayThirdPartyLicensesDialog,
|
||||
TriggerBrowse {
|
||||
options: FileDialogOptions,
|
||||
action: IngestAction,
|
||||
},
|
||||
TriggerSaveDocument {
|
||||
document_id: DocumentId,
|
||||
name: String,
|
||||
path: Option<PathBuf>,
|
||||
folder: Option<PathBuf>,
|
||||
filters: Vec<FileFilter>,
|
||||
content: serde_bytes::ByteBuf,
|
||||
},
|
||||
TriggerSaveFile {
|
||||
name: String,
|
||||
folder: Option<PathBuf>,
|
||||
filters: Vec<FileFilter>,
|
||||
content: serde_bytes::ByteBuf,
|
||||
},
|
||||
TriggerExportImage {
|
||||
svg: String,
|
||||
name: String,
|
||||
#[serde(rename = "fileType")]
|
||||
file_type: FileType,
|
||||
mime: String,
|
||||
size: (f64, f64),
|
||||
},
|
||||
TriggerFetchAndOpenDocument {
|
||||
@@ -136,6 +128,8 @@ pub enum FrontendMessage {
|
||||
},
|
||||
TriggerOpenLaunchDocuments,
|
||||
TriggerLoadPreferences,
|
||||
TriggerOpen,
|
||||
TriggerImport,
|
||||
TriggerSavePreferences {
|
||||
#[cfg_attr(feature = "wasm", tsify(type = "unknown"))]
|
||||
preferences: PreferencesMessageHandler,
|
||||
@@ -350,10 +344,6 @@ pub enum FrontendMessage {
|
||||
position: (f64, f64),
|
||||
},
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
WindowUpdateDirectInput {
|
||||
enabled: bool,
|
||||
},
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
WindowClose,
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
WindowMinimize,
|
||||
|
||||
@@ -47,96 +47,23 @@ pub enum MouseCursorIcon {
|
||||
Rotate,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum FileType {
|
||||
#[default]
|
||||
Png,
|
||||
Jpg,
|
||||
Webp,
|
||||
Tiff,
|
||||
Bmp,
|
||||
Tga,
|
||||
Ico,
|
||||
Svg,
|
||||
}
|
||||
|
||||
impl FileType {
|
||||
pub fn extension(self) -> &'static str {
|
||||
pub fn to_mime(self) -> &'static str {
|
||||
match self {
|
||||
FileType::Png => "png",
|
||||
FileType::Jpg => "jpg",
|
||||
FileType::Webp => "webp",
|
||||
FileType::Tiff => "tiff",
|
||||
FileType::Bmp => "bmp",
|
||||
FileType::Tga => "tga",
|
||||
FileType::Ico => "ico",
|
||||
FileType::Svg => "svg",
|
||||
FileType::Png => "image/png",
|
||||
FileType::Jpg => "image/jpeg",
|
||||
FileType::Svg => "image/svg+xml",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn file_filter(self) -> FileFilter {
|
||||
let name = match self {
|
||||
FileType::Png => "PNG Image",
|
||||
FileType::Jpg => "JPEG Image",
|
||||
FileType::Webp => "WEBP Image",
|
||||
FileType::Tiff => "TIFF Image",
|
||||
FileType::Bmp => "BMP Image",
|
||||
FileType::Tga => "TGA Image",
|
||||
FileType::Ico => "ICO Image",
|
||||
FileType::Svg => "SVG Image",
|
||||
};
|
||||
FileFilter {
|
||||
name: name.into(),
|
||||
extensions: vec![self.extension().into()],
|
||||
mime_types: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes 8-bit RGBA pixels with straight alpha as a file of this raster type.
|
||||
pub fn encode(self, width: u32, height: u32, rgba: Vec<u8>) -> Result<Vec<u8>, String> {
|
||||
use image::buffer::ConvertBuffer;
|
||||
use image::{ImageFormat, RgbImage, RgbaImage};
|
||||
|
||||
let Some(mut image) = RgbaImage::from_raw(width, height, rgba) else {
|
||||
return Err("Failed to create image buffer for export".to_string());
|
||||
};
|
||||
|
||||
let format = match self {
|
||||
FileType::Png => ImageFormat::Png,
|
||||
FileType::Jpg => ImageFormat::Jpeg,
|
||||
FileType::Webp => ImageFormat::WebP,
|
||||
FileType::Tiff => ImageFormat::Tiff,
|
||||
FileType::Bmp => ImageFormat::Bmp,
|
||||
FileType::Tga => ImageFormat::Tga,
|
||||
FileType::Ico => ImageFormat::Ico,
|
||||
FileType::Svg => return Err("SVG cannot be exported from an image buffer".to_string()),
|
||||
};
|
||||
if self == FileType::Ico && (width > 256 || height > 256) {
|
||||
return Err("An ICO image can be at most 256 pixels wide and tall. Lower the scale factor or choose a smaller export area.".to_string());
|
||||
}
|
||||
|
||||
let mut encoded = Vec::new();
|
||||
let mut cursor = std::io::Cursor::new(&mut encoded);
|
||||
|
||||
let result = if self == 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();
|
||||
image.write_to(&mut cursor, format)
|
||||
} else {
|
||||
image.write_to(&mut cursor, format)
|
||||
};
|
||||
result.map_err(|error| format!("Failed to encode {self:?}: {error}"))?;
|
||||
|
||||
Ok(encoded)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -164,55 +91,3 @@ pub struct RasterizedImage {
|
||||
pub height: u32,
|
||||
pub pixels: serde_bytes::ByteBuf,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct FileFilter {
|
||||
pub name: String,
|
||||
pub extensions: Vec<String>,
|
||||
#[serde(rename = "mimeTypes")]
|
||||
pub mime_types: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct FileDialogOptions {
|
||||
pub filters: Vec<FileFilter>,
|
||||
pub multiple: bool,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use graphene_std::raster::Image;
|
||||
|
||||
#[test]
|
||||
fn every_raster_file_type_encodes_an_image_that_reads_back() {
|
||||
// Opaque red, then fully transparent
|
||||
let pixels = vec![255, 0, 0, 255, 0, 0, 0, 0];
|
||||
|
||||
for file_type in [FileType::Png, FileType::Jpg, FileType::Webp, FileType::Tiff, FileType::Bmp, FileType::Tga, FileType::Ico] {
|
||||
let encoded = file_type.encode(2, 1, pixels.clone()).unwrap_or_else(|error| panic!("{file_type:?}: {error}"));
|
||||
let decoded = Image::from_encoded(&encoded).unwrap_or_else(|| panic!("{file_type:?} should read back"));
|
||||
assert_eq!((decoded.width, decoded.height), (2, 1), "{file_type:?}");
|
||||
|
||||
// Only JPG lacks transparency, so it lands on white
|
||||
let transparent = decoded.to_flat_u8().0[4..8].to_vec();
|
||||
if file_type == FileType::Jpg {
|
||||
assert!(transparent.iter().all(|&channel| channel > 250), "{transparent:?}");
|
||||
} else {
|
||||
assert_eq!(transparent[3], 0, "{file_type:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_types_that_cannot_hold_the_image_say_so() {
|
||||
assert!(FileType::Svg.encode(1, 1, vec![0; 4]).is_err());
|
||||
assert!(FileType::Png.encode(2, 2, vec![0; 4]).is_err());
|
||||
|
||||
let too_large = FileType::Ico.encode(257, 1, vec![0; 257 * 4]).unwrap_err();
|
||||
assert!(too_large.contains("256 pixels"), "{too_large}");
|
||||
assert!(FileType::Ico.encode(256, 1, vec![0; 256 * 4]).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::messages::input_mapper::utility_types::keyboard::Key;
|
||||
use crate::messages::input_mapper::utility_types::pointer::MouseButton;
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::MouseButton;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[impl_message(Message, KeyMappingMessage, Lookup)]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::utility_types::keyboard::KeysGroup;
|
||||
use super::utility_types::input_keyboard::KeysGroup;
|
||||
use super::utility_types::misc::Mapping;
|
||||
use crate::application::Editor;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{self, Key};
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::{self, Key};
|
||||
use crate::messages::input_mapper::utility_types::misc::MappingEntry;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
@@ -58,7 +58,7 @@ impl InputMapperMessageHandler {
|
||||
.map(|i| {
|
||||
// TODO: Use a safe solution eventually
|
||||
assert!(
|
||||
i < keyboard::NUMBER_OF_KEYS,
|
||||
i < input_keyboard::NUMBER_OF_KEYS,
|
||||
"Attempting to convert a Key with enum index {i}, which is larger than the number of Key enums",
|
||||
);
|
||||
(i as u8).try_into().unwrap()
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use crate::application::Editor;
|
||||
use crate::consts::{BIG_NUDGE_AMOUNT, BRUSH_SIZE_CHANGE_KEYBOARD, NUDGE_AMOUNT};
|
||||
use crate::messages::input_mapper::key_mapping::MappingVariant;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, KeyStates};
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, KeyStates};
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::MouseButton;
|
||||
use crate::messages::input_mapper::utility_types::macros::*;
|
||||
use crate::messages::input_mapper::utility_types::misc::MappingEntry;
|
||||
use crate::messages::input_mapper::utility_types::misc::{KeyMappingEntries, Mapping};
|
||||
use crate::messages::input_mapper::utility_types::pointer::MouseButton;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::Direction;
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
use crate::messages::prelude::*;
|
||||
@@ -444,11 +444,11 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
entry!(KeyDown(Tab); modifiers=[Control, Shift], action_dispatch=PortfolioMessage::PrevDocument),
|
||||
entry!(KeyDown(KeyW); modifiers=[Accel], action_dispatch=PortfolioMessage::CloseActiveDocumentWithConfirmation),
|
||||
entry!(KeyDown(KeyW); modifiers=[Accel, Alt], action_dispatch=PortfolioMessage::CloseAllDocumentsWithConfirmation),
|
||||
entry!(KeyDown(KeyO); modifiers=[Accel], action_dispatch=IngestMessage::Open),
|
||||
entry!(KeyDown(KeyI); modifiers=[Accel], action_dispatch=IngestMessage::Import),
|
||||
entry!(KeyDown(KeyO); modifiers=[Accel], action_dispatch=PortfolioMessage::Open),
|
||||
entry!(KeyDown(KeyI); modifiers=[Accel], action_dispatch=PortfolioMessage::Import),
|
||||
entry!(KeyDown(KeyR); modifiers=[Alt], action_dispatch=PortfolioMessage::ToggleRulers),
|
||||
entry!(KeyDown(KeyD); modifiers=[Alt], action_dispatch=WorkspaceMessage::ToggleDataPanelOpen),
|
||||
entry!(KeyDown(Enter); modifiers=[Alt], action_dispatch=WorkspaceMessage::ToggleFocusDocument),
|
||||
entry!(KeyDown(KeyD); modifiers=[Alt], action_dispatch=PortfolioMessage::ToggleDataPanelOpen),
|
||||
entry!(KeyDown(Enter); modifiers=[Alt], action_dispatch=PortfolioMessage::ToggleFocusDocument),
|
||||
//
|
||||
// DialogMessage
|
||||
entry!(KeyDown(KeyE); modifiers=[Accel], action_dispatch=DialogMessage::RequestExportDialog),
|
||||
@@ -465,7 +465,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
];
|
||||
let (mut key_up, mut key_down, mut key_up_no_repeat, mut key_down_no_repeat, mut double_click, mut wheel_scroll, mut pointer_move, mut pointer_shake) = mappings;
|
||||
|
||||
let sort = |list: &mut KeyMappingEntries| list.0.sort_by_key(|entry| std::cmp::Reverse(entry.modifiers.count_ones()));
|
||||
let sort = |list: &mut KeyMappingEntries| list.0.sort_by(|a, b| b.modifiers.count_ones().cmp(&a.modifiers.count_ones()));
|
||||
// Sort the sublists of `key_up`, `key_down`, `key_up_no_repeat`, and `key_down_no_repeat`
|
||||
for list in [&mut key_up, &mut key_down, &mut key_up_no_repeat, &mut key_down_no_repeat] {
|
||||
for sublist in list {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::messages::input_mapper::input_mapper_message_handler::InputMapperMessageContext;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::KeysGroup;
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
|
||||
File renamed without changes.
+9
-27
@@ -50,21 +50,15 @@ impl ScrollDelta {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Document the difference between this and EditorPointerState
|
||||
// TODO: Document the difference between this and EditorMouseState
|
||||
#[derive(Debug, Copy, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PointerState {
|
||||
pub struct MouseState {
|
||||
pub position: ViewportPosition,
|
||||
pub mouse_keys: MouseKeys,
|
||||
pub scroll_delta: ScrollDelta,
|
||||
pub time: Option<f64>,
|
||||
pub pressure: Option<f64>,
|
||||
pub tilt: Option<DVec2>,
|
||||
pub twist: Option<f64>,
|
||||
pub wheel: Option<f64>,
|
||||
pub eraser: bool,
|
||||
}
|
||||
|
||||
impl PointerState {
|
||||
impl MouseState {
|
||||
pub fn finish_transaction(&self, drag_start: DVec2, responses: &mut VecDeque<Message>) {
|
||||
let drag_too_small = drag_start.distance(self.position) <= DRAG_THRESHOLD;
|
||||
let response = if drag_too_small { DocumentMessage::AbortTransaction } else { DocumentMessage::EndTransaction };
|
||||
@@ -72,21 +66,15 @@ impl PointerState {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Document the difference between this and PointerState
|
||||
// TODO: Document the difference between this and MouseState
|
||||
#[derive(Debug, Copy, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct EditorPointerState {
|
||||
pub struct EditorMouseState {
|
||||
pub editor_position: EditorPosition,
|
||||
pub mouse_keys: MouseKeys,
|
||||
pub scroll_delta: ScrollDelta,
|
||||
pub time: Option<f64>,
|
||||
pub pressure: Option<f64>,
|
||||
pub tilt: Option<DVec2>,
|
||||
pub twist: Option<f64>,
|
||||
pub wheel: Option<f64>,
|
||||
pub eraser: bool,
|
||||
}
|
||||
|
||||
impl EditorPointerState {
|
||||
impl EditorMouseState {
|
||||
pub fn from_keys_and_editor_position(keys: u8, editor_position: EditorPosition) -> Self {
|
||||
// TODO: Some graphic tablets send key codes not mentioned in the spec. In the future we would like to support these as well.
|
||||
let mouse_keys = MouseKeys::from_bits_truncate(keys);
|
||||
@@ -94,21 +82,15 @@ impl EditorPointerState {
|
||||
Self {
|
||||
editor_position,
|
||||
mouse_keys,
|
||||
..Default::default()
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_pointer_state(&self, viewport: &ViewportMessageHandler) -> PointerState {
|
||||
PointerState {
|
||||
pub fn to_mouse_state(&self, viewport: &ViewportMessageHandler) -> MouseState {
|
||||
MouseState {
|
||||
position: (viewport.logical(self.editor_position) - viewport.offset()).into(),
|
||||
mouse_keys: self.mouse_keys,
|
||||
scroll_delta: self.scroll_delta,
|
||||
time: self.time,
|
||||
pressure: self.pressure,
|
||||
tilt: self.tilt,
|
||||
twist: self.twist,
|
||||
wheel: self.wheel,
|
||||
eraser: self.eraser,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -162,7 +162,7 @@ macro_rules! action_shortcut {
|
||||
macro_rules! action_shortcut_manual {
|
||||
($($keys:expr),*) => {
|
||||
Some(crate::messages::input_mapper::utility_types::misc::ActionShortcut::Shortcut(
|
||||
crate::messages::input_mapper::utility_types::keyboard::LabeledShortcut(vec![$($keys.into()),*]).into(),
|
||||
crate::messages::input_mapper::utility_types::input_keyboard::LabeledShortcut(vec![$($keys.into()),*]).into(),
|
||||
))
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::keyboard::{KeysGroup, LabeledShortcut, all_required_modifiers_pressed};
|
||||
use super::input_keyboard::{KeysGroup, LabeledShortcut, all_required_modifiers_pressed};
|
||||
use crate::messages::input_mapper::key_mapping::MappingVariant;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{KeyStates, NUMBER_OF_KEYS};
|
||||
use crate::messages::input_mapper::utility_types::pointer::NUMBER_OF_MOUSE_BUTTONS;
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::{KeyStates, NUMBER_OF_KEYS};
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::NUMBER_OF_MOUSE_BUTTONS;
|
||||
use crate::messages::prelude::*;
|
||||
use core::time::Duration;
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
pub mod keyboard;
|
||||
pub mod pointer;
|
||||
|
||||
pub mod input_keyboard;
|
||||
pub mod input_mouse;
|
||||
pub mod macros;
|
||||
pub mod misc;
|
||||
@@ -1,17 +1,17 @@
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
|
||||
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, ModifierKeys};
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::EditorMouseState;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[impl_message(Message, InputPreprocessor)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum InputPreprocessorMessage {
|
||||
DoubleClick { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
|
||||
DoubleClick { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
|
||||
KeyDown { key: Key, key_repeat: bool, modifier_keys: ModifierKeys },
|
||||
KeyUp { key: Key, key_repeat: bool, modifier_keys: ModifierKeys },
|
||||
PointerDown { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
|
||||
PointerMove { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
|
||||
PointerUp { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
|
||||
PointerShake { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
|
||||
PointerDown { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
|
||||
PointerMove { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
|
||||
PointerUp { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
|
||||
PointerShake { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
|
||||
CurrentTime { timestamp: u64 },
|
||||
WheelScroll { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
|
||||
WheelScroll { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::application::Editor;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, KeyStates, ModifierKeys};
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, KeyStates, ModifierKeys};
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::{MouseButton, MouseKeys, MouseState};
|
||||
use crate::messages::input_mapper::utility_types::misc::FrameTimeInfo;
|
||||
use crate::messages::input_mapper::utility_types::pointer::{MouseButton, MouseKeys, PointerState};
|
||||
use crate::messages::prelude::*;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -15,8 +15,7 @@ pub struct InputPreprocessorMessageHandler {
|
||||
pub frame_time: FrameTimeInfo,
|
||||
pub time: u64,
|
||||
pub keyboard: KeyStates,
|
||||
pub mouse: PointerState,
|
||||
pointer_down_time: f64,
|
||||
pub mouse: MouseState,
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
@@ -28,10 +27,10 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
|
||||
self.mouse.position = mouse_state.position;
|
||||
|
||||
for key in pointer_state.mouse_keys {
|
||||
for key in mouse_state.mouse_keys {
|
||||
responses.add(InputMapperMessage::DoubleClick(match key {
|
||||
MouseKeys::LEFT => MouseButton::Left,
|
||||
MouseKeys::RIGHT => MouseButton::Right,
|
||||
@@ -61,35 +60,35 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
|
||||
self.mouse.position = mouse_state.position;
|
||||
|
||||
self.translate_mouse_event(pointer_state, true, responses);
|
||||
self.translate_mouse_event(mouse_state, true, responses);
|
||||
}
|
||||
InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
|
||||
self.mouse.position = mouse_state.position;
|
||||
|
||||
responses.add(InputMapperMessage::PointerMove);
|
||||
|
||||
// While any pointer button is already down, additional button down events are not reported, but they are sent as `pointermove` events
|
||||
self.translate_mouse_event(pointer_state, false, responses);
|
||||
self.translate_mouse_event(mouse_state, false, responses);
|
||||
}
|
||||
InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
|
||||
self.mouse.position = mouse_state.position;
|
||||
|
||||
self.translate_mouse_event(pointer_state, false, responses);
|
||||
self.translate_mouse_event(mouse_state, false, responses);
|
||||
}
|
||||
InputPreprocessorMessage::PointerShake { editor_mouse_state, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
|
||||
self.mouse.position = mouse_state.position;
|
||||
|
||||
responses.add(InputMapperMessage::PointerShake);
|
||||
}
|
||||
@@ -101,9 +100,9 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
self.mouse.scroll_delta = pointer_state.scroll_delta;
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
|
||||
self.mouse.position = mouse_state.position;
|
||||
self.mouse.scroll_delta = mouse_state.scroll_delta;
|
||||
|
||||
responses.add(InputMapperMessage::WheelScroll);
|
||||
}
|
||||
@@ -117,7 +116,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
}
|
||||
|
||||
impl InputPreprocessorMessageHandler {
|
||||
fn translate_mouse_event(&mut self, mut new_state: PointerState, allow_first_button_down: bool, responses: &mut VecDeque<Message>) {
|
||||
fn translate_mouse_event(&mut self, mut new_state: MouseState, allow_first_button_down: bool, responses: &mut VecDeque<Message>) {
|
||||
let click_mappings = [
|
||||
(MouseKeys::LEFT, Key::MouseLeft),
|
||||
(MouseKeys::RIGHT, Key::MouseRight),
|
||||
@@ -145,13 +144,6 @@ impl InputPreprocessorMessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
let raw_time = new_state.time.unwrap_or(self.time as f64);
|
||||
if self.mouse.mouse_keys == MouseKeys::empty() {
|
||||
self.pointer_down_time = raw_time;
|
||||
}
|
||||
let interacting = (self.mouse.mouse_keys | new_state.mouse_keys) != MouseKeys::empty();
|
||||
new_state.time = interacting.then_some(raw_time - self.pointer_down_time);
|
||||
|
||||
self.mouse = new_state;
|
||||
}
|
||||
|
||||
@@ -193,17 +185,18 @@ impl InputPreprocessorMessageHandler {
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
|
||||
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, ModifierKeys};
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, MouseKeys, ScrollDelta};
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[test]
|
||||
fn process_action_mouse_move_handle_modifier_keys() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
|
||||
let editor_mouse_state = EditorPointerState {
|
||||
let editor_mouse_state = EditorMouseState {
|
||||
editor_position: (4., 809.).into(),
|
||||
..Default::default()
|
||||
mouse_keys: MouseKeys::default(),
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
};
|
||||
let modifier_keys = ModifierKeys::ALT;
|
||||
let message = InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys };
|
||||
@@ -223,7 +216,7 @@ mod test {
|
||||
fn process_action_mouse_down_handle_modifier_keys() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
|
||||
let editor_mouse_state = EditorPointerState::default();
|
||||
let editor_mouse_state = EditorMouseState::default();
|
||||
let modifier_keys = ModifierKeys::CONTROL;
|
||||
let message = InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys };
|
||||
|
||||
@@ -242,7 +235,7 @@ mod test {
|
||||
fn process_action_mouse_up_handle_modifier_keys() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
|
||||
let editor_mouse_state = EditorPointerState::default();
|
||||
let editor_mouse_state = EditorMouseState::default();
|
||||
let modifier_keys = ModifierKeys::SHIFT;
|
||||
let message = InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys };
|
||||
|
||||
|
||||
@@ -30,9 +30,4 @@ pub enum LayoutMessage {
|
||||
layout_target: LayoutTarget,
|
||||
widget_id: WidgetId,
|
||||
},
|
||||
WidgetValueFileDrop {
|
||||
layout_target: LayoutTarget,
|
||||
widget_id: WidgetId,
|
||||
file: DroppedFile,
|
||||
},
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::messages::input_mapper::utility_types::keyboard::KeysGroup;
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::prelude::*;
|
||||
@@ -76,21 +76,6 @@ impl MessageHandler<LayoutMessage, LayoutMessageContext<'_>> for LayoutMessageHa
|
||||
responses.add((icon_button.on_drag_drop.callback)(icon_button));
|
||||
}
|
||||
}
|
||||
LayoutMessage::WidgetValueFileDrop { layout_target, widget_id, file } => {
|
||||
let Some(layout) = self.layouts.get_mut(layout_target as usize) else {
|
||||
warn!("WidgetValueFileDrop referenced an invalid layout. `widget_id: {widget_id}`, `layout_target: {layout_target:?}`");
|
||||
return;
|
||||
};
|
||||
let Some(widget_instance) = layout.iter_mut().find(|widget| widget.widget_id == widget_id) else {
|
||||
warn!("WidgetValueFileDrop referenced an invalid widget ID. `widget_id: {widget_id}`, `layout_target: {layout_target:?}`");
|
||||
return;
|
||||
};
|
||||
if let Widget::DropdownInput(dropdown_input) = &*widget_instance.widget
|
||||
&& dropdown_input.takes_file_drop
|
||||
{
|
||||
responses.add((dropdown_input.on_file_drop.callback)(&file));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -270,34 +255,20 @@ impl LayoutMessageHandler {
|
||||
|
||||
responses.add(callback_message);
|
||||
}
|
||||
Widget::SliderInput(slider_input) => {
|
||||
Widget::SpectrumInput(spectrum_input) => {
|
||||
let callback_message = match action {
|
||||
WidgetValueAction::Commit => (slider_input.on_commit.callback)(&()),
|
||||
WidgetValueAction::Commit => (spectrum_input.on_commit.callback)(&()),
|
||||
WidgetValueAction::Update => {
|
||||
let Ok(update) = serde_json::from_value::<SliderInputUpdate>(value) else {
|
||||
warn!("SliderInput update was not able to be parsed as SliderInputUpdate");
|
||||
let Ok(update) = serde_json::from_value::<SpectrumInputUpdate>(value) else {
|
||||
warn!("SpectrumInput update was not able to be parsed as SpectrumInputUpdate");
|
||||
return;
|
||||
};
|
||||
// Don't mutate the stored widget here: leaving its old values lets the layout diff detect a change
|
||||
// when the new layout is rebuilt with the updated state. Otherwise the frontend's stored layout
|
||||
// keeps stale values for `activeMarkerIndex`, etc., and any other widget's diff (e.g. the position
|
||||
// NumberInput) will trigger Svelte to re-spread those stale props onto SliderInput, clobbering
|
||||
// NumberInput) will trigger Svelte to re-spread those stale props onto SpectrumInput, clobbering
|
||||
// its local `activeMarkerIndex` and making subsequent drags target the wrong stop.
|
||||
(slider_input.on_update.callback)(&update)
|
||||
}
|
||||
};
|
||||
|
||||
responses.add(callback_message);
|
||||
}
|
||||
Widget::TransferCurveInput(curve_input) => {
|
||||
let callback_message = match action {
|
||||
WidgetValueAction::Commit => (curve_input.on_commit.callback)(&()),
|
||||
WidgetValueAction::Update => {
|
||||
let Ok(update) = serde_json::from_value::<TransferCurveInputUpdate>(value) else {
|
||||
warn!("TransferCurveInput update was not able to be parsed as TransferCurveInputUpdate");
|
||||
return;
|
||||
};
|
||||
(curve_input.on_update.callback)(&update)
|
||||
(spectrum_input.on_update.callback)(&update)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -561,47 +532,22 @@ fn populate_computed_display_fields(layout: &mut Layout) {
|
||||
for instance in layout.iter_mut() {
|
||||
match &mut *instance.widget {
|
||||
Widget::ColorInput(color_input) => {
|
||||
color_input.swatch_samples = match &color_input.value {
|
||||
FillChoice::None => Vec::new(),
|
||||
FillChoice::Solid(color) => vec![GradientSample::new(0., graphene_std::Color::from(*color))],
|
||||
FillChoice::Gradient(ramp) => graphene_std::vector::style::Gradient::from(&ramp.stops)
|
||||
.interpolated_samples_or_black(ramp.into())
|
||||
.into_iter()
|
||||
.map(|(position, color, _)| GradientSample::new(position, color))
|
||||
.collect(),
|
||||
};
|
||||
color_input.chosen_gradient = color_input.value.to_css_background_image();
|
||||
}
|
||||
Widget::TransferCurveInput(curve_input) => {
|
||||
const SAMPLE_COUNT: usize = 128;
|
||||
let curve = graphene_std::transfer_curve::TransferCurve::new(curve_input.points.iter().map(|&(x, y)| glam::DVec2::new(x, y)).collect());
|
||||
let evaluator = curve.evaluator();
|
||||
let [x_min, x_max] = curve_input.domain;
|
||||
let [y_min, y_max] = curve_input.range;
|
||||
let (x_span, y_span) = ((x_max - x_min).max(f64::EPSILON), (y_max - y_min).max(f64::EPSILON));
|
||||
// A spline overshooting the range rides its edge as a flat line, as the clamped adjustment it depicts does
|
||||
let clamp_to_range = curve_input.clamp_to_range;
|
||||
curve_input.samples = (0..=SAMPLE_COUNT)
|
||||
.map(|i| {
|
||||
let t = i as f64 / SAMPLE_COUNT as f64;
|
||||
let y = (evaluator.evaluate(x_min + t * x_span) - y_min) / y_span;
|
||||
(t, if clamp_to_range { y.clamp(0., 1.) } else { y })
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
Widget::SliderInput(slider_input) => {
|
||||
Widget::SpectrumInput(spectrum_input) => {
|
||||
// The track strip spans exactly 0 to 1, which no spread affects, so the widget carries no spread of its own
|
||||
let settings = graphene_std::vector::style::GradientSettings {
|
||||
spread: Default::default(),
|
||||
cyclic: slider_input.track_cyclic,
|
||||
space: slider_input.track_space,
|
||||
hue_direction: slider_input.track_hue_direction,
|
||||
interpolation: slider_input.track_interpolation,
|
||||
cyclic: spectrum_input.track_cyclic,
|
||||
space: spectrum_input.track_space,
|
||||
hue_direction: spectrum_input.track_hue_direction,
|
||||
interpolation: spectrum_input.track_interpolation,
|
||||
};
|
||||
let track_gradient = graphene_std::vector::style::Gradient::from(&slider_input.track);
|
||||
slider_input.track_samples = track_gradient
|
||||
let track_gradient = graphene_std::vector::style::Gradient::from(&spectrum_input.track);
|
||||
spectrum_input.track_samples = track_gradient
|
||||
.interpolated_samples_or_black(settings)
|
||||
.into_iter()
|
||||
.map(|(position, color, _)| GradientSample::new(position, color))
|
||||
.map(|(position, color, _)| SpectrumSample::new(position, color))
|
||||
.collect();
|
||||
// The end caps sample the track's boundary colors, which a cyclic wrap makes the wrapped interval's boundary-crossing color rather than the outermost stops'
|
||||
let track_evaluator = track_gradient.evaluator(settings);
|
||||
@@ -609,8 +555,8 @@ fn populate_computed_display_fields(layout: &mut Layout) {
|
||||
let color = track_evaluator.evaluate(t);
|
||||
SRGBA8::from(color).to_css_hex()
|
||||
};
|
||||
slider_input.track_start_css = cap(0.);
|
||||
slider_input.track_end_css = cap(1.);
|
||||
spectrum_input.track_start_css = cap(0.);
|
||||
spectrum_input.track_end_css = cap(1.);
|
||||
}
|
||||
Widget::ColorComparisonInput(comparison) => {
|
||||
let contrasting = |color: Option<SRGBA8>| color.map_or(SRGBA8::BLACK, |color| color.contrasting_text_color()).to_css_hex();
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::widgets::button_widgets::*;
|
||||
use super::widgets::input_widgets::*;
|
||||
use super::widgets::label_widgets::*;
|
||||
use crate::application::generate_uuid;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::KeysGroup;
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup;
|
||||
use crate::messages::prelude::*;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
@@ -470,8 +470,7 @@ impl LayoutGroup {
|
||||
| Widget::ParameterExposeButton(_)
|
||||
| Widget::ColorComparisonInput(_)
|
||||
| Widget::ColorPresetsInput(_)
|
||||
| Widget::SliderInput(_)
|
||||
| Widget::TransferCurveInput(_)
|
||||
| Widget::SpectrumInput(_)
|
||||
| Widget::VisualColorPickersInput(_) => continue,
|
||||
};
|
||||
if val.is_empty() {
|
||||
@@ -809,7 +808,6 @@ pub enum Widget {
|
||||
ColorComparisonInput(ColorComparisonInput),
|
||||
ColorInput(ColorInput),
|
||||
ColorPresetsInput(ColorPresetsInput),
|
||||
TransferCurveInput(TransferCurveInput),
|
||||
DropdownInput(DropdownInput),
|
||||
IconButton(IconButton),
|
||||
IconLabel(IconLabel),
|
||||
@@ -823,7 +821,7 @@ pub enum Widget {
|
||||
PopoverButton(PopoverButton),
|
||||
RadioInput(RadioInput),
|
||||
Separator(Separator),
|
||||
SliderInput(SliderInput),
|
||||
SpectrumInput(SpectrumInput),
|
||||
TextAreaInput(TextAreaInput),
|
||||
TextButton(TextButton),
|
||||
TextInput(TextInput),
|
||||
@@ -888,8 +886,7 @@ impl DiffUpdate {
|
||||
| Widget::WorkingColorsInput(_)
|
||||
| Widget::ColorComparisonInput(_)
|
||||
| Widget::ColorPresetsInput(_)
|
||||
| Widget::SliderInput(_)
|
||||
| Widget::TransferCurveInput(_)
|
||||
| Widget::SpectrumInput(_)
|
||||
| Widget::VisualColorPickersInput(_) => None,
|
||||
};
|
||||
|
||||
|
||||
@@ -193,11 +193,11 @@ pub struct ColorInput {
|
||||
// Content
|
||||
#[widget_builder(constructor)]
|
||||
pub value: FillChoice<SRGBA8>,
|
||||
/// Straight-alpha color samples drawn by the frontend as the stops of an SVG gradient filling the swatch. Auto-populated from `value` at layout-send time.
|
||||
/// Empty when `value` is `FillChoice::<SRGBA8>::None`, in which case the frontend uses its "none" fallback styling.
|
||||
#[serde(rename = "swatchSamples")]
|
||||
/// CSS `linear-gradient(...)` (or solid-color stand-in) for the swatch's `background-image`. Auto-populated from `value` at layout-send time.
|
||||
/// `None` when `value` is `FillChoice::<SRGBA8>::None`, in which case the frontend uses its "none" fallback styling.
|
||||
#[serde(rename = "chosenGradient")]
|
||||
#[widget_builder(skip)]
|
||||
pub swatch_samples: Vec<GradientSample>,
|
||||
pub chosen_gradient: Option<String>,
|
||||
#[serde(rename = "allowNone")]
|
||||
#[derivative(Default(value = "true"))]
|
||||
pub allow_none: bool,
|
||||
@@ -233,24 +233,6 @@ pub struct ColorInput {
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
}
|
||||
|
||||
/// Shortens a breadcrumb label to fit the trail, replacing the tail with an ellipsis.
|
||||
/// Quotes delimit a string value, so a quoted label budgets only the text between them.
|
||||
pub fn truncate_breadcrumb_label(label: &str) -> String {
|
||||
const MAX_CHARACTERS: usize = 40;
|
||||
|
||||
let quoted = label.len() >= 2 && label.starts_with('"') && label.ends_with('"');
|
||||
let content = if quoted { &label[1..label.len() - 1] } else { label };
|
||||
|
||||
if content.chars().count() <= MAX_CHARACTERS {
|
||||
return label.to_string();
|
||||
}
|
||||
|
||||
let mut truncated: String = content.chars().take(MAX_CHARACTERS - 1).collect();
|
||||
truncated.push('…');
|
||||
|
||||
if quoted { format!("\"{truncated}\"") } else { truncated }
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Default, WidgetBuilder)]
|
||||
#[derivative(Debug, PartialEq)]
|
||||
|
||||
@@ -83,10 +83,6 @@ pub struct DropdownInput {
|
||||
pub virtual_scrolling: bool,
|
||||
#[derivative(Default(value = "true"))]
|
||||
pub interactive: bool,
|
||||
// Set along with the `on_file_drop` callback
|
||||
#[serde(rename = "takesFileDrop")]
|
||||
#[widget_builder(skip)]
|
||||
pub takes_file_drop: bool,
|
||||
|
||||
// Sizing
|
||||
#[serde(rename = "minWidth")]
|
||||
@@ -101,28 +97,8 @@ pub struct DropdownInput {
|
||||
pub tooltip_description: String,
|
||||
#[serde(rename = "tooltipShortcut")]
|
||||
pub tooltip_shortcut: Option<ActionShortcut>,
|
||||
|
||||
// Callbacks
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
#[widget_builder(skip)]
|
||||
pub on_file_drop: WidgetCallback<DroppedFile>,
|
||||
}
|
||||
|
||||
impl DropdownInput {
|
||||
/// Makes the widget take a file dropped on it, which is handed to the callback.
|
||||
pub fn on_file_drop(mut self, callback: impl Fn(&DroppedFile) -> Message + 'static + Send + Sync) -> Self {
|
||||
self.takes_file_drop = true;
|
||||
self.on_file_drop = WidgetCallback::new(callback);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct DroppedFile {
|
||||
pub name: String,
|
||||
pub mime_type: String,
|
||||
pub data: Vec<u8>,
|
||||
//
|
||||
// Callbacks exists on the `MenuListEntry` children, not this parent `DropdownInput`
|
||||
}
|
||||
|
||||
pub type MenuListEntrySections = Vec<Vec<MenuListEntry>>;
|
||||
@@ -605,50 +581,7 @@ pub enum ColorPresetsInputUpdate {
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder)]
|
||||
#[derivative(Debug, PartialEq, Default)]
|
||||
pub struct TransferCurveInput {
|
||||
// Content
|
||||
/// The control points in the units of `domain` and `range`, in any x order, since sampling sorts them.
|
||||
#[widget_builder(constructor)]
|
||||
pub points: Vec<(f64, f64)>,
|
||||
/// The x extent the box spans, left to right.
|
||||
pub domain: [f64; 2],
|
||||
/// The y extent the box spans, bottom to top.
|
||||
pub range: [f64; 2],
|
||||
/// Whether the drawn curve and a dragged point's y stay inside `range`. A point's x always stays inside `domain`.
|
||||
#[serde(rename = "clampToRange")]
|
||||
pub clamp_to_range: bool,
|
||||
/// Polyline of the curve in box-normalized 0..1 coordinates with y upward. Auto-populated from `points` at layout-send time.
|
||||
#[widget_builder(skip)]
|
||||
pub samples: Vec<(f64, f64)>,
|
||||
/// Whether clicking empty space inserts a point.
|
||||
#[serde(rename = "allowInsert")]
|
||||
pub allow_insert: bool,
|
||||
/// Whether double-click or right-click removes a point. The handler still has the final say (e.g., enforcing a minimum count).
|
||||
#[serde(rename = "allowDelete")]
|
||||
pub allow_delete: bool,
|
||||
pub disabled: bool,
|
||||
|
||||
// Callbacks
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_update: WidgetCallback<TransferCurveInputUpdate>,
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum TransferCurveInputUpdate {
|
||||
MovePoint { index: u32, x: f64, y: f64 },
|
||||
InsertPoint { x: f64, y: f64 },
|
||||
DeletePoint { index: u32 },
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder)]
|
||||
#[derivative(Debug, PartialEq, Default)]
|
||||
pub struct SliderInput {
|
||||
pub struct SpectrumInput {
|
||||
// Content
|
||||
/// The colored gradient drawn behind the markers (display-only, caller-owned).
|
||||
#[widget_builder(constructor)]
|
||||
@@ -665,10 +598,10 @@ pub struct SliderInput {
|
||||
/// The path the track's stops interpolate along, used to bake `track_samples` and by the frontend to suppress the midpoint diamonds when stepped.
|
||||
#[serde(rename = "trackInterpolation")]
|
||||
pub track_interpolation: GradientInterpolation,
|
||||
/// Straight-alpha color samples drawn by the frontend as the stops of an SVG gradient filling the track strip. Auto-populated from `track` at layout-send time.
|
||||
/// Straight-alpha samples the frontend draws as the stops of an SVG gradient filling the track strip. Auto-populated from `track` at layout-send time.
|
||||
#[serde(rename = "trackSamples")]
|
||||
#[widget_builder(skip)]
|
||||
pub track_samples: Vec<GradientSample>,
|
||||
pub track_samples: Vec<SpectrumSample>,
|
||||
/// Hex string for the track strip's leftmost solid-color end-cap. Auto-populated by evaluating `track` at position 0.
|
||||
#[serde(rename = "trackStartCSS")]
|
||||
#[widget_builder(skip)]
|
||||
@@ -678,7 +611,7 @@ pub struct SliderInput {
|
||||
#[widget_builder(skip)]
|
||||
pub track_end_css: String,
|
||||
/// The handles the user can drag along the track. Their handle colors are caller-owned (e.g., for a gradient editor they follow the stop colors, for a "Shadows/Midpoints/Highlights" widget they're hardcoded).
|
||||
pub markers: Vec<SliderMarker>,
|
||||
pub markers: Vec<SpectrumMarker>,
|
||||
#[serde(rename = "activeMarkerIndex")]
|
||||
pub active_marker_index: Option<u32>,
|
||||
#[serde(rename = "activeMarkerIsMidpoint")]
|
||||
@@ -686,34 +619,24 @@ pub struct SliderInput {
|
||||
/// Whether to render midpoint diamonds between adjacent markers (only meaningful for gradient-like uses).
|
||||
#[serde(rename = "showMidpoints")]
|
||||
pub show_midpoints: bool,
|
||||
/// Whether clicking the track inserts a new marker at the click position. Otherwise the click picks up the nearest marker.
|
||||
/// Whether clicking the track inserts a new marker at the click position.
|
||||
#[serde(rename = "allowInsert")]
|
||||
pub allow_insert: bool,
|
||||
/// Whether right-click or pressing Delete removes a marker. The handler still has the final say on whether the deletion goes through (e.g., enforcing a minimum count).
|
||||
#[serde(rename = "allowDelete")]
|
||||
pub allow_delete: bool,
|
||||
/// Whether dragging a marker past another reorders them, which also needs `allow_select`. Otherwise the dragged marker is clamped between its neighbors.
|
||||
/// Whether dragging a marker past another reorders them. If false, the dragged marker is clamped between its neighbors.
|
||||
#[serde(rename = "allowReorder")]
|
||||
pub allow_reorder: bool,
|
||||
/// Whether the track's ends meet, as on a hue wheel: a run dragged by its strip or dashed link wraps past them, a lone marker stops.
|
||||
#[serde(rename = "allowWrap")]
|
||||
pub allow_wrap: bool,
|
||||
/// Whether clicking a marker selects it, keeping it highlighted and reported as the active marker until another is chosen,
|
||||
/// as a gradient editor needs for the stop being edited. Otherwise the highlight only follows the pointer and the drag.
|
||||
#[serde(rename = "allowSelect")]
|
||||
pub allow_select: bool,
|
||||
/// Compact mode: 8px track height with 8px top padding, for use in rows alongside other widgets.
|
||||
pub narrow: bool,
|
||||
/// Plain range-slider mode, for a number beside its number input: a flat 4px track is drawn in place of the gradient, so `track` is never shown.
|
||||
#[serde(rename = "rangeSlider")]
|
||||
pub range_slider: bool,
|
||||
/// Whether the input is disabled (dimmed and read-only).
|
||||
pub disabled: bool,
|
||||
|
||||
// Callbacks
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_update: WidgetCallback<SliderInputUpdate>,
|
||||
pub on_update: WidgetCallback<SpectrumInputUpdate>,
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
@@ -721,59 +644,30 @@ pub struct SliderInput {
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct SliderMarker {
|
||||
/// Position along the track, normally 0..1. A shifted or stretched non-cyclic ramp can push it outside, where it is not drawn.
|
||||
pub struct SpectrumMarker {
|
||||
/// Position of the marker along the spectrum track, normally from 0 to 1. A shifted or stretched non-cyclic ramp can
|
||||
/// place it outside that range, where the track draws only the markers falling within its visible span.
|
||||
position: f64,
|
||||
/// Midpoint (0..1) of the interval to the next marker, used only with `show_midpoints`. The last marker's midpoint spans the wrap of a cyclic track, or is otherwise ignored.
|
||||
/// Position (0..1) of the midpoint between this marker and the next, used only if `show_midpoints` is true.
|
||||
/// The last marker's value controls the wrapped interval when `track_cyclic` is set, and is otherwise ignored.
|
||||
midpoint: f64,
|
||||
/// CSS color string for the marker handle's fill. Set via `SliderMarker::new` from a linear [`Color`],
|
||||
/// CSS color string for the marker handle's fill. Set via `SpectrumMarker::new` from a linear [`Color`],
|
||||
/// discarding any transparency so the handle always shows the RGB that steers the interpolation.
|
||||
#[serde(rename = "handleColorCSS")]
|
||||
handle_color_css: String,
|
||||
/// Whether this marker and the next form a split handle: one marker split down the middle while they coincide, two halves joined by a strip once apart.
|
||||
#[serde(rename = "pairedWithNext")]
|
||||
paired_with_next: bool,
|
||||
/// Whether a dashed line runs from this marker to the next through the lane below the track. Dragging it carries both markers, along with any split-handle halves attached to them.
|
||||
#[serde(rename = "dashedToNext")]
|
||||
dashed_to_next: bool,
|
||||
/// Whether this marker follows its neighbors instead of bounding them, so they may drag past its drawn position.
|
||||
#[serde(rename = "betweenNeighbors")]
|
||||
between_neighbors: bool,
|
||||
}
|
||||
|
||||
impl SliderMarker {
|
||||
impl SpectrumMarker {
|
||||
pub fn new(position: f64, midpoint: f64, handle_color: Color) -> Self {
|
||||
let handle_color_css = format!("#{}", SRGBA8::from(handle_color).to_rgb_hex());
|
||||
Self {
|
||||
position,
|
||||
midpoint,
|
||||
handle_color_css,
|
||||
paired_with_next: false,
|
||||
dashed_to_next: false,
|
||||
between_neighbors: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn between_neighbors(mut self) -> Self {
|
||||
self.between_neighbors = true;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn pair_with_next(mut self) -> Self {
|
||||
self.paired_with_next = true;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn dash_to_next(mut self) -> Self {
|
||||
self.dashed_to_next = true;
|
||||
self
|
||||
Self { position, midpoint, handle_color_css }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct GradientSample {
|
||||
/// Position (0..1) of the sample along the gradient, drawn as the SVG stop's `offset`.
|
||||
pub struct SpectrumSample {
|
||||
/// Position (0..1) of the sample along the spectrum track, drawn as the SVG stop's `offset`.
|
||||
position: f64,
|
||||
/// `#rrggbb` hex of the sample's color, drawn as the SVG stop's `stop-color`.
|
||||
color: String,
|
||||
@@ -781,7 +675,7 @@ pub struct GradientSample {
|
||||
alpha: f32,
|
||||
}
|
||||
|
||||
impl GradientSample {
|
||||
impl SpectrumSample {
|
||||
pub fn new(position: f64, color: Color) -> Self {
|
||||
Self {
|
||||
position,
|
||||
@@ -793,7 +687,7 @@ impl GradientSample {
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum SliderInputUpdate {
|
||||
pub enum SpectrumInputUpdate {
|
||||
MoveMarker {
|
||||
index: u32,
|
||||
position: f64,
|
||||
|
||||
@@ -64,8 +64,6 @@ pub struct TextLabel {
|
||||
pub italic: bool,
|
||||
pub monospace: bool,
|
||||
pub multiline: bool,
|
||||
pub enquote: bool,
|
||||
pub selectable: bool,
|
||||
#[serde(rename = "centerAlign")]
|
||||
pub center_align: bool,
|
||||
#[serde(rename = "tableAlign")]
|
||||
|
||||
@@ -123,8 +123,8 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
MenuListEntry::new("Open…")
|
||||
.label("Open…")
|
||||
.icon("Folder")
|
||||
.tooltip_shortcut(action_shortcut!(IngestMessageDiscriminant::Open))
|
||||
.on_commit(|_| IngestMessage::Open.into()),
|
||||
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::Open))
|
||||
.on_commit(|_| PortfolioMessage::Open.into()),
|
||||
MenuListEntry::new("Open Demo Artwork…")
|
||||
.label("Open Demo Artwork…")
|
||||
.icon("Image")
|
||||
@@ -163,8 +163,8 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
MenuListEntry::new("Import…")
|
||||
.label("Import…")
|
||||
.icon("FileImport")
|
||||
.tooltip_shortcut(action_shortcut!(IngestMessageDiscriminant::Import))
|
||||
.on_commit(|_| IngestMessage::Import.into())
|
||||
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::Import))
|
||||
.on_commit(|_| PortfolioMessage::Import.into())
|
||||
.disabled(no_active_document),
|
||||
MenuListEntry::new("Export…")
|
||||
.label("Export…")
|
||||
@@ -651,33 +651,33 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
MenuListEntry::new("Focus Document")
|
||||
.label("Focus Document")
|
||||
.icon(if self.focus_document { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.tooltip_shortcut(action_shortcut!(WorkspaceMessageDiscriminant::ToggleFocusDocument))
|
||||
.on_commit(|_| WorkspaceMessage::ToggleFocusDocument.into()),
|
||||
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::ToggleFocusDocument))
|
||||
.on_commit(|_| PortfolioMessage::ToggleFocusDocument.into()),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Reset Workspace")
|
||||
.label("Reset Workspace")
|
||||
.icon("Reset")
|
||||
.on_commit(|_| WorkspaceMessage::ResetWorkspaceLayout.into()),
|
||||
.on_commit(|_| PortfolioMessage::ResetWorkspaceLayout.into()),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Properties")
|
||||
.label("Properties")
|
||||
.icon(if self.properties_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.tooltip_shortcut(action_shortcut!(WorkspaceMessageDiscriminant::TogglePropertiesPanelOpen))
|
||||
.on_commit(|_| WorkspaceMessage::TogglePropertiesPanelOpen.into())
|
||||
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::TogglePropertiesPanelOpen))
|
||||
.on_commit(|_| PortfolioMessage::TogglePropertiesPanelOpen.into())
|
||||
.disabled(self.focus_document),
|
||||
MenuListEntry::new("Layers")
|
||||
.label("Layers")
|
||||
.icon(if self.layers_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.tooltip_shortcut(action_shortcut!(WorkspaceMessageDiscriminant::ToggleLayersPanelOpen))
|
||||
.on_commit(|_| WorkspaceMessage::ToggleLayersPanelOpen.into())
|
||||
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::ToggleLayersPanelOpen))
|
||||
.on_commit(|_| PortfolioMessage::ToggleLayersPanelOpen.into())
|
||||
.disabled(self.focus_document),
|
||||
MenuListEntry::new("Data")
|
||||
.label("Data")
|
||||
.icon(if self.data_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.tooltip_shortcut(action_shortcut!(WorkspaceMessageDiscriminant::ToggleDataPanelOpen))
|
||||
.on_commit(|_| WorkspaceMessage::ToggleDataPanelOpen.into())
|
||||
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::ToggleDataPanelOpen))
|
||||
.on_commit(|_| PortfolioMessage::ToggleDataPanelOpen.into())
|
||||
.disabled(self.focus_document),
|
||||
],
|
||||
])
|
||||
|
||||
@@ -39,5 +39,6 @@ pub enum VectorTableTab {
|
||||
#[default]
|
||||
Points,
|
||||
Segments,
|
||||
Regions,
|
||||
Handles,
|
||||
}
|
||||
@@ -10,24 +10,20 @@ use graph_craft::document::NodeId;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::blending::BlendMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::core_types::misc::format_f64;
|
||||
use graphene_std::extract_xy::XY;
|
||||
use graphene_std::gradient::Gradient;
|
||||
use graphene_std::list::{Item, List, NodeIdPath};
|
||||
use graphene_std::math::float_noise::round_away_float_noise;
|
||||
use graphene_std::memo::IORecord;
|
||||
use graphene_std::raster::{
|
||||
AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RedGreenBlueAlpha, RelativeAbsolute,
|
||||
SelectiveColorChoice, TonalRange,
|
||||
CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, LuminanceCalculation, NoiseType, RedGreenBlue, RedGreenBlueAlpha, RelativeAbsolute, SelectiveColorChoice,
|
||||
};
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::subpath::BezierHandles;
|
||||
use graphene_std::text::TextAlign;
|
||||
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
||||
use graphene_std::transfer_curve::TransferCurve;
|
||||
use graphene_std::text_nodes::StringCapitalization;
|
||||
use graphene_std::transform::{ReferencePoint, ScaleType};
|
||||
use graphene_std::vector::misc::{
|
||||
ArcType, BezierHandles, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns,
|
||||
SpiralType,
|
||||
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType,
|
||||
};
|
||||
use graphene_std::vector::style::{
|
||||
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
|
||||
@@ -154,8 +150,7 @@ impl DataPanelMessageHandler {
|
||||
|
||||
// Element path breadcrumbs
|
||||
if !layout_data.breadcrumbs.is_empty() {
|
||||
let labels = layout_data.breadcrumbs.iter().map(|label| truncate_breadcrumb_label(label)).collect();
|
||||
let breadcrumb = BreadcrumbTrailButtons::new(labels)
|
||||
let breadcrumb = BreadcrumbTrailButtons::new(layout_data.breadcrumbs)
|
||||
.on_update(|&len| DataPanelMessage::TruncateElementPath { len: len as usize }.into())
|
||||
.widget_instance();
|
||||
widgets.push(breadcrumb);
|
||||
@@ -231,7 +226,6 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
|
||||
List<GradientInterpolation>,
|
||||
List<DashPattern>,
|
||||
List<BoxCorners>,
|
||||
List<TransferCurve>,
|
||||
List<StrokeJoin>,
|
||||
List<StrokeAlign>,
|
||||
List<StrokeCap>,
|
||||
@@ -239,15 +233,11 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
|
||||
List<ExtrudeJoiningAlgorithm>,
|
||||
List<PointSpacingType>,
|
||||
List<StringCapitalization>,
|
||||
List<TextDenomination>,
|
||||
List<DesaturateMethod>,
|
||||
List<LuminanceCalculation>,
|
||||
List<RedGreenBlue>,
|
||||
List<RedGreenBlueAlpha>,
|
||||
List<RelativeAbsolute>,
|
||||
List<SelectiveColorChoice>,
|
||||
List<TonalRange>,
|
||||
List<AdjustmentChannel>,
|
||||
List<HueSaturationRange>,
|
||||
List<XY>,
|
||||
List<ScaleType>,
|
||||
List<ReferencePoint>,
|
||||
@@ -291,7 +281,6 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
|
||||
Item<GradientInterpolation>,
|
||||
Item<DashPattern>,
|
||||
Item<BoxCorners>,
|
||||
Item<TransferCurve>,
|
||||
Item<StrokeJoin>,
|
||||
Item<StrokeAlign>,
|
||||
Item<StrokeCap>,
|
||||
@@ -299,15 +288,11 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
|
||||
Item<ExtrudeJoiningAlgorithm>,
|
||||
Item<PointSpacingType>,
|
||||
Item<StringCapitalization>,
|
||||
Item<TextDenomination>,
|
||||
Item<DesaturateMethod>,
|
||||
Item<LuminanceCalculation>,
|
||||
Item<RedGreenBlue>,
|
||||
Item<RedGreenBlueAlpha>,
|
||||
Item<RelativeAbsolute>,
|
||||
Item<SelectiveColorChoice>,
|
||||
Item<TonalRange>,
|
||||
Item<AdjustmentChannel>,
|
||||
Item<HueSaturationRange>,
|
||||
Item<XY>,
|
||||
Item<ScaleType>,
|
||||
Item<ReferencePoint>,
|
||||
@@ -507,15 +492,6 @@ impl TableItemLayout for Artboard {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for graphene_std::brush::Stroke {
|
||||
fn type_name() -> &'static str {
|
||||
"Stroke"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("Stroke ({} {})", self.len(), if self.len() == 1 { "sample" } else { "samples" })
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for DashPattern {
|
||||
fn type_name() -> &'static str {
|
||||
"DashPattern"
|
||||
@@ -575,26 +551,6 @@ impl TableItemLayout for Coverage {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for TransferCurve {
|
||||
fn type_name() -> &'static str {
|
||||
"Transfer Curve"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
let points = self.points().len();
|
||||
format!("Transfer Curve ({points} {})", if points == 1 { "point" } else { "points" })
|
||||
}
|
||||
// The wrapping `Item` already contributes the breadcrumb; the inner list supplies the next level
|
||||
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.value_page(data)
|
||||
}
|
||||
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
self.0.value_widgets(target, data)
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.0.layout_with_breadcrumb(data)
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for BoxCorners {
|
||||
fn type_name() -> &'static str {
|
||||
"BoxCorners"
|
||||
@@ -649,7 +605,6 @@ impl TableItemLayout for Graphic {
|
||||
Self::ColorList(list) => list.identifier(),
|
||||
Self::GradientList(list) => list.identifier(),
|
||||
Self::TextList(list) => list.identifier(),
|
||||
Self::StrokeList(list) => list.identifier(),
|
||||
}
|
||||
}
|
||||
// Don't put a breadcrumb for Graphic
|
||||
@@ -674,7 +629,6 @@ impl TableItemLayout for Graphic {
|
||||
Self::ColorList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::GradientList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::TextList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::StrokeList(list) => list.layout_with_breadcrumb(data),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -693,7 +647,7 @@ impl TableItemLayout for Vector {
|
||||
)
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
let table_tab_entries = [VectorTableTab::Points, VectorTableTab::Segments, VectorTableTab::Handles]
|
||||
let table_tab_entries = [VectorTableTab::Points, VectorTableTab::Segments, VectorTableTab::Regions, VectorTableTab::Handles]
|
||||
.into_iter()
|
||||
.map(|tab| {
|
||||
RadioEntryData::new(format!("{tab:?}"))
|
||||
@@ -740,6 +694,17 @@ impl TableItemLayout for Vector {
|
||||
]
|
||||
}));
|
||||
}
|
||||
VectorTableTab::Regions => {
|
||||
table_rows.push(column_headings(&["", "segment_range"]));
|
||||
table_rows.extend(self.region_domain.iter().map(|(id, segment_range, _)| {
|
||||
vec![
|
||||
TextLabel::new(format!("{}", id.inner())).narrow(true).widget_instance(),
|
||||
TextLabel::new(format!("Segment {} – Segment {}", segment_range.start().inner(), segment_range.end().inner()))
|
||||
.narrow(true)
|
||||
.widget_instance(),
|
||||
]
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
vec![LayoutGroup::row(table_tabs), LayoutGroup::table(table_rows, false)]
|
||||
@@ -842,53 +807,18 @@ impl TableItemLayout for Gradient {
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_table_item_layout_for_number {
|
||||
($($ty:ty => $type_name:literal),* $(,)?) => {
|
||||
$(
|
||||
impl TableItemLayout for $ty {
|
||||
fn type_name() -> &'static str {
|
||||
$type_name
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{self}")
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
|
||||
}
|
||||
}
|
||||
)*
|
||||
}
|
||||
}
|
||||
impl_table_item_layout_for_number!(
|
||||
u32 => "Number (u32)",
|
||||
i32 => "Number (i32)",
|
||||
u64 => "Number (u64)",
|
||||
i64 => "Number (i64)",
|
||||
);
|
||||
|
||||
impl TableItemLayout for f32 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (f32)"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
// Only infinity widens to f64 without gaining digits, so finite values keep the f32 spelling
|
||||
if self.is_infinite() { format_f64(*self as f64) } else { format!("{self}") }
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
|
||||
}
|
||||
}
|
||||
|
||||
// Denoised so 0.1 + 0.2 reads as 0.3 rather than 0.30000000000000004. We don't do this for f32 because it lacks precision to reliably distinguish between intentional digits and noise.
|
||||
impl TableItemLayout for f64 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number"
|
||||
"Number (f64)"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format_f64(round_away_float_noise(*self))
|
||||
format!("{self}")
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
|
||||
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![
|
||||
NumberInput::new(Some(*self)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
|
||||
])]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -897,10 +827,88 @@ impl TableItemLayout for u8 {
|
||||
"Byte"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("0x{self:02X} ({self})")
|
||||
format!("{self:02X}")
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
|
||||
// Values fall back to the default drill-in button (labeled with the hex string via `identifier`); the value page shows the same hex value as a label.
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![TextLabel::new(self.identifier()).widget_instance()])]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for f32 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (f32)"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{self}")
|
||||
}
|
||||
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![
|
||||
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
|
||||
])]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for u32 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (u32)"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{self}")
|
||||
}
|
||||
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![
|
||||
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
|
||||
])]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for i32 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (i32)"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{self}")
|
||||
}
|
||||
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![
|
||||
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
|
||||
])]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for i64 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (i64)"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{self}")
|
||||
}
|
||||
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
|
||||
// TODO: Make this robust for large i64 values that don't fit in f64 (beyond roughly 2^53), as with u64.
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![
|
||||
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
|
||||
])]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for u64 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (u64)"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{self}")
|
||||
}
|
||||
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
|
||||
// TODO: Make this robust for large u64 values that don't fit in f64 (above roughly 2^53). Perhaps using a bigint kind of approach through the widget's data flow.
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![
|
||||
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
|
||||
])]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -924,50 +932,20 @@ impl TableItemLayout for String {
|
||||
"String"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("\"{}\"", string_preview(self))
|
||||
}
|
||||
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
data.breadcrumbs.push(character_count_label(self));
|
||||
self.value_page(data)
|
||||
}
|
||||
// The preview truncates for length and line breaks, so a button beside it reaches the full text, labeled by length
|
||||
fn value_widgets(&self, target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
vec![
|
||||
TextLabel::new(string_preview(self)).enquote(true).selectable(true).monospace(true).narrow(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextButton::new(character_count_label(self))
|
||||
.on_update(move |_| DataPanelMessage::PushToElementPath { step: target.clone() }.into())
|
||||
.narrow(true)
|
||||
.widget_instance(),
|
||||
]
|
||||
// Show the first line, and if there are more, indicate that with an ellipsis
|
||||
let first_line = self.lines().next().unwrap_or("");
|
||||
if self.lines().count() > 1 {
|
||||
format!("\"{} …\"", first_line)
|
||||
} else {
|
||||
format!("\"{}\"", first_line)
|
||||
}
|
||||
}
|
||||
// Values fall back to the default drill-in button (labeled with the truncated quoted preview via `identifier`); the value page shows the full multi-line text in a `TextAreaInput`.
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![TextAreaInput::new(self.to_string()).monospace(true).disabled(true).widget_instance()])]
|
||||
}
|
||||
}
|
||||
|
||||
fn character_count_label(value: &str) -> String {
|
||||
let character_count = value.chars().count();
|
||||
|
||||
format!("{character_count} Char{}", if character_count == 1 { "" } else { "s" })
|
||||
}
|
||||
|
||||
/// Shortens a string to fit a table cell, cutting at the first line break or 40 characters with an ellipsis.
|
||||
/// The 40 matches `truncate_breadcrumb_label`, so a preview reaching the trail isn't cut twice.
|
||||
fn string_preview(value: &str) -> String {
|
||||
const MAX_CHARACTERS: usize = 40;
|
||||
|
||||
let first_line = value.lines().next().unwrap_or_default();
|
||||
let cut_by_line_break = value.contains('\n');
|
||||
let cut_by_length = first_line.chars().count() > MAX_CHARACTERS;
|
||||
|
||||
if !cut_by_line_break && !cut_by_length {
|
||||
return value.to_string();
|
||||
}
|
||||
|
||||
first_line.chars().take(MAX_CHARACTERS - 1).chain(['…']).collect()
|
||||
}
|
||||
|
||||
impl TableItemLayout for Option<f64> {
|
||||
fn type_name() -> &'static str {
|
||||
"Option<f64>"
|
||||
@@ -976,12 +954,7 @@ impl TableItemLayout for Option<f64> {
|
||||
"Option<f64>".to_string()
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
let text = match self {
|
||||
Some(value) => format!("Some({})", format_f64(round_away_float_noise(*value))),
|
||||
None => "None".to_string(),
|
||||
};
|
||||
|
||||
vec![TextLabel::new(text).selectable(true).narrow(true).widget_instance()]
|
||||
vec![TextLabel::new(format!("{self:?}")).narrow(true).widget_instance()]
|
||||
}
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(self.value_widgets(PathStep::Element(0), _data))]
|
||||
@@ -1026,7 +999,7 @@ impl TableItemLayout for DAffine2 {
|
||||
"Transform".to_string()
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
transform_widgets(*self)
|
||||
vec![TextLabel::new(format_transform_matrix(*self)).narrow(true).widget_instance()]
|
||||
}
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(self.value_widgets(PathStep::Element(0), _data))]
|
||||
@@ -1041,7 +1014,8 @@ impl TableItemLayout for Affine2 {
|
||||
"Transform".to_string()
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
transform_widgets(DAffine2::from_cols_array(&self.to_cols_array().map(|x| x as f64)))
|
||||
let matrix = DAffine2::from_cols_array(&self.to_cols_array().map(|x| x as f64));
|
||||
vec![TextLabel::new(format_transform_matrix(matrix)).narrow(true).widget_instance()]
|
||||
}
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(self.value_widgets(PathStep::Element(0), _data))]
|
||||
@@ -1084,15 +1058,11 @@ impl_table_item_layout_for_choice_enum!(
|
||||
ExtrudeJoiningAlgorithm,
|
||||
PointSpacingType,
|
||||
StringCapitalization,
|
||||
TextDenomination,
|
||||
DesaturateMethod,
|
||||
LuminanceCalculation,
|
||||
RedGreenBlue,
|
||||
RedGreenBlueAlpha,
|
||||
RelativeAbsolute,
|
||||
SelectiveColorChoice,
|
||||
TonalRange,
|
||||
AdjustmentChannel,
|
||||
HueSaturationRange,
|
||||
XY,
|
||||
ScaleType,
|
||||
CentroidType,
|
||||
@@ -1292,7 +1262,6 @@ macro_rules! known_item_types {
|
||||
Cover,
|
||||
DashPattern,
|
||||
BoxCorners,
|
||||
TransferCurve,
|
||||
BlendMode,
|
||||
GradientForm,
|
||||
GradientSpread,
|
||||
@@ -1306,15 +1275,11 @@ macro_rules! known_item_types {
|
||||
ExtrudeJoiningAlgorithm,
|
||||
PointSpacingType,
|
||||
StringCapitalization,
|
||||
TextDenomination,
|
||||
DesaturateMethod,
|
||||
LuminanceCalculation,
|
||||
RedGreenBlue,
|
||||
RedGreenBlueAlpha,
|
||||
RelativeAbsolute,
|
||||
SelectiveColorChoice,
|
||||
TonalRange,
|
||||
AdjustmentChannel,
|
||||
HueSaturationRange,
|
||||
XY,
|
||||
ScaleType,
|
||||
ReferencePoint,
|
||||
@@ -1431,8 +1396,7 @@ fn drilldown_attribute_layout(any: &dyn Any, data: &mut LayoutData) -> Option<Ve
|
||||
None
|
||||
}
|
||||
|
||||
/// Decomposes a transform into location, rotation, and scale, each headed by the icon of its Layer menu action.
|
||||
fn transform_widgets(transform: DAffine2) -> Vec<WidgetInstance> {
|
||||
fn format_transform_matrix(transform: DAffine2) -> String {
|
||||
let (scale, angle, translation) = if transform.matrix2.determinant().abs() <= f64::EPSILON {
|
||||
let [col_0, col_1] = transform.matrix2.to_cols_array_2d().map(|[x, y]| DVec2::new(x, y));
|
||||
|
||||
@@ -1450,24 +1414,15 @@ fn transform_widgets(transform: DAffine2) -> Vec<WidgetInstance> {
|
||||
} else {
|
||||
transform.to_scale_angle_translation()
|
||||
};
|
||||
let rotation = format_rounded(angle.to_degrees(), 3);
|
||||
|
||||
let location_text = format!("({} px, {} px)", format_rounded(translation.x, 3), format_rounded(translation.y, 3));
|
||||
let rotation_text = format!("{}°", format_rounded(angle.to_degrees(), 3));
|
||||
let scale_text = format!("({}x, {}x)", format_rounded(scale.x, 3), format_rounded(scale.y, 3));
|
||||
|
||||
vec![
|
||||
IconLabel::new("TransformationGrab").tooltip_label("Location").widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
TextLabel::new(location_text).narrow(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
IconLabel::new("TransformationRotate").tooltip_label("Rotation").widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
TextLabel::new(rotation_text).narrow(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
IconLabel::new("TransformationScale").tooltip_label("Scale").widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
TextLabel::new(scale_text).narrow(true).widget_instance(),
|
||||
]
|
||||
format!(
|
||||
"Location: ({} px, {} px) — Rotation: {rotation}° — Scale: ({}x, {}x)",
|
||||
format_rounded(translation.x, 3),
|
||||
format_rounded(translation.y, 3),
|
||||
format_rounded(scale.x, 3),
|
||||
format_rounded(scale.y, 3)
|
||||
)
|
||||
}
|
||||
|
||||
fn format_dvec2(value: DVec2) -> String {
|
||||
|
||||
@@ -5,7 +5,6 @@ use document_graph_storage::Registry;
|
||||
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry, ResourceStorage};
|
||||
|
||||
use super::utility_types::network_interface::NodeNetworkInterface;
|
||||
use super::utility_types::network_interface::editor_delta::{EditorDelta, construct_batch};
|
||||
use super::utility_types::network_interface::storage_metadata::{StorageMetadataView, collect_network_view_settings};
|
||||
|
||||
/// Per-document undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor that is
|
||||
@@ -102,7 +101,6 @@ impl DocumentHistory {
|
||||
/// round-trip check, off by default for its perf cost.
|
||||
pub fn stage_snapshot(
|
||||
&mut self,
|
||||
deltas: &[EditorDelta],
|
||||
interface: &NodeNetworkInterface,
|
||||
registry: &ResourceRegistry,
|
||||
view_settings: BTreeMap<String, serde_json::Value>,
|
||||
@@ -111,68 +109,21 @@ impl DocumentHistory {
|
||||
) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
|
||||
// A working copy that does not hold the document yet has no baseline for a batch of changes to
|
||||
// apply to, so the first commit writes the whole document and every later one stages only what
|
||||
// the store recorded. Reading that from the working copy rather than from the caller means a path
|
||||
// that mounts storage and then commits does not have to know which of the two it is.
|
||||
let staged = match storage.registry().node_instances.is_empty() {
|
||||
true => Self::stage_whole_document(storage, interface, registry, byte_store),
|
||||
// An autosave with nothing edited since the last commit still persists the view state below.
|
||||
false if deltas.is_empty() => Ok(()),
|
||||
false => Self::stage_recorded(storage, deltas, interface, registry, byte_store),
|
||||
};
|
||||
if let Err(error) = staged {
|
||||
let network = interface.document_network();
|
||||
let metadata_view = StorageMetadataView::new(interface);
|
||||
|
||||
let network_view_settings = storage
|
||||
.network_ids(network, &metadata_view)
|
||||
.ok()
|
||||
.map(|network_ids| collect_network_view_settings(interface, &network_ids));
|
||||
|
||||
// Stage without retiring: a tool drag fires several `CommitTransaction`s but is one legacy undo
|
||||
// step, so the deltas accumulate as hot ops and coalesce at the next undo-step boundary.
|
||||
if let Err(error) = storage.stage_runtime_snapshot(network, &metadata_view, registry, byte_store) {
|
||||
log::error!("Storage snapshot staging failed: {error}");
|
||||
return;
|
||||
}
|
||||
|
||||
self.persist_view_state(interface, view_settings, legacy_document);
|
||||
}
|
||||
|
||||
/// Converts the whole document and stages the difference from what the working copy holds.
|
||||
///
|
||||
/// Stages without retiring: a tool drag fires several `CommitTransaction`s but is one legacy undo
|
||||
/// step, so the ops accumulate in the hot log and coalesce at the next undo-step boundary.
|
||||
fn stage_whole_document(storage: &mut document_format::GddV1, interface: &NodeNetworkInterface, registry: &ResourceRegistry, byte_store: &dyn ResourceStorage) -> Result<(), String> {
|
||||
let metadata_view = StorageMetadataView::new(interface);
|
||||
storage
|
||||
.stage_runtime_snapshot(interface.document_network(), &metadata_view, registry, byte_store)
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
/// Stages what the store recorded since the last drain.
|
||||
///
|
||||
/// This and the whole-document conversion produce the same registry for the same edit, which
|
||||
/// `verify_round_trip` checks when the `validate_storage_round_trip` preference is on. They differ in
|
||||
/// what they cost and in what they can miss: a conversion sees every change however it was made,
|
||||
/// while this sees only what went through the store, so a write that bypasses it is not persisted.
|
||||
fn stage_recorded(
|
||||
storage: &mut document_format::GddV1,
|
||||
deltas: &[EditorDelta],
|
||||
interface: &NodeNetworkInterface,
|
||||
registry: &ResourceRegistry,
|
||||
byte_store: &dyn ResourceStorage,
|
||||
) -> Result<(), String> {
|
||||
let peer = storage.session().peer();
|
||||
let metadata_view = StorageMetadataView::new(interface);
|
||||
let constructed = construct_batch(deltas, storage.registry(), registry, &metadata_view, peer).map_err(|error| error.to_string())?;
|
||||
|
||||
storage
|
||||
.stage_constructed_ops(constructed.ops, &constructed.declaration_bytes, byte_store)
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
/// The parts of a commit that are not the graph: the per-peer view settings, and the legacy bytes the
|
||||
/// dual-write soak validates the new format against. Both staging paths persist them; they differ
|
||||
/// only in how the graph ops are derived.
|
||||
fn persist_view_state(&mut self, interface: &NodeNetworkInterface, view_settings: BTreeMap<String, serde_json::Value>, legacy_document: &str) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
|
||||
let network_view_settings = storage
|
||||
.network_ids(interface.document_network(), &StorageMetadataView::new(interface))
|
||||
.ok()
|
||||
.map(|network_ids| collect_network_view_settings(interface, &network_ids));
|
||||
|
||||
if let Err(error) = storage.set_view_settings(view_settings) {
|
||||
log::error!("Persisting view settings failed: {error}");
|
||||
}
|
||||
@@ -183,6 +134,8 @@ impl DocumentHistory {
|
||||
log::error!("Persisting per-network view settings failed: {error}");
|
||||
}
|
||||
|
||||
// Dual-write soak: embed the legacy `.graphite` bytes so the new format
|
||||
// can be validated against (and recovered from) the old one on open.
|
||||
if let Err(error) = storage.store_legacy_document(legacy_document.as_bytes()) {
|
||||
log::error!("Embedding legacy document into working copy failed: {error}");
|
||||
}
|
||||
|
||||
@@ -2,17 +2,19 @@ use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::utility_types::misc::{GroupFolderType, SnappingState};
|
||||
use crate::messages::input_mapper::utility_types::keyboard::Key;
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
|
||||
use crate::messages::portfolio::document::data_panel::DataPanelMessage;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::{OverlayContext, OverlaysType};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
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, UVec2};
|
||||
use glam::{DAffine2, IVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Appearance;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::vector::click_target::ClickTarget;
|
||||
@@ -115,8 +117,7 @@ pub enum DocumentMessage {
|
||||
},
|
||||
InsertImage {
|
||||
name: Option<String>,
|
||||
data: Arc<[u8]>,
|
||||
size: UVec2,
|
||||
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`
|
||||
|
||||
@@ -10,7 +10,6 @@ use crate::consts::{
|
||||
ASYMPTOTIC_EFFECT, BLEND_COUNT_PER_LAYER, COLOR_OVERLAY_GRAY, DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, GDD_FILE_EXTENSION, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH, SCALE_EFFECT, SCROLLBAR_SPACING,
|
||||
VIEWPORT_ROTATE_SNAP_INTERVAL,
|
||||
};
|
||||
use crate::messages::frontend::utility_types::FileFilter;
|
||||
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};
|
||||
@@ -42,12 +41,12 @@ use graphene_std::Cover;
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::path_bool_nodes::boolean_intersect;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::vector::algorithms::bezpath_algorithms::bezpath_is_inside_bezpath;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
|
||||
use graphene_std::vector::graphic_types;
|
||||
use graphene_std::vector::misc::dvec2_to_point;
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
use kurbo::{Affine, BezPath, Line, PathSeg, Shape};
|
||||
use graphene_std::vector::{PointId, graphic_types};
|
||||
use kurbo::{Affine, BezPath, Line, PathSeg};
|
||||
use std::collections::HashSet;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
@@ -249,7 +248,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
DocumentMessage::PropertiesPanel(message) => {
|
||||
let context = PropertiesPanelMessageContext {
|
||||
executor,
|
||||
document_id,
|
||||
network_interface: &mut self.network_interface,
|
||||
resources: &self.resources,
|
||||
selection_network_path: &self.selection_network_path,
|
||||
@@ -301,7 +299,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
graph_operation_message_handler.process_message(message, responses, context);
|
||||
}
|
||||
DocumentMessage::Resource(message) => {
|
||||
let context = ResourceMessageContext { document_id, fonts, resource_storage };
|
||||
let context = ResourceMessageContext { document_id, fonts };
|
||||
self.resources.process_message(message, responses, context);
|
||||
}
|
||||
DocumentMessage::AlignSelectedLayers { axis, aggregate } => {
|
||||
@@ -798,14 +796,15 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
DocumentMessage::InsertImage {
|
||||
name,
|
||||
data,
|
||||
size,
|
||||
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 = size.as_dvec2();
|
||||
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
|
||||
@@ -813,7 +812,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
} 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 nonzero position does not offset the placement.
|
||||
// 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)
|
||||
@@ -828,7 +827,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
|
||||
let layer = graph_modification_utils::new_image_layer(data, layer_node_id, layer_parent, responses);
|
||||
let layer = graph_modification_utils::new_image_layer(image, layer_node_id, layer_parent, responses);
|
||||
|
||||
if let Some(name) = name {
|
||||
responses.add(NodeGraphMessage::SetDisplayName {
|
||||
@@ -876,7 +875,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
} 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 nonzero position does not offset the placement.
|
||||
// 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)
|
||||
@@ -917,14 +916,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
responses.add(SelectToolMessage::Abort);
|
||||
responses.add(DocumentMessage::DocumentHistoryForward);
|
||||
|
||||
// The Pen tool advances its in-progress drawing to match the re-applied document once the graph has re-evaluated
|
||||
if *current_tool == ToolType::Pen {
|
||||
responses.add(DeferMessage::AfterGraphRun {
|
||||
messages: vec![PenToolMessage::Redo.into()],
|
||||
});
|
||||
}
|
||||
|
||||
responses.add(ToolMessage::Redo);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
responses.add(EventMessage::SelectionChanged);
|
||||
}
|
||||
@@ -1074,10 +1066,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
(true, Some(storage)) => storage
|
||||
.export_to_bytes(
|
||||
document_format::ExportFormat::Xz,
|
||||
document_format::ExportOptions {
|
||||
include_history: false,
|
||||
..Default::default()
|
||||
},
|
||||
document_format::ExportOptions::default(),
|
||||
export_load_handle.as_ref(),
|
||||
Some(&legacy_document),
|
||||
)
|
||||
@@ -1097,11 +1086,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
name,
|
||||
path,
|
||||
folder,
|
||||
filters: vec![FileFilter {
|
||||
name: "Graphite Document".into(),
|
||||
extensions: vec![extension.into()],
|
||||
mime_types: Vec::new(),
|
||||
}],
|
||||
content: content.into(),
|
||||
})
|
||||
});
|
||||
@@ -1537,19 +1521,10 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
if self.network_interface.transaction_status() != TransactionStatus::Finished {
|
||||
return;
|
||||
}
|
||||
|
||||
// The Pen tool keeps drawing across an undo, so instead of aborting beforehand it rewinds to match the reverted document once the graph has re-evaluated
|
||||
if *current_tool == ToolType::Pen {
|
||||
responses.add(DocumentMessage::DocumentHistoryBackward);
|
||||
responses.add(DeferMessage::AfterGraphRun {
|
||||
messages: vec![PenToolMessage::Undo.into()],
|
||||
});
|
||||
} else {
|
||||
responses.add(EventMessage::ToolAbort);
|
||||
responses.add(DocumentMessage::DocumentHistoryBackward);
|
||||
}
|
||||
|
||||
responses.add(ToolMessage::PreUndo);
|
||||
responses.add(DocumentMessage::DocumentHistoryBackward);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
responses.add(ToolMessage::Undo);
|
||||
responses.add(EventMessage::SelectionChanged);
|
||||
}
|
||||
DocumentMessage::UngroupSelectedLayers => {
|
||||
@@ -1856,16 +1831,16 @@ impl DocumentMessageHandler {
|
||||
self.intersect_quad(viewport_quad, viewport).filter(|layer| !self.network_interface.is_artboard(&layer.to_node(), &[]))
|
||||
}
|
||||
|
||||
/// Runs an intersection test with all layers and a viewport space polygon path
|
||||
pub fn intersect_polygon<'a>(&'a self, mut viewport_polygon: BezPath, viewport: &ViewportMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
|
||||
/// Runs an intersection test with all layers and a viewport space subpath
|
||||
pub fn intersect_polygon<'a>(&'a self, mut viewport_polygon: Subpath<PointId>, 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);
|
||||
viewport_polygon.apply_affine(Affine::new(document_to_viewport.inverse().to_cols_array()));
|
||||
viewport_polygon.apply_transform(document_to_viewport.inverse());
|
||||
|
||||
ClickXRayIter::new(&self.network_interface, XRayTarget::Path(viewport_polygon))
|
||||
ClickXRayIter::new(&self.network_interface, XRayTarget::Polygon(viewport_polygon))
|
||||
}
|
||||
|
||||
/// Runs an intersection test with all layers and a viewport space polygon path; ignoring artboards
|
||||
pub fn intersect_polygon_no_artboards<'a>(&'a self, viewport_polygon: BezPath, viewport: &ViewportMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
|
||||
/// Runs an intersection test with all layers and a viewport space subpath; ignoring artboards
|
||||
pub fn intersect_polygon_no_artboards<'a>(&'a self, viewport_polygon: Subpath<PointId>, viewport: &ViewportMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
|
||||
self.intersect_polygon(viewport_polygon, viewport)
|
||||
.filter(|layer| !self.network_interface.is_artboard(&layer.to_node(), &[]))
|
||||
}
|
||||
@@ -1893,24 +1868,29 @@ impl DocumentMessageHandler {
|
||||
layer_left >= quad_left && layer_right <= quad_right && layer_top <= quad_top && layer_bottom >= quad_bottom
|
||||
}
|
||||
|
||||
pub fn is_layer_fully_inside_polygon(&self, layer: &LayerNodeIdentifier, viewport: &ViewportMessageHandler, mut viewport_polygon: BezPath) -> bool {
|
||||
pub fn is_layer_fully_inside_polygon(&self, layer: &LayerNodeIdentifier, viewport: &ViewportMessageHandler, mut viewport_polygon: Subpath<PointId>) -> bool {
|
||||
let document_to_viewport = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
|
||||
viewport_polygon.apply_affine(Affine::new(document_to_viewport.inverse().to_cols_array()));
|
||||
viewport_polygon.apply_transform(document_to_viewport.inverse());
|
||||
|
||||
let layer_click_targets = self.network_interface.document_metadata().click_targets(*layer);
|
||||
let layer_transform = self.network_interface.document_metadata().transform_to_document(*layer);
|
||||
|
||||
layer_click_targets.is_some_and(|targets| {
|
||||
targets.iter().all(|target| match target.target_type() {
|
||||
ClickTargetType::Path(path) => {
|
||||
let mut path = path.clone();
|
||||
path.apply_affine(Affine::new(layer_transform.to_cols_array()));
|
||||
bezpath_is_inside_bezpath(&path, &viewport_polygon, None, None)
|
||||
ClickTargetType::Subpath(subpath) => {
|
||||
let mut subpath = subpath.clone();
|
||||
subpath.apply_transform(layer_transform);
|
||||
subpath.is_inside_subpath(&viewport_polygon, None, None)
|
||||
}
|
||||
ClickTargetType::CompoundPath(subpaths) => subpaths.iter().all(|subpath| {
|
||||
let mut subpath = subpath.clone();
|
||||
subpath.apply_transform(layer_transform);
|
||||
subpath.is_inside_subpath(&viewport_polygon, None, None)
|
||||
}),
|
||||
ClickTargetType::FreePoint(point) => {
|
||||
let mut point = *point;
|
||||
point.apply_transform(layer_transform);
|
||||
viewport_polygon.contains(dvec2_to_point(point.position))
|
||||
viewport_polygon.contains_point(point.position)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -2026,30 +2006,14 @@ impl DocumentMessageHandler {
|
||||
self.history.retire_storage_interaction();
|
||||
}
|
||||
|
||||
/// Stages what the store recorded since the last commit into the `Gdd` working copy.
|
||||
///
|
||||
/// The batch boundary: everything the interface recorded since the last one is this commit's batch.
|
||||
/// Draining happens whether or not a working copy is mounted, so the buffer cannot grow across a
|
||||
/// session that never mounts one.
|
||||
/// Stages the runtime network into the `Gdd` working copy.
|
||||
pub fn commit_storage_snapshot(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage, validate: bool) {
|
||||
let deltas = self.network_interface.take_deltas();
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::DocumentSettings;
|
||||
|
||||
if self.history.storage().is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
let (view_settings, legacy_document) = self.storage_side_channels();
|
||||
self.history
|
||||
.stage_snapshot(&deltas, &self.network_interface, &self.resources.registry, view_settings, legacy_document.as_str(), byte_store);
|
||||
|
||||
if validate {
|
||||
self.history.verify_round_trip(&self.network_interface, &self.resources.registry);
|
||||
}
|
||||
}
|
||||
|
||||
/// The per-peer view settings and legacy bytes that ride along with either kind of staging.
|
||||
fn storage_side_channels(&self) -> (std::collections::BTreeMap<String, serde_json::Value>, String) {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::DocumentSettings;
|
||||
|
||||
let view_settings = DocumentSettings {
|
||||
document_ptz: &self.document_ptz,
|
||||
render_mode: &self.render_mode,
|
||||
@@ -2060,7 +2024,14 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
.to_view_map();
|
||||
|
||||
(view_settings, self.serialize_document())
|
||||
let legacy_document = self.serialize_document();
|
||||
|
||||
self.history
|
||||
.stage_snapshot(&self.network_interface, &self.resources.registry, view_settings, legacy_document.as_str(), byte_store);
|
||||
|
||||
if validate {
|
||||
self.history.verify_round_trip(&self.network_interface, &self.resources.registry);
|
||||
}
|
||||
}
|
||||
|
||||
/// Restore `view_settings` map into the document.
|
||||
@@ -2787,7 +2758,7 @@ impl DocumentMessageHandler {
|
||||
let appearance = self.network_interface.document_metadata().layer_appearance_attributes.get(&layer);
|
||||
|
||||
let has_fill = appearance.is_some_and(|appearance| appearance.has_painted_cover(Cover::Fill));
|
||||
// A visible stroke needs both renderable geometry (nonzero weight) and paint that draws something
|
||||
// A visible stroke needs both renderable geometry (non-zero weight) and paint that draws something
|
||||
let has_stroke = appearance.is_some_and(|appearance| {
|
||||
appearance.first_coverage_of(Cover::Stroke).is_some_and(|coverage| coverage.stroke_params().has_renderable_stroke())
|
||||
&& appearance.first_paint_of(Cover::Stroke).is_some_and(|paint| !paint.is_guaranteed_fully_transparent())
|
||||
@@ -3549,7 +3520,7 @@ impl DocumentMessageHandler {
|
||||
})
|
||||
.on_commit(|_| DocumentMessage::AddTransaction.into())
|
||||
.max_width(100)
|
||||
.tooltip_label("Fill Opacity")
|
||||
.tooltip_label("Fill")
|
||||
.widget_instance(),
|
||||
];
|
||||
let layers_panel_control_bar_left = Layout(vec![LayoutGroup::row(widgets)]);
|
||||
@@ -3760,7 +3731,7 @@ impl DocumentMessageHandler {
|
||||
let first_or_last_selected_layer = match relative_index_offset.signum() {
|
||||
-1 => selected_layers.next(),
|
||||
1 => selected_layers.last(),
|
||||
_ => panic!("selected_layers_reorder() must be given a nonzero value"),
|
||||
_ => panic!("selected_layers_reorder() must be given a non-zero value"),
|
||||
};
|
||||
|
||||
let Some(pivot_layer) = first_or_last_selected_layer else {
|
||||
@@ -3820,6 +3791,7 @@ enum XRayTarget {
|
||||
Point(DVec2),
|
||||
Quad(Quad),
|
||||
Path(BezPath),
|
||||
Polygon(Subpath<PointId>),
|
||||
}
|
||||
|
||||
/// The result for the [`ClickXRayIter`] on the layer
|
||||
@@ -3842,7 +3814,13 @@ fn quad_to_kurbo(quad: Quad) -> BezPath {
|
||||
|
||||
fn click_targets_to_kurbo<'a>(click_targets: impl Iterator<Item = &'a ClickTarget>, transform: DAffine2) -> BezPath {
|
||||
let segments = click_targets
|
||||
.filter_map(|target| if let ClickTargetType::Path(path) = target.target_type() { Some(path.segments()) } else { None })
|
||||
.filter_map(|target| {
|
||||
if let ClickTargetType::Subpath(subpath) = target.target_type() {
|
||||
Some(subpath.iter())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.flatten()
|
||||
.map(|bezier| Affine::new(transform.to_cols_array()) * bezier);
|
||||
BezPath::from_path_segments(segments)
|
||||
@@ -3913,6 +3891,10 @@ impl<'a> ClickXRayIter<'a> {
|
||||
}
|
||||
XRayTarget::Quad(quad) => self.check_layer_area_target(click_targets, clip, layer, quad_to_kurbo(*quad), transform),
|
||||
XRayTarget::Path(path) => self.check_layer_area_target(click_targets, clip, layer, path.clone(), transform),
|
||||
XRayTarget::Polygon(polygon) => {
|
||||
let polygon = BezPath::from_path_segments(polygon.iter_closed());
|
||||
self.check_layer_area_target(click_targets, clip, layer, polygon, transform)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4115,11 +4097,10 @@ mod document_message_handler_tests {
|
||||
async fn get_layer_by_bounds(editor: &mut EditorTestUtils, min_x: f64, min_y: f64) -> Option<LayerNodeIdentifier> {
|
||||
let document = editor.active_document();
|
||||
for layer in document.metadata().all_layers() {
|
||||
if let Some(bbox) = document.metadata().bounding_box_viewport(layer)
|
||||
&& (bbox[0].x - min_x).abs() < 1.
|
||||
&& (bbox[0].y - min_y).abs() < 1.
|
||||
{
|
||||
return Some(layer);
|
||||
if let Some(bbox) = document.metadata().bounding_box_viewport(layer) {
|
||||
if (bbox[0].x - min_x).abs() < 1. && (bbox[0].y - min_y).abs() < 1. {
|
||||
return Some(layer);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
@@ -4176,6 +4157,7 @@ mod document_message_handler_tests {
|
||||
// The operation completed without crashing
|
||||
// Verifying application still functions by performing another operation
|
||||
editor.handle_message(DocumentMessage::CreateEmptyFolder).await;
|
||||
assert!(true, "Application didn't crash after folder move operation");
|
||||
}
|
||||
|
||||
// Merging nodes whose output isn't wired downstream produces an encapsulating subnetwork with no exports.
|
||||
|
||||
@@ -5,11 +5,13 @@ use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::brush::brush_stroke::BrushStroke;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster_types::Image;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
|
||||
use graphene_std::vector::{Gradient, VectorModificationType};
|
||||
use std::sync::Arc;
|
||||
use graphene_std::vector::{Gradient, PointId, VectorModificationType};
|
||||
|
||||
#[impl_message(Message, DocumentMessage, GraphOperation)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
@@ -111,23 +113,9 @@ pub enum GraphOperationMessage {
|
||||
layer: LayerNodeIdentifier,
|
||||
modification_type: VectorModificationType,
|
||||
},
|
||||
NewBrushGroupLayer {
|
||||
id: NodeId,
|
||||
strokes_node_id: NodeId,
|
||||
parent: LayerNodeIdentifier,
|
||||
insert_index: usize,
|
||||
color: Color,
|
||||
diameter: f64,
|
||||
hardness: f64,
|
||||
flow: f64,
|
||||
},
|
||||
NewBrushStrokesNode {
|
||||
Brush {
|
||||
layer: LayerNodeIdentifier,
|
||||
strokes_node_id: NodeId,
|
||||
color: Color,
|
||||
diameter: f64,
|
||||
hardness: f64,
|
||||
flow: f64,
|
||||
strokes: Vec<BrushStroke>,
|
||||
},
|
||||
SetUpstreamToChain {
|
||||
layer: LayerNodeIdentifier,
|
||||
@@ -141,7 +129,7 @@ pub enum GraphOperationMessage {
|
||||
},
|
||||
NewBitmapLayer {
|
||||
id: NodeId,
|
||||
data: Arc<[u8]>,
|
||||
image: Image<Color>,
|
||||
parent: LayerNodeIdentifier,
|
||||
insert_index: usize,
|
||||
},
|
||||
@@ -174,6 +162,12 @@ pub enum GraphOperationMessage {
|
||||
parent: LayerNodeIdentifier,
|
||||
insert_index: usize,
|
||||
},
|
||||
NewVectorLayer {
|
||||
id: NodeId,
|
||||
subpaths: Vec<Subpath<PointId>>,
|
||||
parent: LayerNodeIdentifier,
|
||||
insert_index: usize,
|
||||
},
|
||||
NewTextLayer {
|
||||
id: NodeId,
|
||||
text: String,
|
||||
|
||||
+16
-51
@@ -2,14 +2,13 @@ use super::transform_utils;
|
||||
use super::utility_types::{ModifyInputsContext, set_stroke_paint_order};
|
||||
use crate::consts::{LAYER_INDENT_OFFSET, STACK_VERTICAL_GAP};
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{BLEND_PATH_INPUT_INDEX, DefinitionIdentifier, resolve_proto_node_type};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{BLEND_PATH_INPUT_INDEX, DefinitionIdentifier};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface, OutputConnector};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::CollapsedLayers;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_clip_mode;
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graph_craft::list;
|
||||
use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
|
||||
@@ -173,35 +172,10 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
modify_inputs.vector_modify(modification_type);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::NewBrushGroupLayer {
|
||||
id,
|
||||
strokes_node_id,
|
||||
parent,
|
||||
insert_index,
|
||||
color,
|
||||
diameter,
|
||||
hardness,
|
||||
flow,
|
||||
} => {
|
||||
let layer = ModifyInputsContext::new(network_interface, responses).create_layer(id);
|
||||
insert_brush_strokes_chain(network_interface, layer, strokes_node_id, color, diameter, hardness, flow);
|
||||
|
||||
responses.add(NodeGraphMessage::MoveLayerToStack { layer, parent, insert_index });
|
||||
responses.add(GraphOperationMessage::SetUpstreamToChain { layer });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
GraphOperationMessage::NewBrushStrokesNode {
|
||||
layer,
|
||||
strokes_node_id,
|
||||
color,
|
||||
diameter,
|
||||
hardness,
|
||||
flow,
|
||||
} => {
|
||||
insert_brush_strokes_chain(network_interface, layer, strokes_node_id, color, diameter, hardness, flow);
|
||||
|
||||
responses.add(GraphOperationMessage::SetUpstreamToChain { layer });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
GraphOperationMessage::Brush { layer, strokes } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.brush_modify(strokes);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::SetUpstreamToChain { layer } => {
|
||||
let Some(OutputConnector::Node { node_id: first_chain_node, .. }) = network_interface.upstream_output_connector(&InputConnector::layer_secondary_input(layer.to_node()), &[]) else {
|
||||
@@ -267,10 +241,10 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
responses.add_front(NodeGraphMessage::SelectedNodesSet { nodes: vec![id] });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
GraphOperationMessage::NewBitmapLayer { id, data, parent, insert_index } => {
|
||||
GraphOperationMessage::NewBitmapLayer { id, image, parent, insert_index } => {
|
||||
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
|
||||
let layer = modify_inputs.create_layer(id);
|
||||
modify_inputs.insert_image_data(data, layer);
|
||||
modify_inputs.insert_image_data(image, layer);
|
||||
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
@@ -389,6 +363,13 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
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);
|
||||
modify_inputs.insert_vector(subpaths, layer, true, true, true);
|
||||
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
GraphOperationMessage::NewTextLayer {
|
||||
id,
|
||||
text,
|
||||
@@ -873,31 +854,15 @@ fn import_usvg_node_inner(
|
||||
}
|
||||
}
|
||||
|
||||
fn insert_brush_strokes_chain(network_interface: &mut NodeNetworkInterface, layer: LayerNodeIdentifier, strokes_node_id: NodeId, color: Color, diameter: f64, hardness: f64, flow: f64) {
|
||||
let Some(strokes_node_type) = resolve_proto_node_type(graphene_std::brush::brush_strokes::IDENTIFIER) else {
|
||||
log::error!("Brush strokes node does not exist");
|
||||
return;
|
||||
};
|
||||
let strokes_node = strokes_node_type.node_template_input_override([
|
||||
Some(NodeInput::value(TaggedValue::Strokes(Vec::new()), false)),
|
||||
Some(NodeInput::value(TaggedValue::Color(color), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(diameter), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(hardness), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(flow), false)),
|
||||
]);
|
||||
network_interface.insert_node(strokes_node_id, strokes_node, &[]);
|
||||
network_interface.set_input(&InputConnector::node_at_index(layer.to_node(), 1), NodeInput::node(strokes_node_id, 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, gradient_info: &SvgGradientInfo) {
|
||||
let bezpath = convert_usvg_path(path);
|
||||
let subpaths = convert_usvg_path(path);
|
||||
|
||||
// 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(bezpath, layer, has_transform, path.fill().is_some(), path.stroke().is_some());
|
||||
modify_inputs.insert_vector(subpaths, layer, has_transform, path.fill().is_some(), path.stroke().is_some());
|
||||
|
||||
if has_transform && let Some(transform_node_id) = modify_inputs.existing_proto_node_id(graphene_std::transform_nodes::transform::IDENTIFIER, false) {
|
||||
transform_utils::update_transform(modify_inputs.network_interface, &transform_node_id, node_transform);
|
||||
|
||||
@@ -2,7 +2,9 @@ use crate::messages::portfolio::document::utility_types::network_interface::{Inp
|
||||
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;
|
||||
|
||||
/// 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) {
|
||||
@@ -85,6 +87,32 @@ pub fn get_current_normalized_pivot(inputs: &[NodeInput]) -> DVec2 {
|
||||
if let Some(&TaggedValue::DVec2(pivot)) = inputs[5].as_value() { pivot } else { DVec2::splat(0.5) }
|
||||
}
|
||||
|
||||
/// Expand a bounds to avoid div zero errors
|
||||
fn clamp_bounds(bounds_min: DVec2, mut bounds_max: DVec2) -> [DVec2; 2] {
|
||||
let bounds_size = bounds_max - bounds_min;
|
||||
if bounds_size.x < 1e-10 {
|
||||
bounds_max.x = bounds_min.x + 1.;
|
||||
}
|
||||
if bounds_size.y < 1e-10 {
|
||||
bounds_max.y = bounds_min.y + 1.;
|
||||
}
|
||||
[bounds_min, bounds_max]
|
||||
}
|
||||
/// Returns corners of all subpaths
|
||||
fn subpath_bounds(subpaths: &[Subpath<PointId>]) -> [DVec2; 2] {
|
||||
subpaths
|
||||
.iter()
|
||||
.filter_map(|subpath| subpath.bounding_box())
|
||||
.reduce(|b1, b2| [b1[0].min(b2[0]), b1[1].max(b2[1])])
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Returns corners of all subpaths (but expanded to avoid division-by-zero errors)
|
||||
pub fn nonzero_subpath_bounds(subpaths: &[Subpath<PointId>]) -> [DVec2; 2] {
|
||||
let [bounds_min, bounds_max] = subpath_bounds(subpaths);
|
||||
clamp_bounds(bounds_min, bounds_max)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -13,13 +13,14 @@ use graph_craft::application_io::resource::ResourceId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graph_craft::{ProtoNodeIdentifier, list};
|
||||
use graphene_std::brush::brush_stroke::BrushStroke;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster_types::Image;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
|
||||
use graphene_std::vector::{Gradient, GradientRamp, Vector, VectorModification, VectorModificationType};
|
||||
use graphene_std::vector::{Gradient, GradientRamp, PointId, Vector, VectorModification, VectorModificationType};
|
||||
use graphene_std::{Artboard, Color, Graphic};
|
||||
use kurbo::BezPath;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(PartialEq, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum TransformIn {
|
||||
@@ -145,9 +146,9 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
path_id
|
||||
}
|
||||
|
||||
pub fn insert_vector(&mut self, bezpath: BezPath, layer: LayerNodeIdentifier, include_transform: bool, include_fill: bool, include_stroke: bool) {
|
||||
pub fn insert_vector(&mut self, subpaths: Vec<Subpath<PointId>>, layer: LayerNodeIdentifier, include_transform: bool, include_fill: bool, include_stroke: bool) {
|
||||
// Build a VectorModification that reproduces the geometry (same format the Pen tool uses)
|
||||
let vector = Vector::from_bezpath(bezpath);
|
||||
let vector = Vector::from_subpaths(subpaths, true);
|
||||
let modification = Box::new(VectorModification::create_from_vector(&vector));
|
||||
|
||||
let shape = resolve_network_node_type("Path")
|
||||
@@ -270,17 +271,20 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.network_interface.set_chain_position(node_id, &[]);
|
||||
}
|
||||
|
||||
pub fn insert_image_data(&mut self, data: Arc<[u8]>, layer: LayerNodeIdentifier) {
|
||||
pub fn insert_image_data(&mut self, image: Image<Color>, layer: LayerNodeIdentifier) {
|
||||
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
|
||||
.expect("Transform node does not exist")
|
||||
.default_node_template();
|
||||
|
||||
let resource_id = ResourceId::new();
|
||||
self.responses.add(ResourceMessage::StoreEmbedded { resource_id, data });
|
||||
self.responses.add(ResourceMessage::StoreEmbedded {
|
||||
resource_id,
|
||||
data: image.to_png().into(),
|
||||
});
|
||||
|
||||
let image_node = resolve_proto_node_type(graphene_std::raster_nodes::std_nodes::image::IDENTIFIER)
|
||||
.expect("Image node does not exist")
|
||||
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Resource(resource_id), false))]);
|
||||
.node_template_input_override([Some(NodeInput::value(TaggedValue::Resource(resource_id), false))]);
|
||||
|
||||
let image_node_id = NodeId::new();
|
||||
self.network_interface.insert_node(image_node_id, image_node, &[]);
|
||||
@@ -661,7 +665,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
.nodes
|
||||
.get(&node_id)
|
||||
.and_then(|node| node.input(graphene_std::math_nodes::gradient_positions::PositionsInput));
|
||||
if current_input.is_none_or(|input| input.as_value().is_none()) {
|
||||
if !current_input.is_some_and(|input| input.as_value().is_some()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -685,7 +689,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
.nodes
|
||||
.get(&node_id)
|
||||
.and_then(|node| node.input(graphene_std::math_nodes::gradient_midpoints::MidpointsInput));
|
||||
if current_input.is_none_or(|input| input.as_value().is_none()) {
|
||||
if !current_input.is_some_and(|input| input.as_value().is_some()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -973,6 +977,17 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
pub fn brush_modify(&mut self, strokes: Vec<BrushStroke>) {
|
||||
let Some(brush_node_id) = self.existing_proto_node_id(graphene_std::brush::brush::brush::IDENTIFIER, true) else {
|
||||
return;
|
||||
};
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(brush_node_id, graphene_std::brush::brush::brush::TraceInput),
|
||||
NodeInput::value(TaggedValue::BrushStrokes(strokes), false),
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn resize_artboard(&mut self, location: DVec2, dimensions: DVec2) {
|
||||
let Some(artboard_node_id) = self.existing_network_node_id("Artboard", true) else {
|
||||
return;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::messages::input_mapper::utility_types::keyboard::Key;
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
|
||||
use crate::messages::prelude::*;
|
||||
use glam::DVec2;
|
||||
|
||||
|
||||
Loaded 100 of 407 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user