Compare commits

..
Author SHA1 Message Date
firestar99 953a9312f0 GPU: add support for N-many input images and not just exactly one 2026-06-07 20:39:30 -07:00
Keavon Chambers 7a6e4f6f25 Fix new nodes being added in the wrong place near graph edges (#4211) 2026-06-07 19:22:30 -07:00
Hemu b645871dbc Fix duplicated dropdown selection styling when multiple entries have identical labels (#4180)
* Fix dropdown select if options have identical labels

* update other uses of label in favor of value

* simplify null checks
2026-06-07 17:53:58 -07:00
Keavon Chambers 85ee5e41b9 Fix strokes with inside/outside alignment not being selectable when above other layers (#4207) 2026-06-07 17:08:04 -07:00
Dennis Kobert d5c67eeb55 Drop MemoHash's std Hash impl and route cache-identity hashing through CacheHash (#4209) 2026-06-07 17:49:56 +00:00
Keavon Chambers 2c29d2c406 Fix Gradient tool inserting new nodes in the wrong position when updating a Fill node's gradient chain (#4203)
* Fix Gradient tool inserting new nodes in the wrong position when updating a Fill node's gradient chain

* Improve robustness
2026-06-05 21:02:42 -07:00
YohYamasakiandKeavon Chambers a3b62dac00 Make the Gradient tool work with gradient node chains feeding a Fill node (#4177)
* Add Gradient node

* Add support of new Gradient node for Gradient tool

* Adapt gemini reviews

* Add tests

* Bring back visibility check

* Remove the 'Gradient' node since it's unwanted after all

* Formatting

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-06-06 03:23:14 +00:00
Timon 9d2071ce6a Desktop: Disable UI acceleration by default on Linux (#4201) 2026-06-05 22:16:37 +00:00
Dennis KobertandTimon 6fe1af3afe Add document-container crate (#4191)
* Add document-container crate: container backends and archive codecs

* Address PR review: path/prefix split, safe size casts, OPFS stream aborts

* Address PR review round 2: mmap read check, UTF8 entry names, prefix normalization

* Make MmappedBytes::new fallible so mmap reads can't silently degrade

* Address PR review round 3: backend contract uniformity (symlinks, remove, list)

* Apply symlink-component check to FolderBackend listing paths

* Address PR review: idempotent OPFS delete logging, tar default-features, shared entry-size cap

* Fix validate_path doc: dotfiles pass, CurDir/ParentDir rejected

* Omit symlink entries from FolderBackend listings for consistency with resolve

* Preserve zip I/O errors and reject non-canonical paths in validate_path

* Extend archive apis to return the archive writer

* Rename document/document-container directory to document/container

* Add archive format sniffing and deserialize_auto

* Drop temporal hedge from checked_entry_size comment

* Tighten verbose doc comments in document-container

* Coalesce consecutive same-path OPFS appends to avoid O(n^2) file copies

* Review

* Update document-container for the deserialize/store_non_blocking renames

---------

Co-authored-by: Timon <[email protected]>
2026-06-05 13:28:02 -04:00
Timon 08c6d02e5b Introduce network request handler (#4194)
* Impl NetworkMessageHandler

* Repalce Frontend fetch like messages with NetworkMessage

* Reimpl resource loading with NetworkMessage

* Fix wasm

* dedublicate resource requests

* Embedd font resources created by migration

* Fixup

* Fix tests

* Fix font catalog not loading

* Cleanup

* Fix layouts not updating when font catalog is loaded

* Review

* Review

* Cleanup
2026-06-05 13:27:45 -04:00
Timon cd8ea1f554 Migrate fonts to be stored as resources (#4165)
* Good start

* Impl

* allow responses.add(async { Message::NoOp });

* Fix

* Cache font blob in text node

* Refactor font handling to use Font struct direcly

* Fix fmt

* Embedd Font Resources by default

* Review

* Review

* Cache font info based on ResourceHash
2026-06-05 13:27:25 -04:00
Dennis Kobert 7b9c480a8d Make ResourceStorage trait &self-based and remove 'static requirement (#4188)
* Make ResourceStorage trait &self-based with elided-lifetime ResourceFuture

* Adress review comments
2026-06-01 10:37:05 +00:00
Timon e32ff4b7f0 Make Resource aware of its own hash (#4187)
* Fix future message handler field name

* Add Resource::hash()

* Move all remaining resource types from core-types to graphene-resources

* Review
2026-05-31 23:08:01 +00:00
Dennis KobertandTimon 78679a5ba2 Implement editor level future message handler (#4182)
* Implement proper editor level async message handler

* Take application_io and wake callback as Editor::new arguments

* Rename AsyncMessage -> FutureMessage

* add DesktopWrapperMessage::Wake

---------

Co-authored-by: Timon <[email protected]>
2026-05-31 21:26:29 +00:00
Timon 51427bef5f Fix CI profiling compile failure (#4184) 2026-05-31 20:32:34 +00:00
Timon a40e0d2887 Use ResourceId for referring to Resources (#4176)
* Use ResourceId for referring to Resources

* Use Doc

* use error for preprocessor ResourceId replacement failure

* Keep hashes in DocumentInfo

* Migrate with less mem copy

* Global ResourceMessage -> ResourceStorageMessage

* Add document ResourceMessage

* Move embedding logic

* Fix

* Cleanup

* Review

* Fix
2026-05-29 10:56:32 +00:00
TimonandDennis Kobert bbbe04903f Define data types for ID-based resource handling (#4168)
* Add resource lib

* rename ResourceSource to ResourceInput

* Rename ResourceInput -> DataSource and improve API

* Review

---------

Co-authored-by: Dennis Kobert <[email protected]>
2026-05-25 10:50:57 +00:00
Keavon Chambers d0d9a350c7 Add new May 2026 release update video to website home page 2026-05-23 02:04:59 -04:00
Keavon Chambers 9dccc526bb Add the May 2026 release message to the welcome screen 2026-05-23 01:41:42 -04:00
Keavon Chambers 96be4ec351 Add an "Initializing Renderer…" overlay when Vello shader compilation is slow on web 2026-05-23 01:07:26 -04:00
Keavon Chambers 62287d7893 Add a recovery path for autosaved documents that don't open successfully (#4157)
* Add a recovery path for autosaved documents that don't open successfully

* Fix file naming edge case

* Add edge cases for Windows zip names

* Simplify comments and remove desktop portion
2026-05-22 21:14:28 -07:00
Timon c3b0c87cfe Antialias checkered artboard background edges (#4163)
* Antialias checkered artboard background edges

* Review
2026-05-22 16:48:05 +00:00
Timon 2770df7567 Implement content-addressed resource storage for raster images (#4148)
* Implement content-addressed resource storage

* Implement OPFS resource storage

* Remove ResourceStorage::read

* Review
2026-05-21 19:31:07 +00:00
Keavon Chambers 21d2994059 Fix 'Solidify Strokes' node to produce dashed segments in an ordered sequence per open subpath (#3820)
Fix the ordering of dashed segments of open paths with the 'Solidify Stroke' node
2026-05-17 10:56:40 -07:00
Timon d5f0140f26 Upgrade WGPU and Linebender dependencies (#4154) 2026-05-17 15:36:59 +00:00
Keavon Chambers c4a978009a Fix SVG import treating gamma-encoded colors as linear-light 2026-05-16 05:37:01 -07:00
Keavon Chambers 256dd26b99 Recognize ExtractPosition/InjectPosition in the node macro context analyzer
Also, fix migration missing alias
2026-05-16 01:40:49 -07:00
Keavon Chambers 06e2a049de Implement dragging layers into the group/new/delete buttons in the Layers panel (#4153) 2026-05-15 15:39:01 -07:00
Keavon Chambers 79df7cfa87 Implement dragging the visibility/lock icons in the Layers panel to toggle each (#4152)
* Implement dragging the visibility/lock icons in the Layers panel to toggle each

* Code review fixes
2026-05-15 15:16:40 -07:00
Keavon Chambers 16c7544d96 Add the Layer > Expand Fill/Stroke menu action (#4151)
* Add the Layer > Expand Fill/Stroke menu action

* Code review feedback
2026-05-15 13:10:50 -07:00
Keavon Chambers a56746c6bf Deprecate all usages of the Color struct representing gamma space values, fixing round-trip precision bugs (#4149)
* Deprecate all usages of the Color struct representing gamma space values, fixing round-trip precision bugs

* Code review fixes
2026-05-14 22:48:33 -07:00
gamma0987andDennis Kobert 456a7c868d Migrate iai-callgrind to the renamed successor gungraun (#4056)
* Add .nvim.lua to gitignore

* Migrate from iai-callgrind to the renamed successor gungraun

---------

Co-authored-by: Dennis Kobert <[email protected]>
2026-05-14 08:18:59 +00:00
Keavon Chambers 1c9c19a697 Simplify and standardize how data types are presented in user-facing strings (#4147)
* User-facing type formatting

* Parse unicode not ASCII chars
2026-05-14 00:56:43 -07:00
Keavon Chambers 696b625a3e Fix hover transfer bugs occurring with the color picker popover (#4146)
* Fix hover transfer bugs occurring with the color picker popover

* Code review fix
2026-05-13 20:19:56 -07:00
Keavon Chambers 4d5dce976e Replace the control bar's stroke weight with a full stroke properties popover (#4145)
* Replace the control bar's stroke weight with a full stroke properties popover

* Code review
2026-05-13 03:58:12 -07:00
Keavon Chambers 629a1f4b4c Redesign how the control bar handles fill and stroke colors (#4137)
* Revamp how the control bar handles fill and stroke colors

* Fix bugs

* Code review
2026-05-11 18:13:02 -07:00
Keavon Chambers f6def3b911 Add icons for stroke align, cap, join, and order (#4136) 2026-05-11 03:53:38 -07:00
230 changed files with 10167 additions and 3986 deletions

No files matched your search

+2 -2
View File
@@ -1,2 +1,2 @@
https://github.com/Keavon/graphite-branded-assets/archive/b83626b10f0f9102503c845354e9e3f161949ce0.tar.gz
353e9cba90f420b11863055a32e554937638b47d1539632ef0e8a30f37a353d7
https://github.com/Keavon/graphite-branded-assets/archive/0d004aa61e6b48d316e8e5db6d59ccc4788f192d.tar.gz
772d64518be43c99977ba56f69e574531c56e83d2df2f42ab066f77f74b0dd1f
+4
View File
@@ -1,3 +1,7 @@
[build]
# Keep `--cfg=web_sys_unstable_apis` here so the wasm wrapper crates build with the same web-sys API signatures (e.g. `put_image_data`/`get_image_data` taking `i32` rather than `f64`) on both native test builds and the wasm target. Cargo applies `[build]` rustflags only when no target-specific rustflags table matches, so the wasm-specific list below must continue to include this cfg.
rustflags = ["--cfg=web_sys_unstable_apis"]
[target.wasm32-unknown-unknown]
rustflags = [
# Currently disabled because of https://github.com/GraphiteEditor/Graphite/issues/1262
+1 -1
View File
@@ -6,7 +6,7 @@
},
"ghcr.io/devcontainers/features/node:1": {}
},
"onCreateCommand": "cargo install cargo-watch wasm-pack cargo-about && cargo install -f [email protected]00",
"onCreateCommand": "cargo install cargo-watch wasm-pack cargo-about && cargo install -f [email protected]21",
"customizations": {
"vscode": {
// NOTE: Keep this in sync with `.vscode/extensions.json`
+3 -3
View File
@@ -123,7 +123,7 @@ jobs:
DELAY=15
for ATTEMPT in $(seq 1 $MAX_ATTEMPTS); do
echo "Attempt $ATTEMPT of $MAX_ATTEMPTS..."
npx wrangler@3 pages deploy "frontend/dist" --project-name="${{ steps.production-env.outputs.cf_project || 'graphite-dev' }}" --commit-dirty=true 2>&1 | tee /tmp/wrangler_output
npx wrangler@3 pages deploy "frontend/dist" --project-name="${{ steps.production-env.outputs.cf_project || 'graphite-dev' }}" --branch="master" --commit-dirty=true 2>&1 | tee /tmp/wrangler_output
if [ ${PIPESTATUS[0]} -eq 0 ]; then
URL=$(grep -oP 'https://[^\s]+\.pages\.dev' /tmp/wrangler_output | head -1)
echo "url=$URL" >> "$GITHUB_OUTPUT"
@@ -283,7 +283,7 @@ jobs:
pull-requests: write
env:
WASM_BINDGEN_CLI_VERSION: "0.2.100"
WASM_BINDGEN_CLI_VERSION: "0.2.121"
steps:
- name: 📥 Clone repository
@@ -474,7 +474,7 @@ jobs:
pull-requests: write
env:
WASM_BINDGEN_CLI_VERSION: "0.2.100"
WASM_BINDGEN_CLI_VERSION: "0.2.121"
steps:
- name: 📥 Clone repository
+2 -1
View File
@@ -57,7 +57,8 @@ jobs:
- name: 🧪 Run Rust tests
env:
RUSTFLAGS: -Dwarnings
# `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml`
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
run: mold -run cargo test --all-features
# Rust format check on GitHub runner
@@ -22,27 +22,14 @@ jobs:
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
- name: Install Valgrind
run: |
sudo apt update
sudo apt install -y valgrind
- name: Cache Rust dependencies
uses: Swatinem/rust-cache@v2
with:
# Cache on Cargo.lock file
cache-on-failure: true
- name: Cache iai-callgrind binary
id: cache-iai
uses: actions/cache@v5
with:
path: ~/.cargo/bin/iai-callgrind-runner
key: ${{ runner.os }}-iai-callgrind-runner-0.16.1
- name: Install iai-callgrind
if: steps.cache-iai.outputs.cache-hit != 'true'
run: cargo install [email protected]
- name: Install gungraun-runner and valgrind
uses: gungraun/setup-gungraun@v1
- name: Checkout master branch
run: |
@@ -66,21 +53,21 @@ jobs:
id: cache-benchmark-baselines
uses: actions/cache@v5
with:
path: target/iai
key: ${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-benchmark-baselines-master-${{ steps.master-sha.outputs.sha }}
path: target/gungraun
key: ${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-gungraun-benchmark-baselines-master-${{ steps.master-sha.outputs.sha }}
restore-keys: |
${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-benchmark-baselines-master-
${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-gungraun-benchmark-baselines-master-
- name: Run baseline benchmarks
if: steps.cache-benchmark-baselines.outputs.cache-hit != 'true'
run: |
# Compile benchmarks
cargo bench --bench compile_demo_art_iai -- --save-baseline=master
cargo bench --bench compile_demo_art_gungraun -- --save-baseline=master
# Runtime benchmarks
cargo bench --bench update_executor_iai -- --save-baseline=master
cargo bench --bench run_once_iai -- --save-baseline=master
cargo bench --bench run_cached_iai -- --save-baseline=master
cargo bench --bench update_executor_gungraun -- --save-baseline=master
cargo bench --bench run_once_gungraun -- --save-baseline=master
cargo bench --bench run_cached_gungraun -- --save-baseline=master
- name: Checkout PR branch
run: git checkout ${{ github.event.pull_request.head.sha }}
@@ -88,12 +75,12 @@ jobs:
- name: Run PR benchmarks
run: |
# Compile benchmarks
cargo bench --bench compile_demo_art_iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/compile_output.json
cargo bench --bench compile_demo_art_gungraun -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/compile_output.json
# Runtime benchmarks
cargo bench --bench update_executor_iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/update_output.json
cargo bench --bench run_once_iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/run_once_output.json
cargo bench --bench run_cached_iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/run_cached_output.json
cargo bench --bench update_executor_gungraun -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/update_output.json
cargo bench --bench run_once_gungraun -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/run_once_output.json
cargo bench --bench run_cached_gungraun -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/run_cached_output.json
- name: Make old comments collapsed by default
# Only run if we have write permissions (not a fork)
+1
View File
@@ -12,3 +12,4 @@ flamegraph.svg
.idea/
.direnv
.DS_Store
.nvim.lua
+1 -1
View File
@@ -29,7 +29,7 @@ pkgs.mkShell (
pkgs.lld
pkgs.nodejs
pkgs.binaryen
pkgs.wasm-bindgen-cli_0_2_100
pkgs.wasm-bindgen-cli_0_2_121
pkgs.wasm-pack
pkgs.cargo-about
+3 -3
View File
@@ -1,10 +1,10 @@
{ pkgs, ... }:
let
version = "147.0.10+gd58e84d+chromium-147.0.7727.118";
version = "147.0.14+g76d2442+chromium-147.0.7727.138";
hashes = {
aarch64-linux = "sha256-kaRijMDacPcoeCcS31zmRSNOvgozx+uq2M34mD28bu4=";
x86_64-linux = "sha256-CHzPofBDhCniDZEpOxXK4I7p57SYjMAY1HVo3Vna0e8=";
aarch64-linux = "sha256-Gy2Xs1NHwmIr+buzoqDso1QJVkKlA/UMXytHjNGqpNk=";
x86_64-linux = "sha256-os7wAFJ+mVK65HCikvEjhMeQUj2ty7y+6Ad0OlOcbeA=";
};
selectSystem =
+2 -5
View File
@@ -83,7 +83,7 @@ deps.crane.lib.buildPackage (
pkgs.lld
pkgs.nodejs
pkgs.binaryen
pkgs.wasm-bindgen-cli_0_2_100
pkgs.wasm-bindgen-cli_0_2_121
pkgs.wasm-pack
pkgs.cargo-about
pkgs.removeReferencesTo
@@ -134,10 +134,7 @@ deps.crane.lib.buildPackage (
cp target/${if dev then "debug" else "release"}/graphite $out/bin/graphite
mkdir -p $out/share/applications
cp $src/desktop/assets/art.graphite.Graphite.desktop $out/share/applications/
mkdir -p $out/share/mime/packages
cp $src/desktop/assets/art.graphite.Graphite.xml $out/share/mime/packages/
cp $src/desktop/assets/*.desktop $out/share/applications/
mkdir -p $out/share/icons/hicolor/scalable/apps
cp ${branding}/app-icons/graphite.svg $out/share/icons/hicolor/scalable/apps/art.graphite.Graphite.svg
Generated
+516 -434
View File
File diff suppressed because it is too large. Load diff
+18 -11
View File
@@ -7,6 +7,7 @@ members = [
"desktop/platform/linux",
"desktop/platform/mac",
"desktop/platform/win",
"document/container",
"editor",
"frontend/wrapper",
"libraries/dyn-any",
@@ -68,6 +69,7 @@ graphene-hash = { path = "node-graph/libraries/graphene-hash", features = ["deri
preprocessor = { path = "node-graph/preprocessor" }
math-parser = { path = "libraries/math-parser" }
graphene-application-io = { path = "node-graph/libraries/application-io" }
graphene-resource = { path = "node-graph/libraries/resources" }
core-types = { path = "node-graph/libraries/core-types" }
no-std-types = { path = "node-graph/libraries/no-std-types" }
raster-types = { path = "node-graph/libraries/raster-types" }
@@ -120,17 +122,17 @@ quote = "1.0"
chrono = "0.4"
ron = "0.12"
fastnoise-lite = "1.1"
wgpu = { version = "28.0", features = [
wgpu = { version = "29.0", features = [
# We don't have wgpu on multiple threads (yet) https://github.com/gfx-rs/wgpu/blob/trunk/CHANGELOG.md#wgpu-types-now-send-sync-on-wasm
"fragile-send-sync-non-atomic-wasm",
"spirv",
"strict_asserts",
] }
once_cell = "1.13" # Remove and replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>)
wasm-bindgen = "=0.2.100" # NOTICE: ensure this stays in sync with the `wasm-bindgen-cli` version in `website/content/volunteer/guide/project-setup/_index.md`. We pin this version because wasm-bindgen upgrades may break various things.
wasm-bindgen = "=0.2.121" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned across CI workflows, devcontainer, Nix, and the `cargo-run` tool. We pin this version because wasm-bindgen upgrades may break various things.
wasm-bindgen-futures = "0.4"
js-sys = "=0.3.77"
web-sys = { version = "=0.3.77", features = [
js-sys = "=0.3.98"
web-sys = { version = "=0.3.98", features = [
"Document",
"DomRect",
"Element",
@@ -154,12 +156,12 @@ url = "2.5"
tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-multi-thread"] }
# Linebender ecosystem (BEGIN)
kurbo = { version = "0.13", features = ["serde"] }
vello = "0.8"
vello_encoding = "0.8"
vello = "0.9"
vello_encoding = "0.9"
resvg = "0.47"
usvg = "0.47"
parley = "0.6"
skrifa = "0.40"
parley = { version = "0.9", default-features = false, features = ["std"] }
skrifa = "0.42"
polycool = "0.4"
color = "0.3"
# Linebender ecosystem (END)
@@ -171,6 +173,8 @@ glam = { version = "0.32.1", default-features = false, features = [
"bytemuck",
] }
base64 = "0.22"
blake3 = "1.5"
mmap-io = { version = "0.9", features = ["hugepages"] }
image = { version = "0.25", default-features = false, features = [
"png",
"jpeg",
@@ -199,12 +203,12 @@ petgraph = { version = "0.7", default-features = false, features = ["graphmap"]
half = { version = "2.4", default-features = false, features = ["bytemuck"] }
tinyvec = { version = "1", features = ["std"] }
criterion = { version = "0.7", features = ["html_reports"] }
iai-callgrind = { version = "0.16" }
gungraun = { version = "0.18" }
ndarray = "0.16"
strum = { version = "0.27", features = ["derive"] }
dirs = "6.0"
cef = "147"
cef-dll-sys = "147"
cef = "148"
cef-dll-sys = "148"
include_dir = "0.7"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tracing = "0.1"
@@ -219,6 +223,7 @@ lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "e
scraper = "0.25"
linesweeper = "0.3"
smallvec = "1.13.2"
zip = { version = "8", default-features = false }
[workspace.lints.rust]
unexpected_cfgs = { level = "allow", check-cfg = ['cfg(target_arch, values("spirv"))'] }
@@ -245,3 +250,5 @@ debug = true
# Force cargo to use only one version of the dpi crate (vendoring breaks without this)
dpi = { git = "https://github.com/rust-windowing/winit.git" }
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
cef = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite" }
cef-dll-sys = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite" }
+1 -1
View File
@@ -42,7 +42,7 @@ ignore = [
"RUSTSEC-2024-0388", # Unmaintained `derivative`, used directly by graphite-editor and graphite-desktop
"RUSTSEC-2024-0436", # Unmaintained `paste`, pulled in by dependencies `metal` and `wgpu-hal`
"RUSTSEC-2025-0134", # Unmaintained `rustls-pemfile`, pulled in by build dependency `download-cef`
"RUSTSEC-2025-0141", # Unmaintained `bincode`, pulled in by dev dependency `iai-callgrind`
"RUSTSEC-2025-0141", # Unmaintained `bincode`, pulled in by dev dependency `gungraun`
]
# Threshold for security vulnerabilities, any vulnerability with a CVSS score
# lower than the range specified will be ignored. Note that ignored advisories
+1 -2
View File
@@ -2,11 +2,10 @@
Name=Graphite
GenericName=Vector & Raster Graphics Editor
Comment=Open-source vector & raster graphics editor. Featuring node based procedural nondestructive editing workflow.
Exec=graphite %F
Exec=graphite
Terminal=false
Type=Application
Icon=art.graphite.Graphite
Categories=Graphics;VectorGraphics;RasterGraphics;
Keywords=graphite;editor;vector;raster;procedural;design;
StartupWMClass=art.graphite.Graphite
MimeType=application/graphite+json;image/svg+xml;image/png;image/jpeg;
-9
View File
@@ -1,9 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
<mime-type type="application/graphite+json">
<comment>Graphite Document</comment>
<sub-class-of type="application/json"/>
<glob pattern="*.graphite"/>
<icon name="art.graphite.Graphite"/>
</mime-type>
</mime-info>
-4
View File
@@ -14,7 +14,3 @@ cef-dll-sys = { workspace = true }
[target.'cfg(target_os = "macos")'.dependencies]
serde = { workspace = true }
plist = { version = "*" }
[target.'cfg(target_os = "windows")'.dependencies]
msi = "0.10"
cab = "0.6"
+15 -528
View File
@@ -1,574 +1,61 @@
use std::collections::{BTreeMap, BTreeSet};
use std::error::Error;
use std::fs;
use std::io::{Cursor, Write};
use std::path::{Path, PathBuf};
use cab::{CabinetBuilder, CompressionType};
use msi::{Column, Insert, Package, PackageType, Value};
use crate::common::*;
const EXECUTABLE: &str = "Graphite.exe";
const PRODUCT_VERSION: &str = "0.0.0";
const MANUFACTURER: &str = "Graphite Labs, LLC";
const UPGRADE_CODE: &str = "{8D42B6D4-B0E8-41BC-9F41-74F1E319BC1D}";
const PROG_ID: &str = "Graphite.Document";
const DOCUMENT_FRIENDLY_NAME: &str = "Graphite Document";
const FILE_EXTENSION: &str = ".graphite";
const MIME_TYPE: &str = "application/graphite+json";
const EXTRA_EXTENSIONS: &[&str] = &[".svg", ".png", ".jpg", ".jpeg"];
const CABINET_STREAM: &str = "Data1.cab";
pub fn main() -> Result<(), Box<dyn Error>> {
let app_bin = build_bin("graphite-desktop-platform-win", None)?;
let profile_path = profile_path();
let bundle_dir = bundle(&profile_path, &app_bin);
let msi_path = create_msi(&bundle_dir, &profile_path)?;
let executable = bundle(&profile_path(), &app_bin);
// TODO: Consider adding more useful cli
let args: Vec<String> = std::env::args().collect();
if let Some(pos) = args.iter().position(|a| a == "open") {
let executable = bundle_dir.join(EXECUTABLE);
let extra_args: Vec<&str> = args[pos + 1..].iter().map(|s| s.as_str()).collect();
run_command(&executable.to_string_lossy(), &extra_args)?;
} else {
println!("MSI created at: {}", msi_path.display());
run_command(&executable.to_string_lossy(), &extra_args).expect("failed to open app")
}
Ok(())
}
fn bundle(out_dir: &Path, app_bin: &Path) -> PathBuf {
let app_dir = out_dir.join(APP_NAME);
clean_dir(&app_dir);
copy_dir(&cef_path(), &app_dir);
if let Err(e) = remove_unnecessary_cef_files(&app_dir) {
eprintln!("Failed to remove unnecessary CEF files: {}", e);
}
fs::copy(app_bin, app_dir.join(EXECUTABLE)).unwrap();
app_dir
let bin_path = app_dir.join(EXECUTABLE);
fs::copy(app_bin, &bin_path).unwrap();
bin_path
}
fn remove_unnecessary_cef_files(app_dir: &Path) -> Result<(), Box<dyn Error>> {
fs::remove_dir_all(app_dir.join("cmake"))?;
fs::remove_dir_all(app_dir.join("include"))?;
fs::remove_dir_all(app_dir.join("libcef_dll"))?;
for entry in fs::read_dir(app_dir.join("locales"))? {
let path = entry?.path();
if path.is_file() && path.file_name() != Some("en-US.pak".as_ref()) {
fs::remove_file(path)?;
}
}
fs::remove_file(app_dir.join("archive.json"))?;
fs::remove_file(app_dir.join("CMakeLists.txt"))?;
fs::remove_file(app_dir.join("bootstrapc.exe"))?;
fs::remove_file(app_dir.join("bootstrap.exe"))?;
fs::remove_file(app_dir.join("libcef.lib"))?;
fs::remove_file(app_dir.join("CREDITS.html"))?;
Ok(())
}
struct AppFile {
abs_path: PathBuf,
file_id: String,
msi_filename: String,
component_id: String,
sequence: u32,
size: u64,
}
struct AppDirectory {
dir_id: String,
parent_id: Option<String>,
default_dir: String,
}
struct AppComponent {
component_id: String,
component_guid: String,
dir_id: String,
key_file_id: String,
}
struct Entries {
files: Vec<AppFile>,
directories: Vec<AppDirectory>,
components: Vec<AppComponent>,
}
fn product_code() -> String {
let commit = std::process::Command::new("git")
.args(["rev-parse", "HEAD"])
.output()
.ok()
.and_then(|o| String::from_utf8(o.stdout).ok())
.map(|s| s.trim().to_ascii_uppercase())
.filter(|s| s.len() >= 32)
.unwrap_or_else(|| "0".repeat(32));
format!("{{{}-{}-{}-{}-{}}}", &commit[..8], &commit[8..12], &commit[12..16], &commit[16..20], &commit[20..32],)
}
fn fnv1a(s: &str) -> u64 {
s.bytes().fold(14695981039346656037u64, |h, b| (h ^ b as u64).wrapping_mul(1099511628211))
}
fn component_guid(seed: &str) -> String {
let h1 = fnv1a(seed);
let h2 = fnv1a(&format!("{seed}_2"));
format!(
"{{{:08X}-{:04X}-{:04X}-{:04X}-{:012X}}}",
(h1 >> 32) as u32,
((h1 >> 16) & 0xFFFF) as u16,
(h1 & 0xFFFF) as u16,
((h2 >> 48) & 0xFFFF) as u16,
h2 & 0x0000_FFFF_FFFF_FFFF,
)
}
fn msi_filename(name: &str) -> String {
let dot = name.rfind('.');
let (base, ext) = dot.map(|i| (&name[..i], &name[i + 1..])).unwrap_or((name, ""));
if base.len() <= 8 && ext.len() <= 3 {
return name.to_string();
}
let short_base: String = base.chars().filter(|c| c.is_ascii_alphanumeric()).take(6).map(|c| c.to_ascii_uppercase()).collect();
let short_ext: String = ext.chars().filter(|c| c.is_ascii_alphanumeric()).take(3).map(|c| c.to_ascii_uppercase()).collect();
if short_ext.is_empty() {
format!("{short_base}~1|{name}")
} else {
format!("{short_base}~1.{short_ext}|{name}")
}
}
fn collect_entries(bundle_dir: &Path) -> Result<Entries, Box<dyn Error>> {
let mut raw_files: Vec<(PathBuf, PathBuf)> = Vec::new();
gather_files(bundle_dir, bundle_dir, &mut raw_files)?;
let mut all_dir_strs: BTreeSet<String> = BTreeSet::new();
all_dir_strs.insert(String::new());
for (_, rel) in &raw_files {
let mut path = rel.parent().unwrap_or(Path::new("")).to_owned();
loop {
let s = path.to_string_lossy().replace('\\', "/");
if s.is_empty() {
break;
}
all_dir_strs.insert(s);
match path.parent().filter(|p| !p.as_os_str().is_empty()) {
Some(p) => path = p.to_owned(),
None => break,
}
}
}
let mut dir_to_ids: BTreeMap<String, (String, String)> = BTreeMap::new();
for dir_str in &all_dir_strs {
let h = fnv1a(dir_str);
let dir_id = if dir_str.is_empty() { "INSTALLDIR".to_string() } else { format!("DIR_{h:016X}") };
let comp_id = format!("COMP_{h:016X}");
dir_to_ids.insert(dir_str.clone(), (dir_id, comp_id));
}
let mut directories = vec![
AppDirectory {
dir_id: "TARGETDIR".into(),
parent_id: None,
default_dir: "SourceDir".into(),
},
AppDirectory {
dir_id: "ProgramFiles64Folder".into(),
parent_id: Some("TARGETDIR".into()),
default_dir: ".".into(),
},
AppDirectory {
dir_id: "INSTALLDIR".into(),
parent_id: Some("ProgramFiles64Folder".into()),
default_dir: APP_NAME.into(),
},
];
let mut subdir_strs: Vec<&str> = all_dir_strs.iter().filter(|s| !s.is_empty()).map(String::as_str).collect();
subdir_strs.sort_by_key(|s| s.len());
for dir_str in subdir_strs {
let (dir_id, _) = &dir_to_ids[dir_str];
let path = Path::new(dir_str);
let parent_str = path.parent().filter(|p| !p.as_os_str().is_empty()).map(|p| p.to_string_lossy().replace('\\', "/")).unwrap_or_default();
let parent_id = dir_to_ids.get(parent_str.as_str()).map(|(id, _)| id.clone()).unwrap_or_else(|| "INSTALLDIR".into());
let name = path.file_name().unwrap_or_default().to_string_lossy().into_owned();
directories.push(AppDirectory {
dir_id: dir_id.clone(),
parent_id: Some(parent_id),
default_dir: name,
});
}
let mut comp_key_files: BTreeMap<String, String> = BTreeMap::new();
let mut file_dir_strs: BTreeSet<String> = BTreeSet::new();
let mut files = Vec::new();
let mut seq = 1u32;
for (abs_path, rel_path) in &raw_files {
let dir_str = rel_path.parent().unwrap_or(Path::new("")).to_string_lossy().replace('\\', "/");
let (dir_id, comp_id) = dir_to_ids[dir_str.as_str()].clone();
file_dir_strs.insert(dir_str.clone());
let h = fnv1a(&rel_path.to_string_lossy().replace('\\', "/"));
let file_id = format!("FILE_{h:016X}");
let filename = msi_filename(rel_path.file_name().unwrap_or_default().to_str().unwrap_or_default());
let size = fs::metadata(abs_path)?.len();
comp_key_files.entry(comp_id.clone()).or_insert_with(|| file_id.clone());
files.push(AppFile {
abs_path: abs_path.clone(),
file_id,
msi_filename: filename,
component_id: comp_id,
sequence: seq,
size,
});
seq += 1;
}
let components: Vec<AppComponent> = file_dir_strs
.iter()
.filter_map(|dir_str| {
let (dir_id, comp_id) = dir_to_ids.get(dir_str.as_str())?;
let key_file_id = comp_key_files.get(comp_id)?.clone();
Some(AppComponent {
component_id: comp_id.clone(),
component_guid: component_guid(dir_str),
dir_id: dir_id.clone(),
key_file_id,
})
})
.collect();
Ok(Entries { files, directories, components })
}
fn gather_files(base: &Path, dir: &Path, out: &mut Vec<(PathBuf, PathBuf)>) -> std::io::Result<()> {
let mut entries: Vec<_> = fs::read_dir(dir)?.collect::<Result<_, _>>()?;
entries.sort_by_key(|e| e.file_name());
for entry in entries {
let path = entry.path();
if path.is_dir() {
gather_files(base, &path, out)?;
} else {
let rel = path.strip_prefix(base).unwrap().to_path_buf();
out.push((path, rel));
}
}
Ok(())
}
fn build_cabinet(files: &[AppFile]) -> Result<Vec<u8>, Box<dyn Error>> {
let mut builder = CabinetBuilder::new();
{
let folder = builder.add_folder(CompressionType::MSZIP);
for file in files {
folder.add_file(file.file_id.as_str());
}
}
let mut writer = builder.build(Cursor::new(Vec::new()))?;
let mut iter = files.iter();
while let Some(mut fw) = writer.next_file()? {
let file = iter.next().expect("cabinet/file count mismatch");
fw.write_all(&fs::read(&file.abs_path)?)?;
}
Ok(writer.finish()?.into_inner())
}
fn create_msi(bundle_dir: &Path, out_dir: &Path) -> Result<PathBuf, Box<dyn Error>> {
let entries = collect_entries(bundle_dir)?;
let cabinet_bytes = build_cabinet(&entries.files)?;
let msi_path = out_dir.join("Graphite.msi");
let mut pkg = Package::create(PackageType::Installer, fs::File::create(&msi_path)?)?;
{
let info = pkg.summary_info_mut();
info.set_title("Graphite Installation Database");
info.set_subject(APP_NAME);
info.set_author(MANUFACTURER);
info.set_creating_application("graphite-desktop-bundle");
info.set_arch("x64");
}
define_tables(&mut pkg)?;
populate_properties(&mut pkg)?;
populate_directories(&mut pkg, &entries.directories)?;
populate_components(&mut pkg, &entries.components)?;
populate_features(&mut pkg)?;
populate_feature_components(&mut pkg, &entries.components)?;
populate_files(&mut pkg, &entries.files)?;
populate_media(&mut pkg, entries.files.len() as u32)?;
populate_registry(&mut pkg, &entries.components)?;
populate_sequences(&mut pkg)?;
{
let mut stream = pkg.write_stream(CABINET_STREAM)?;
stream.write_all(&cabinet_bytes)?;
}
pkg.flush()?;
Ok(msi_path)
}
fn define_tables(pkg: &mut Package<fs::File>) -> Result<(), Box<dyn Error>> {
pkg.create_table("Property", vec![Column::build("Property").primary_key().id_string(72), Column::build("Value").text_string(0)])?;
pkg.create_table(
"Directory",
vec![
Column::build("Directory").primary_key().id_string(72),
Column::build("Directory_Parent").nullable().id_string(72),
Column::build("DefaultDir").string(255),
],
)?;
pkg.create_table(
"Component",
vec![
Column::build("Component").primary_key().id_string(72),
Column::build("ComponentId").nullable().string(38),
Column::build("Directory_").id_string(72),
Column::build("Attributes").int16(),
Column::build("Condition").nullable().text_string(255),
Column::build("KeyPath").nullable().id_string(72),
],
)?;
pkg.create_table(
"Feature",
vec![
Column::build("Feature").primary_key().id_string(38),
Column::build("Feature_Parent").nullable().id_string(38),
Column::build("Title").nullable().text_string(64),
Column::build("Description").nullable().text_string(255),
Column::build("Display").nullable().int16(),
Column::build("Level").int16(),
Column::build("Directory_").nullable().id_string(72),
Column::build("Attributes").int16(),
],
)?;
pkg.create_table(
"FeatureComponents",
vec![Column::build("Feature_").primary_key().id_string(38), Column::build("Component_").primary_key().id_string(72)],
)?;
pkg.create_table(
"File",
vec![
Column::build("File").primary_key().id_string(72),
Column::build("Component_").id_string(72),
Column::build("FileName").string(255),
Column::build("FileSize").int32(),
Column::build("Version").nullable().string(72),
Column::build("Language").nullable().string(20),
Column::build("Attributes").nullable().int16(),
Column::build("Sequence").int32(),
],
)?;
pkg.create_table(
"Media",
vec![
Column::build("DiskId").primary_key().int16(),
Column::build("LastSequence").int32(),
Column::build("DiskPrompt").nullable().text_string(64),
Column::build("Cabinet").nullable().string(255),
Column::build("VolumeLabel").nullable().string(32),
Column::build("Source").nullable().string(72),
],
)?;
pkg.create_table(
"Registry",
vec![
Column::build("Registry").primary_key().id_string(72),
Column::build("Root").int16(),
Column::build("Key").formatted_string(255),
Column::build("Name").nullable().formatted_string(255),
Column::build("Value").nullable().formatted_string(0),
Column::build("Component_").id_string(72),
],
)?;
pkg.create_table(
"InstallExecuteSequence",
vec![
Column::build("Action").primary_key().id_string(72),
Column::build("Condition").nullable().text_string(255),
Column::build("Sequence").int16(),
],
)?;
pkg.create_table(
"InstallUISequence",
vec![
Column::build("Action").primary_key().id_string(72),
Column::build("Condition").nullable().text_string(255),
Column::build("Sequence").int16(),
],
)?;
Ok(())
}
fn populate_properties(pkg: &mut Package<fs::File>) -> Result<(), Box<dyn Error>> {
pkg.insert_rows(Insert::into("Property").rows(vec![
vec![Value::from("ProductName"), Value::from(APP_NAME)],
vec![Value::from("ProductCode"), Value::from(product_code())],
vec![Value::from("ProductVersion"), Value::from(PRODUCT_VERSION)],
vec![Value::from("Manufacturer"), Value::from(MANUFACTURER)],
vec![Value::from("UpgradeCode"), Value::from(UPGRADE_CODE)],
vec![Value::from("INSTALLLEVEL"), Value::from("1")],
]))?;
Ok(())
}
fn populate_directories(pkg: &mut Package<fs::File>, dirs: &[AppDirectory]) -> Result<(), Box<dyn Error>> {
let rows: Vec<Vec<Value>> = dirs
.iter()
.map(|d| {
vec![
Value::from(d.dir_id.as_str()),
d.parent_id.as_deref().map(Value::from).unwrap_or(Value::Null),
Value::from(d.default_dir.as_str()),
]
})
.collect();
pkg.insert_rows(Insert::into("Directory").rows(rows))?;
Ok(())
}
fn populate_components(pkg: &mut Package<fs::File>, components: &[AppComponent]) -> Result<(), Box<dyn Error>> {
let rows: Vec<Vec<Value>> = components
.iter()
.map(|c| {
vec![
Value::from(c.component_id.as_str()),
Value::from(c.component_guid.as_str()),
Value::from(c.dir_id.as_str()),
Value::from(0i16),
Value::Null,
Value::from(c.key_file_id.as_str()),
]
})
.collect();
pkg.insert_rows(Insert::into("Component").rows(rows))?;
Ok(())
}
fn populate_features(pkg: &mut Package<fs::File>) -> Result<(), Box<dyn Error>> {
pkg.insert_rows(Insert::into("Feature").row(vec![
Value::from("ProductFeature"),
Value::Null,
Value::from(APP_NAME),
Value::from("Graphite Vector Editor"),
Value::from(1i16),
Value::from(1i16),
Value::from("INSTALLDIR"),
Value::from(0i16),
]))?;
Ok(())
}
fn populate_feature_components(pkg: &mut Package<fs::File>, components: &[AppComponent]) -> Result<(), Box<dyn Error>> {
let rows: Vec<Vec<Value>> = components.iter().map(|c| vec![Value::from("ProductFeature"), Value::from(c.component_id.as_str())]).collect();
pkg.insert_rows(Insert::into("FeatureComponents").rows(rows))?;
Ok(())
}
fn populate_files(pkg: &mut Package<fs::File>, files: &[AppFile]) -> Result<(), Box<dyn Error>> {
let rows: Vec<Vec<Value>> = files
.iter()
.map(|f| {
vec![
Value::from(f.file_id.as_str()),
Value::from(f.component_id.as_str()),
Value::from(f.msi_filename.as_str()),
Value::Int(f.size as i32),
Value::Null,
Value::Null,
Value::Null,
Value::Int(f.sequence as i32),
]
})
.collect();
pkg.insert_rows(Insert::into("File").rows(rows))?;
Ok(())
}
fn populate_media(pkg: &mut Package<fs::File>, last_sequence: u32) -> Result<(), Box<dyn Error>> {
pkg.insert_rows(Insert::into("Media").row(vec![
Value::from(1i16),
Value::Int(last_sequence as i32),
Value::Null,
Value::from(format!("#{CABINET_STREAM}")),
Value::Null,
Value::Null,
]))?;
Ok(())
}
fn populate_registry(pkg: &mut Package<fs::File>, components: &[AppComponent]) -> Result<(), Box<dyn Error>> {
let root_comp = components
.iter()
.find(|c| c.dir_id == "INSTALLDIR")
.map(|c| c.component_id.as_str())
.unwrap_or_else(|| components.first().map(|c| c.component_id.as_str()).unwrap_or(""));
let exe = format!("[INSTALLDIR]{EXECUTABLE}");
let open_cmd = format!("\"[INSTALLDIR]{EXECUTABLE}\" \"%1\"");
let mut rows: Vec<Vec<Value>> = vec![
reg("reg_progid", PROG_ID, None, Some(DOCUMENT_FRIENDLY_NAME), root_comp),
reg("reg_progid_icon", &format!("{PROG_ID}\\DefaultIcon"), None, Some(&format!("{exe},0")), root_comp),
reg("reg_progid_cmd", &format!("{PROG_ID}\\shell\\open\\command"), None, Some(&open_cmd), root_comp),
reg("reg_ext", FILE_EXTENSION, None, Some(PROG_ID), root_comp),
reg("reg_ext_mime", FILE_EXTENSION, Some("Content Type"), Some(MIME_TYPE), root_comp),
reg("reg_app_name", &format!("Applications\\{EXECUTABLE}"), Some("FriendlyAppName"), Some(APP_NAME), root_comp),
reg("reg_app_cmd", &format!("Applications\\{EXECUTABLE}\\shell\\open\\command"), None, Some(&open_cmd), root_comp),
reg("reg_app_ext", &format!("Applications\\{EXECUTABLE}\\SupportedTypes"), Some(FILE_EXTENSION), Some(""), root_comp),
];
for (i, ext) in EXTRA_EXTENSIONS.iter().enumerate() {
rows.push(reg(&format!("reg_app_ext_{i}"), &format!("Applications\\{EXECUTABLE}\\SupportedTypes"), Some(ext), Some(""), root_comp));
}
pkg.insert_rows(Insert::into("Registry").rows(rows))?;
Ok(())
}
fn reg(id: &str, key: &str, name: Option<&str>, value: Option<&str>, comp: &str) -> Vec<Value> {
vec![
Value::from(id),
Value::from(0i16),
Value::from(key),
name.map(Value::from).unwrap_or(Value::Null),
value.map(Value::from).unwrap_or(Value::Null),
Value::from(comp),
]
}
fn populate_sequences(pkg: &mut Package<fs::File>) -> Result<(), Box<dyn Error>> {
pkg.insert_rows(Insert::into("InstallExecuteSequence").rows(vec![
seq("CostInitialize", 800),
seq("FileCost", 900),
seq("CostFinalize", 1000),
seq("InstallValidate", 1400),
seq("InstallInitialize", 1500),
seq("ProcessComponents", 1600),
seq("UnpublishComponents", 1700),
seq("UnpublishFeatures", 1800),
seq("RemoveRegistryValues", 2600),
seq("RemoveFiles", 3500),
seq("InstallFiles", 4000),
seq("WriteRegistryValues", 5000),
seq("RegisterUser", 6000),
seq("RegisterProduct", 6100),
seq("PublishComponents", 6200),
seq("PublishFeatures", 6300),
seq("PublishProduct", 6400),
seq("InstallFinalize", 6600),
]))?;
pkg.insert_rows(Insert::into("InstallUISequence").rows(vec![seq("CostInitialize", 800), seq("FileCost", 900), seq("CostFinalize", 1000), seq("ExecuteAction", 1300)]))?;
Ok(())
}
fn seq(action: &str, sequence: i16) -> Vec<Value> {
vec![Value::from(action), Value::Null, Value::from(sequence)]
}
-1
View File
@@ -1,5 +1,4 @@
#![windows_subsystem = "windows"]
fn main() {
graphite_desktop::start();
}
+12 -10
View File
@@ -16,13 +16,14 @@ use winit::window::WindowId;
use crate::cef;
use crate::consts::CEF_MESSAGE_LOOP_MAX_ITERATIONS;
use crate::dirs;
use crate::event::{AppEvent, AppEventScheduler};
use crate::persist;
use crate::preferences;
use crate::render::{RenderError, RenderState};
use crate::window::Window;
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, InputMessage, MouseKeys, MouseState, Preferences};
use crate::wrapper::{DesktopWrapper, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
pub(crate) struct App {
render_state: Option<RenderState>,
@@ -91,7 +92,14 @@ impl App {
}
});
let desktop_wrapper = DesktopWrapper::new(rand::rng().random());
let resource_storage = MmapResourceStorage::new(dirs::app_resources_dir()).expect("Failed to initialize on-disk resource storage");
// Wake the winit event loop when an editor future completes.
let wake_scheduler = app_event_scheduler.clone();
let wake = Arc::new(move || {
wake_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Wake));
});
let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), wgpu_context.clone(), wake);
Self {
render_state: None,
@@ -526,8 +534,6 @@ impl ApplicationHandler for App {
self.resize();
self.desktop_wrapper.init(self.wgpu_context.clone());
self.startup_time = Some(Instant::now());
}
@@ -582,14 +588,10 @@ impl ApplicationHandler for App {
Err(RenderError::OutdatedUITextureError) => {
self.cef_context.notify_view_info_changed();
}
Err(RenderError::SurfaceError(wgpu::SurfaceError::Lost)) => {
Err(RenderError::SurfaceLost) => {
tracing::warn!("lost surface");
}
Err(RenderError::SurfaceError(wgpu::SurfaceError::OutOfMemory)) => {
tracing::error!("GPU out of memory");
self.exit(None);
}
Err(RenderError::SurfaceError(e)) => tracing::error!("Render error: {:?}", e),
Err(other) => tracing::error!("Render error: {:?}", other),
}
let _ = self.start_render_sender.try_send(());
}
+1
View File
@@ -11,6 +11,7 @@ pub(crate) const APP_SOCKET_FILE_NAME: &str = "instance.sock";
pub(crate) const APP_STATE_FILE_NAME: &str = "state.ron";
pub(crate) const APP_PREFERENCES_FILE_NAME: &str = "preferences.ron";
pub(crate) const APP_DOCUMENTS_DIRECTORY_NAME: &str = "documents";
pub(crate) const APP_RESOURCES_DIRECTORY_NAME: &str = "resources";
// CEF configuration constants
pub(crate) const CEF_WINDOWLESS_FRAME_RATE: i32 = 60;
+7 -1
View File
@@ -2,7 +2,7 @@ use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use crate::consts::{APP_DIRECTORY_NAME, APP_DOCUMENTS_DIRECTORY_NAME};
use crate::consts::{APP_DIRECTORY_NAME, APP_DOCUMENTS_DIRECTORY_NAME, APP_RESOURCES_DIRECTORY_NAME};
pub(crate) fn ensure_dir_exists(path: &PathBuf) {
if !path.exists() {
@@ -51,6 +51,12 @@ pub(crate) fn app_autosave_documents_dir() -> PathBuf {
path
}
pub(crate) fn app_resources_dir() -> PathBuf {
let path = app_data_dir().join(APP_RESOURCES_DIRECTORY_NAME);
ensure_dir_exists(&path);
path
}
/// Temporary directory that is automatically deleted when dropped.
pub struct TempDir {
path: PathBuf,
+21 -3
View File
@@ -120,7 +120,7 @@ impl RenderState {
let render_pipeline_layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Render Pipeline Layout"),
bind_group_layouts: &[&texture_bind_group_layout],
bind_group_layouts: &[Some(&texture_bind_group_layout)],
immediate_size: size_of::<Immediates>() as u32,
});
@@ -262,7 +262,17 @@ impl RenderState {
self.render_overlays(scene);
}
let output = self.surface.get_current_texture().map_err(RenderError::SurfaceError)?;
let (output, suboptimal) = match self.surface.get_current_texture() {
wgpu::CurrentSurfaceTexture::Success(t) => (t, false),
// wgpu reports the swapchain no longer matches the underlying surface; present this frame and reconfigure after present, since `Surface::configure` panics while an acquired `SurfaceTexture` is still alive
wgpu::CurrentSurfaceTexture::Suboptimal(t) => (t, true),
// Window is minimized or behind another window: skip the frame silently and try again once it becomes visible
wgpu::CurrentSurfaceTexture::Occluded => return Ok(()),
wgpu::CurrentSurfaceTexture::Lost => return Err(RenderError::SurfaceLost),
wgpu::CurrentSurfaceTexture::Outdated => return Err(RenderError::SurfaceOutdated),
wgpu::CurrentSurfaceTexture::Timeout => return Err(RenderError::SurfaceTimeout),
wgpu::CurrentSurfaceTexture::Validation => return Err(RenderError::SurfaceValidation),
};
let view = output.texture.create_view(&wgpu::TextureViewDescriptor::default());
@@ -308,6 +318,10 @@ impl RenderState {
window.pre_present_notify();
output.present();
if suboptimal {
self.surface.configure(&self.context.device, &self.config);
}
if ui_scale.is_some() {
return Err(RenderError::OutdatedUITextureError);
}
@@ -349,9 +363,13 @@ impl RenderState {
}
}
#[derive(Debug)]
pub(crate) enum RenderError {
OutdatedUITextureError,
SurfaceError(wgpu::SurfaceError),
SurfaceLost,
SurfaceOutdated,
SurfaceTimeout,
SurfaceValidation,
}
#[repr(C)]
-1
View File
@@ -20,7 +20,6 @@ wgpu-executor = { workspace = true }
wgpu = { workspace = true }
thiserror = { workspace = true }
futures = { workspace = true }
tracing = { workspace = true }
dirs = { workspace = true }
ron = { workspace = true}
@@ -9,6 +9,9 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
DesktopWrapperMessage::FromWeb(message) => {
dispatcher.queue_editor_message(*message);
}
DesktopWrapperMessage::Wake => {
dispatcher.queue_editor_message(EditorMessage::Future(FutureMessage::Wake));
}
DesktopWrapperMessage::Input(message) => {
dispatcher.queue_editor_message(EditorMessage::InputPreprocessor(message));
}
+7 -8
View File
@@ -1,9 +1,12 @@
use graph_craft::application_io::PlatformApplicationIo;
use graph_craft::application_io::resource::ResourceStorage;
use graphite_editor::application::{Editor, Environment, Host, Platform};
use graphite_editor::messages::prelude::{FrontendMessage, Message};
use graphite_editor::messages::prelude::{FrontendMessage, Message, Wake};
use message_dispatcher::DesktopWrapperMessageDispatcher;
use messages::{DesktopFrontendMessage, DesktopWrapperMessage};
use std::sync::Arc;
pub use graph_craft::application_io::resource::MmapResourceStorage;
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
pub use wgpu_executor::WgpuContext;
pub use wgpu_executor::WgpuContextBuilder;
@@ -22,7 +25,7 @@ pub struct DesktopWrapper {
}
impl DesktopWrapper {
pub fn new(uuid_random_seed: u64) -> Self {
pub fn new(uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self {
#[cfg(target_os = "windows")]
let host = Host::Windows;
#[cfg(target_os = "macos")]
@@ -30,17 +33,13 @@ impl DesktopWrapper {
#[cfg(target_os = "linux")]
let host = Host::Linux;
let env = Environment { platform: Platform::Desktop, host };
let application_io = PlatformApplicationIo::new_with_context(wgpu_context);
Self {
editor: Editor::new(env, uuid_random_seed),
editor: Editor::new(env, uuid_random_seed, resource_storage, application_io, schedule_wake),
}
}
pub fn init(&self, wgpu_context: WgpuContext) {
let application_io = PlatformApplicationIo::new_with_context(wgpu_context);
futures::executor::block_on(graphite_editor::node_graph_executor::replace_application_io(application_io));
}
pub fn dispatch(&mut self, message: DesktopWrapperMessage) -> Vec<DesktopFrontendMessage> {
let mut executor = DesktopWrapperMessageDispatcher::new(&mut self.editor);
executor.queue_desktop_wrapper_message(message);
+1
View File
@@ -82,6 +82,7 @@ pub enum DesktopFrontendMessage {
pub enum DesktopWrapperMessage {
FromWeb(Box<EditorMessage>),
Wake,
Input(InputMessage),
FileDialogResult { path: PathBuf, content: Vec<u8>, context: OpenFileDialogContext },
SaveFileDialogResult { path: PathBuf, context: SaveFileDialogContext },
+48
View File
@@ -0,0 +1,48 @@
[package]
name = "document-container"
description = "Container abstraction for the on-disk side of the .gdd document format"
edition.workspace = true
version.workspace = true
license.workspace = true
authors.workspace = true
[features]
default = []
zip = ["dep:zip"]
xz = ["dep:lzma-rust2", "dep:tar"]
[dependencies]
thiserror = "2.0"
log = { workspace = true }
zip = { workspace = true, optional = true, features = ["deflate-flate2-zlib-rs"], default-features = false}
lzma-rust2 = { workspace = true, optional = true }
tar = { version = "0.4", optional = true, default-features = false }
[target.'cfg(not(target_family = "wasm"))'.dependencies]
mmap-io = { workspace = true }
[target.'cfg(target_family = "wasm")'.dependencies]
web-sys = { workspace = true, features = [
"Navigator",
"DomException",
"Window",
"StorageManager",
"FileSystemCreateWritableOptions",
"FileSystemDirectoryHandle",
"FileSystemFileHandle",
"FileSystemGetFileOptions",
"FileSystemGetDirectoryOptions",
"FileSystemHandle",
"FileSystemHandleKind",
"FileSystemWritableFileStream",
"WritableStream",
"Blob",
] }
js-sys = { workspace = true }
wasm-bindgen = { workspace = true }
wasm-bindgen-futures = { workspace = true }
futures = { workspace = true }
[dev-dependencies]
tempfile = "3"
futures = { workspace = true }
+97
View File
@@ -0,0 +1,97 @@
//! Archive codecs (zip, xz).
//!
//! Each codec streams entries in both directions: writers wrap an `io::Write` sink, and
//! `deserialize` reads from any `io::Read + Seek` source and streams entries into any [`Container`].
#[cfg(any(feature = "zip", feature = "xz"))]
use crate::ContainerError;
use crate::{Container, Result};
use std::io::{Read, Seek, Write};
/// Hard cap on the total decompressed size a codec will materialize from one archive.
/// Defends against decompression bombs at the cost of refusing legitimately huge archives.
#[cfg(any(feature = "zip", feature = "xz"))]
pub(crate) const MAX_DECOMPRESSED_SIZE: u64 = 4 * 1024 * 1024 * 1024; // 4GB
/// Fold one entry's declared `size` into the running `total` and return it as a `usize` for `write_sized`.
/// Both codecs route entries through here so the decompression-bomb cap and 32-bit-safe conversion live in
/// one place. `write_sized` pre-allocates the declared size, so an over-large one is rejected before that.
#[cfg(any(feature = "zip", feature = "xz"))]
pub(crate) fn checked_entry_size(total: &mut u64, size: u64) -> Result<usize> {
*total = total.saturating_add(size);
if *total > MAX_DECOMPRESSED_SIZE {
return Err(ContainerError::SizeLimitExceeded {
declared: *total,
limit: MAX_DECOMPRESSED_SIZE,
});
}
// `usize` is 32-bit on wasm, so convert fallibly to rule out a silent truncation into a smaller allocation.
usize::try_from(size).map_err(|_| ContainerError::SizeLimitExceeded {
declared: size,
limit: usize::MAX as u64,
})
}
#[cfg(feature = "zip")]
mod zip;
#[cfg(feature = "zip")]
pub use zip::{Zip, ZipWriter};
#[cfg(feature = "xz")]
mod xz;
#[cfg(feature = "xz")]
pub use xz::{Xz, XzWriter};
/// Streaming archive codec. The associated `Writer` type wraps a `Write + Seek` sink (zip needs
/// `Seek` for the central directory; xz doesn't but `Seek` is free on file-like sinks) and
/// accepts entries one at a time. `finish` flushes the codec's trailer and consumes the wrapper.
pub trait Archive {
type Writer<W: Write + Seek>: ArchiveWriter
where
W: Write + Seek;
fn writer<W: Write + Seek>(output: W) -> Result<Self::Writer<W>>;
/// Read entries from `source` and write each into `dest`, streaming so neither the full
/// archive nor the full container ever sits in memory at once.
fn open<R: Read + Seek, C: Container>(source: R, dest: &mut C) -> Result<()>;
}
pub trait ArchiveWriter {
fn write_entry(&mut self, path: &str, bytes: &[u8]) -> Result<()>;
fn finish(self) -> Result<()>;
}
/// Archive container formats distinguishable by their leading magic bytes.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ArchiveFormat {
Xz,
Zip,
}
impl ArchiveFormat {
/// Sniff the format from the leading magic bytes: xz streams start with `FD 37 7A 58 5A 00`,
/// zip archives with `50 4B 03 04` (`PK\x03\x04`). Returns `None` for anything else.
pub fn detect(bytes: &[u8]) -> Option<Self> {
if bytes.starts_with(&[0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00]) {
Some(Self::Xz)
} else if bytes.starts_with(&[0x50, 0x4B, 0x03, 0x04]) {
Some(Self::Zip)
} else {
None
}
}
}
/// Deserialize an archive into `dest`, auto-detecting the format from `bytes`' magic header.
/// Errors if the bytes are neither a recognized xz nor zip archive.
#[cfg(all(feature = "xz", feature = "zip"))]
pub fn open_auto<C: Container>(bytes: &[u8], dest: &mut C) -> Result<()> {
let source = std::io::Cursor::new(bytes);
match ArchiveFormat::detect(bytes) {
Some(ArchiveFormat::Xz) => Xz::open(source, dest),
Some(ArchiveFormat::Zip) => Zip::open(source, dest),
None => Err(ContainerError::Codec("unrecognized archive format (not xz or zip)".into())),
}
}
+97
View File
@@ -0,0 +1,97 @@
//! Xz-compressed tarball archive codec.
use crate::archive::{Archive, ArchiveWriter, MAX_DECOMPRESSED_SIZE, checked_entry_size};
use crate::{Container, ContainerError, Result, validate_path};
use lzma_rust2::{XzOptions, XzReader, XzWriter as InnerXzWriter};
use std::io::{Read, Seek, Write};
pub struct Xz;
/// xz-tar writer. Held as an `Option` so `finish` can take ownership and unwind the layered
/// writers in the right order: drop the tar builder first to flush its trailer, then finish xz.
pub struct XzWriter<W: Write + Seek> {
tar: Option<tar::Builder<InnerXzWriter<W>>>,
}
impl Archive for Xz {
type Writer<W: Write + Seek> = XzWriter<W>;
fn writer<W: Write + Seek>(output: W) -> Result<Self::Writer<W>> {
let xz_writer = InnerXzWriter::new(output, XzOptions::default()).map_err(lzma_err)?;
Ok(XzWriter {
tar: Some(tar::Builder::new(xz_writer)),
})
}
fn open<R: Read + Seek, C: Container>(source: R, dest: &mut C) -> Result<()> {
// `take` bounds how many bytes we decompress from the xz stream, but each tar entry's declared
// size is fed to `write_sized`, which pre-allocates from it before reading. Cap the cumulative
// declared size too so a header claiming a huge size can't trigger a giant allocation up front.
let xz_reader = XzReader::new(source, false);
let bounded = xz_reader.take(MAX_DECOMPRESSED_SIZE);
let mut tar_reader = tar::Archive::new(bounded);
let mut total_size = 0u64;
for entry in tar_reader.entries()? {
let mut entry = entry?;
if entry.header().entry_type() != tar::EntryType::Regular {
continue;
}
// Reject non-UTF8 entry names rather than lossily rewriting them, so the path we store matches
// the archive exactly.
let path = entry.path()?;
let path = path.to_str().ok_or_else(|| ContainerError::Codec(format!("tar: non-UTF8 entry name {path:?}")))?.to_owned();
validate_path(&path)?;
let size = checked_entry_size(&mut total_size, entry.size())?;
dest.write_sized(&path, size, &mut |buffer| {
entry.read_exact(buffer).map_err(ContainerError::Io)?;
Ok(())
})?;
}
Ok(())
}
}
impl<W: Write + Seek> ArchiveWriter for XzWriter<W> {
fn write_entry(&mut self, path: &str, bytes: &[u8]) -> Result<()> {
validate_path(path)?;
let tar = self.tar.as_mut().ok_or_else(|| ContainerError::Codec("XzWriter already finished".into()))?;
let mut header = tar::Header::new_gnu();
header.set_path(path).map_err(|error| ContainerError::Codec(format!("tar: invalid path {path}: {error}")))?;
header.set_size(bytes.len() as u64);
header.set_mode(0o644);
header.set_cksum();
tar.append(&header, bytes)?;
Ok(())
}
fn finish(mut self) -> Result<()> {
self.finish_inner()?;
Ok(())
}
}
impl<W: Write + Seek> XzWriter<W> {
/// Finish the archive and return the underlying sink, for in-memory archives where the caller
/// wants the written bytes (e.g. `Cursor<Vec<u8>>`) back.
pub fn finish_into(mut self) -> Result<W> {
self.finish_inner()
}
/// Unwind the layered writers in order (flush the tar trailer, then finish xz) and hand back the
/// innermost sink. Shared by `finish` and `finish_into`.
fn finish_inner(&mut self) -> Result<W> {
let mut tar = self.tar.take().ok_or_else(|| ContainerError::Codec("XzWriter already finished".into()))?;
tar.finish()?;
let xz_writer = tar.into_inner()?;
xz_writer.finish().map_err(lzma_err)
}
}
fn lzma_err(error: std::io::Error) -> ContainerError {
ContainerError::Codec(format!("lzma: {error}"))
}
+83
View File
@@ -0,0 +1,83 @@
//! Zip archive codec.
use crate::archive::{Archive, ArchiveWriter, checked_entry_size};
use crate::{Container, ContainerError, Result, validate_path};
use std::io::{Read, Seek, Write};
use zip::ZipArchive;
use zip::write::{SimpleFileOptions, ZipWriter as InnerZipWriter};
pub struct Zip;
pub struct ZipWriter<W: Write + Seek> {
inner: InnerZipWriter<W>,
options: SimpleFileOptions,
}
impl Archive for Zip {
type Writer<W: Write + Seek> = ZipWriter<W>;
fn writer<W: Write + Seek>(output: W) -> Result<Self::Writer<W>> {
Ok(ZipWriter {
inner: InnerZipWriter::new(output),
options: SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated),
})
}
fn open<R: Read + Seek, C: Container>(source: R, dest: &mut C) -> Result<()> {
let mut archive = ZipArchive::new(source).map_err(zip_err)?;
// Zip headers declare each entry's uncompressed size up front; `checked_entry_size` caps the running
// total so a malicious archive can't exhaust memory or disk before any bytes are read.
let mut total_size = 0u64;
for index in 0..archive.len() {
let mut entry = archive.by_index(index).map_err(zip_err)?;
if !entry.is_file() {
continue;
}
let name = entry.name().to_string();
validate_path(&name)?;
let size = checked_entry_size(&mut total_size, entry.size())?;
dest.write_sized(&name, size, &mut |buffer| {
entry.read_exact(buffer).map_err(ContainerError::Io)?;
Ok(())
})?;
}
Ok(())
}
}
impl<W: Write + Seek> ArchiveWriter for ZipWriter<W> {
fn write_entry(&mut self, path: &str, bytes: &[u8]) -> Result<()> {
validate_path(path)?;
self.inner.start_file(path, self.options).map_err(zip_err)?;
self.inner.write_all(bytes)?;
Ok(())
}
fn finish(self) -> Result<()> {
self.inner.finish().map_err(zip_err)?;
Ok(())
}
}
impl<W: Write + Seek> ZipWriter<W> {
/// Finish the archive and return the underlying sink, for in-memory archives where the caller
/// wants the written bytes (e.g. `Cursor<Vec<u8>>`) back.
pub fn finish_into(self) -> Result<W> {
self.inner.finish().map_err(zip_err)
}
}
fn zip_err(error: zip::result::ZipError) -> ContainerError {
// Preserve a real I/O failure (disk full, etc.) as a structured `Io` so callers can tell it apart from a
// corrupt-archive `Codec` error; only the genuinely archive-format errors collapse into `Codec`.
match error {
zip::result::ZipError::Io(io) => ContainerError::Io(io),
other => ContainerError::Codec(format!("zip: {other}")),
}
}
+9
View File
@@ -0,0 +1,9 @@
//! Container backend implementations.
pub mod memory;
#[cfg(not(target_family = "wasm"))]
pub mod folder;
#[cfg(target_family = "wasm")]
pub mod opfs;
+191
View File
@@ -0,0 +1,191 @@
//! Loose-folder backend.
use crate::{ByteHolder, Container, ContainerError, MmappedBytes, Result, validate_path, validate_prefix};
use mmap_io::mmap::{MemoryMappedFile, MmapMode};
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
pub struct FolderBackend {
root: PathBuf,
}
impl FolderBackend {
/// Open an existing folder. Errors if `root` is not a directory.
pub fn open(root: impl Into<PathBuf>) -> Result<Self> {
let root = root.into();
if !root.is_dir() {
return Err(ContainerError::NotFound(root.display().to_string()));
}
Ok(Self { root })
}
/// Create the folder if it does not exist, then open it.
pub fn create(root: impl Into<PathBuf>) -> Result<Self> {
let root = root.into();
fs::create_dir_all(&root)?;
Ok(Self { root })
}
pub fn root(&self) -> &std::path::Path {
&self.root
}
fn resolve(&self, path: &str) -> Result<PathBuf> {
validate_path(path)?;
self.reject_symlinked_components(path)?;
Ok(self.root.join(path))
}
/// Reject any existing component along `root/relative` that is a symlink. `validate_path`/`validate_prefix`
/// block `..` and absolute paths, but a symlink stored under the root could still point outside it, so every
/// path that gets joined onto the root must pass through here before it is opened or traversed.
fn reject_symlinked_components(&self, relative: &str) -> Result<()> {
let mut partial = self.root.clone();
for component in Path::new(relative).components() {
partial.push(component);
if let Ok(metadata) = fs::symlink_metadata(&partial)
&& metadata.file_type().is_symlink()
{
return Err(ContainerError::InvalidPath(relative.to_string()));
}
}
Ok(())
}
fn list_filtered(&self, prefix: &str, want_files: bool) -> Result<Vec<String>> {
validate_prefix(prefix)?;
let base = if prefix.is_empty() || prefix == "." {
self.root.clone()
} else {
self.reject_symlinked_components(prefix)?;
self.root.join(prefix)
};
// A missing prefix has no entries; a prefix that names a file is a misuse.
if base.is_file() {
return Err(ContainerError::NotADirectory(prefix.to_string()));
}
if !base.is_dir() {
return Ok(Vec::new());
}
let mut results = Vec::new();
for entry in fs::read_dir(&base)? {
let entry = entry?;
// `file_type` does not follow symlinks, unlike `is_file`/`is_dir`. Skip symlink entries so a
// listing never advertises a path that `resolve` would then reject as a container escape.
let Ok(file_type) = entry.file_type() else { continue };
let matches = if want_files { file_type.is_file() } else { file_type.is_dir() };
if !matches {
continue;
}
let path = entry.path();
let relative = path.strip_prefix(&self.root).map_err(|_| ContainerError::Backend("path escaped root".into()))?;
results.push(relative.to_string_lossy().replace('\\', "/"));
}
Ok(results)
}
}
impl Container for FolderBackend {
fn read(&self, path: &str) -> Result<ByteHolder> {
let full = self.resolve(path)?;
if !full.is_file() {
return Err(ContainerError::NotFound(path.to_string()));
}
// Mmapping a zero-length file is platform-dependent and often fails, so serve empty files as owned
// bytes and reserve mmap for files that actually have content.
if fs::metadata(&full).map(|metadata| metadata.len() == 0).unwrap_or(false) {
return Ok(ByteHolder::Owned(Vec::new()));
}
Ok(ByteHolder::Mmapped(MmappedBytes::new(open_mmap(&full)?)?))
}
fn write(&self, path: &str, bytes: &[u8]) -> Result<()> {
let full = self.resolve(path)?;
if let Some(parent) = full.parent() {
fs::create_dir_all(parent)?;
}
fs::write(&full, bytes)?;
Ok(())
}
fn append(&self, path: &str, bytes: &[u8]) -> Result<()> {
let full = self.resolve(path)?;
if let Some(parent) = full.parent() {
fs::create_dir_all(parent)?;
}
let mut file = OpenOptions::new().create(true).append(true).open(&full)?;
file.write_all(bytes)?;
Ok(())
}
fn write_sized(&self, path: &str, size: usize, fill: &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()> {
if size == 0 {
return self.write(path, &[]);
}
let full = self.resolve(path)?;
if let Some(parent) = full.parent() {
fs::create_dir_all(parent)?;
}
let file = MemoryMappedFile::create_rw(&full, size as u64).map_err(|error| ContainerError::Backend(format!("create_rw {full:?} failed: {error}")))?;
let result = {
let mut slice = file
.as_slice_mut(0, size as u64)
.map_err(|error| ContainerError::Backend(format!("as_slice_mut {full:?} failed: {error}")))?;
fill(slice.as_mut())?;
drop(slice);
file.flush().map_err(|error| ContainerError::Backend(format!("flush {full:?} failed: {error}")))
};
// `create_rw` materializes the full-size file before `fill` runs, so remove it on failure rather
// than leave a zeroed or half-written remnant.
if result.is_err() {
drop(file);
let _ = fs::remove_file(&full);
}
result
}
fn list(&self, prefix: &str) -> Result<Vec<String>> {
self.list_filtered(prefix, true)
}
fn list_dirs(&self, prefix: &str) -> Result<Vec<String>> {
self.list_filtered(prefix, false)
}
fn exists(&self, path: &str) -> bool {
match self.resolve(path) {
Ok(full) => full.is_file(),
Err(_) => false,
}
}
fn remove(&self, path: &str) -> Result<()> {
let full = self.resolve(path)?;
// Idempotent: a missing file is not an error. Directories are left alone.
if full.is_file() {
fs::remove_file(full)?;
}
// TODO: decide if we should remove empty parent directories
Ok(())
}
}
/// Open a memory-mapped read-only view of `path`, trying huge pages first. Callers must ensure `path`
/// is non-empty, since mmapping a zero-length file is platform-dependent.
fn open_mmap(path: &Path) -> Result<MemoryMappedFile> {
match MemoryMappedFile::builder(path).mode(MmapMode::ReadOnly).huge_pages(true).open() {
Ok(file) => Ok(file),
Err(_) => MemoryMappedFile::open_ro(path).map_err(|error| ContainerError::Backend(format!("mmap of {path:?} failed: {error}"))),
}
}
+89
View File
@@ -0,0 +1,89 @@
//! In-memory backend. Useful for tests and as the deserialize target for archive codecs.
use crate::{ByteHolder, Container, ContainerError, Result, validate_path, validate_prefix, with_trailing_slash};
use std::collections::{HashMap, HashSet};
use std::sync::Mutex;
#[derive(Default)]
pub struct MemoryBackend {
files: Mutex<HashMap<String, Vec<u8>>>,
}
impl MemoryBackend {
pub fn new() -> Self {
Self::default()
}
}
impl Container for MemoryBackend {
fn read(&self, path: &str) -> Result<ByteHolder> {
validate_path(path)?;
self.files
.lock()
.unwrap()
.get(path)
.map(|bytes| ByteHolder::Owned(bytes.clone()))
.ok_or_else(|| ContainerError::NotFound(path.to_string()))
}
fn write(&self, path: &str, bytes: &[u8]) -> Result<()> {
validate_path(path)?;
self.files.lock().unwrap().insert(path.to_string(), bytes.to_vec());
Ok(())
}
fn append(&self, path: &str, bytes: &[u8]) -> Result<()> {
validate_path(path)?;
self.files.lock().unwrap().entry(path.to_string()).or_default().extend_from_slice(bytes);
Ok(())
}
fn list(&self, prefix: &str) -> Result<Vec<String>> {
validate_prefix(prefix)?;
let files = self.files.lock().unwrap();
// A prefix that is itself a stored key names a file, not a directory.
if files.contains_key(prefix) {
return Err(ContainerError::NotADirectory(prefix.to_string()));
}
let normalized = with_trailing_slash(prefix);
let results = files.keys().filter(|path| path.starts_with(&normalized) && !path[normalized.len()..].contains('/')).cloned().collect();
Ok(results)
}
fn list_dirs(&self, prefix: &str) -> Result<Vec<String>> {
validate_prefix(prefix)?;
let files = self.files.lock().unwrap();
if files.contains_key(prefix) {
return Err(ContainerError::NotADirectory(prefix.to_string()));
}
let normalized = with_trailing_slash(prefix);
let mut seen = HashSet::new();
let mut results = Vec::new();
for path in files.keys() {
if !path.starts_with(&normalized) {
continue;
}
let remainder = &path[normalized.len()..];
if let Some((segment, _)) = remainder.split_once('/') {
let dir = format!("{normalized}{segment}");
if seen.insert(dir.clone()) {
results.push(dir);
}
}
}
Ok(results)
}
fn exists(&self, path: &str) -> bool {
validate_path(path).is_ok() && self.files.lock().unwrap().contains_key(path)
}
fn remove(&self, path: &str) -> Result<()> {
validate_path(path)?;
// Idempotent: removing a missing path is not an error.
self.files.lock().unwrap().remove(path);
Ok(())
}
}
+475
View File
@@ -0,0 +1,475 @@
//! OPFS (Origin Private File System) backend for browser wasm.
use crate::{AsyncContainer, ByteHolder, ContainerError, Result, validate_path, validate_prefix, with_trailing_slash};
use futures::channel::oneshot;
use js_sys::Uint8Array;
use std::collections::{HashSet, VecDeque};
use std::sync::{Arc, Mutex};
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::{JsFuture, spawn_local};
use web_sys::{
Blob, DomException, FileSystemCreateWritableOptions, FileSystemDirectoryHandle, FileSystemFileHandle, FileSystemGetDirectoryOptions, FileSystemGetFileOptions, FileSystemWritableFileStream,
WritableStream,
};
enum Mutation {
Write {
path: String,
bytes: Vec<u8>,
},
Append {
path: String,
bytes: Vec<u8>,
},
Delete {
path: String,
},
/// In-band flush barrier. The worker fulfills the sender once it dequeues this, which (by FIFO
/// order) signals that every mutation enqueued before it has been applied to disk.
Barrier(oneshot::Sender<()>),
}
struct Inner {
directory: FileSystemDirectoryHandle,
/// Paths believed to be on disk, letting `exists_non_blocking` answer without OPFS's missing sync API.
/// Optimistic: a path is inserted when its write is queued and kept even if that write later fails, so it
/// can briefly over-report. Rebuilt from real disk state on the next `open`.
on_disk: HashSet<String>,
queue: VecDeque<Mutation>,
worker_active: bool,
}
pub struct OpfsBackend {
inner: Arc<Mutex<Inner>>,
}
// Safety: only built for browser wasm where JS handles never leave the main thread.
unsafe impl Send for OpfsBackend {}
unsafe impl Sync for OpfsBackend {}
impl OpfsBackend {
/// Open (or create) `directory_name` under the OPFS root.
pub async fn open(directory_name: &str) -> Result<Self> {
let directory = open_directory(directory_name).await.map_err(js_err)?;
let on_disk = enumerate_paths(&directory, "").await.map_err(js_err)?;
Ok(Self {
inner: Arc::new(Mutex::new(Inner {
directory,
on_disk,
queue: VecDeque::new(),
worker_active: false,
})),
})
}
fn directory(&self) -> FileSystemDirectoryHandle {
self.inner.lock().unwrap().directory.clone()
}
/// Wait until all queued non-blocking mutations have hit disk, so awaited reads observe them. Plants a
/// barrier at the back of the queue and awaits the worker reaching it; by FIFO order, everything ahead is
/// then applied. Draining stays the worker's job so it remains the sole mutator.
async fn flush(&self) {
let (sender, receiver) = oneshot::channel();
{
let mut guard = self.inner.lock().unwrap();
guard.queue.push_back(Mutation::Barrier(sender));
kick_worker(&self.inner, &mut guard);
}
// The sender is only dropped without sending if the worker is torn down mid-drain; either way
// there is nothing left to wait for, so a receive error is treated as "already flushed".
let _ = receiver.await;
}
}
impl AsyncContainer for OpfsBackend {
async fn read(&self, path: &str) -> Result<ByteHolder> {
validate_path(path)?;
// Non-blocking writes only land on disk once the queue drains, so flush first and then treat
// disk as authoritative. Draining (rather than folding the queue against an awaited base read)
// avoids racing the background worker, which could otherwise double-apply a queued append.
self.flush().await;
let bytes = read_file(&self.directory(), path).await.map_err(js_err)?;
Ok(ByteHolder::Owned(bytes))
}
async fn write(&self, path: &str, bytes: &[u8]) -> Result<()> {
validate_path(path)?;
// Flush first so this awaited write lands after any non-blocking mutation already queued for the
// same path, then apply directly so the real disk error still propagates to the caller.
self.flush().await;
write_file(&self.directory(), path, bytes).await.map_err(js_err)?;
self.inner.lock().unwrap().on_disk.insert(path.to_string());
Ok(())
}
async fn append(&self, path: &str, bytes: &[u8]) -> Result<()> {
validate_path(path)?;
self.flush().await;
append_file(&self.directory(), path, bytes).await.map_err(js_err)?;
self.inner.lock().unwrap().on_disk.insert(path.to_string());
Ok(())
}
async fn write_sized(&self, path: &str, size: usize, fill: &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()> {
validate_path(path)?;
let mut buffer = vec![0; size];
fill(&mut buffer)?;
self.flush().await;
write_file(&self.directory(), path, &buffer).await.map_err(js_err)?;
self.inner.lock().unwrap().on_disk.insert(path.to_string());
Ok(())
}
async fn list(&self, prefix: &str) -> Result<Vec<String>> {
validate_prefix(prefix)?;
self.flush().await;
list_entries(&self.directory(), prefix, EntryKind::File).await.map_err(|error| list_error(prefix, error))
}
async fn list_dirs(&self, prefix: &str) -> Result<Vec<String>> {
validate_prefix(prefix)?;
self.flush().await;
list_entries(&self.directory(), prefix, EntryKind::Directory).await.map_err(|error| list_error(prefix, error))
}
async fn exists(&self, path: &str) -> bool {
if validate_path(path).is_err() {
return false;
}
self.flush().await;
file_exists(&self.directory(), path).await
}
async fn remove(&self, path: &str) -> Result<()> {
validate_path(path)?;
self.flush().await;
// Idempotent: a missing entry is not an error, matching the other backends.
if let Err(error) = remove_file(&self.directory(), path).await
&& !is_not_found(&error)
{
return Err(js_err(error));
}
self.inner.lock().unwrap().on_disk.remove(path);
Ok(())
}
fn write_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()> {
validate_path(path)?;
let mut guard = self.inner.lock().unwrap();
guard.on_disk.insert(path.to_string());
guard.queue.push_back(Mutation::Write {
path: path.to_string(),
bytes: bytes.to_vec(),
});
kick_worker(&self.inner, &mut guard);
Ok(())
}
fn append_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()> {
validate_path(path)?;
let mut guard = self.inner.lock().unwrap();
guard.on_disk.insert(path.to_string());
guard.queue.push_back(Mutation::Append {
path: path.to_string(),
bytes: bytes.to_vec(),
});
kick_worker(&self.inner, &mut guard);
Ok(())
}
fn remove_non_blocking(&self, path: &str) -> Result<()> {
validate_path(path)?;
let mut guard = self.inner.lock().unwrap();
guard.on_disk.remove(path);
guard.queue.push_back(Mutation::Delete { path: path.to_string() });
kick_worker(&self.inner, &mut guard);
Ok(())
}
fn exists_non_blocking(&self, path: &str) -> bool {
validate_path(path).is_ok() && self.inner.lock().unwrap().on_disk.contains(path)
}
}
fn kick_worker(inner: &Arc<Mutex<Inner>>, guard: &mut Inner) {
if guard.worker_active {
return;
}
guard.worker_active = true;
let inner = inner.clone();
spawn_local(drain_queue(inner));
}
/// Apply every queued mutation to disk, in FIFO order, until the queue is empty, then mark the worker
/// idle. Spawned once via [`kick_worker`] and runs as the sole mutator; the awaited read paths wait on
/// a [`Mutation::Barrier`] rather than draining themselves, so there is never more than one drainer.
///
/// Consecutive appends to the same path are coalesced into one combined append. Each `createWritable`
/// on OPFS copies the whole existing file, so appending N frames one at a time is O(N^2) in bytes
/// copied (every per-op autosave queues one append per hot op). Concatenating a run into a single
/// append collapses that to one file copy, while staying byte-identical to applying them in order.
async fn drain_queue(inner: Arc<Mutex<Inner>>) {
loop {
// Pop the front mutation, coalescing a run of same-path appends behind it into one batch.
let (directory, mutation) = {
let mut guard = inner.lock().unwrap();
let Some(mut mutation) = guard.queue.pop_front() else {
guard.worker_active = false;
return;
};
if let Mutation::Append { path, bytes } = &mut mutation {
while let Some(Mutation::Append { path: next_path, .. }) = guard.queue.front()
&& next_path == path
{
let Some(Mutation::Append { bytes: next_bytes, .. }) = guard.queue.pop_front() else {
unreachable!()
};
bytes.extend_from_slice(&next_bytes);
}
}
(guard.directory.clone(), mutation)
};
match mutation {
Mutation::Write { path, bytes } => {
if let Err(error) = write_file(&directory, &path, &bytes).await {
log::error!("OPFS background write for {path} failed: {error:?}");
}
}
Mutation::Append { path, bytes } => {
if let Err(error) = append_file(&directory, &path, &bytes).await {
log::error!("OPFS background append for {path} failed: {error:?}");
}
}
Mutation::Delete { path } => {
// Removal is idempotent, so a missing entry is the expected outcome of a redundant delete, not an error.
if let Err(error) = remove_file(&directory, &path).await
&& !is_not_found(&error)
{
log::error!("OPFS background delete for {path} failed: {error:?}");
}
}
// A receive error on the waiter side just means the reader gave up; nothing to apply.
Mutation::Barrier(sender) => {
let _ = sender.send(());
}
}
}
}
fn js_err(error: JsValue) -> ContainerError {
ContainerError::Backend(format!("{error:?}"))
}
/// Resolve `directory_path` (a `/`-separated relative path) under the OPFS root, creating each
/// segment. OPFS rejects directory names containing `/`, so a multi-segment path like
/// `documents/<id>` must be descended one segment at a time rather than passed whole.
async fn open_directory(directory_path: &str) -> std::result::Result<FileSystemDirectoryHandle, JsValue> {
let storage = web_sys::window().ok_or_else(|| JsValue::from_str("no window"))?.navigator().storage();
let mut current: FileSystemDirectoryHandle = JsFuture::from(storage.get_directory()).await?.dyn_into()?;
for segment in directory_path.split('/').filter(|segment| !segment.is_empty()) {
let options = FileSystemGetDirectoryOptions::new();
options.set_create(true);
current = JsFuture::from(current.get_directory_handle_with_options(segment, &options)).await?.dyn_into()?;
}
Ok(current)
}
/// Descend the `/`-separated path against `root` and return the directory handle plus the final segment.
async fn descend<'a>(root: &FileSystemDirectoryHandle, relative: &'a str, create_dirs: bool) -> std::result::Result<(FileSystemDirectoryHandle, &'a str), JsValue> {
let mut current = root.clone();
let mut segments = relative.split('/').filter(|s| !s.is_empty()).collect::<Vec<_>>();
let file = segments.pop().ok_or_else(|| JsValue::from_str("empty path"))?;
for segment in segments {
let options = FileSystemGetDirectoryOptions::new();
options.set_create(create_dirs);
current = JsFuture::from(current.get_directory_handle_with_options(segment, &options)).await?.dyn_into()?;
}
Ok((current, file))
}
async fn read_file(root: &FileSystemDirectoryHandle, path: &str) -> std::result::Result<Vec<u8>, JsValue> {
let (directory, name) = descend(root, path, false).await?;
let handle: FileSystemFileHandle = JsFuture::from(directory.get_file_handle(name)).await?.dyn_into()?;
let file_value = JsFuture::from(handle.get_file()).await?;
let blob: Blob = file_value.dyn_into()?;
let buffer = JsFuture::from(blob.array_buffer()).await?;
Ok(Uint8Array::new(&buffer).to_vec())
}
async fn write_file(root: &FileSystemDirectoryHandle, path: &str, bytes: &[u8]) -> std::result::Result<(), JsValue> {
let (directory, name) = descend(root, path, true).await?;
let options = FileSystemGetFileOptions::new();
options.set_create(true);
let handle: FileSystemFileHandle = JsFuture::from(directory.get_file_handle_with_options(name, &options)).await?.dyn_into()?;
let writable: FileSystemWritableFileStream = JsFuture::from(handle.create_writable()).await?.dyn_into()?;
let stream: WritableStream = writable.clone().unchecked_into();
// Wrap in an async block so any failure, including a synchronous JS throw from `write_with_js_u8_array`,
// aborts the stream before returning instead of leaving a dangling locked writable.
let write = async {
let array = Uint8Array::from(bytes);
JsFuture::from(writable.write_with_js_u8_array(&array)?).await?;
Ok::<(), JsValue>(())
}
.await;
if let Err(error) = write {
let _ = JsFuture::from(stream.abort()).await;
return Err(error);
}
JsFuture::from(stream.close()).await?;
Ok(())
}
async fn append_file(root: &FileSystemDirectoryHandle, path: &str, bytes: &[u8]) -> std::result::Result<(), JsValue> {
let (directory, name) = descend(root, path, true).await?;
let file_options = FileSystemGetFileOptions::new();
file_options.set_create(true);
let handle: FileSystemFileHandle = JsFuture::from(directory.get_file_handle_with_options(name, &file_options)).await?.dyn_into()?;
// Determine the current end-of-file so we can seek there before writing.
let file_value = JsFuture::from(handle.get_file()).await?;
let blob: Blob = file_value.dyn_into()?;
let offset = blob.size();
// `keepExistingData: true` preserves bytes outside the written range; without it OPFS truncates to the written length.
let writable_options = FileSystemCreateWritableOptions::new();
writable_options.set_keep_existing_data(true);
let writable: FileSystemWritableFileStream = JsFuture::from(handle.create_writable_with_options(&writable_options)).await?.dyn_into()?;
let stream: WritableStream = writable.clone().unchecked_into();
// Wrap in an async block so a synchronous JS throw from `seek_with_f64`/`write_with_js_u8_array`
// aborts the stream instead of bypassing the abort via `?`.
let seek_and_write = async {
JsFuture::from(writable.seek_with_f64(offset)?).await?;
let array = Uint8Array::from(bytes);
JsFuture::from(writable.write_with_js_u8_array(&array)?).await?;
Ok::<(), JsValue>(())
}
.await;
if let Err(error) = seek_and_write {
let _ = JsFuture::from(stream.abort()).await;
return Err(error);
}
JsFuture::from(stream.close()).await?;
Ok(())
}
async fn remove_file(root: &FileSystemDirectoryHandle, path: &str) -> std::result::Result<(), JsValue> {
let (directory, name) = descend(root, path, false).await?;
JsFuture::from(directory.remove_entry(name)).await?;
Ok(())
}
async fn file_exists(root: &FileSystemDirectoryHandle, path: &str) -> bool {
let Ok((directory, name)) = descend(root, path, false).await else {
return false;
};
JsFuture::from(directory.get_file_handle(name)).await.is_ok()
}
#[derive(Clone, Copy)]
enum EntryKind {
File,
Directory,
}
async fn list_entries(root: &FileSystemDirectoryHandle, prefix: &str, want: EntryKind) -> std::result::Result<Vec<String>, JsValue> {
// `.` and the empty string both name the container root.
let prefix = if prefix == "." { "" } else { prefix };
let directory = if prefix.is_empty() {
root.clone()
} else {
let mut current = root.clone();
for segment in prefix.split('/').filter(|s| !s.is_empty()) {
let options = FileSystemGetDirectoryOptions::new();
options.set_create(false);
current = match JsFuture::from(current.get_directory_handle_with_options(segment, &options)).await {
Ok(value) => value.dyn_into()?,
Err(error) if is_not_found(&error) => return Ok(Vec::new()),
Err(error) => return Err(error),
};
}
current
};
let entries = directory.entries();
let iterator: js_sys::AsyncIterator = entries.unchecked_into();
let mut results = Vec::new();
let prefix_with_slash = with_trailing_slash(prefix);
let want_kind = match want {
EntryKind::File => web_sys::FileSystemHandleKind::File,
EntryKind::Directory => web_sys::FileSystemHandleKind::Directory,
};
loop {
let next: js_sys::IteratorNext = JsFuture::from(iterator.next()?).await?.unchecked_into();
if next.done() {
break;
}
let pair: js_sys::Array = next.value().unchecked_into();
let Some(name) = pair.get(0).as_string() else { continue };
let handle: web_sys::FileSystemHandle = pair.get(1).unchecked_into();
if handle.kind() != want_kind {
continue;
}
results.push(format!("{prefix_with_slash}{name}"));
}
Ok(results)
}
/// Walk every file under `prefix` (recursively) and collect their full container paths.
/// Used at open time to populate the in-memory tracking set.
async fn enumerate_paths(root: &FileSystemDirectoryHandle, prefix: &str) -> std::result::Result<HashSet<String>, JsValue> {
let mut paths = HashSet::new();
let mut to_visit = vec![prefix.to_string()];
while let Some(current_prefix) = to_visit.pop() {
for file in list_entries(root, &current_prefix, EntryKind::File).await? {
paths.insert(file);
}
for dir in list_entries(root, &current_prefix, EntryKind::Directory).await? {
to_visit.push(dir);
}
}
Ok(paths)
}
fn is_not_found(error: &JsValue) -> bool {
error.dyn_ref::<DomException>().is_some_and(|error| error.name() == "NotFoundError")
}
/// OPFS raises `TypeMismatchError` when a path segment used as a directory is actually a file.
fn is_type_mismatch(error: &JsValue) -> bool {
error.dyn_ref::<DomException>().is_some_and(|error| error.name() == "TypeMismatchError")
}
/// Map a listing error: a prefix that names a file becomes [`ContainerError::NotADirectory`], anything
/// else passes through as a backend error.
fn list_error(prefix: &str, error: JsValue) -> ContainerError {
if is_type_mismatch(&error) {
ContainerError::NotADirectory(prefix.to_string())
} else {
js_err(error)
}
}
+500
View File
@@ -0,0 +1,500 @@
//! Container abstraction for the on-disk side of the `.gdd` document format.
//!
//! A [`Container`] is a virtual filesystem of named byte payloads.
//! Backends include a loose folder, an in-memory map, and an OPFS-backed wasm store.
//! Archive codecs ([`archive::Zip`], [`archive::Xz`]) round-trip a container's contents
//! through a compressed byte stream.
//!
//! Reads return a [`ByteHolder`], an ownership-carrying handle whose variant depends on
//! how the backend produced the bytes (mmap region, owned vector, external file mmap).
//! [`AsyncContainer`] mirrors [`Container`] for inherently async backends; every sync
//! [`Container`] is reachable from async code via a blanket impl.
pub mod archive;
pub mod backends;
pub enum ByteHolder {
/// Bytes synthesized in memory (decompressed from an archive, produced by serialization).
/// The only variant available on `target_family = "wasm"`.
Owned(Vec<u8>),
/// Bytes mmap'd from a file inside the container.
#[cfg(not(target_family = "wasm"))]
Mmapped(MmappedBytes),
/// Bytes mmap'd from a file outside the container (e.g. a linked resource).
#[cfg(not(target_family = "wasm"))]
External { path: std::path::PathBuf, bytes: MmappedBytes },
}
impl ByteHolder {
pub fn as_slice(&self) -> &[u8] {
match self {
ByteHolder::Owned(bytes) => bytes,
#[cfg(not(target_family = "wasm"))]
ByteHolder::Mmapped(bytes) => bytes.as_ref(),
#[cfg(not(target_family = "wasm"))]
ByteHolder::External { bytes, .. } => bytes.as_ref(),
}
}
/// If the bytes are backed by a real filesystem path, return it. Enables consumers to
/// short-circuit byte copies with `fs::copy` (CoW on supported filesystems).
#[cfg(not(target_family = "wasm"))]
pub fn source_path(&self) -> Option<&std::path::Path> {
match self {
ByteHolder::Owned(_) => None,
ByteHolder::Mmapped(bytes) => Some(bytes.path()),
ByteHolder::External { path, .. } => Some(path),
}
}
#[cfg(target_family = "wasm")]
pub fn source_path(&self) -> Option<&std::path::Path> {
None
}
/// Open an external file and produce a [`ByteHolder::External`] backed by mmap.
#[cfg(not(target_family = "wasm"))]
pub fn open_external(path: impl Into<std::path::PathBuf>) -> Result<Self> {
let path = path.into();
let file = mmap_io::mmap::MemoryMappedFile::open_ro(&path).map_err(|error| ContainerError::Backend(format!("mmap of {path:?} failed: {error}")))?;
let bytes = MmappedBytes::new(file)?;
Ok(ByteHolder::External { path, bytes })
}
}
impl AsRef<[u8]> for ByteHolder {
fn as_ref(&self) -> &[u8] {
self.as_slice()
}
}
impl std::fmt::Debug for ByteHolder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ByteHolder::Owned(bytes) => f.debug_tuple("Owned").field(&format_args!("{} bytes", bytes.len())).finish(),
#[cfg(not(target_family = "wasm"))]
ByteHolder::Mmapped(bytes) => f.debug_tuple("Mmapped").field(&format_args!("{} bytes", bytes.as_ref().len())).finish(),
#[cfg(not(target_family = "wasm"))]
ByteHolder::External { path, bytes } => f.debug_struct("External").field("path", path).field("len", &bytes.as_ref().len()).finish(),
}
}
}
/// Owning wrapper around a memory-mapped file that exposes the mapped region as `&[u8]`.
#[cfg(not(target_family = "wasm"))]
pub struct MmappedBytes(mmap_io::mmap::MemoryMappedFile);
#[cfg(not(target_family = "wasm"))]
impl MmappedBytes {
/// Wrap a mapped file, probing that its region is sliceable so the failure surfaces here rather than
/// later degrading to the `&[]` fallback in [`AsRef::as_ref`], which cannot return an error.
pub fn new(file: mmap_io::mmap::MemoryMappedFile) -> Result<Self> {
let len = file.len();
file.as_slice(0, len)
.map_err(|error| ContainerError::Backend(format!("mmap slice of {:?} failed: {error}", file.path())))?;
Ok(Self(file))
}
pub fn path(&self) -> &std::path::Path {
self.0.path()
}
}
#[cfg(not(target_family = "wasm"))]
impl AsRef<[u8]> for MmappedBytes {
fn as_ref(&self) -> &[u8] {
let len = self.0.len();
match self.0.as_slice(0, len) {
Ok(slice) => slice,
Err(error) => {
log::error!("Failed to obtain mmap slice: {error}");
&[]
}
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum ContainerError {
#[error("path not found: {0}")]
NotFound(String),
#[error("invalid path: {0}")]
InvalidPath(String),
#[error("not a directory: {0}")]
NotADirectory(String),
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
/// An archive declared more decompressed data (`declared` bytes) than the codec is willing to
/// materialize (`limit` bytes).
#[error("declared decompressed size {declared} exceeds the {limit}-byte limit")]
SizeLimitExceeded { declared: u64, limit: u64 },
/// Failure inside an archive codec (zip, lzma, tar). Wraps a foreign error as text since those
/// error types don't share a common Rust trait we can chain through.
#[error("codec error: {0}")]
Codec(String),
/// Failure inside a storage backend (mmap, OPFS/JS). Wraps a foreign error as text for the same reason.
#[error("backend error: {0}")]
Backend(String),
}
pub type Result<T> = std::result::Result<T, ContainerError>;
/// Normalize a listing prefix to end with a trailing slash (unless it names the container root).
/// The root (empty string or `.`) normalizes to the empty string, so backends concatenate child paths
/// as `prefix/child` without a double, missing, or `./`-rooted slash.
pub(crate) fn with_trailing_slash(prefix: &str) -> String {
if prefix.is_empty() || prefix == "." {
String::new()
} else if prefix.ends_with('/') {
prefix.to_string()
} else {
format!("{prefix}/")
}
}
/// Validate that `path` names a container-safe file: relative, no `.`/`..` segments, no backslashes,
/// no redundant separators (`a//b`, `a/b/`). Dotfile names like `.gitignore` are fine. Requiring a canonical
/// form gives a file one identity across backends, some of which key on the raw string rather than path
/// components. Used by backends to block container escapes and by archive codecs on untrusted entry names.
/// For listing prefixes, which may name the container root, use [`validate_prefix`] instead.
pub fn validate_path(path: &str) -> Result<()> {
let invalid = || ContainerError::InvalidPath(path.to_string());
if path.is_empty() || path.contains('\\') || path.starts_with('/') {
return Err(invalid());
}
// `Path::components` silently folds away `//`, trailing `/`, and interior `.` segments, but backends key
// on the raw string, so a non-canonical path would resolve to one file on a path-joining backend yet a
// different identity on a string-keyed backend. Reject the redundant segments the component loop below
// can't see (it never observes a folded-away `CurDir`/empty segment).
if path.split('/').any(|segment| segment.is_empty() || segment == ".") {
return Err(invalid());
}
// Reject Windows drive-letter prefixes (`C:foo`, `C:/foo`) that platform-agnostic Path doesn't recognize as absolute on Linux.
let bytes = path.as_bytes();
if bytes.len() >= 2 && bytes[1] == b':' && bytes[0].is_ascii_alphabetic() {
return Err(invalid());
}
for component in std::path::Path::new(path).components() {
use std::path::Component;
match component {
Component::Normal(_) => {}
Component::CurDir | Component::ParentDir | Component::Prefix(_) | Component::RootDir => return Err(invalid()),
}
}
Ok(())
}
/// Validate a listing prefix. Same rules as [`validate_path`], except the container root is also a valid
/// prefix, named by either the empty string or `.`. Backends pass this to `list`/`list_dirs`.
pub fn validate_prefix(prefix: &str) -> Result<()> {
if prefix.is_empty() || prefix == "." {
return Ok(());
}
validate_path(prefix)
}
/// Synchronous virtual filesystem of named byte payloads.
pub trait Container {
/// Read the contents of `path` into a [`ByteHolder`].
fn read(&self, path: &str) -> Result<ByteHolder>;
/// Write `bytes` at `path`, creating intermediate directories as needed.
fn write(&self, path: &str, bytes: &[u8]) -> Result<()>;
/// Append `bytes` to the file at `path`, creating it (and any intermediate directories)
/// if it does not yet exist. Equivalent to `write` on a fresh path.
fn append(&self, path: &str, bytes: &[u8]) -> Result<()>;
/// Write `size` bytes whose contents are produced by `fill`.
/// The default implementation allocates and forwards to [`Container::write`];
/// backends that can mmap a writable region may override to fill in place.
fn write_sized(&self, path: &str, size: usize, fill: &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()> {
let mut buffer = vec![0; size];
fill(&mut buffer)?;
self.write(path, &buffer)
}
/// List file entries directly under `prefix` (non-recursive).
/// Returned paths include the `prefix` (e.g. `list("resources")` returns
/// `["resources/abc123", ...]`). A missing prefix yields an empty list; a prefix that names a
/// file (not a directory) is an error.
fn list(&self, prefix: &str) -> Result<Vec<String>>;
/// List subdirectory entries directly under `prefix` (non-recursive).
/// Returned names include the `prefix`, without a trailing slash
/// (e.g. `list_dirs("")` returns `["resources"]`). Same missing/file-prefix semantics as [`Container::list`].
fn list_dirs(&self, prefix: &str) -> Result<Vec<String>>;
/// Whether a file exists at `path`. Directories return `false`.
fn exists(&self, path: &str) -> bool;
/// Remove the file at `path`. Idempotent: removing a missing path succeeds. Directories are never
/// removed (they exist only implicitly as parents of files).
fn remove(&self, path: &str) -> Result<()>;
}
/// Asynchronous virtual filesystem of named byte payloads. Mirrors [`Container`].
///
/// The returned futures are intentionally not `Send`: native uses `block_on` at the save seam
/// and wasm is single-threaded, so neither needs cross-thread futures. Revisit if we ever want
/// to run container I/O on a thread pool.
#[expect(async_fn_in_trait, reason = "see trait docs — Send is not required")]
pub trait AsyncContainer {
async fn read(&self, path: &str) -> Result<ByteHolder>;
async fn write(&self, path: &str, bytes: &[u8]) -> Result<()>;
async fn append(&self, path: &str, bytes: &[u8]) -> Result<()>;
async fn write_sized(&self, path: &str, size: usize, fill: &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()>;
async fn list(&self, prefix: &str) -> Result<Vec<String>>;
async fn list_dirs(&self, prefix: &str) -> Result<Vec<String>>;
async fn exists(&self, path: &str) -> bool;
async fn remove(&self, path: &str) -> Result<()>;
/// Synchronous write. On backends with sync I/O (folder, memory) the write completes durably
/// before return and reports real errors. On OPFS the write is enqueued onto a background task
/// and `Ok` is returned eagerly; a later failure is logged.
fn write_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()>;
/// Synchronous append. Same eager-enqueue semantics on OPFS as [`write_non_blocking`](Self::write_non_blocking);
/// queued appends preserve order relative to earlier queued writes/appends.
fn append_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()>;
/// Synchronous remove. Same semantics as [`write_non_blocking`](Self::write_non_blocking).
fn remove_non_blocking(&self, path: &str) -> Result<()>;
/// Non-blocking existence check. On OPFS this reads from an in-memory tracking set populated by
/// the sync write/remove paths, since the underlying OPFS existence API is async only.
fn exists_non_blocking(&self, path: &str) -> bool;
}
impl<C: Container + ?Sized> AsyncContainer for C {
async fn read(&self, path: &str) -> Result<ByteHolder> {
Container::read(self, path)
}
async fn write(&self, path: &str, bytes: &[u8]) -> Result<()> {
Container::write(self, path, bytes)
}
async fn append(&self, path: &str, bytes: &[u8]) -> Result<()> {
Container::append(self, path, bytes)
}
async fn write_sized(&self, path: &str, size: usize, fill: &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()> {
Container::write_sized(self, path, size, fill)
}
async fn list(&self, prefix: &str) -> Result<Vec<String>> {
Container::list(self, prefix)
}
async fn list_dirs(&self, prefix: &str) -> Result<Vec<String>> {
Container::list_dirs(self, prefix)
}
async fn exists(&self, path: &str) -> bool {
Container::exists(self, path)
}
async fn remove(&self, path: &str) -> Result<()> {
Container::remove(self, path)
}
fn write_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()> {
Container::write(self, path, bytes)
}
fn append_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()> {
Container::append(self, path, bytes)
}
fn remove_non_blocking(&self, path: &str) -> Result<()> {
Container::remove(self, path)
}
fn exists_non_blocking(&self, path: &str) -> bool {
Container::exists(self, path)
}
}
/// Type-erased container that dispatches to one of the in-tree backends.
///
/// `AsyncContainer::read` returns `impl Future`, so `dyn AsyncContainer` is not object-safe.
/// `AnyContainer` is the workaround: `Gdd` holds one of these by value, and the `AsyncContainer`
/// impl forwards to the active variant.
pub enum AnyContainer {
Memory(backends::memory::MemoryBackend),
#[cfg(not(target_family = "wasm"))]
Folder(backends::folder::FolderBackend),
#[cfg(target_family = "wasm")]
Opfs(backends::opfs::OpfsBackend),
}
impl AsyncContainer for AnyContainer {
async fn read(&self, path: &str) -> Result<ByteHolder> {
match self {
Self::Memory(backend) => AsyncContainer::read(backend, path).await,
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::read(backend, path).await,
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::read(backend, path).await,
}
}
async fn write(&self, path: &str, bytes: &[u8]) -> Result<()> {
match self {
Self::Memory(backend) => AsyncContainer::write(backend, path, bytes).await,
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::write(backend, path, bytes).await,
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::write(backend, path, bytes).await,
}
}
async fn append(&self, path: &str, bytes: &[u8]) -> Result<()> {
match self {
Self::Memory(backend) => AsyncContainer::append(backend, path, bytes).await,
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::append(backend, path, bytes).await,
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::append(backend, path, bytes).await,
}
}
async fn write_sized(&self, path: &str, size: usize, fill: &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()> {
match self {
Self::Memory(backend) => AsyncContainer::write_sized(backend, path, size, fill).await,
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::write_sized(backend, path, size, fill).await,
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::write_sized(backend, path, size, fill).await,
}
}
async fn list(&self, prefix: &str) -> Result<Vec<String>> {
match self {
Self::Memory(backend) => AsyncContainer::list(backend, prefix).await,
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::list(backend, prefix).await,
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::list(backend, prefix).await,
}
}
async fn list_dirs(&self, prefix: &str) -> Result<Vec<String>> {
match self {
Self::Memory(backend) => AsyncContainer::list_dirs(backend, prefix).await,
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::list_dirs(backend, prefix).await,
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::list_dirs(backend, prefix).await,
}
}
async fn exists(&self, path: &str) -> bool {
match self {
Self::Memory(backend) => AsyncContainer::exists(backend, path).await,
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::exists(backend, path).await,
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::exists(backend, path).await,
}
}
async fn remove(&self, path: &str) -> Result<()> {
match self {
Self::Memory(backend) => AsyncContainer::remove(backend, path).await,
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::remove(backend, path).await,
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::remove(backend, path).await,
}
}
fn write_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()> {
match self {
Self::Memory(backend) => AsyncContainer::write_non_blocking(backend, path, bytes),
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::write_non_blocking(backend, path, bytes),
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::write_non_blocking(backend, path, bytes),
}
}
fn append_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()> {
match self {
Self::Memory(backend) => AsyncContainer::append_non_blocking(backend, path, bytes),
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::append_non_blocking(backend, path, bytes),
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::append_non_blocking(backend, path, bytes),
}
}
fn remove_non_blocking(&self, path: &str) -> Result<()> {
match self {
Self::Memory(backend) => AsyncContainer::remove_non_blocking(backend, path),
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::remove_non_blocking(backend, path),
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::remove_non_blocking(backend, path),
}
}
fn exists_non_blocking(&self, path: &str) -> bool {
match self {
Self::Memory(backend) => AsyncContainer::exists_non_blocking(backend, path),
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::exists_non_blocking(backend, path),
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::exists_non_blocking(backend, path),
}
}
}
#[cfg(test)]
mod tests {
use super::{ContainerError, validate_path, validate_prefix};
#[test]
fn validate_path_accepts_well_formed() {
// `..` and `.` are only rejected as whole path components; as substrings of a name they are fine.
for ok in ["manifest.json", "resources/abc", "a/b/c.bin", "my..file.txt", "..hidden", ".gitignore"] {
assert!(validate_path(ok).is_ok(), "{ok:?} should be accepted");
}
}
#[test]
fn validate_path_rejects_unsafe() {
for bad in ["", "../escape", "a/../b", ".", "./leading", "/abs", "back\\slash", "C:/win", "\\\\?\\unc"] {
let result = validate_path(bad);
assert!(matches!(result, Err(ContainerError::InvalidPath(_))), "{bad:?} should be rejected, got {result:?}");
}
}
#[test]
fn validate_prefix_accepts_root_tokens() {
// The container root is a valid listing prefix, named by either the empty string or `.`.
for root in ["", ".", "resources", "a/b"] {
assert!(validate_prefix(root).is_ok(), "{root:?} should be accepted as a prefix");
}
// Unsafe prefixes are still rejected, same as paths.
assert!(validate_prefix("../escape").is_err());
}
}
+81
View File
@@ -0,0 +1,81 @@
#![cfg(any(feature = "zip", feature = "xz"))]
use document_container::Container;
use document_container::archive::{Archive, ArchiveWriter};
use document_container::backends::folder::FolderBackend;
use document_container::backends::memory::MemoryBackend;
fn entries() -> Vec<(&'static str, &'static [u8])> {
vec![
("manifest.json", br#"{"format":"gdd"}"#),
("document.json", b"{\"registry\":\"...\"}"),
("history.jsonl", b"{\"rev\":1}\n{\"rev\":2}\n"),
("resources/abc123", &[0xDE, 0xAD, 0xBE, 0xEF]),
("resources/xyz789", b"another resource"),
]
}
fn assert_round_trip(restored: &MemoryBackend) {
assert_eq!(restored.read("manifest.json").unwrap().as_slice(), br#"{"format":"gdd"}"#);
assert_eq!(restored.read("document.json").unwrap().as_slice(), b"{\"registry\":\"...\"}");
assert_eq!(restored.read("history.jsonl").unwrap().as_slice(), b"{\"rev\":1}\n{\"rev\":2}\n");
assert_eq!(restored.read("resources/abc123").unwrap().as_slice(), &[0xDE, 0xAD, 0xBE, 0xEF]);
assert_eq!(restored.read("resources/xyz789").unwrap().as_slice(), b"another resource");
}
#[cfg(feature = "zip")]
#[test]
fn zip_round_trip() {
use document_container::archive::Zip;
use std::io::Cursor;
let mut buffer = Cursor::new(Vec::new());
let mut writer = Zip::writer(&mut buffer).unwrap();
for (path, bytes) in entries() {
writer.write_entry(path, bytes).unwrap();
}
writer.finish().unwrap();
let mut restored = MemoryBackend::new();
<Zip as Archive>::open(Cursor::new(buffer.get_ref()), &mut restored).unwrap();
assert_round_trip(&restored);
}
#[cfg(feature = "zip")]
#[test]
fn zip_deserialize_streams_into_folder_backend() {
use document_container::archive::Zip;
use std::io::Cursor;
let mut buffer = Cursor::new(Vec::new());
let mut writer = Zip::writer(&mut buffer).unwrap();
for (path, bytes) in entries() {
writer.write_entry(path, bytes).unwrap();
}
writer.finish().unwrap();
let dir = tempfile::tempdir().unwrap();
let mut restored = FolderBackend::create(dir.path()).unwrap();
<Zip as Archive>::open(Cursor::new(buffer.get_ref()), &mut restored).unwrap();
assert_eq!(restored.read("manifest.json").unwrap().as_slice(), br#"{"format":"gdd"}"#);
assert_eq!(restored.read("resources/abc123").unwrap().as_slice(), &[0xDE, 0xAD, 0xBE, 0xEF]);
}
#[cfg(feature = "xz")]
#[test]
fn xz_round_trip() {
use document_container::archive::Xz;
use std::io::Cursor;
let mut buffer = Cursor::new(Vec::new());
let mut writer = Xz::writer(&mut buffer).unwrap();
for (path, bytes) in entries() {
writer.write_entry(path, bytes).unwrap();
}
writer.finish().unwrap();
let mut restored = MemoryBackend::new();
<Xz as Archive>::open(Cursor::new(buffer.get_ref()), &mut restored).unwrap();
assert_round_trip(&restored);
}
+178
View File
@@ -0,0 +1,178 @@
use document_container::backends::folder::FolderBackend;
use document_container::backends::memory::MemoryBackend;
use document_container::{AnyContainer, Container, ContainerError};
fn run_round_trip<C: Container>(container: C) {
container.write("manifest.json", br#"{"format":"gdd"}"#).unwrap();
container.write("resources/abc123", &[0xDE, 0xAD, 0xBE, 0xEF]).unwrap();
container.write("resources/xyz789", b"another resource").unwrap();
assert!(container.exists("manifest.json"));
assert!(container.exists("resources/abc123"));
assert!(!container.exists("does-not-exist"));
let manifest = container.read("manifest.json").unwrap();
assert_eq!(manifest.as_slice(), br#"{"format":"gdd"}"#);
let blob = container.read("resources/abc123").unwrap();
assert_eq!(blob.as_slice(), &[0xDE, 0xAD, 0xBE, 0xEF]);
let top_level = container.list("").unwrap();
assert!(top_level.iter().any(|p| p == "manifest.json"));
assert!(
top_level.iter().all(|p| !p.starts_with("resources/")),
"list(\"\") must not descend into subdirectories, got {top_level:?}"
);
let mut resources = container.list("resources").unwrap();
resources.sort();
assert_eq!(resources, vec!["resources/abc123".to_string(), "resources/xyz789".to_string()]);
container.remove("resources/abc123").unwrap();
assert!(!container.exists("resources/abc123"));
assert!(matches!(container.read("resources/abc123"), Err(ContainerError::NotFound(_))));
}
#[test]
fn memory_backend_round_trip() {
run_round_trip(MemoryBackend::new());
}
#[test]
fn folder_backend_round_trip() {
let dir = tempfile::tempdir().unwrap();
let backend = FolderBackend::create(dir.path()).unwrap();
run_round_trip(backend);
}
fn run_list_and_remove_semantics<C: Container>(container: C) {
container.write("dir/file", b"x").unwrap();
// Removing a missing path is idempotent.
container.remove("dir/missing").unwrap();
container.remove("dir/file").unwrap();
container.remove("dir/file").unwrap();
// Listing a missing prefix yields an empty list.
assert_eq!(container.list("nonexistent").unwrap(), Vec::<String>::new());
// Listing a prefix that names a file is an error.
container.write("manifest.json", b"{}").unwrap();
assert!(matches!(container.list("manifest.json"), Err(ContainerError::NotADirectory(_))));
assert!(matches!(container.list_dirs("manifest.json"), Err(ContainerError::NotADirectory(_))));
}
#[test]
fn memory_backend_list_and_remove_semantics() {
run_list_and_remove_semantics(MemoryBackend::new());
}
#[test]
fn folder_backend_list_and_remove_semantics() {
let dir = tempfile::tempdir().unwrap();
run_list_and_remove_semantics(FolderBackend::create(dir.path()).unwrap());
}
#[test]
#[cfg(unix)]
fn folder_backend_rejects_symlink_escape() {
let outside = tempfile::tempdir().unwrap();
std::fs::write(outside.path().join("secret"), b"sensitive").unwrap();
let dir = tempfile::tempdir().unwrap();
let backend = FolderBackend::create(dir.path()).unwrap();
// A symlink planted inside the root pointing outside it must not be traversable.
std::os::unix::fs::symlink(outside.path(), dir.path().join("link")).unwrap();
let result = backend.read("link/secret");
assert!(matches!(result, Err(ContainerError::InvalidPath(_))), "symlink escape should be rejected, got {result:?}");
// Listing must reject the symlinked prefix too, not just reads, so it can't leak entry names from outside the root.
assert!(matches!(backend.list("link"), Err(ContainerError::InvalidPath(_))), "list through symlink should be rejected");
assert!(matches!(backend.list_dirs("link"), Err(ContainerError::InvalidPath(_))), "list_dirs through symlink should be rejected");
// A symlink entry directly under root must not appear in listings, since `resolve` would reject reading it.
std::os::unix::fs::symlink(outside.path().join("secret"), dir.path().join("file_link")).unwrap();
std::fs::write(dir.path().join("real"), b"ok").unwrap();
assert_eq!(backend.list("").unwrap(), vec!["real".to_string()], "symlink entries should be omitted from file listings");
assert!(backend.list_dirs("").unwrap().is_empty(), "symlink-to-dir entries should be omitted from dir listings");
}
#[test]
fn folder_backend_rejects_path_traversal() {
let dir = tempfile::tempdir().unwrap();
let backend = FolderBackend::create(dir.path()).unwrap();
for bad in ["../escape", "subdir/../escape", "/abs", "back\\slash", "a//b", "trailing/", "a/./b"] {
let result = backend.write(bad, b"nope");
assert!(matches!(result, Err(ContainerError::InvalidPath(_))), "expected InvalidPath for {bad:?}, got {result:?}");
}
}
fn run_append<C: Container>(container: C) {
// Appending to a non-existent path creates it — same semantics as `OpenOptions::append().create(true)`.
container.append("history.jsonl", b"{\"op\":1}\n").unwrap();
container.append("history.jsonl", b"{\"op\":2}\n").unwrap();
container.append("history.jsonl", b"{\"op\":3}\n").unwrap();
let log = container.read("history.jsonl").unwrap();
assert_eq!(log.as_slice(), b"{\"op\":1}\n{\"op\":2}\n{\"op\":3}\n");
}
#[test]
fn memory_backend_append() {
run_append(MemoryBackend::new());
}
#[test]
fn folder_backend_append() {
let dir = tempfile::tempdir().unwrap();
let backend = FolderBackend::create(dir.path()).unwrap();
run_append(backend);
}
#[test]
fn any_container_dispatches_to_active_variant() {
use document_container::AsyncContainer;
let container = AnyContainer::Memory(MemoryBackend::new());
futures::executor::block_on(async {
container.write("manifest.json", br#"{"format":"gdd"}"#).await.unwrap();
container.append("history.jsonl", b"frame-1\n").await.unwrap();
container.append("history.jsonl", b"frame-2\n").await.unwrap();
assert!(container.exists("manifest.json").await);
let manifest = container.read("manifest.json").await.unwrap();
assert_eq!(manifest.as_slice(), br#"{"format":"gdd"}"#);
let history = container.read("history.jsonl").await.unwrap();
assert_eq!(history.as_slice(), b"frame-1\nframe-2\n");
});
}
#[test]
fn folder_backend_reads_empty_file() {
let dir = tempfile::tempdir().unwrap();
let backend = FolderBackend::create(dir.path()).unwrap();
backend.write("empty.bin", &[]).unwrap();
let read_back = backend.read("empty.bin").unwrap();
assert_eq!(read_back.as_slice(), &[] as &[u8]);
}
#[test]
fn folder_backend_write_sized_fills_via_mmap() {
let dir = tempfile::tempdir().unwrap();
let backend = FolderBackend::create(dir.path()).unwrap();
let payload = b"hello world";
backend
.write_sized("resources/sized", payload.len(), &mut |buffer| {
buffer.copy_from_slice(payload);
Ok(())
})
.unwrap();
let read_back = backend.read("resources/sized").unwrap();
assert_eq!(read_back.as_slice(), payload);
}
+9 -1
View File
@@ -47,6 +47,9 @@ base64 = { workspace = true }
spin = { workspace = true }
image = { workspace = true }
color = { workspace = true }
zip = { workspace = true }
reqwest = { workspace = true }
url = { workspace = true }
# Optional local dependencies
wgpu-executor = { workspace = true, optional = true }
@@ -54,8 +57,13 @@ wgpu-executor = { workspace = true, optional = true }
# Optional workspace dependencies
wasm-bindgen = { workspace = true, optional = true }
[target.'cfg(not(target_family = "wasm"))'.dependencies]
tokio = { workspace = true }
[target.'cfg(target_family = "wasm")'.dependencies]
wasm-bindgen-futures = { workspace = true }
[dev-dependencies]
# Workspace dependencies
env_logger = { workspace = true }
futures = { workspace = true }
tokio = { workspace = true }
+15 -4
View File
@@ -1,18 +1,25 @@
use crate::dispatcher::Dispatcher;
use crate::messages::prelude::*;
use graph_craft::application_io::PlatformApplicationIo;
use graph_craft::application_io::resource::ResourceStorage;
pub use graphene_std::uuid::*;
use std::sync::OnceLock;
use std::sync::{Arc, OnceLock};
pub struct Editor {
pub dispatcher: Dispatcher,
}
impl Editor {
pub fn new(environment: Environment, uuid_random_seed: u64) -> Self {
pub fn new(environment: Environment, uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, mut application_io: PlatformApplicationIo, wake: Wake) -> Self {
ENVIRONMENT.set(environment).expect("Editor shoud only be initialized once");
graphene_std::uuid::set_uuid_seed(uuid_random_seed);
Self { dispatcher: Dispatcher::new() }
let mut dispatcher = Dispatcher::new(resource_storage);
dispatcher.message_handlers.future_message_handler.set_wake(wake);
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
crate::node_graph_executor::replace_application_io(application_io);
Self { dispatcher }
}
#[cfg(test)]
@@ -20,11 +27,15 @@ impl Editor {
let _ = ENVIRONMENT.set(*Editor::environment());
graphene_std::uuid::set_uuid_seed(0);
let (runtime, executor) = crate::node_graph_executor::NodeGraphExecutor::new_with_local_runtime();
let (mut runtime, executor) = crate::node_graph_executor::NodeGraphExecutor::new_with_local_runtime();
let editor = Self {
dispatcher: Dispatcher::with_executor(executor),
};
let mut application_io = PlatformApplicationIo::default();
application_io.inject_resource_proxy(editor.dispatcher.message_handlers.resource_storage_message_handler.resources());
runtime.replace_application_io(application_io);
(editor, runtime)
}
+41 -20
View File
@@ -6,6 +6,8 @@ use crate::messages::portfolio::utility_types::PanelType;
use crate::messages::preferences::preferences_message_handler::PreferencesMessageContext;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::utility_functions::make_path_editable_is_allowed;
use graph_craft::application_io::resource::ResourceStorage;
use std::sync::Arc;
#[derive(Debug, Default)]
pub struct Dispatcher {
@@ -19,6 +21,7 @@ pub struct Dispatcher {
pub struct DispatcherMessageHandlers {
animation_message_handler: AnimationMessageHandler,
app_window_message_handler: AppWindowMessageHandler,
pub(crate) future_message_handler: FutureMessageHandler,
broadcast_message_handler: BroadcastMessageHandler,
clipboard_message_handler: ClipboardMessageHandler,
color_picker_message_handler: ColorPickerMessageHandler,
@@ -29,17 +32,26 @@ pub struct DispatcherMessageHandlers {
key_mapping_message_handler: KeyMappingMessageHandler,
layout_message_handler: LayoutMessageHandler,
menu_bar_message_handler: MenuBarMessageHandler,
network_message_handler: NetworkMessageHandler,
pub(crate) portfolio_message_handler: PortfolioMessageHandler,
preferences_message_handler: PreferencesMessageHandler,
pub(crate) resource_storage_message_handler: ResourceStorageMessageHandler,
tool_message_handler: ToolMessageHandler,
viewport_message_handler: ViewportMessageHandler,
}
impl DispatcherMessageHandlers {
pub fn with_resource_storage(resource_storage: Arc<dyn ResourceStorage>) -> Self {
Self {
resource_storage_message_handler: ResourceStorageMessageHandler::new(resource_storage),
..Self::default()
}
}
pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self {
Self {
portfolio_message_handler: PortfolioMessageHandler::with_executor(executor),
..Default::default()
..Self::default()
}
}
}
@@ -54,7 +66,6 @@ const SIDE_EFFECT_FREE_MESSAGES: &[MessageDiscriminant] = &[
))),
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::SubmitActiveGraphRender),
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::SubmitEyedropperPreviewRender),
MessageDiscriminant::Frontend(FrontendMessageDiscriminant::TriggerFontDataLoad),
MessageDiscriminant::Frontend(FrontendMessageDiscriminant::UpdateUIScale),
];
/// Since we don't need to update the frontend multiple times per frame,
@@ -78,15 +89,16 @@ const DEBUG_MESSAGE_BLOCK_LIST: &[MessageDiscriminant] = &[
const DEBUG_MESSAGE_ENDING_BLOCK_LIST: &[&str] = &["PointerMove", "PointerOutsideViewport", "Overlays", "Draw", "CurrentTime", "Time"];
impl Dispatcher {
pub fn new() -> Self {
Self::default()
pub fn new(resource_storage: Arc<dyn ResourceStorage>) -> Self {
let mut s = Self::default();
s.message_handlers.resource_storage_message_handler = ResourceStorageMessageHandler::new(resource_storage);
s
}
pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self {
Self {
message_handlers: DispatcherMessageHandlers::with_executor(executor),
..Default::default()
}
let mut s = Self::default();
s.message_handlers.portfolio_message_handler = PortfolioMessageHandler::with_executor(executor);
s
}
// If the deepest queues (higher index in queues list) are now empty (after being popped from) then remove them
@@ -114,6 +126,13 @@ impl Dispatcher {
pub fn handle_message<T: Into<Message>>(&mut self, message: T, process_after_all_current: bool) {
let message = message.into();
// Drain async results into the queue before processing the new message.
let mut async_results = VecDeque::new();
self.message_handlers.future_message_handler.drain_results(&mut async_results);
if !async_results.is_empty() {
Self::schedule_execution(&mut self.message_queues, true, async_results);
}
// If we are not maintaining the buffer, simply add to the current queue
Self::schedule_execution(&mut self.message_queues, process_after_all_current, [message]);
@@ -163,6 +182,9 @@ impl Dispatcher {
Message::AppWindow(message) => {
self.message_handlers.app_window_message_handler.process_message(message, &mut queue, ());
}
Message::Future(message) => {
self.message_handlers.future_message_handler.process_message(message, &mut queue, FutureMessageContext {});
}
Message::Broadcast(message) => self.message_handlers.broadcast_message_handler.process_message(message, &mut queue, ()),
Message::Clipboard(message) => self.message_handlers.clipboard_message_handler.process_message(message, &mut queue, ()),
Message::ColorPicker(message) => self.message_handlers.color_picker_message_handler.process_message(message, &mut queue, ()),
@@ -183,17 +205,7 @@ impl Dispatcher {
self.message_handlers.dialog_message_handler.process_message(message, &mut queue, context);
}
Message::Frontend(message) => {
// Handle these messages immediately by returning early
if let FrontendMessage::TriggerFontDataLoad { .. } | FrontendMessage::TriggerFontCatalogLoad = message {
self.responses.push(message);
self.cleanup_queues(false);
// Return early to avoid running the code after the match block
return;
} else {
// `FrontendMessage`s are saved and will be sent to the frontend after the message queue is done being processed
self.responses.push(message);
}
self.responses.push(message);
}
Message::InputPreprocessor(message) => {
self.message_handlers.input_preprocessor_message_handler.process_message(
@@ -218,6 +230,14 @@ impl Dispatcher {
self.message_handlers.layout_message_handler.process_message(message, &mut queue, context);
}
Message::Network(message) => {
self.message_handlers.network_message_handler.process_message(message, &mut queue, NetworkMessageContext {});
}
Message::ResourceStorage(message) => {
self.message_handlers
.resource_storage_message_handler
.process_message(message, &mut queue, ResourceStorageMessageContext {});
}
Message::Portfolio(message) => {
self.message_handlers.portfolio_message_handler.process_message(
message,
@@ -230,6 +250,7 @@ impl Dispatcher {
timing_information: self.message_handlers.animation_message_handler.timing_information(),
animation: &self.message_handlers.animation_message_handler,
viewport: &self.message_handlers.viewport_message_handler,
resource_storage: &self.message_handlers.resource_storage_message_handler,
},
);
}
@@ -297,7 +318,7 @@ impl Dispatcher {
document_id,
document,
input: &self.message_handlers.input_preprocessor_message_handler,
cached_data: &self.message_handlers.portfolio_message_handler.cached_data,
fonts: &self.message_handlers.portfolio_message_handler.fonts,
node_graph: &self.message_handlers.portfolio_message_handler.executor,
preferences: &self.message_handlers.preferences_message_handler,
viewport: &self.message_handlers.viewport_message_handler,
@@ -21,7 +21,7 @@ pub enum HsvChannel {
#[impl_message(Message, ColorPicker)]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum ColorPickerMessage {
/// Initialize the picker state from an external color/gradient and announce its options. Called by the frontend when a `<ColorPicker>` opens.
/// Initialize the picker state from an external color/gradient and announce its options. Called by the frontend when a `<ColorPicker />` opens.
Open { initial_value: FillChoice, allow_none: bool, disabled: bool },
/// Clear the picker state. Called by the frontend when the popover closes.
Close,
@@ -2,9 +2,10 @@ use crate::messages::color_picker::color_picker_message::{HsvChannel, RgbChannel
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::layout::utility_types::widgets::input_widgets::{ColorPresetsInputUpdate, SpectrumInputUpdate, SpectrumMarker, VisualColorPickersInputUpdate};
use crate::messages::prelude::*;
use color::{AlphaColor, Srgb};
use graphene_std::Color;
use graphene_std::vector::style::{FillChoice, GradientStops};
use graphene_std::color::SRGBA8;
use graphene_std::core_types::misc::parse_css_color;
use graphene_std::vector::style::{FillChoice, FillChoiceUI, GradientStops, GradientStopsUI};
/// Bounds for a midpoint position (relative to the interval between two adjacent gradient stops).
const MIN_MIDPOINT: f64 = 0.01;
@@ -65,14 +66,6 @@ impl MessageHandler<ColorPickerMessage, ()> for ColorPickerMessageHandler {
self.allow_none = allow_none;
self.disabled = disabled;
// Each `<ColorPicker>` Svelte instance maintains its own local layout state, but the Rust `LayoutMessageHandler` keeps a single shared layout per target. When a new picker instance opens after a previous one closed, the new instance's layout starts empty and a diff from the previously-shared state would not apply. Destroying the stored layouts here forces the next `SendLayout` to send the full layout instead of a diff.
responses.add(LayoutMessage::DestroyLayout {
layout_target: LayoutTarget::ColorPickerPickersAndGradient,
});
responses.add(LayoutMessage::DestroyLayout {
layout_target: LayoutTarget::ColorPickerDetails,
});
match initial_value {
FillChoice::None => {
self.set_new_hsva(0., 0., 0., 1., true);
@@ -99,9 +92,7 @@ impl MessageHandler<ColorPickerMessage, ()> for ColorPickerMessageHandler {
self.send_layouts(responses);
}
ColorPickerMessage::Close => {
self.gradient = None;
self.active_marker_index = None;
self.active_marker_is_midpoint = false;
responses.add(DocumentMessage::EndTransaction);
}
ColorPickerMessage::VisualUpdate { update } => {
self.hue = update.hue;
@@ -115,10 +106,13 @@ impl MessageHandler<ColorPickerMessage, ()> for ColorPickerMessageHandler {
ColorPickerMessage::SetChannelRgb { channel, value } => {
let Some(strength) = value else { return };
let Some(current) = self.current_color() else { return };
// The RGB inputs are 0..255 sRGB display values; substitute the new channel into the gamma triple and lift back to linear for storage.
let new_gamma_channel = (strength / 255.) as f32;
let [cur_r, cur_g, cur_b, cur_a] = current.to_gamma_srgb_channels();
let updated = match channel {
RgbChannel::Red => Color::from_rgbaf32_unchecked((strength / 255.) as f32, current.g(), current.b(), current.a()),
RgbChannel::Green => Color::from_rgbaf32_unchecked(current.r(), (strength / 255.) as f32, current.b(), current.a()),
RgbChannel::Blue => Color::from_rgbaf32_unchecked(current.r(), current.g(), (strength / 255.) as f32, current.a()),
RgbChannel::Red => Color::from_gamma_srgb_channels(new_gamma_channel, cur_g, cur_b, cur_a),
RgbChannel::Green => Color::from_gamma_srgb_channels(cur_r, new_gamma_channel, cur_b, cur_a),
RgbChannel::Blue => Color::from_gamma_srgb_channels(cur_r, cur_g, new_gamma_channel, cur_a),
};
self.adopt_color(updated);
self.emit_color(responses);
@@ -160,7 +154,7 @@ impl MessageHandler<ColorPickerMessage, ()> for ColorPickerMessageHandler {
match preset {
FillChoice::None => {
self.set_new_hsva(0., 0., 0., 1., true);
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoice::None });
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoiceUI::None });
}
FillChoice::Solid(color) => {
self.adopt_color(color);
@@ -185,7 +179,7 @@ impl MessageHandler<ColorPickerMessage, ()> for ColorPickerMessageHandler {
self.set_old_hsva(temp.0, temp.1, temp.2, temp.3, temp.4);
if self.is_none {
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoice::None });
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoiceUI::None });
} else {
self.emit_color(responses);
}
@@ -207,6 +201,7 @@ impl MessageHandler<ColorPickerMessage, ()> for ColorPickerMessageHandler {
}
impl ColorPickerMessageHandler {
// The picker's internal HSV state is HSV of sRGB display values
fn current_color(&self) -> Option<Color> {
if self.is_none {
None
@@ -249,7 +244,8 @@ impl ColorPickerMessageHandler {
/// Set HSV state from a Color, preserving hue and saturation in degenerate cases.
fn adopt_color(&mut self, color: Color) {
let [target_h, target_s, target_v] = rgb_to_hsv(color.r() as f64, color.g() as f64, color.b() as f64);
let [target_h, target_s, target_v, target_a] = color.to_hsva();
let (target_h, target_s, target_v, target_a) = (target_h as f64, target_s as f64, target_v as f64, target_a as f64);
// Preserve hue: avoid jumping from 360° (top) to 0° (bottom) and don't reset hue when the color is desaturated or fully dark.
if !(target_h == 0. && self.hue == 1.) && target_s > 0. && target_v > 0. {
@@ -260,7 +256,7 @@ impl ColorPickerMessageHandler {
self.saturation = target_s;
}
self.value = target_v;
self.alpha = color.a() as f64;
self.alpha = target_a;
self.is_none = false;
}
@@ -274,9 +270,15 @@ impl ColorPickerMessageHandler {
{
*stop_color = color;
let stops = gradient.clone();
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoice::Gradient(stops) });
let fill_choice = FillChoice::Gradient(stops);
responses.add(FrontendMessage::ColorPickerColorChanged {
value: FillChoiceUI::from(&fill_choice),
});
} else {
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoice::Solid(color) });
let fill_choice = FillChoice::Solid(color);
responses.add(FrontendMessage::ColorPickerColorChanged {
value: FillChoiceUI::from(&fill_choice),
});
}
}
@@ -374,8 +376,9 @@ impl ColorPickerMessageHandler {
}
self.gradient = Some(gradient.clone());
let fill_choice = FillChoice::Gradient(gradient);
responses.add(FrontendMessage::ColorPickerColorChanged {
value: FillChoice::Gradient(gradient),
value: FillChoiceUI::from(&fill_choice),
});
self.send_layouts(responses);
}
@@ -402,7 +405,7 @@ impl ColorPickerMessageHandler {
// For gradient editing, the markers' handle colors mirror their gradient stop colors
let markers = gradient.iter().map(|stop| SpectrumMarker::new(stop.position, stop.midpoint, stop.color)).collect();
let mut row_widgets = vec![
SpectrumInput::new(gradient.clone())
SpectrumInput::new(GradientStopsUI::from(gradient))
.markers(markers)
.active_marker_index(self.active_marker_index)
.active_marker_is_midpoint(self.active_marker_is_midpoint)
@@ -463,7 +466,11 @@ impl ColorPickerMessageHandler {
let old_color = self.old_color();
let hex_value = new_color.map(|c| color_to_hex_optional_alpha(&c)).unwrap_or_else(|| "-".to_string());
let rgb_255 = new_color.map(|c| (c.r() as f64 * 255., c.g() as f64 * 255., c.b() as f64 * 255.));
// RGB readouts display sRGB byte values to the user, so we convert from linear-light to gamma here before quantizing.
let rgb_255 = new_color.map(|c| {
let [r, g, b, _] = c.to_gamma_srgb_channels();
(r as f64 * 255., g as f64 * 255., b as f64 * 255.)
});
// Epsilon comparison since the picker round-trips through HSV
let differs = match (new_color, old_color) {
@@ -480,7 +487,7 @@ impl ColorPickerMessageHandler {
// New/old comparison swatch with swap button
groups.push(LayoutGroup::row(vec![
ColorComparisonInput::new(new_color, old_color)
ColorComparisonInput::new(new_color.map(SRGBA8::from), old_color.map(SRGBA8::from))
.is_none(self.is_none)
.old_is_none(self.old_is_none)
.disabled(self.disabled)
@@ -576,7 +583,10 @@ impl ColorPickerMessageHandler {
.disabled(self.disabled)
.show_none_option(self.allow_none && self.gradient.is_none())
.on_update(|update: &ColorPresetsInputUpdate| match update {
ColorPresetsInputUpdate::Preset(fill_choice) => ColorPickerMessage::PickPreset { preset: fill_choice.clone() }.into(),
ColorPresetsInputUpdate::Preset(fill_choice) => ColorPickerMessage::PickPreset {
preset: FillChoice::from(fill_choice),
}
.into(),
ColorPresetsInputUpdate::EyedropperColorCode(code) => ColorPickerMessage::EyedropperColorCode { code: code.clone() }.into(),
})
.widget_instance(),
@@ -621,33 +631,10 @@ const SATURATION_DESCRIPTION: &str = "The vividness from grayscale to full color
const VALUE_DESCRIPTION: &str = "The brightness from black to full color.";
const ALPHA_DESCRIPTION: &str = "The level of translucency, from transparent (0%) to opaque (100%).";
/// Convert an `rgb(0..1)` triple to `hsv(0..1)`. Mirrors the legacy frontend `colorToHSV`.
fn rgb_to_hsv(red: f64, green: f64, blue: f64) -> [f64; 3] {
let max = red.max(green).max(blue);
let min = red.min(green).min(blue);
let delta = max - min;
let mut hue = if delta == 0. {
0.
} else if max == red {
((green - blue) / delta).rem_euclid(6.)
} else if max == green {
(blue - red) / delta + 2.
} else {
(red - green) / delta + 4.
};
hue = (hue * 60. + 360.).rem_euclid(360.) / 360.;
let saturation = if max == 0. { 0. } else { delta / max };
let value = max;
[hue, saturation, value]
}
/// The popover's background color (the `--color-2-mildblack` design token, `#222`). Used by the comparison swatch's
/// outline computation to brighten the inset border for colors close to this background.
const POPOVER_BACKGROUND: Color = Color::from_rgbaf32_unchecked(0x22 as f32 / 255., 0x22 as f32 / 255., 0x22 as f32 / 255., 1.);
/// The luminance window (in linear-light) within which a color is considered close enough to the popover background
/// The popover's background color as sRGB gamma-encoded channels (the `--color-2-mildblack` design token, `#222`).
/// Used by the comparison swatch's outline computation to brighten the inset border for colors close to this background.
const POPOVER_BACKGROUND_GAMMA_CHANNELS: [f32; 4] = [0x22 as f32 / 255., 0x22 as f32 / 255., 0x22 as f32 / 255., 1.];
/// The luminance window within which a color is considered close enough to the popover background
/// to warrant an outline. Mirrors the `proximityRange` argument the legacy frontend passed to `contrastingOutlineFactor`.
const OUTLINE_PROXIMITY_RANGE: f64 = 0.01;
@@ -656,61 +643,22 @@ const OUTLINE_PROXIMITY_RANGE: f64 = 0.01;
fn contrasting_outline_factor(color: Option<Color>) -> f64 {
let Some(color) = color else { return 0. };
// WCAG-style relative luminance, with alpha composited over white in gamma space
let luminance = |color: Color| {
// TODO: Remove the `.to_linear_srgb()` once we move to correctly treating `Color` as linear.
Color::WHITE
.alpha_blend(Color::from_unassociated_alpha(color.r(), color.g(), color.b(), color.a()))
.to_linear_srgb()
.luminance_srgb() as f64
// WCAG-style relative luminance, with alpha composited over white in sRGB gamma space (matching the perceptual intent of `SRGBA8::contrasting_text_color`).
let luminance_from_gamma_channels = |[r, g, b, a]: [f32; 4]| -> f64 {
let inv_a = 1. - a;
Color::from_gamma_srgb_channels(inv_a + r * a, inv_a + g * a, inv_a + b * a, 1.).luminance_rec_709() as f64
};
let distance = (luminance(POPOVER_BACKGROUND) - luminance(color)).abs().max(0.);
let color_gamma_channels = color.to_gamma_srgb_channels();
let distance = (luminance_from_gamma_channels(POPOVER_BACKGROUND_GAMMA_CHANNELS) - luminance_from_gamma_channels(color_gamma_channels))
.abs()
.max(0.);
let proximity = 1. - (distance / OUTLINE_PROXIMITY_RANGE).min(1.);
let [_, saturation, _] = rgb_to_hsv(color.r() as f64, color.g() as f64, color.b() as f64);
proximity * (1. - saturation)
let [_, saturation, _, _] = color.to_hsva();
proximity * (1. - saturation as f64)
}
/// Format a Color as a `#`-prefixed hex string, including the alpha component only if it's not fully opaque.
/// Format a linear `Color` as a `#`-prefixed hex string, including the alpha component only if it's not fully opaque.
fn color_to_hex_optional_alpha(color: &Color) -> String {
format!(
"#{}",
if color.a() >= 1. {
color.to_rgb_hex_srgb_from_gamma()
} else {
color.to_rgba_hex_srgb_from_gamma()
}
)
}
/// Parse a CSS color string (named color, hex, `rgb(...)`, etc.) into a `Color` using the `color` crate's CSS Color 4 parser.
/// Tries the input as-is first (catches CSS named colors like `red`, `rgb(...)`, and well-formed hex like `#abcdef`), then falls back to treating the input as bare hex with length-based expansion to a CSS-parseable form:
/// - 1 char `f` → `#fff` (CSS 3-char shorthand)
/// - 2 char `ab` → `#ababab` (repeated to 6 chars)
/// - 4 char `abcd` → `#00abcd` (left-padded with `00`)
/// - 5 char `abcde` → `#0abcde` (left-padded with `0`)
/// - 3, 6, 8 char inputs are passed through with a `#` prefix.
fn parse_css_color(input: &str) -> Option<Color> {
let trimmed = input.trim();
let parsed = color::parse_color(trimmed).ok().or_else(|| {
let bare = trimmed.strip_prefix('#').unwrap_or(trimmed);
if bare.is_empty() || !bare.chars().all(|c| c.is_ascii_hexdigit()) {
return None;
}
let expanded = match bare.len() {
1 => bare.repeat(3),
2 => bare.repeat(3),
4 => format!("00{bare}"),
5 => format!("0{bare}"),
_ => bare.to_string(),
};
let candidate = format!("#{expanded}");
// Avoid retrying the exact same string we just failed to parse.
(candidate != trimmed).then(|| color::parse_color(&candidate).ok()).flatten()
})?;
let srgb: AlphaColor<Srgb> = parsed.to_alpha_color();
let [red, green, blue, alpha] = srgb.components;
Color::from_rgbaf32(red, green, blue, alpha)
SRGBA8::from(*color).to_css_hex()
}
@@ -3,7 +3,7 @@ use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use crate::messages::preferences::SelectionMode;
use crate::messages::prelude::*;
use graphene_std::render_node::{EditorPreferences, wgpu_available};
use graph_craft::application_io::EditorPreferences;
#[derive(ExtractField)]
pub struct PreferencesDialogMessageContext<'a> {
@@ -307,7 +307,7 @@ impl PreferencesDialogMessageHandler {
// COMPATIBILITY
// =============
{
let wgpu_available = wgpu_available().unwrap_or(false);
let wgpu_available = graph_craft::application_io::wgpu_available().unwrap_or(false);
let is_desktop = cfg!(not(target_family = "wasm"));
if wgpu_available || is_desktop {
let header = vec![TextLabel::new("Compatibility").italic(true).widget_instance()];
@@ -0,0 +1,113 @@
// TODO: Eventually remove this document upgrade code
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
pub struct FailedToLoadDocumentsDialog {
pub failed_document_names: Vec<String>,
}
impl DialogLayoutHolder for FailedToLoadDocumentsDialog {
const ICON: &'static str = "Warning";
const TITLE: &'static str = "Failed to Open Documents";
fn layout_buttons(&self) -> Layout {
let widgets = vec![
TextButton::new("Download")
.emphasized(true)
.tooltip_description("Save the raw document data to disk so it can be recovered later.")
.on_update(|_| {
DialogMessage::CloseAndThen {
followups: vec![PortfolioMessage::DownloadFailedToLoadDocuments.into()],
}
.into()
})
.widget_instance(),
TextButton::new("Discard")
.tooltip_description("Permanently delete the autosaved data for these documents.")
.on_update(|_| {
DialogMessage::CloseAndThen {
followups: vec![PortfolioMessage::DiscardFailedToLoadDocuments.into()],
}
.into()
})
.widget_instance(),
TextButton::new("Dismiss")
.tooltip_description("Close this dialog. The autosaved data is kept and this dialog will reappear on next launch.")
.on_update(|_| FrontendMessage::DialogClose.into())
.widget_instance(),
];
Layout(vec![LayoutGroup::row(widgets)])
}
}
impl LayoutHolder for FailedToLoadDocumentsDialog {
fn layout(&self) -> Layout {
let count = self.failed_document_names.len();
let header = format!("{count} document{} couldn't be reopened.", if count == 1 { "" } else { "s" });
let list = "• ".to_string() + &self.failed_document_names.join("\n• ");
let plural_s = if count == 1 { "" } else { "s" };
let plural_it_them = if count == 1 { "it" } else { "them" };
Layout(vec![
LayoutGroup::row(vec![TextLabel::new(header).bold(true).multiline(true).widget_instance()]),
LayoutGroup::row(vec![
TextLabel::new(format!(
"Sorry about that!\n\
This shouldn't happen, and we'd like to help.\n\
\n\
Click \"Download\" to save a copy of the affected file{plural_s},\n\
then please share {plural_it_them} with us so we can investigate:"
))
.multiline(true)
.widget_instance(),
]),
LayoutGroup::row(vec![
TextButton::new("Ask on Discord")
.icon("Volunteer")
.flush(true)
.on_update(|_| {
FrontendMessage::TriggerVisitLink {
url: "https://discord.graphite.art".into(),
}
.into()
})
.widget_instance(),
]),
LayoutGroup::row(vec![
TextButton::new("Report on GitHub")
.icon("Bug")
.flush(true)
.on_update(|_| {
FrontendMessage::TriggerVisitLink {
url: "https://github.com/GraphiteEditor/Graphite/issues/new".into(),
}
.into()
})
.widget_instance(),
]),
LayoutGroup::row(vec![
TextLabel::new(
"In the meantime, you can keep working in the\n\
previous version of Graphite:",
)
.multiline(true)
.widget_instance(),
]),
LayoutGroup::row(vec![
TextButton::new("Sept. 2025 Release")
.icon("GraphiteLogo")
.flush(true)
.on_update(|_| {
FrontendMessage::TriggerVisitLink {
url: "https://57130155.graphite.pages.dev/".into(),
}
.into()
})
.widget_instance(),
]),
LayoutGroup::row(vec![TextLabel::new(format!("Affected document{plural_s}:\n{list}")).multiline(true).widget_instance()]),
])
}
}
@@ -0,0 +1,84 @@
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
pub struct FailedToOpenDocumentDialog {
pub document_name: String,
}
impl DialogLayoutHolder for FailedToOpenDocumentDialog {
const ICON: &'static str = "Warning";
const TITLE: &'static str = "Failed to Open Document";
fn layout_buttons(&self) -> Layout {
let widgets = vec![TextButton::new("OK").emphasized(true).on_update(|_| FrontendMessage::DialogClose.into()).widget_instance()];
Layout(vec![LayoutGroup::row(widgets)])
}
}
impl LayoutHolder for FailedToOpenDocumentDialog {
fn layout(&self) -> Layout {
let header = if self.document_name.trim().is_empty() {
"The document couldn't be opened.".to_string()
} else {
format!("\"{}\" couldn't be opened.", self.document_name)
};
Layout(vec![
LayoutGroup::row(vec![TextLabel::new(header).bold(true).multiline(true).widget_instance()]),
LayoutGroup::row(vec![
TextLabel::new(
"Sorry about that!\n\
This shouldn't happen, and we'd like to help.\n\
\n\
Please share the file with us so we can investigate:",
)
.multiline(true)
.widget_instance(),
]),
LayoutGroup::row(vec![
TextButton::new("Ask on Discord")
.icon("Volunteer")
.flush(true)
.on_update(|_| {
FrontendMessage::TriggerVisitLink {
url: "https://discord.graphite.art".into(),
}
.into()
})
.widget_instance(),
]),
LayoutGroup::row(vec![
TextButton::new("Report on GitHub")
.icon("Bug")
.flush(true)
.on_update(|_| {
FrontendMessage::TriggerVisitLink {
url: "https://github.com/GraphiteEditor/Graphite/issues/new".into(),
}
.into()
})
.widget_instance(),
]),
LayoutGroup::row(vec![
TextLabel::new(
"In the meantime, you can keep working in the\n\
previous version of Graphite:",
)
.multiline(true)
.widget_instance(),
]),
LayoutGroup::row(vec![
TextButton::new("Sept. 2025 Release")
.icon("GraphiteLogo")
.flush(true)
.on_update(|_| {
FrontendMessage::TriggerVisitLink {
url: "https://57130155.graphite.pages.dev/".into(),
}
.into()
})
.widget_instance(),
]),
])
}
}
@@ -4,6 +4,8 @@ mod close_document_dialog;
mod confirm_restart_dialog;
mod demo_artwork_dialog;
mod error_dialog;
mod failed_to_load_documents_dialog;
mod failed_to_open_document_dialog;
mod licenses_dialog;
mod licenses_third_party_dialog;
@@ -14,5 +16,7 @@ pub use confirm_restart_dialog::ConfirmRestartDialog;
pub use demo_artwork_dialog::ARTWORK;
pub use demo_artwork_dialog::DemoArtworkDialog;
pub use error_dialog::ErrorDialog;
pub use failed_to_load_documents_dialog::FailedToLoadDocumentsDialog;
pub use failed_to_open_document_dialog::FailedToOpenDocumentDialog;
pub use licenses_dialog::LicensesDialog;
pub use licenses_third_party_dialog::LicensesThirdPartyDialog;
@@ -13,10 +13,9 @@ use crate::messages::portfolio::utility_types::WorkspacePanelLayout;
use crate::messages::prelude::*;
use crate::messages::tool::tool_messages::eyedropper_tool::PrimarySecondary;
use graph_craft::document::NodeId;
use graphene_std::color::SRGBA8;
use graphene_std::raster::Image;
use graphene_std::raster::color::Color;
use graphene_std::text::Font;
use graphene_std::vector::style::FillChoice;
use graphene_std::vector::style::FillChoiceUI;
use std::path::PathBuf;
#[cfg(not(target_family = "wasm"))]
@@ -111,11 +110,6 @@ pub enum FrontendMessage {
name: String,
filename: String,
},
TriggerFontCatalogLoad,
TriggerFontDataLoad {
font: Font,
url: String,
},
TriggerPersistenceReadState,
TriggerPersistenceReadDocument {
#[serde(rename = "documentId")]
@@ -167,16 +161,16 @@ pub enum FrontendMessage {
document_id: DocumentId,
},
UpdateGradientStopColorPickerPosition {
color: Color, // TODO: Color (without `none`) -> Color (with `none`)
color: SRGBA8, // TODO: Color (without `none`) -> Color (with `none`)
position: (f64, f64),
},
/// The Rust color picker handler picked a new color/gradient. The frontend `<ColorPicker>` forwards this as its `colorOrGradient` event.
/// The Rust color picker handler picked a new color/gradient. The frontend `<ColorPicker />` forwards this as its `colorOrGradient` event.
ColorPickerColorChanged {
value: FillChoice,
value: FillChoiceUI,
},
/// The Rust color picker handler is starting an undo transaction. The frontend `<ColorPicker>` forwards this as its `startHistoryTransaction` event.
/// The Rust color picker handler is starting an undo transaction. The frontend `<ColorPicker />` forwards this as its `startHistoryTransaction` event.
ColorPickerStartHistoryTransaction,
/// The Rust color picker handler is committing the in-flight undo transaction. The frontend `<ColorPicker>` forwards this as its `commitHistoryTransaction` event.
/// The Rust color picker handler is committing the in-flight undo transaction. The frontend `<ColorPicker />` forwards this as its `commitHistoryTransaction` event.
ColorPickerCommitHistoryTransaction,
UpdateImportsExports {
/// If the primary import is not visible, then it is None.
@@ -241,7 +235,7 @@ pub enum FrontendMessage {
svg: String,
},
UpdateImageData {
image_data: Vec<(u64, Image<Color>)>,
image_data: Vec<(u64, Image<SRGBA8>)>,
},
UpdateDocumentLayerDetails {
data: LayerPanelEntry,
@@ -1,5 +1,7 @@
use std::path::PathBuf;
use graph_craft::application_io::resource::ResourceHash;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::utility_types::WorkspacePanelLayout;
use crate::messages::prelude::*;
@@ -10,11 +12,14 @@ pub struct DocumentInfo {
pub id: DocumentId,
pub name: String,
#[serde(default)]
#[cfg_attr(feature = "wasm", tsify(type = "unknown"))]
pub resources: Option<Box<[ResourceHash]>>,
#[serde(default)]
pub path: Option<PathBuf>,
pub is_saved: bool,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints, from_wasm_abi))]
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct PersistedState {
pub documents: Vec<DocumentInfo>,
@@ -0,0 +1,16 @@
use crate::messages::future::MessageFuture;
use crate::messages::prelude::*;
#[impl_message(Message, Future)]
#[derive(derivative::Derivative, Clone, serde::Serialize, serde::Deserialize)]
#[derivative(Debug, PartialEq)]
pub enum FutureMessage {
/// Spawn `future`; its resolved [`Message`] re-enters the dispatcher on the next tick.
Await {
#[serde(skip, default)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
future: MessageFuture,
},
/// Sent by a wake callback to nudge an idle event loop into a dispatch tick.
Wake,
}
@@ -0,0 +1,193 @@
use std::future::{Future, IntoFuture};
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use dyn_any::WasmNotSend;
use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender, unbounded};
use crate::messages::prelude::*;
#[cfg(not(target_family = "wasm"))]
type InnerMessageFuture = Pin<Box<dyn Future<Output = Message> + Send + 'static>>;
#[cfg(target_family = "wasm")]
type InnerMessageFuture = Pin<Box<dyn Future<Output = Message> + 'static>>;
/// Invoked by the spawner after a result is sent, to wake the platform event loop.
pub type Wake = Arc<dyn Fn() + Send + Sync>;
fn noop_wake() -> Wake {
Arc::new(|| {})
}
/// One-shot async work whose result re-enters the dispatcher as a [`Message`].
/// Resolves to [`Message::NoOp`] if polled after the inner future has already been taken.
#[derive(Clone, Default)]
pub struct MessageFuture {
inner: Arc<Mutex<Option<InnerMessageFuture>>>,
}
impl MessageFuture {
pub fn new(future: impl Future<Output = Message> + WasmNotSend + 'static) -> Self {
Self {
inner: Arc::new(Mutex::new(Some(Box::pin(future)))),
}
}
}
impl IntoFuture for MessageFuture {
type Output = Message;
type IntoFuture = InnerMessageFuture;
fn into_future(self) -> Self::IntoFuture {
let taken = self.inner.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).take();
match taken {
Some(future) => future,
None => Box::pin(async { Message::NoOp }),
}
}
}
impl From<MessageFuture> for Message {
fn from(future: MessageFuture) -> Self {
FutureMessage::Await { future }.into()
}
}
impl<T> From<T> for Message
where
T: Future<Output = Message> + WasmNotSend + 'static,
{
fn from(future: T) -> Self {
MessageFuture::new(future).into()
}
}
/// Platform-specific async-task executor.
/// Runs `future`, sends the resolved message on `results`, then calls `wake`.
pub trait MessageSpawner: Send + Sync {
fn spawn(&self, future: InnerMessageFuture, results: UnboundedSender<Message>, wake: Wake);
}
#[derive(ExtractField)]
pub struct FutureMessageContext {}
#[derive(ExtractField)]
pub struct FutureMessageHandler {
spawner: Arc<dyn MessageSpawner>,
wake: Wake,
results_sender: UnboundedSender<Message>,
results_receiver: UnboundedReceiver<Message>,
}
impl FutureMessageHandler {
pub fn with_wake(wake: Wake) -> Self {
let (results_sender, results_receiver) = unbounded();
Self {
spawner: default_spawner(),
wake,
results_sender,
results_receiver,
}
}
pub fn set_wake(&mut self, wake: Wake) {
self.wake = wake;
}
/// Pull every resolved async result into `out`.
pub fn drain_results(&mut self, out: &mut VecDeque<Message>) {
while let Ok(Some(message)) = self.results_receiver.try_next() {
out.push_back(message);
}
}
}
impl Default for FutureMessageHandler {
fn default() -> Self {
Self::with_wake(noop_wake())
}
}
impl std::fmt::Debug for FutureMessageHandler {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FutureMessageHandler").finish_non_exhaustive()
}
}
#[message_handler_data]
impl MessageHandler<FutureMessage, FutureMessageContext> for FutureMessageHandler {
fn process_message(&mut self, message: FutureMessage, _responses: &mut VecDeque<Message>, _context: FutureMessageContext) {
match message {
FutureMessage::Await { future } => {
self.spawner.spawn(future.into_future(), self.results_sender.clone(), self.wake.clone());
}
FutureMessage::Wake => {
// Tick-only message: the dispatcher's top-of-tick drain handles the real work.
}
}
}
advertise_actions!(FutureMessageDiscriminant;);
}
#[cfg(not(target_family = "wasm"))]
fn default_spawner() -> Arc<dyn MessageSpawner> {
Arc::new(TokioSpawner::default())
}
#[cfg(target_family = "wasm")]
fn default_spawner() -> Arc<dyn MessageSpawner> {
Arc::new(WasmSpawner)
}
#[cfg(not(target_family = "wasm"))]
struct TokioSpawner {
/// Built lazily on first spawn. `multi_thread(1)` lets Tokio manage its own driver.
runtime: std::sync::OnceLock<tokio::runtime::Runtime>,
}
#[cfg(not(target_family = "wasm"))]
impl Default for TokioSpawner {
fn default() -> Self {
Self { runtime: std::sync::OnceLock::new() }
}
}
#[cfg(not(target_family = "wasm"))]
impl TokioSpawner {
fn runtime(&self) -> &tokio::runtime::Runtime {
self.runtime.get_or_init(|| {
tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.thread_name("graphite-async")
.enable_all()
.build()
.expect("failed to construct async-message tokio runtime")
})
}
}
#[cfg(not(target_family = "wasm"))]
impl MessageSpawner for TokioSpawner {
fn spawn(&self, future: InnerMessageFuture, results: UnboundedSender<Message>, wake: Wake) {
self.runtime().spawn(async move {
let message = future.await;
let _ = results.unbounded_send(message);
wake();
});
}
}
#[cfg(target_family = "wasm")]
struct WasmSpawner;
#[cfg(target_family = "wasm")]
impl MessageSpawner for WasmSpawner {
fn spawn(&self, future: InnerMessageFuture, results: UnboundedSender<Message>, wake: Wake) {
wasm_bindgen_futures::spawn_local(async move {
let message = future.await;
let _ = results.unbounded_send(message);
wake();
});
}
}
+7
View File
@@ -0,0 +1,7 @@
mod future_message;
mod future_message_handler;
#[doc(inline)]
pub use future_message::{FutureMessage, FutureMessageDiscriminant};
#[doc(inline)]
pub use future_message_handler::{FutureMessageContext, FutureMessageHandler, MessageFuture, MessageSpawner, Wake};
@@ -26,4 +26,8 @@ pub enum LayoutMessage {
widget_id: WidgetId,
value: serde_json::Value,
},
WidgetValueDragDrop {
layout_target: LayoutTarget,
widget_id: WidgetId,
},
}
@@ -1,7 +1,8 @@
use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
use graphene_std::vector::style::FillChoice;
use graphene_std::color::SRGBA8;
use graphene_std::vector::style::FillChoiceUI;
use serde_json::Value;
use std::collections::HashMap;
@@ -61,6 +62,19 @@ impl MessageHandler<LayoutMessage, LayoutMessageContext<'_>> for LayoutMessageHa
LayoutMessage::WidgetValueUpdate { layout_target, widget_id, value } => {
self.handle_widget_callback(layout_target, widget_id, value, WidgetValueAction::Update, responses);
}
LayoutMessage::WidgetValueDragDrop { layout_target, widget_id } => {
let Some(layout) = self.layouts.get_mut(layout_target as usize) else {
warn!("WidgetValueDragDrop referenced an invalid layout. `widget_id: {widget_id}`, `layout_target: {layout_target:?}`");
return;
};
let Some(widget_instance) = layout.iter_mut().find(|widget| widget.widget_id == widget_id) else {
warn!("WidgetValueDragDrop referenced an invalid widget ID. `widget_id: {widget_id}`, `layout_target: {layout_target:?}`");
return;
};
if let Widget::IconButton(icon_button) = &mut *widget_instance.widget {
responses.add((icon_button.on_drag_drop.callback)(icon_button));
}
}
}
}
@@ -179,11 +193,11 @@ impl LayoutMessageHandler {
let callback_message = match action {
WidgetValueAction::Commit => (color_button.on_commit.callback)(&()),
WidgetValueAction::Update => {
let Ok(fill_choice) = serde_json::from_value::<FillChoice>(value) else {
warn!("ColorInput update was not able to be parsed as FillChoice: {color_button:?}");
let Ok(fill_choice_ui) = serde_json::from_value::<FillChoiceUI>(value) else {
warn!("ColorInput update was not able to be parsed as FillChoiceUI: {color_button:?}");
return;
};
color_button.value = fill_choice;
color_button.value = fill_choice_ui;
(color_button.on_update.callback)(color_button)
}
};
@@ -496,25 +510,14 @@ fn populate_computed_display_fields(layout: &mut Layout) {
}
Widget::SpectrumInput(spectrum_input) => {
spectrum_input.track_css = spectrum_input.track.to_css_linear_gradient();
spectrum_input.track_start_css = spectrum_input
.track
.color
.first()
.map(|color| format!("#{}", color.to_rgba_hex_srgb_from_gamma()))
.unwrap_or_else(|| "black".to_string());
spectrum_input.track_end_css = spectrum_input
.track
.color
.last()
.map(|color| format!("#{}", color.to_rgba_hex_srgb_from_gamma()))
.unwrap_or_else(|| "black".to_string());
spectrum_input.track_start_css = spectrum_input.track.color.first().map(|color| color.to_css_hex()).unwrap_or_else(|| "black".to_string());
spectrum_input.track_end_css = spectrum_input.track.color.last().map(|color| color.to_css_hex()).unwrap_or_else(|| "black".to_string());
}
Widget::ColorComparisonInput(comparison) => {
use graphene_std::Color;
let contrasting = |color: Option<Color>| format!("#{}", color.map_or(Color::BLACK, |color| color.contrasting_text_color_from_gamma()).to_rgba_hex_srgb_from_gamma());
comparison.new_color_css = comparison.new_color.map(|color| format!("#{}", color.to_rgba_hex_srgb_from_gamma())).unwrap_or_default();
let contrasting = |color: Option<SRGBA8>| color.map_or(SRGBA8::BLACK, |color| color.contrasting_text_color()).to_css_hex();
comparison.new_color_css = comparison.new_color.map(|color| color.to_css_hex()).unwrap_or_default();
comparison.new_color_contrasting = contrasting(comparison.new_color);
comparison.old_color_css = comparison.old_color.map(|color| format!("#{}", color.to_rgba_hex_srgb_from_gamma())).unwrap_or_default();
comparison.old_color_css = comparison.old_color.map(|color| color.to_css_hex()).unwrap_or_default();
comparison.old_color_contrasting = contrasting(comparison.old_color);
}
_ => {}
@@ -22,7 +22,7 @@ impl core::fmt::Display for WidgetId {
macro_rules! define_layout_target {
($($(#[$attr:meta])* $variant:ident),* $(,)?) => {
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
#[derive(PartialEq, Clone, Debug, Hash, Eq, Copy, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum LayoutTarget {
@@ -668,6 +668,7 @@ impl Diffable for WidgetInstance {
&& button1.tooltip_description == button2.tooltip_description
&& button1.tooltip_shortcut == button2.tooltip_shortcut
&& button1.popover_min_width == button2.popover_min_width
&& button1.popover_layout.0.len() == button2.popover_layout.0.len()
{
// Only the popover layout differs, diff it recursively
for (i, (a, b)) in button1.popover_layout.0.iter_mut().zip(button2.popover_layout.0.iter()).enumerate() {
@@ -4,7 +4,7 @@ use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
use crate::messages::tool::tool_messages::tool_prelude::WidgetCallback;
use derivative::*;
use graphene_std::vector::style::FillChoice;
use graphene_std::vector::style::FillChoiceUI;
use graphite_proc_macros::WidgetBuilder;
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -39,6 +39,9 @@ pub struct IconButton {
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_drag_drop: WidgetCallback<IconButton>,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -187,11 +190,10 @@ pub struct ImageButton {
#[derivative(Debug, PartialEq, Default)]
pub struct ColorInput {
// Content
/// WARNING: The colors are gamma, not linear!
#[widget_builder(constructor)]
pub value: FillChoice,
pub value: FillChoiceUI,
/// CSS `linear-gradient(...)` (or solid-color stand-in) for the swatch's `background-image`. Auto-populated from `value` at layout-send time.
/// `None` when `value` is `FillChoice::None`, in which case the frontend uses its "none" fallback styling.
/// `None` when `value` is `FillChoiceUI::None`, in which case the frontend uses its "none" fallback styling.
#[serde(rename = "chosenGradient")]
#[widget_builder(skip)]
pub chosen_gradient: Option<String>,
@@ -202,6 +204,13 @@ pub struct ColorInput {
#[serde(rename = "menuDirection")]
pub menu_direction: Option<MenuDirection>,
pub disabled: bool,
pub mixed: bool,
// Sizing
#[serde(rename = "minWidth")]
pub min_width: u32,
#[serde(rename = "maxWidth")]
pub max_width: u32,
// Styling
pub narrow: bool,
@@ -4,8 +4,9 @@ use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use derivative::*;
use graphene_std::Color;
use graphene_std::color::SRGBA8;
use graphene_std::transform::ReferencePoint;
use graphene_std::vector::style::{FillChoice, GradientStops};
use graphene_std::vector::style::{FillChoiceUI, GradientStopsUI};
use graphite_proc_macros::WidgetBuilder;
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -20,6 +21,7 @@ pub struct CheckboxInput {
#[serde(rename = "forLabel")]
pub for_label: CheckboxId,
pub disabled: bool,
pub mixed: bool,
// Tooltips
#[serde(rename = "tooltipLabel")]
@@ -348,9 +350,9 @@ pub struct RadioEntryData {
pub struct WorkingColorsInput {
// Content
#[widget_builder(constructor)]
pub primary: Color,
pub primary: SRGBA8,
#[widget_builder(constructor)]
pub secondary: Color,
pub secondary: SRGBA8,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -483,10 +485,10 @@ pub struct ColorComparisonInput {
// Content
#[widget_builder(constructor)]
#[serde(rename = "newColor")]
pub new_color: Option<Color>,
pub new_color: Option<SRGBA8>,
#[widget_builder(constructor)]
#[serde(rename = "oldColor")]
pub old_color: Option<Color>,
pub old_color: Option<SRGBA8>,
#[serde(rename = "isNone")]
pub is_none: bool,
#[serde(rename = "oldIsNone")]
@@ -543,7 +545,7 @@ pub struct ColorPresetsInput {
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum ColorPresetsInputUpdate {
Preset(FillChoice),
Preset(FillChoiceUI),
EyedropperColorCode(String),
}
@@ -554,7 +556,7 @@ pub struct SpectrumInput {
// Content
/// The colored gradient drawn behind the markers (display-only, caller-owned).
#[widget_builder(constructor)]
pub track: GradientStops,
pub track: GradientStopsUI,
/// CSS `linear-gradient(...)` string for the track strip's `background-image`. Auto-populated from `track` at layout-send time.
#[serde(rename = "trackCSS")]
#[widget_builder(skip)]
@@ -606,14 +608,14 @@ pub struct SpectrumMarker {
position: f64,
/// Position (0..1) of the midpoint between this marker and the next, used only if `show_midpoints` is true. The last marker's value is ignored.
midpoint: f64,
/// CSS color string for the marker handle's fill. Set via `SpectrumMarker::new` from a [`Color`] (gamma space).
/// CSS color string for the marker handle's fill. Set via `SpectrumMarker::new` from a linear [`Color`].
#[serde(rename = "handleColorCSS")]
handle_color_css: String,
}
impl SpectrumMarker {
pub fn new(position: f64, midpoint: f64, handle_color: Color) -> Self {
let handle_color_css = format!("#{}", handle_color.to_rgba_hex_srgb_from_gamma());
let handle_color_css = SRGBA8::from(handle_color).to_css_hex();
Self { position, midpoint, handle_color_css }
}
}
@@ -72,6 +72,8 @@ pub struct TextLabel {
// Sizing
#[serde(rename = "minWidth")]
pub min_width: u32,
#[serde(rename = "maxWidth")]
pub max_width: u32,
#[serde(rename = "minWidthCharacters")]
pub min_width_characters: u32,
@@ -514,6 +514,11 @@ impl LayoutHolder for MenuBarMessageHandler {
.icon("NodeShape")
.on_commit(|_| NodeGraphMessage::AddPathNode.into())
.disabled(!make_path_editable_is_allowed),
MenuListEntry::new("Expand Fill/Stroke")
.label("Expand Fill/Stroke")
.icon("ExpandFillStroke")
.on_commit(|_| DocumentMessage::ExpandFillStrokeOnSelectedLayers.into())
.disabled(no_active_document || !has_selected_layers),
],
])
.widget_instance(),
+6
View File
@@ -24,6 +24,8 @@ pub enum Message {
#[child]
Frontend(FrontendMessage),
#[child]
Future(FutureMessage),
#[child]
InputPreprocessor(InputPreprocessorMessage),
#[child]
KeyMapping(KeyMappingMessage),
@@ -32,10 +34,14 @@ pub enum Message {
#[child]
MenuBar(MenuBarMessage),
#[child]
Network(NetworkMessage),
#[child]
Portfolio(PortfolioMessage),
#[child]
Preferences(PreferencesMessage),
#[child]
ResourceStorage(ResourceStorageMessage),
#[child]
Tool(ToolMessage),
#[child]
Viewport(ViewportMessage),
+3
View File
@@ -9,13 +9,16 @@ pub mod debug;
pub mod defer;
pub mod dialog;
pub mod frontend;
pub mod future;
pub mod input_mapper;
pub mod input_preprocessor;
pub mod layout;
pub mod menu_bar;
pub mod message;
pub mod network;
pub mod portfolio;
pub mod preferences;
pub mod prelude;
pub mod resource_storage;
pub mod tool;
pub mod viewport;
+10
View File
@@ -0,0 +1,10 @@
mod network_message;
mod network_message_handler;
pub mod utility_types;
#[doc(inline)]
pub use network_message::{NetworkMessage, NetworkMessageDiscriminant};
#[doc(inline)]
pub use network_message_handler::{NetworkMessageContext, NetworkMessageHandler};
#[doc(inline)]
pub use utility_types::Client;
@@ -0,0 +1,49 @@
use std::pin::Pin;
use dyn_any::WasmNotSend;
use crate::messages::network::utility_types::Client;
use crate::messages::prelude::*;
#[impl_message(Message, Network)]
#[derive(derivative::Derivative, serde::Serialize, serde::Deserialize)]
#[derivative(Debug, PartialEq)]
pub enum NetworkMessage {
Request {
#[serde(skip, default)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
request: Option<RequestFn>,
},
}
impl NetworkMessage {
pub fn request<F, Fut>(f: F) -> Self
where
F: FnOnce(Client) -> Fut + WasmNotSend + 'static,
Fut: Future<Output = Message> + WasmNotSend + 'static,
{
NetworkMessage::Request {
request: Some(Box::new(move |c| Box::pin(f(c)))),
}
}
}
#[cfg(not(target_family = "wasm"))]
type RequestFuture = Pin<Box<dyn Future<Output = Message> + Send>>;
#[cfg(target_family = "wasm")]
type RequestFuture = Pin<Box<dyn Future<Output = Message>>>;
#[cfg(not(target_family = "wasm"))]
type RequestFn = Box<dyn FnOnce(Client) -> RequestFuture + Send>;
#[cfg(target_family = "wasm")]
type RequestFn = Box<dyn FnOnce(Client) -> RequestFuture>;
impl Clone for NetworkMessage {
fn clone(&self) -> Self {
match self {
NetworkMessage::Request { .. } => {
log::error!("Cloning a NetworkMessage::Request is not supported");
NetworkMessage::Request { request: None }
}
}
}
}
@@ -0,0 +1,27 @@
use crate::messages::network::utility_types::Client;
use crate::messages::prelude::*;
#[derive(ExtractField)]
pub struct NetworkMessageContext {}
#[derive(Debug, Default, ExtractField)]
pub struct NetworkMessageHandler {
client: Client,
}
#[message_handler_data]
impl MessageHandler<NetworkMessage, NetworkMessageContext> for NetworkMessageHandler {
fn process_message(&mut self, message: NetworkMessage, responses: &mut VecDeque<Message>, _context: NetworkMessageContext) {
match message {
NetworkMessage::Request { request } => {
if let Some(request) = request {
responses.add(request(self.client.clone()));
} else {
log::error!("received a empty NetworkMessage::Request");
}
}
}
}
advertise_actions!(NetworkMessageDiscriminant;
);
}
@@ -0,0 +1,30 @@
use reqwest::IntoUrl;
#[derive(Debug, Clone)]
pub struct Client {
inner: Option<reqwest::Client>,
}
impl Default for Client {
fn default() -> Self {
Self {
#[cfg(not(target_family = "wasm"))]
inner: reqwest::Client::builder().timeout(std::time::Duration::from_secs(100)).build().ok(),
#[cfg(target_family = "wasm")]
inner: reqwest::Client::builder().build().ok(),
}
}
}
impl Client {
pub async fn fetch<U: IntoUrl>(&self, url: U) -> Option<Box<[u8]>> {
let Some(client) = &self.inner else {
log::error!("HTTP client failed to initialize, cannot fetch");
return None;
};
let response = client.get(url).send().await;
let response = response.and_then(|r| r.error_for_status()).map_err(|err| log::error!("failed to fetch: {err}")).ok()?;
let bytes = response.bytes().await.map_err(|err| log::error!("failed to read response body: {err}")).ok()?;
Some(bytes.to_vec().into_boxed_slice())
}
}
@@ -7,12 +7,13 @@ use crate::messages::tool::tool_messages::tool_prelude::*;
use glam::{Affine2, DAffine2, Vec2};
use graph_craft::document::NodeId;
use graphene_std::blending::BlendMode;
use graphene_std::color::SRGBA8;
use graphene_std::gradient::GradientStops;
use graphene_std::list::List;
use graphene_std::memo::IORecord;
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::vector::Vector;
use graphene_std::vector::style::{Fill, FillChoice, GradientSpreadMethod, GradientType};
use graphene_std::vector::style::{Fill, FillChoice, FillChoiceUI, GradientSpreadMethod, GradientType};
use graphene_std::{Artboard, Color, Context, Graphic};
use std::any::Any;
use std::sync::Arc;
@@ -385,11 +386,15 @@ impl TableItemLayout for Vector {
match self.style.fill.clone() {
Fill::None => table_rows.push(vec![
TextLabel::new("Fill").narrow(true).widget_instance(),
ColorInput::new(FillChoice::None).disabled(true).menu_direction(Some(MenuDirection::Top)).narrow(true).widget_instance(),
ColorInput::new(FillChoiceUI::None)
.disabled(true)
.menu_direction(Some(MenuDirection::Top))
.narrow(true)
.widget_instance(),
]),
Fill::Solid(color) => table_rows.push(vec![
TextLabel::new("Fill").narrow(true).widget_instance(),
ColorInput::new(FillChoice::Solid(color))
ColorInput::new(FillChoiceUI::from(&FillChoice::Solid(color)))
.disabled(true)
.menu_direction(Some(MenuDirection::Top))
.narrow(true)
@@ -398,7 +403,7 @@ impl TableItemLayout for Vector {
Fill::Gradient(gradient) => {
table_rows.push(vec![
TextLabel::new("Fill").narrow(true).widget_instance(),
ColorInput::new(FillChoice::Gradient(gradient.stops))
ColorInput::new(FillChoiceUI::from(&FillChoice::Gradient(gradient.stops)))
.disabled(true)
.menu_direction(Some(MenuDirection::Top))
.narrow(true)
@@ -423,7 +428,11 @@ impl TableItemLayout for Vector {
let color = if let Some(color) = stroke.color { FillChoice::Solid(color) } else { FillChoice::None };
table_rows.push(vec![
TextLabel::new("Stroke").narrow(true).widget_instance(),
ColorInput::new(color).disabled(true).menu_direction(Some(MenuDirection::Top)).narrow(true).widget_instance(),
ColorInput::new(FillChoiceUI::from(&color))
.disabled(true)
.menu_direction(Some(MenuDirection::Top))
.narrow(true)
.widget_instance(),
]);
table_rows.push(vec![
TextLabel::new("Stroke Weight").narrow(true).widget_instance(),
@@ -561,10 +570,10 @@ impl TableItemLayout for Color {
"Color"
}
fn identifier(&self) -> String {
format!("Color (#{})", self.to_gamma_srgb().to_rgba_hex_srgb())
format!("Color (#{})", SRGBA8::from(*self).to_rgba_hex())
}
fn value_widget(&self, _target: PathStep, _data: &LayoutData) -> WidgetInstance {
ColorInput::new(FillChoice::Solid(*self))
ColorInput::new(FillChoiceUI::from(&FillChoice::Solid(*self)))
.disabled(true)
.menu_direction(Some(MenuDirection::Top))
.narrow(true)
@@ -584,7 +593,7 @@ impl TableItemLayout for GradientStops {
format!("Gradient ({} stops)", self.len())
}
fn value_widget(&self, _target: PathStep, _data: &LayoutData) -> WidgetInstance {
ColorInput::new(FillChoice::Gradient(self.clone()))
ColorInput::new(FillChoiceUI::from(&FillChoice::Gradient(self.clone())))
.menu_direction(Some(MenuDirection::Top))
.disabled(true)
.narrow(true)
@@ -37,6 +37,8 @@ pub enum DocumentMessage {
PropertiesPanel(PropertiesPanelMessage),
#[child]
DataPanel(DataPanelMessage),
#[child]
Resource(ResourceMessage),
// Messages
AlignSelectedLayers {
@@ -86,6 +88,8 @@ pub enum DocumentMessage {
},
BlendSelectedLayers,
MorphSelectedLayers,
ExpandFillStrokeOnSelectedLayers,
ExpandFillStrokeOnSelectedLayersNoTransaction,
GroupSelectedLayers {
group_folder_type: GroupFolderType,
},
@@ -11,7 +11,7 @@ use crate::consts::{
use crate::messages::input_mapper::utility_types::macros::action_shortcut;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::data_panel::{DataPanelMessageContext, DataPanelMessageHandler};
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::graph_operation::utility_types::{ModifyInputsContext, TransformIn};
use crate::messages::portfolio::document::node_graph::NodeGraphMessageContext;
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
@@ -20,8 +20,8 @@ use crate::messages::portfolio::document::overlays::utility_types::{OverlaysType
use crate::messages::portfolio::document::properties_panel::properties_panel_message_handler::PropertiesPanelMessageContext;
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, PTZ};
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate};
use crate::messages::portfolio::utility_types::{CachedData, PanelType};
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate, OutputConnector};
use crate::messages::portfolio::utility_types::PanelType;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::{self, get_blend_mode, get_fill, get_opacity};
use crate::messages::tool::tool_messages::select_tool::SelectToolPointerKeys;
@@ -29,18 +29,19 @@ use crate::messages::tool::tool_messages::tool_prelude::Key;
use crate::messages::tool::utility_types::ToolType;
use crate::node_graph_executor::NodeGraphExecutor;
use glam::{DAffine2, DVec2};
use graph_craft::application_io::resource::ResourceId;
use graph_craft::application_io::wgpu_available;
use graph_craft::descriptor;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork};
use graphene_std::math::quad::Quad;
use graphene_std::path_bool_nodes::boolean_intersect;
use graphene_std::raster::BlendMode;
use graphene_std::render_node::wgpu_available;
use graphene_std::subpath::Subpath;
use graphene_std::vector::PointId;
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
use graphene_std::vector::misc::dvec2_to_point;
use graphene_std::vector::style::RenderMode;
use graphene_std::vector::style::{Fill, RenderMode};
use kurbo::{Affine, BezPath, Line, PathSeg};
use std::collections::HashSet;
use std::path::PathBuf;
@@ -51,7 +52,6 @@ use std::time::Duration;
pub struct DocumentMessageContext<'a> {
pub document_id: DocumentId,
pub ipp: &'a InputPreprocessorMessageHandler,
pub cached_data: &'a CachedData,
pub executor: &'a mut NodeGraphExecutor,
pub current_tool: &'a ToolType,
pub preferences: &'a PreferencesMessageHandler,
@@ -59,6 +59,8 @@ pub struct DocumentMessageContext<'a> {
pub layers_panel_open: bool,
pub properties_panel_open: bool,
pub viewport: &'a ViewportMessageHandler,
pub resource_storage: &'a ResourceStorageMessageHandler,
pub fonts: &'a FontsMessageHandler,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ExtractField)]
@@ -85,6 +87,9 @@ pub struct DocumentMessageHandler {
//
// Contains the NodeNetwork and acts an an interface to manipulate the NodeNetwork with custom setters in order to keep NetworkMetadata in sync
pub network_interface: NodeNetworkInterface,
/// Resources embedded in the document.
#[serde(default, skip_serializing_if = "ResourceMessageHandler::is_empty")]
pub resources: ResourceMessageHandler,
/// Tracks which layer occurrences are collapsed in the Layers panel, keyed by tree path.
#[serde(deserialize_with = "deserialize_collapsed_layers", default)]
pub collapsed: CollapsedLayers,
@@ -160,6 +165,7 @@ impl Default for DocumentMessageHandler {
// Fields that are saved in the document format
// ============================================
network_interface: default_document_network_interface(),
resources: ResourceMessageHandler::default(),
collapsed: CollapsedLayers::default(),
commit_hash: GRAPHITE_GIT_COMMIT_HASH.to_string(),
document_ptz: PTZ::default(),
@@ -192,7 +198,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
let DocumentMessageContext {
document_id,
ipp,
cached_data,
executor,
viewport,
current_tool,
@@ -200,6 +205,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
data_panel_open,
layers_panel_open,
properties_panel_open,
resource_storage,
fonts,
} = context;
match message {
@@ -226,11 +233,12 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
}
DocumentMessage::PropertiesPanel(message) => {
let context = PropertiesPanelMessageContext {
executor,
network_interface: &mut self.network_interface,
resources: &self.resources,
selection_network_path: &self.selection_network_path,
document_name: self.name.as_str(),
executor,
cached_data,
fonts,
properties_panel_open,
};
self.properties_panel_message_handler.process_message(message, responses, context);
@@ -274,6 +282,10 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
let mut graph_operation_message_handler = GraphOperationMessageHandler {};
graph_operation_message_handler.process_message(message, responses, context);
}
DocumentMessage::Resource(message) => {
let context = ResourceMessageContext { document_id, fonts };
self.resources.process_message(message, responses, context);
}
DocumentMessage::AlignSelectedLayers { axis, aggregate } => {
let axis = match axis {
AlignAxis::X => DVec2::X,
@@ -631,6 +643,24 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
DocumentMessage::MorphSelectedLayers => {
self.handle_group_selected_layers(GroupFolderType::Morph, responses);
}
DocumentMessage::ExpandFillStrokeOnSelectedLayers => {
// Snapshot must be taken before the mutations, so the actual work runs as a separate message
// queued after AddTransaction (which prepends StartTransaction/CommitTransaction to the queue).
// All mutations currently target the root document network, so guard against being invoked from inside a nested network.
if !self.selection_network_path.is_empty() {
log::error!("Expanding fill/stroke is only supported for the document network");
return;
}
if self.network_interface.selected_nodes().selected_layers(self.metadata()).next().is_none() {
return;
}
responses.add(DocumentMessage::AddTransaction);
responses.add(DocumentMessage::ExpandFillStrokeOnSelectedLayersNoTransaction);
}
DocumentMessage::ExpandFillStrokeOnSelectedLayersNoTransaction => {
// Mutates the network directly, so it must be queued to run after `AddTransaction` has snapshotted the document
self.handle_expand_fill_stroke_on_selected_layers(responses);
}
DocumentMessage::GroupSelectedLayers { group_folder_type } => {
self.handle_group_selected_layers(group_folder_type, responses);
}
@@ -894,19 +924,29 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
DocumentMessage::SaveDocument | DocumentMessage::SaveDocumentAs => {
responses.add(PortfolioMessage::AutoSaveActiveDocument);
let name = format!("{}.{}", self.name.clone(), FILE_EXTENSION);
let path = if let DocumentMessage::SaveDocumentAs = message { None } else { self.path.clone() };
if path.is_some() {
responses.add(DocumentMessage::MarkAsSaved);
}
let folder = self.path.as_ref().and_then(|path| path.parent()).map(|parent| parent.to_path_buf());
responses.add(FrontendMessage::TriggerSaveDocument {
document_id,
name: format!("{}.{}", self.name.clone(), FILE_EXTENSION),
path,
folder,
content: self.serialize_document().into_bytes().into(),
let mut document = self.clone();
let resources_load_handle = resource_storage.resources();
responses.add(async move {
document.resources.collect_garbage(document.used_resources(false).as_ref());
document.resources.embed_resources(resources_load_handle).await;
let content = document.serialize_document().into_bytes().into();
Message::Frontend(FrontendMessage::TriggerSaveDocument {
document_id,
name,
path,
folder,
content,
})
});
}
DocumentMessage::SavedDocument { path } => {
@@ -1288,11 +1328,10 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
let layer_text_frames = text_frames
.into_iter()
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id))
.filter_map(|(node_id, frame)| {
self.network_interface.is_layer(&node_id, &[]).then(|| {
let layer = LayerNodeIdentifier::new(node_id, &self.network_interface);
(layer, frame)
})
.filter(|&(node_id, _)| self.network_interface.is_layer(&node_id, &[]))
.map(|(node_id, frame)| {
let layer = LayerNodeIdentifier::new(node_id, &self.network_interface);
(layer, frame)
})
.collect();
self.network_interface.update_text_frames(layer_text_frames);
@@ -2350,6 +2389,86 @@ impl DocumentMessageHandler {
}
}
/// For each selected layer, splits its fill and stroke into two stacked layers connected
/// to a shared `Solidify Stroke` node via two `Index Elements` nodes (indices 0 and 1).
/// Layers with only a stroke get just a `Solidify Stroke` added.
/// Layers with only a fill, or neither, are left untouched.
fn handle_expand_fill_stroke_on_selected_layers(&mut self, responses: &mut VecDeque<Message>) {
let selected_layers: Vec<LayerNodeIdentifier> = self.network_interface.selected_nodes().selected_layers(self.metadata()).collect();
if selected_layers.is_empty() {
return;
}
let solidify_stroke_definition = document_node_definitions::resolve_proto_node_type(graphene_std::vector::solidify_stroke::IDENTIFIER).expect("Solidify Stroke node should exist");
let index_elements_definition = document_node_definitions::resolve_proto_node_type(graphene_std::graphic::index_elements::IDENTIFIER).expect("Index Elements node should exist");
let mut resulting_layers: Vec<NodeId> = Vec::new();
for layer in selected_layers {
let style = self.network_interface.document_metadata().layer_vector_data.get(&layer).map(|arc| arc.style.clone());
let Some(style) = style else {
resulting_layers.push(layer.to_node());
continue;
};
let has_fill = !matches!(style.fill, Fill::None);
// `style.stroke` is `Some` whenever a `Stroke` node is in the chain, even with weight 0 or a transparent color.
// So `is_some()` would treat invisibly-stroked fill-only layers as having a stroke.
let has_stroke = style.stroke.as_ref().is_some_and(|s| s.has_renderable_stroke());
// No stroke means there's nothing to solidify. Fill-only layers are already in the desired form, so skip.
if !has_stroke {
resulting_layers.push(layer.to_node());
continue;
}
let solidify_id = NodeId::new();
self.network_interface.insert_node(solidify_id, solidify_stroke_definition.default_node_template(), &[]);
self.network_interface.move_node_to_chain_start(&solidify_id, layer, &[], false);
if has_fill && has_stroke {
let (existing_index, new_index) = (0_f64, 1_f64);
let existing_index_template = index_elements_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(existing_index), false))]);
let existing_index_id = NodeId::new();
self.network_interface.insert_node(existing_index_id, existing_index_template, &[]);
self.network_interface.move_node_to_chain_start(&existing_index_id, layer, &[], false);
let parent = layer.parent(self.metadata()).unwrap_or(LayerNodeIdentifier::ROOT_PARENT);
let insert_index = parent.children(self.metadata()).position(|c| c == layer).unwrap_or(0);
let new_layer_id = NodeId::new();
let new_layer = ModifyInputsContext::new(&mut self.network_interface, responses).create_layer(new_layer_id);
self.network_interface.move_layer_to_stack(new_layer, parent, insert_index, &[]);
// Copy the original layer's stored name so the new layer shares it
let original_name = self
.network_interface
.node_metadata(&layer.to_node(), &[])
.map(|m| m.persistent_metadata.display_name.clone())
.unwrap_or_default();
if !original_name.is_empty() {
self.network_interface.set_display_name(&new_layer_id, original_name, &[]);
}
let new_index_template = index_elements_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(new_index), false))]);
let new_index_id = NodeId::new();
self.network_interface.insert_node(new_index_id, new_index_template, &[]);
self.network_interface.move_node_to_chain_start(&new_index_id, new_layer, &[], false);
self.network_interface.create_wire(&OutputConnector::node(solidify_id, 0), &InputConnector::node(new_index_id, 0), &[]);
resulting_layers.push(layer.to_node());
resulting_layers.push(new_layer.to_node());
} else {
resulting_layers.push(layer.to_node());
}
}
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: resulting_layers });
responses.add(NodeGraphMessage::RunDocumentGraph);
}
/// Helper method for MoveSelectedLayersTo message.
/// Handles moving selected layers to a new parent with proper transform preservation.
fn handle_move_selected_layers_to(&mut self, parent: LayerNodeIdentifier, insert_index: usize, responses: &mut VecDeque<Message>) {
@@ -2448,6 +2567,7 @@ impl DocumentMessageHandler {
/// Helper method for NudgeSelectedLayers message.
/// Handles keyboard nudging of selected layers with optional resize mode.
#[allow(clippy::too_many_arguments)]
fn handle_nudge_selected_layers(
&mut self,
delta_x: f64,
@@ -2537,23 +2657,6 @@ impl DocumentMessageHandler {
}
}
/// Loads all of the fonts in the document.
pub fn load_layer_resources(&self, responses: &mut VecDeque<Message>) {
let mut fonts_to_load = HashSet::new();
for (_, node, _) in self.document_network().recursive_nodes() {
for input in &node.inputs {
if let Some(TaggedValue::Font(font)) = input.as_value() {
fonts_to_load.insert(font.clone());
}
}
}
for font in fonts_to_load {
responses.add(PortfolioMessage::LoadFontData { font });
}
}
pub fn update_document_widgets(&self, responses: &mut VecDeque<Message>, animation_is_playing: bool, time: Duration) {
let mut snapping_state = self.snapping_state.clone();
let mut snapping_state2 = self.snapping_state.clone();
@@ -3190,17 +3293,23 @@ impl DocumentMessageHandler {
let group_folder_type = GroupFolderType::Layer;
DocumentMessage::GroupSelectedLayers { group_folder_type }.into()
})
.on_drag_drop(|_| {
let group_folder_type = GroupFolderType::Layer;
DocumentMessage::GroupSelectedLayers { group_folder_type }.into()
})
.disabled(!has_selection)
.widget_instance(),
IconButton::new("NewLayer", 24)
.tooltip_label("New Layer")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::CreateEmptyFolder))
.on_update(|_| DocumentMessage::CreateEmptyFolder.into())
.on_drag_drop(|_| DocumentMessage::DuplicateSelectedLayers.into())
.widget_instance(),
IconButton::new("Trash", 24)
.tooltip_label("Delete Selected")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::DeleteSelectedLayers))
.on_update(|_| DocumentMessage::DeleteSelectedLayers.into())
.on_drag_drop(|_| DocumentMessage::DeleteSelectedLayers.into())
.disabled(!has_selection)
.widget_instance(),
];
@@ -3340,6 +3449,21 @@ impl DocumentMessageHandler {
pub fn graph_view_overlay_open(&self) -> bool {
self.graph_view_overlay_open
}
pub fn garbage_collect_resources(&mut self) {
let used_resources = self.used_resources(true);
self.resources.collect_garbage(&used_resources);
}
pub fn used_resources(&self, include_history: bool) -> Box<[ResourceId]> {
let mut resources = HashSet::new();
self.network_interface.collect_used_resources(&mut resources);
if include_history {
self.document_undo_history.iter().for_each(|interface| interface.collect_used_resources(&mut resources));
self.document_redo_history.iter().for_each(|interface| interface.collect_used_resources(&mut resources));
}
resources.into_iter().collect::<Vec<_>>().into_boxed_slice()
}
}
/// Create a network interface with a single export
@@ -32,7 +32,7 @@ pub struct GraphOperationMessageHandler {}
#[message_handler_data]
impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for GraphOperationMessageHandler {
fn process_message(&mut self, message: GraphOperationMessage, responses: &mut VecDeque<Message>, context: GraphOperationMessageContext) {
let network_interface = context.network_interface;
let GraphOperationMessageContext { network_interface, .. } = context;
match message {
GraphOperationMessage::FillSet { layer, fill } => {
@@ -323,7 +323,6 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
let layer = modify_inputs.create_layer(id);
modify_inputs.insert_text(text, font, typesetting, layer);
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
responses.add(GraphOperationMessage::StrokeSet { layer, stroke: Stroke::default() });
responses.add(NodeGraphMessage::RunDocumentGraph);
}
GraphOperationMessage::ResizeArtboard { layer, location, dimensions } => {
@@ -486,7 +485,8 @@ struct ArtboardInfo {
}
fn usvg_color(c: usvg::Color, a: f32) -> Color {
Color::from_rgbaf32_unchecked(c.red as f32 / 255., c.green as f32 / 255., c.blue as f32 / 255., a)
// `usvg::Color` channels are u8 sRGB display values (gamma-encoded); lift to linear-light for the internal `Color`
Color::from_gamma_srgb_channels(c.red as f32 / 255., c.green as f32 / 255., c.blue as f32 / 255., a)
}
fn usvg_transform(c: usvg::Transform) -> DAffine2 {
@@ -1,9 +1,11 @@
use super::transform_utils;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type, resolve_network_node_type, resolve_proto_node_type};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{self, InputConnector, NodeNetworkInterface, OutputConnector};
use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, OutputConnector};
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::{get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input};
use glam::{DAffine2, DVec2};
use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graph_craft::{ProtoNodeIdentifier, concrete, descriptor};
@@ -248,12 +250,13 @@ impl<'a> ModifyInputsContext<'a> {
}
pub fn insert_text(&mut self, text: String, font: Font, typesetting: TypesettingConfig, layer: LayerNodeIdentifier) {
let font_resource_id = ResourceId::new();
let text = resolve_proto_node_type(graphene_std::text::text::IDENTIFIER)
.expect("Text node does not exist")
.node_template_input_override([
Some(NodeInput::scope("editor-api")),
Some(NodeInput::value(TaggedValue::None, false)),
Some(NodeInput::value(TaggedValue::String(text), false)),
Some(NodeInput::value(TaggedValue::Font(font), false)),
Some(NodeInput::value(TaggedValue::Resource(font_resource_id), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.font_size), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.line_height_ratio), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.character_spacing), false)),
@@ -263,13 +266,11 @@ impl<'a> ModifyInputsContext<'a> {
Some(NodeInput::value(TaggedValue::F64(typesetting.max_height.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.tilt), false)),
Some(NodeInput::value(TaggedValue::TextAlign(typesetting.align), false)),
Some(NodeInput::value(TaggedValue::Bool(false), false)),
]);
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
.expect("Transform node does not exist")
.default_node_template();
let stroke = resolve_proto_node_type(graphene_std::vector_nodes::stroke::IDENTIFIER)
.expect("Stroke node does not exist")
.default_node_template();
let fill = resolve_proto_node_type(graphene_std::vector_nodes::fill::IDENTIFIER)
.expect("Fill node does not exist")
.default_node_template();
@@ -278,14 +279,12 @@ impl<'a> ModifyInputsContext<'a> {
self.network_interface.insert_node(text_id, text, &[]);
self.network_interface.move_node_to_chain_start(&text_id, layer, &[], self.import);
self.responses.add(DocumentMessage::Resource(ResourceMessage::AddFont { resource_id: font_resource_id, font }));
let transform_id = NodeId::new();
self.network_interface.insert_node(transform_id, transform, &[]);
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[], self.import);
let stroke_id = NodeId::new();
self.network_interface.insert_node(stroke_id, stroke, &[]);
self.network_interface.move_node_to_chain_start(&stroke_id, layer, &[], self.import);
let fill_id = NodeId::new();
self.network_interface.insert_node(fill_id, fill, &[]);
self.network_interface.move_node_to_chain_start(&fill_id, layer, &[], self.import);
@@ -305,13 +304,20 @@ impl<'a> ModifyInputsContext<'a> {
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: image.to_png().into(),
});
let image_node = resolve_proto_node_type(graphene_std::raster_nodes::std_nodes::image::IDENTIFIER)
.expect("Image node does not exist")
.node_template_input_override([Some(NodeInput::value(TaggedValue::None, false)), Some(NodeInput::value(TaggedValue::ImageData(image), false))]);
.node_template_input_override([Some(NodeInput::value(TaggedValue::Resource(resource_id), false))]);
let image_id = NodeId::new();
self.network_interface.insert_node(image_id, image_node, &[]);
self.network_interface.move_node_to_chain_start(&image_id, layer, &[], self.import);
let image_node_id = NodeId::new();
self.network_interface.insert_node(image_node_id, image_node, &[]);
self.network_interface.move_node_to_chain_start(&image_node_id, layer, &[], self.import);
let transform_id = NodeId::new();
self.network_interface.insert_node(transform_id, transform, &[]);
@@ -334,6 +340,37 @@ impl<'a> ModifyInputsContext<'a> {
self.existing_node_id(&DefinitionIdentifier::Network(reference.into()), create_if_nonexistent)
}
/// Like `existing_proto_node_id`, but walks/inserts at `target_input` instead of the layer's content input.
/// Used when a chain lives on a non-layer input.
pub fn existing_proto_node_id_at(&mut self, target_input: &InputConnector, reference: ProtoNodeIdentifier, create_if_nonexistent: bool) -> Option<NodeId> {
let identifier = DefinitionIdentifier::ProtoNode(reference.clone());
// Walk upstream from whatever is currently connected to target_input
let walk_start = self.network_interface.upstream_output_connector(target_input, &[]).and_then(|out| out.node_id());
let existing = walk_start.and_then(|start| {
self.network_interface
.upstream_flow_back_from_nodes(vec![start], &[], FlowType::HorizontalFlow)
.take_while(|id| !self.network_interface.is_layer(id, &[]))
.find(|id| self.network_interface.reference(id, &[]).as_ref() == Some(&identifier) && self.network_interface.is_visible(id, &[]))
});
if let Some(id) = existing {
return Some(id);
}
if !create_if_nonexistent {
return None;
}
// Splice a new node onto the wire feeding `target_input`, positioning it sensibly within the chain.
let node_definition = resolve_proto_node_type(reference)?;
let node_id = NodeId::new();
self.network_interface.insert_node(node_id, node_definition.default_node_template(), &[]);
self.network_interface.insert_node_before_input(&node_id, target_input, &[]);
Some(node_id)
}
/// Gets the node id of a proto node with a specific reference that is upstream from the layer node, and optionally creates it if it does not exist.
pub fn existing_proto_node_id(&mut self, reference: ProtoNodeIdentifier, create_if_nonexistent: bool) -> Option<NodeId> {
self.existing_node_id(&DefinitionIdentifier::ProtoNode(reference), create_if_nonexistent)
@@ -489,12 +526,14 @@ impl<'a> ModifyInputsContext<'a> {
);
}
/// Set the GradientStops list on the 'Gradient Value' node, creating it if necessary.
/// Write the gradient stops to the 'Gradient Value' node feeding the layer.
pub fn gradient_stops_set(&mut self, stops: GradientStops) {
let Some(gradient_node_id) = self.existing_proto_node_id(graphene_std::math_nodes::gradient_value::IDENTIFIER, true) else {
let Some(output_layer) = self.get_output_layer() else { return };
let Some(gradient_value_id) = get_upstream_gradient_value_node_id(output_layer, self.network_interface) else {
return;
};
let input_connector = InputConnector::node(gradient_node_id, graphene_std::math_nodes::gradient_value::GradientInput::INDEX);
let input_connector = InputConnector::node(gradient_value_id, graphene_std::math_nodes::gradient_value::GradientInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Gradient(stops), false), false);
}
@@ -504,13 +543,21 @@ impl<'a> ModifyInputsContext<'a> {
pub fn gradient_line_set(&mut self, new_start: DVec2, new_end: DVec2) {
let Some(output_layer) = self.get_output_layer() else { return };
let walk_from = if let Some(fill_input_node_id) = get_fill_input_node_id(output_layer, self.network_interface) {
// Some nodes are connected to a Fill node, this means that the primary path is a `List<Vector>`, so we need to traverse it
fill_input_node_id
} else {
// No Fill node found, we will traverse the primary path to find transforms
output_layer.to_node()
};
let transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
let upstream_transforms: Vec<NodeId> = self
.network_interface
.upstream_flow_back_from_nodes(vec![output_layer.to_node()], &[], network_interface::FlowType::HorizontalFlow)
.skip(1)
.upstream_flow_back_from_nodes(vec![walk_from], &[], FlowType::HorizontalFlow)
.skip_while(|node_id| self.network_interface.is_layer(node_id, &[]))
.take_while(|node_id| !self.network_interface.is_layer(node_id, &[]))
.filter(|node_id| self.network_interface.reference(node_id, &[]).as_ref() == Some(&transform_reference))
.filter(|id| self.network_interface.reference(id, &[]).as_ref() == Some(&transform_reference))
.collect();
// Upstream walk yields downstream-to-upstream order, so the first hit is the chain's last `Transform`
@@ -535,15 +582,10 @@ impl<'a> ModifyInputsContext<'a> {
// Rebuild the y-axis from the new x-axis using the old (parallel, perpendicular) decomposition and length ratio,
// so the gradient's aspect ratio and skew survive an endpoint drag (so an ellipse stays the same ellipse) instead of
// the old y-axis vector remaining fixed while x changes
let new_x_axis = new_end - new_start;
let preserved_y_axis = scale_y_axis_to_match_new_x(composed_old.matrix2.x_axis, composed_old.matrix2.y_axis, new_x_axis);
let new_composed = DAffine2 {
matrix2: glam::DMat2::from_cols(new_x_axis, preserved_y_axis),
translation: new_start,
};
let new_composed = build_transform_with_y_preservation(composed_old, new_start, new_end);
let last_transform_value = new_composed * prior_combined.inverse();
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let transform_node_id = if let Some(id) = last_transform_node_id {
id
} else {
@@ -551,7 +593,7 @@ impl<'a> ModifyInputsContext<'a> {
if last_transform_value.abs_diff_eq(DAffine2::IDENTITY, 1e-6) {
return;
}
let Some(id) = self.existing_proto_node_id(graphene_std::transform_nodes::transform::IDENTIFIER, true) else {
let Some(id) = self.existing_proto_node_id_at(&target_input, graphene_std::transform_nodes::transform::IDENTIFIER, true) else {
return;
};
id
@@ -565,9 +607,13 @@ impl<'a> ModifyInputsContext<'a> {
/// Write the gradient type to the last 'Gradient Type' node in the chain, inserting one only when the value differs
/// from the default (`Linear`).
pub fn gradient_type_set(&mut self, gradient_type: GradientType) {
let Some(output_layer) = self.get_output_layer() else { return };
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let identifier = graphene_std::math_nodes::gradient_type::IDENTIFIER;
let create_if_nonexistent = gradient_type != GradientType::default();
let Some(node_id) = self.existing_proto_node_id(identifier, create_if_nonexistent) else { return };
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, create_if_nonexistent) else {
return;
};
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_type::GradientTypeInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientType(gradient_type), false), false);
@@ -576,9 +622,13 @@ impl<'a> ModifyInputsContext<'a> {
/// Write the spread method to the last 'Spread Method' node in the chain, inserting one only when the value differs
/// from the default (`Pad`).
pub fn gradient_spread_method_set(&mut self, spread_method: GradientSpreadMethod) {
let Some(output_layer) = self.get_output_layer() else { return };
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let identifier = graphene_std::math_nodes::spread_method::IDENTIFIER;
let create_if_nonexistent = spread_method != GradientSpreadMethod::default();
let Some(node_id) = self.existing_proto_node_id(identifier, create_if_nonexistent) else { return };
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, create_if_nonexistent) else {
return;
};
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::spread_method::SpreadMethodInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientSpreadMethod(spread_method), false), false);
@@ -773,3 +823,14 @@ fn scale_y_axis_to_match_new_x(old_x: DVec2, old_y: DVec2, new_x: DVec2) -> DVec
scale * (parallel * ex_new + perpendicular * ey_new)
}
/// Build a new affine that maps canonical (0,0) -> (1,0) to (new_start, new_end), preserving the y-axis
/// shape of `old` proportionally to the x-axis length change.
fn build_transform_with_y_preservation(old: DAffine2, new_start: DVec2, new_end: DVec2) -> DAffine2 {
let new_x_axis = new_end - new_start;
let preserved_y_axis = scale_y_axis_to_match_new_x(old.matrix2.x_axis, old.matrix2.y_axis, new_x_axis);
DAffine2 {
matrix2: glam::DMat2::from_cols(new_x_axis, preserved_y_axis),
translation: new_start,
}
}
@@ -7,6 +7,7 @@ pub mod navigation;
pub mod node_graph;
pub mod overlays;
pub mod properties_panel;
pub mod resource;
pub mod utility_types;
#[doc(inline)]
@@ -8,8 +8,7 @@ use crate::messages::portfolio::document::utility_types::network_interface::{
DocumentNodeMetadata, DocumentNodePersistentMetadata, InputMetadata, NodeNetworkInterface, NodeNetworkMetadata, NodeNetworkPersistentMetadata, NodeTemplate, NodeTypePersistentMetadata,
Vec2InputSettings, WidgetOverride,
};
use crate::messages::portfolio::utility_types::CachedData;
use crate::messages::prelude::Message;
use crate::messages::prelude::{FontsMessageHandler, Message, ResourceMessageHandler};
use crate::node_graph_executor::NodeGraphExecutor;
use glam::DVec2;
use graph_craft::ProtoNodeIdentifier;
@@ -28,10 +27,11 @@ use serde_json::Value;
use std::collections::{HashMap, VecDeque};
pub struct NodePropertiesContext<'a> {
pub cached_data: &'a CachedData,
pub responses: &'a mut VecDeque<Message>,
pub executor: &'a mut NodeGraphExecutor,
pub network_interface: &'a mut NodeNetworkInterface,
pub resources: &'a ResourceMessageHandler,
pub fonts: &'a FontsMessageHandler,
pub selection_network_path: &'a [NodeId],
pub document_name: &'a str,
}
@@ -355,19 +355,21 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
responses.add(NodeGraphMessage::DeleteSelectedNodes { delete_children: true });
}
NodeGraphMessage::DeleteNodes { node_ids, delete_children } => {
// Detect stroke proto nodes among the doomed nodes before they're gone, so the stroke-using tools'
// Weight widgets can re-read the layer (they'll now read 0 px since the stroke node is missing).
let any_stroke_deleted = node_ids.iter().any(|node_id| {
// Detect stroke/fill proto nodes among the doomed nodes before they're gone so the tool control bars can re-sync
let stroke = DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
let fill = DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER);
let any_fill_or_stroke_deleted = node_ids.iter().any(|node_id| {
network_interface
.reference(node_id, selection_network_path)
.is_some_and(|reference| reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER))
.is_some_and(|reference| reference == stroke || reference == fill)
});
network_interface.delete_nodes(node_ids, delete_children, selection_network_path);
if any_stroke_deleted {
if any_fill_or_stroke_deleted {
responses.add(PenToolMessage::SelectionChanged);
responses.add(FreehandToolMessage::SelectionChanged);
responses.add(SplineToolMessage::SelectionChanged);
responses.add(ShapeToolMessage::SelectionChanged);
responses.add(TextToolMessage::SelectionChanged);
}
}
// Deletes selected_nodes. If `reconnect` is true, then all children nodes (secondary input) of the selected nodes are deleted and the siblings (primary input/output) are reconnected.
@@ -874,6 +876,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
self.context_menu = Some(ContextMenuInformation {
context_menu_coordinates: (node_graph_point + node_graph_shift).as_ivec2().into(),
node_creation_coordinates: node_graph_point.as_ivec2().into(),
context_menu_data,
});
@@ -1313,6 +1316,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
self.context_menu = Some(ContextMenuInformation {
context_menu_coordinates: (point + node_graph_shift).as_ivec2().into(),
node_creation_coordinates: point.as_ivec2().into(),
context_menu_data: ContextMenuData::CreateNode { compatible_type },
});
@@ -1555,7 +1559,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
// Only disconnect inputs to non selected nodes
if network_interface
.upstream_output_connector(&input_connector, selection_network_path)
.is_some_and(|connector| connector.node_id().map_or(true, |node_id| !all_selected_nodes.contains(&node_id)))
.is_some_and(|connector| connector.node_id().is_none_or(|node_id| !all_selected_nodes.contains(&node_id)))
{
responses.add(NodeGraphMessage::DisconnectInput { input_connector });
}
@@ -1740,21 +1744,17 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
}
NodeGraphMessage::SetInputValue { node_id, input_index, value } => {
use graphene_std::vector::generator_nodes::*;
let is_fill = matches!(value, TaggedValue::Fill(_));
let reference = network_interface.reference(&node_id, selection_network_path);
let is_text_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER));
let is_stroke_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER));
let is_fill_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER));
let is_shape_generator_node = reference.as_ref().is_some_and(|r| {
[
graphene_std::vector::generator_nodes::regular_polygon::IDENTIFIER,
graphene_std::vector::generator_nodes::star::IDENTIFIER,
graphene_std::vector::generator_nodes::arc::IDENTIFIER,
graphene_std::vector::generator_nodes::spiral::IDENTIFIER,
graphene_std::vector::generator_nodes::grid::IDENTIFIER,
graphene_std::vector::generator_nodes::arrow::IDENTIFIER,
]
.into_iter()
.any(|id| *r == DefinitionIdentifier::ProtoNode(id))
[regular_polygon::IDENTIFIER, star::IDENTIFIER, arc::IDENTIFIER, spiral::IDENTIFIER, grid::IDENTIFIER, arrow::IDENTIFIER]
.into_iter()
.any(|id| *r == DefinitionIdentifier::ProtoNode(id))
});
let input = NodeInput::value(value, false);
@@ -1766,15 +1766,12 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
if is_fill {
responses.add(OverlaysMessage::Draw);
}
if is_text_node {
responses.add(TextToolMessage::SelectionChanged);
}
if is_stroke_node || is_shape_generator_node {
// The dispatcher delivers each only to its tool when active, so this just covers all four stroke-using tools.
if is_stroke_node || is_fill_node || is_shape_generator_node || is_text_node {
responses.add(PenToolMessage::SelectionChanged);
responses.add(FreehandToolMessage::SelectionChanged);
responses.add(SplineToolMessage::SelectionChanged);
responses.add(ShapeToolMessage::SelectionChanged);
responses.add(TextToolMessage::SelectionChanged);
}
if network_interface.connected_to_output(&node_id, selection_network_path) {
responses.add(NodeGraphMessage::RunDocumentGraph);
@@ -6,12 +6,13 @@ use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
use crate::messages::portfolio::utility_types::{CachedData, FontCatalogStyle};
use crate::messages::portfolio::fonts::utility_types::FontCatalogStyle;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils;
use choice::enum_choice;
use dyn_any::DynAny;
use glam::{DAffine2, DVec2};
use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
use graph_craft::{Type, concrete};
@@ -30,7 +31,7 @@ use graphene_std::text_nodes::StringCapitalization;
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
use graphene_std::vector::misc::BooleanOperation;
use graphene_std::vector::misc::{ArcType, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType};
use graphene_std::vector::style::{Fill, FillChoice, GradientSpreadMethod, GradientStops, GradientType, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::style::{Fill, FillChoice, FillChoiceUI, GradientSpreadMethod, GradientStops, GradientStopsUI, GradientType, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
pub(crate) fn string_properties(text: &str) -> Vec<LayoutGroup> {
@@ -276,7 +277,7 @@ pub(crate) fn property_from_type(
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextLabel::new("-")
.tooltip_label(format!("Data Type: {concrete_type}"))
.tooltip_label(concrete_type.to_string())
.tooltip_description("This data can only be supplied through the node graph because no widget exists for its type.")
.widget_instance(),
]);
@@ -822,11 +823,27 @@ pub fn array_of_number_widget(parameter_widgets_info: ParameterWidgetsInfo, text
}
pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetInstance>, Option<Vec<WidgetInstance>>) {
pub fn assign_font_message(node_id: NodeId, font: Font) -> Message {
let resource_id = ResourceId::new();
Message::Batched {
messages: Box::new([
DocumentMessage::Resource(ResourceMessage::AddFont { resource_id, font }).into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: graphene_std::text::text::FontInput::INDEX,
value: TaggedValue::Resource(resource_id),
}
.into(),
]),
}
}
let ParameterWidgetsInfo {
cached_data,
document_node,
node_id,
index,
resources,
fonts,
..
} = parameter_widgets_info;
@@ -839,66 +856,32 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
return (vec![], None);
};
if let Some(TaggedValue::Font(font)) = &input.as_non_exposed_value() {
if let Some(TaggedValue::Resource(resource_id)) = input.as_non_exposed_value() {
let font = fonts.id_font(resources, *resource_id).unwrap_or_default();
first_widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
DropdownInput::new(vec![
cached_data
fonts
.font_catalog
.0
.iter()
.map(|family| {
let FontCatalogStyle { weight, italic, .. } = FontCatalogStyle::from_named_style(&font.font_style, "");
let new_font = Font::new(family.name.clone(), family.closest_style(weight, italic).to_named_style());
let commit_font = new_font.clone();
MenuListEntry::new(family.name.clone())
.label(family.name.clone())
.font(family.closest_style(400, false).preview_url(&family.name))
.on_update({
// Construct the new font using the new family and the initial or previous style, although this style might not exist in the catalog
let mut new_font = Font::new(family.name.clone(), font.font_style_to_restore.clone().unwrap_or_else(|| font.font_style.clone()));
new_font.font_style_to_restore = font.font_style_to_restore.clone();
// If not already, store the initial style so it can be restored if the user switches to another family
if new_font.font_style_to_restore.is_none() {
new_font.font_style_to_restore = Some(new_font.font_style.clone());
}
// Use the closest style available in the family for the new font to ensure the style exists
let FontCatalogStyle { weight, italic, .. } = FontCatalogStyle::from_named_style(&new_font.font_style, "");
new_font.font_style = family.closest_style(weight, italic).to_named_style();
move |_| {
let new_font = new_font.clone();
Message::Batched {
messages: Box::new([
PortfolioMessage::LoadFontData { font: new_font.clone() }.into(),
update_value(move |_| TaggedValue::Font(new_font.clone()), node_id, index)(&()),
]),
}
}
})
.on_commit({
// Use the new value from the user selection
let font_family = family.name.clone();
// Use the previous style selection and extract its weight and italic properties, then find the closest style in the new family
let FontCatalogStyle { weight, italic, .. } = FontCatalogStyle::from_named_style(&font.font_style, "");
let font_style = family.closest_style(weight, italic).to_named_style();
move |_| {
// Intentionally drop `font_style_to_restore` on commit so the committed style becomes the new basis
// for subsequent family switches. Preserving the original style intent is hover-only behavior.
let new_font = Font::new(font_family.clone(), font_style.clone());
DeferMessage::AfterGraphRun {
messages: vec![update_value(move |_| TaggedValue::Font(new_font.clone()), node_id, index)(&()), commit_value(&())],
}
.into()
.on_update(move |_| assign_font_message(node_id, new_font.clone()))
.on_commit(move |_| {
DeferMessage::AfterGraphRun {
messages: vec![assign_font_message(node_id, commit_font.clone()), commit_value(&())],
}
.into()
})
})
.collect::<Vec<_>>(),
])
.selected_index(cached_data.font_catalog.0.iter().position(|family| family.name == font.font_family).map(|i| i as u32))
.selected_index(fonts.font_catalog.iter().position(|family| family.name == font.font_family).map(|i| i as u32))
.virtual_scrolling(true)
.widget_instance(),
]);
@@ -908,32 +891,18 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
second_row.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
DropdownInput::new({
cached_data
fonts
.font_catalog
.0
.iter()
.find(|family| family.name == font.font_family)
.map(|family| {
let build_entry = |style: &FontCatalogStyle| {
let font_style = style.to_named_style();
let font_family = font.font_family.clone();
let new_font = Font::new(font_family, font_style.clone());
MenuListEntry::new(font_style.clone())
.label(font_style.clone())
.on_update({
let font_family = font.font_family.clone();
let font_style = font_style.clone();
move |_| {
// Keep the existing family
let new_font = Font::new(font_family.clone(), font_style.clone());
Message::Batched {
messages: Box::new([
PortfolioMessage::LoadFontData { font: new_font.clone() }.into(),
update_value(move |_| TaggedValue::Font(new_font.clone()), node_id, index)(&()),
]),
}
}
})
.label(font_style)
.on_update(move |_| assign_font_message(node_id, new_font.clone()))
.on_commit(commit_value)
};
@@ -946,9 +915,8 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
.unwrap_or_default()
})
.selected_index(
cached_data
fonts
.font_catalog
.0
.iter()
.find(|family| family.name == font.font_family)
.and_then(|family| {
@@ -1164,19 +1132,19 @@ pub fn color_widget(parameter_widgets_info: ParameterWidgetsInfo, color_button:
match &**tagged_value {
TaggedValue::Color(color) => widgets.push(
color_button
.value(match color {
.value(FillChoiceUI::from(&match color {
Some(color) => FillChoice::Solid(*color),
None => FillChoice::None,
})
.on_update(update_value(|input: &ColorInput| TaggedValue::Color(input.value.as_solid()), node_id, index))
}))
.on_update(update_value(|input: &ColorInput| TaggedValue::Color(input.value.as_solid().map(Color::from)), node_id, index))
.on_commit(commit_value)
.widget_instance(),
),
TaggedValue::Gradient(stops) => widgets.push(
color_button
.value(FillChoice::Gradient(stops.clone()))
.value(FillChoiceUI::from(&FillChoice::Gradient(stops.clone())))
.on_update(update_value(
|input: &ColorInput| TaggedValue::Gradient(input.value.as_gradient().cloned().unwrap_or_default()),
|input: &ColorInput| TaggedValue::Gradient(input.value.as_gradient().map(GradientStops::from).unwrap_or_default()),
node_id,
index,
))
@@ -1417,7 +1385,7 @@ fn build_shared_spectrum_section(node_id: NodeId, context: &mut NodePropertiesCo
// Build the shared spectrum widget (placed on the first non-exposed row)
let spectrum_widget = (!spectrum_markers.is_empty()).then(|| {
SpectrumInput::new(bw_track())
SpectrumInput::new(GradientStopsUI::from(&bw_track()))
.markers(spectrum_markers)
.show_midpoints(false)
.allow_insert(false)
@@ -1591,7 +1559,7 @@ fn spectrum_slider_row(
let position_to_value = move |position: f64| value_min + position * value_range;
row.push(
SpectrumInput::new(track)
SpectrumInput::new(GradientStopsUI::from(&track))
.markers(vec![SpectrumMarker::new(position, 0.5, handle_color)])
.show_midpoints(false)
.allow_insert(false)
@@ -2482,7 +2450,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
widgets_first_row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
widgets_first_row.push(
ColorInput::default()
.value(fill.clone().into())
.value(FillChoiceUI::from(&FillChoice::from(fill.clone())))
.on_update(move |x: &ColorInput| Message::Batched {
messages: Box::new([
match &fill2 {
@@ -2508,7 +2476,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
NodeGraphMessage::SetInputValue {
node_id,
input_index: FillInput::<Color>::INDEX,
value: TaggedValue::Fill(x.value.to_fill(fill2.as_gradient())),
value: TaggedValue::Fill(FillChoice::from(&x.value).to_fill(fill2.as_gradient())),
}
.into(),
]),
@@ -2813,8 +2781,8 @@ pub fn math_properties(node_id: NodeId, context: &mut NodePropertiesContext) ->
}
pub struct ParameterWidgetsInfo<'a> {
cached_data: &'a CachedData,
network_interface: &'a NodeNetworkInterface,
resources: &'a ResourceMessageHandler,
selection_network_path: &'a [NodeId],
document_node: Option<&'a DocumentNode>,
node_id: NodeId,
@@ -2824,6 +2792,7 @@ pub struct ParameterWidgetsInfo<'a> {
input_type: FrontendGraphDataType,
blank_assist: bool,
exposable: bool,
fonts: &'a FontsMessageHandler,
}
impl<'a> ParameterWidgetsInfo<'a> {
@@ -2836,9 +2805,10 @@ impl<'a> ParameterWidgetsInfo<'a> {
let document_node = context.network_interface.document_node(&node_id, context.selection_network_path);
ParameterWidgetsInfo {
cached_data: context.cached_data,
network_interface: context.network_interface,
resources: context.resources,
selection_network_path: context.selection_network_path,
fonts: context.fonts,
document_node,
node_id,
index,
@@ -162,9 +162,12 @@ pub enum ContextMenuData {
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ContextMenuInformation {
// Stores whether the context menu is open and its position in graph coordinates
// The menu's display position in graph coordinates, which may be shifted from the click point to keep the menu on-screen
#[serde(rename = "contextMenuCoordinates")]
pub context_menu_coordinates: (i32, i32),
// The click point in graph coordinates, where a node created from the menu is placed (unshifted, unlike the display position)
#[serde(rename = "nodeCreationCoordinates")]
pub node_creation_coordinates: (i32, i32),
#[serde(rename = "contextMenuData")]
pub context_menu_data: ContextMenuData,
}
@@ -3,9 +3,9 @@ use crate::messages::portfolio::document::overlays::utility_types::OverlayContex
use crate::messages::portfolio::document::utility_types::misc::{GridSnapping, GridType};
use crate::messages::prelude::*;
use glam::DVec2;
use graphene_std::raster::color::Color;
use graphene_std::color::SRGBA8;
use graphene_std::renderer::Quad;
use graphene_std::vector::style::FillChoice;
use graphene_std::vector::style::FillChoiceUI;
fn grid_overlay_rectangular(document: &DocumentMessageHandler, overlay_context: &mut OverlayContext, spacing: DVec2) {
let origin = document.snapping_state.grid.origin;
@@ -231,7 +231,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
widgets.push(LayoutGroup::row(vec![TextLabel::new("Grid").bold(true).widget_instance()]));
widgets.push(LayoutGroup::row(vec![
TextLabel::new("Type").table_align(true).widget_instance(),
TextLabel::new("Type").min_width(60).max_width(60).table_align(true).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
RadioInput::new(vec![
RadioEntryData::new("rectangular").label("Rectangular").on_update(update_val(grid, |grid, _| {
@@ -262,7 +262,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
]));
let mut color_widgets = vec![
TextLabel::new("Display").table_align(true).widget_instance(),
TextLabel::new("Display").min_width(60).max_width(60).table_align(true).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
];
color_widgets.extend([
@@ -274,12 +274,12 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
Separator::new(SeparatorStyle::Related).widget_instance(),
]);
color_widgets.push(
ColorInput::new(FillChoice::Solid(Color::from_hex_str(&grid.color).unwrap_or(Color::BLACK)))
ColorInput::new(FillChoiceUI::Solid(SRGBA8::from_hex_str(&grid.color).unwrap_or(SRGBA8::BLACK)))
.tooltip_label("Grid Display Color")
.allow_none(false)
.on_update(update_val::<ColorInput, _>(grid, |grid, color| {
if let Some(color) = color.value.as_solid() {
grid.color = format!("#{}", color.to_rgba_hex_srgb_from_gamma());
if let Some(srgba) = color.value.as_solid() {
grid.color = srgba.to_css_hex();
}
}))
.widget_instance(),
@@ -287,7 +287,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
widgets.push(LayoutGroup::row(color_widgets));
widgets.push(LayoutGroup::row(vec![
TextLabel::new("Origin").table_align(true).widget_instance(),
TextLabel::new("Origin").min_width(60).max_width(60).table_align(true).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(grid.origin.x))
.label("X")
@@ -306,7 +306,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
match grid.grid_type {
GridType::Rectangular { spacing } => widgets.push(LayoutGroup::row(vec![
TextLabel::new("Spacing").table_align(true).widget_instance(),
TextLabel::new("Spacing").min_width(60).max_width(60).table_align(true).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(spacing.x))
.label("X")
@@ -326,7 +326,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
])),
GridType::Isometric { y_axis_spacing, angle_a, angle_b } => {
widgets.push(LayoutGroup::row(vec![
TextLabel::new("Y Spacing").table_align(true).widget_instance(),
TextLabel::new("Y Spacing").min_width(60).max_width(60).table_align(true).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(y_axis_spacing))
.unit(" px")
@@ -336,7 +336,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
.widget_instance(),
]));
widgets.push(LayoutGroup::row(vec![
TextLabel::new("Angles").table_align(true).widget_instance(),
TextLabel::new("Angles").min_width(60).max_width(60).table_align(true).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(angle_a))
.unit("°")
@@ -2,11 +2,12 @@ use super::utility_types::{DrawHandles, OverlayContext};
use crate::consts::HIDE_HANDLE_DISTANCE;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
use crate::messages::portfolio::fonts::FALLBACK_FONT_RESOURCE;
use crate::messages::tool::common_functionality::shape_editor::{SelectedLayerState, ShapeState};
use crate::messages::tool::tool_messages::tool_prelude::DocumentMessageHandler;
use glam::{DAffine2, DVec2};
use graphene_std::subpath::{Bezier, BezierHandles};
use graphene_std::text::{Font, FontCache, TextAlign, TextContext, TypesettingConfig};
use graphene_std::text::{TextAlign, TextContext, TypesettingConfig};
use graphene_std::vector::misc::ManipulatorPointId;
use graphene_std::vector::{PointId, SegmentId, Vector};
use std::collections::HashMap;
@@ -221,16 +222,6 @@ pub fn path_endpoint_overlays(document: &DocumentMessageHandler, shape_editor: &
}
}
// Global lazy initialized font cache and text context
pub static GLOBAL_FONT_CACHE: LazyLock<FontCache> = LazyLock::new(|| {
let mut font_cache = FontCache::default();
// Initialize with the hardcoded font used by overlay text
const FONT_DATA: &[u8] = include_bytes!("source-sans-pro-regular.ttf");
let font = Font::new("Source Sans Pro".to_string(), "Regular".to_string());
font_cache.insert(font, FONT_DATA.to_vec());
font_cache
});
pub static GLOBAL_TEXT_CONTEXT: LazyLock<Mutex<TextContext>> = LazyLock::new(|| Mutex::new(TextContext::default()));
pub fn text_width(text: &str, font_size: f64) -> f64 {
@@ -244,12 +235,8 @@ pub fn text_width(text: &str, font_size: f64) -> f64 {
align: TextAlign::AlignLeft,
};
// Load Source Sans Pro font data
// TODO: Grab this from the node_modules folder (either with `include_bytes!` or ideally at runtime) instead of checking the font file into the repo.
// TODO: And maybe use the WOFF2 version (if it's supported) for its smaller, compressed file size.
let font = Font::new("Source Sans Pro".to_string(), "Regular".to_string());
let mut text_context = GLOBAL_TEXT_CONTEXT.lock().expect("Failed to lock global text context");
let bounds = text_context.bounding_box(text, &font, &GLOBAL_FONT_CACHE, typesetting, false);
let bounds = text_context.bounding_box(text, &FALLBACK_FONT_RESOURCE, typesetting, false);
bounds.x
}
@@ -3,8 +3,9 @@ use crate::consts::{
COLOR_OVERLAY_YELLOW_DULL, COMPASS_ROSE_ARROW_SIZE, COMPASS_ROSE_HOVER_RING_DIAMETER, COMPASS_ROSE_MAIN_RING_DIAMETER, COMPASS_ROSE_RING_INNER_DIAMETER, DOWEL_PIN_RADIUS,
GRADIENT_MIDPOINT_DIAMOND_RADIUS, MANIPULATOR_GROUP_MARKER_SIZE, PIVOT_CROSSHAIR_LENGTH, PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER, RESIZE_HANDLE_SIZE, SKEW_TRIANGLE_OFFSET, SKEW_TRIANGLE_SIZE,
};
use crate::messages::portfolio::document::overlays::utility_functions::{GLOBAL_FONT_CACHE, GLOBAL_TEXT_CONTEXT, hex_to_rgba_u8};
use crate::messages::portfolio::document::overlays::utility_functions::{GLOBAL_TEXT_CONTEXT, hex_to_rgba_u8};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::fonts::FALLBACK_FONT_RESOURCE;
use crate::messages::prelude::Message;
use crate::messages::prelude::ViewportMessageHandler;
use core::borrow::Borrow;
@@ -14,7 +15,7 @@ use graphene_std::ATTR_TRANSFORM;
use graphene_std::list::List;
use graphene_std::math::quad::Quad;
use graphene_std::subpath::{self, Subpath};
use graphene_std::text::{Font, TextAlign, TypesettingConfig};
use graphene_std::text::{TextAlign, TypesettingConfig};
use graphene_std::vector::click_target::ClickTargetType;
use graphene_std::vector::misc::point_to_dvec2;
use graphene_std::vector::{PointId, SegmentId, Vector};
@@ -1115,21 +1116,16 @@ impl OverlayContextInternal {
align: TextAlign::AlignLeft,
};
// Load Source Sans Pro font data
// TODO: Grab this from the node_modules folder (either with `include_bytes!` or ideally at runtime) instead of checking the font file into the repo.
// TODO: And maybe use the WOFF2 version (if it's supported) for its smaller, compressed file size.
let font = Font::new("Source Sans Pro".to_string(), "Regular".to_string());
// Get text dimensions directly from layout
let mut text_context = GLOBAL_TEXT_CONTEXT.lock().expect("Failed to lock global text context");
let text_size = text_context.bounding_box(text, &font, &GLOBAL_FONT_CACHE, typesetting, false);
let text_size = text_context.bounding_box(text, &FALLBACK_FONT_RESOURCE, typesetting, false);
let text_width = text_size.x;
let text_height = text_size.y;
// Create a rect from the size (assuming text starts at origin)
let text_bounds = kurbo::Rect::new(0., 0., text_width, text_height);
// Convert text to vector paths for rendering
let text_list = text_context.to_path(text, &font, &GLOBAL_FONT_CACHE, typesetting, false);
let text_list = text_context.to_path(text, &FALLBACK_FONT_RESOURCE, typesetting, false);
// Calculate position based on pivot
let mut position = DVec2::ZERO;
@@ -1040,7 +1040,7 @@ impl OverlayContext {
}
let image_data = web_sys::ImageData::new_with_u8_clamped_array_and_sh(wasm_bindgen::Clamped(&data), PATTERN_WIDTH as u32, PATTERN_HEIGHT as u32).unwrap();
pattern_context.put_image_data(&image_data, 0., 0.).unwrap();
pattern_context.put_image_data(&image_data, 0, 0).unwrap();
let pattern = self.render_context.create_pattern_with_offscreen_canvas(&pattern_canvas, "repeat").unwrap().unwrap();
self.push_path(subpaths, transform);
@@ -3,17 +3,17 @@ use graphene_std::uuid::NodeId;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::NodePropertiesContext;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
use crate::messages::portfolio::utility_types::CachedData;
use crate::messages::prelude::*;
use crate::node_graph_executor::NodeGraphExecutor;
#[derive(ExtractField)]
pub struct PropertiesPanelMessageContext<'a> {
pub executor: &'a mut NodeGraphExecutor,
pub network_interface: &'a mut NodeNetworkInterface,
pub resources: &'a ResourceMessageHandler,
pub selection_network_path: &'a [NodeId],
pub document_name: &'a str,
pub executor: &'a mut NodeGraphExecutor,
pub cached_data: &'a CachedData,
pub fonts: &'a FontsMessageHandler,
pub properties_panel_open: bool,
}
@@ -24,11 +24,12 @@ pub struct PropertiesPanelMessageHandler {}
impl MessageHandler<PropertiesPanelMessage, PropertiesPanelMessageContext<'_>> for PropertiesPanelMessageHandler {
fn process_message(&mut self, message: PropertiesPanelMessage, responses: &mut VecDeque<Message>, context: PropertiesPanelMessageContext) {
let PropertiesPanelMessageContext {
executor,
network_interface,
resources,
selection_network_path,
document_name,
executor,
cached_data,
fonts,
properties_panel_open,
} = context;
@@ -46,12 +47,13 @@ impl MessageHandler<PropertiesPanelMessage, PropertiesPanelMessageContext<'_>> f
}
let mut node_properties_context = NodePropertiesContext {
cached_data,
responses,
executor,
network_interface,
resources,
selection_network_path,
document_name,
executor,
fonts,
};
let layout = Layout(NodeGraphMessageHandler::collate_properties(&mut node_properties_context));
@@ -0,0 +1,8 @@
mod resource_message;
mod resource_message_handler;
pub mod utility_types;
#[doc(inline)]
pub use resource_message::{ResourceMessage, ResourceMessageDiscriminant};
#[doc(inline)]
pub use resource_message_handler::{ResourceMessageContext, ResourceMessageHandler};
@@ -0,0 +1,15 @@
use crate::messages::prelude::*;
use graph_craft::application_io::resource::{DataSource, ResourceHash, ResourceId};
use graphene_std::text::Font;
use std::sync::Arc;
#[impl_message(Message, DocumentMessage, Resource)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum ResourceMessage {
StoreEmbedded { resource_id: ResourceId, data: Arc<[u8]> },
AddFont { resource_id: ResourceId, font: Font },
ResolveAll,
Resolve { resource_id: ResourceId },
Resolved { resource_id: ResourceId, source: DataSource, hash: ResourceHash },
ResolveFailed { resource_id: ResourceId },
}
@@ -0,0 +1,299 @@
use crate::messages::network::Client;
use crate::messages::portfolio::{document::resource::utility_types::EmbeddedResources, fonts::utility_types::FontCatalog};
use crate::messages::prelude::*;
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use graph_craft::application_io::resource::{DataSource, LoadResource, Resource, ResourceHash, ResourceId, ResourceRegistry};
use graphene_std::text::Font;
use std::sync::Arc;
use url::Url;
#[derive(ExtractField)]
pub struct ResourceMessageContext<'a> {
pub document_id: DocumentId,
pub fonts: &'a FontsMessageHandler,
}
#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, ExtractField)]
pub struct ResourceMessageHandler {
pub registry: ResourceRegistry,
pub embedded: EmbeddedResources,
#[serde(skip)]
pending_resolves: HashSet<ResourceId>,
}
#[message_handler_data]
impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMessageHandler {
fn process_message(&mut self, message: ResourceMessage, responses: &mut VecDeque<Message>, context: ResourceMessageContext) {
let ResourceMessageContext { document_id, fonts } = context;
match message {
ResourceMessage::StoreEmbedded { resource_id, data } => {
let hash = ResourceHash::from(data.as_ref());
self.registry.push_source_back(&resource_id, DataSource::Embedded);
self.registry.resolve(&resource_id, hash);
responses.add(ResourceStorageMessage::Store { data });
}
ResourceMessage::AddFont { resource_id, font } => {
let style = fonts.font_catalog.find_font_style_in_catalog(&font);
let style_name = style.map(|style| style.to_named_style()).unwrap_or_else(|| font.font_style.clone());
self.registry.push_source_back(&resource_id, DataSource::Embedded);
self.registry.push_source_back(
&resource_id,
DataSource::Font {
family: font.font_family,
style: Some(style_name),
},
);
responses.add(ResourceMessage::Resolve { resource_id });
}
ResourceMessage::ResolveAll => {
let unresolved_ids: Vec<ResourceId> = self.registry.unresolved().map(|info| info.id).collect();
for id in unresolved_ids {
if self.pending_resolves.contains(&id) {
continue;
}
responses.add(ResourceMessage::Resolve { resource_id: id });
}
}
ResourceMessage::Resolve { resource_id } => {
if self.pending_resolves.contains(&resource_id) {
log::warn!("Already pending resolve for {resource_id}; skipping");
return;
}
let Some(info) = self.registry.info(&resource_id) else {
log::error!("Resolve for {resource_id}: no registry entry");
return;
};
if info.hash.is_some() {
log::warn!("Resource {resource_id} already resolved");
return;
}
self.pending_resolves.insert(resource_id);
let font_catalog = fonts.font_catalog.clone();
let sources = info
.sources
.iter()
.map(|source| match source {
DataSource::Font { family, style } => {
let font = match style {
Some(style) => Font::new(family.clone(), style.clone()),
None => Font::new_with_default_style(family.clone()),
};
let hash = fonts.cached_hash(&font);
(source.clone(), hash)
}
source => (source.clone(), None),
})
.collect::<Vec<(DataSource, Option<ResourceHash>)>>();
async fn resolve_to_message(document_id: DocumentId, resource_id: ResourceId, source: DataSource, url: Url, client: &Client) -> Option<Message> {
let result = client.fetch(url.clone()).await;
match result {
Some(data) => {
let hash = ResourceHash::from(data.as_ref());
Some(Message::Batched {
messages: Box::new([
PortfolioMessage::DocumentPassMessage {
document_id,
message: ResourceMessage::Resolved { resource_id, source, hash }.into(),
}
.into(),
ResourceStorageMessage::Store { data: Arc::from(data) }.into(),
]),
})
}
None => {
log::warn!("Failed to fetch resource {resource_id} from {url}");
None
}
}
}
responses.add(NetworkMessage::request(async move |client| {
let mut loaded_catalog = None;
let mut response: Option<Message> = None;
for (source, hash) in sources {
if let Some(hash) = hash {
response = Some(ResourceMessage::Resolved { resource_id, source, hash }.into());
break;
}
match &source {
DataSource::Embedded => continue,
DataSource::Url(url) => {
response = resolve_to_message(document_id, resource_id, source.clone(), url.clone(), &client).await;
}
DataSource::Font { family, style } => {
let font = match style {
Some(style) => Font::new(family.clone(), style.clone()),
None => Font::new_with_default_style(family.clone()),
};
if font_catalog.is_empty() && loaded_catalog.as_ref().is_none() {
loaded_catalog = FontCatalog::load_from_api(&client).await;
}
let url = loaded_catalog.as_ref().and_then(|catalog| catalog.download_url(&font)).or_else(|| font_catalog.download_url(&font));
if let Some(url) = url {
let Ok(url) = Url::parse(&url) else {
log::warn!("Invalid URL {url} for font resource {resource_id}");
continue;
};
response = resolve_to_message(document_id, resource_id, source.clone(), url, &client).await;
} else {
log::warn!("No download URL found for font resource {resource_id}");
}
}
}
if response.is_some() {
break;
}
}
let mut response = response.unwrap_or_else(|| {
log::error!("Resolve for {resource_id}: all sources exhausted");
PortfolioMessage::DocumentPassMessage {
document_id,
message: ResourceMessage::ResolveFailed { resource_id }.into(),
}
.into()
});
if let Some(catalog) = loaded_catalog.take() {
response = Message::Batched {
messages: Box::new([response, FontsMessage::CatalogLoaded { catalog }.into()]),
};
}
response
}))
}
ResourceMessage::Resolved { resource_id, source, hash } => {
self.pending_resolves.remove(&resource_id);
if self.registry.info(&resource_id).is_none() {
// Resource was removed from registry after the fetch started.
return;
}
self.registry.resolve(&resource_id, hash);
if let DataSource::Font { family, style } = source {
let font = match style {
Some(style) => Font::new(family, style),
None => Font::new_with_default_style(family),
};
responses.add(FontsMessage::ResourceResolved { font, hash });
}
responses.add(NodeGraphMessage::RunDocumentGraph);
}
ResourceMessage::ResolveFailed { resource_id } => {
self.pending_resolves.remove(&resource_id);
}
}
}
fn actions(&self) -> ActionList {
actions!(ResourceMessageDiscriminant;)
}
}
impl ResourceMessageHandler {
pub fn is_empty(&self) -> bool {
self.registry.is_empty() && self.embedded.is_empty()
}
pub async fn embed_resources(&mut self, resources_load_handle: Box<dyn LoadResource>) {
let embedded = self
.registry
.resolved()
.filter(|info| info.sources.contains(&DataSource::Embedded))
.filter_map(|info| {
if let Some(hash) = info.hash {
let resource = resources_load_handle.load(*hash);
Some(async move { resource.await.map(|resource| (*hash, resource)) })
} else {
None
}
})
.collect::<Vec<_>>();
self.embedded = EmbeddedResources::from_iter(futures::future::join_all(embedded).await.into_iter().flatten());
}
pub fn collect_garbage(&mut self, used: &[ResourceId]) {
let used = HashSet::<ResourceId>::from_iter(used.iter().cloned());
let unused = self.registry.ids().filter(|id| !used.contains(id)).collect::<Vec<_>>();
unused.into_iter().for_each(|id| {
self.registry.delete(&id);
});
}
}
// TODO: Eventually remove this document upgrade code
impl<'de> serde::Deserialize<'de> for ResourceMessageHandler {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
enum Key {
Registry,
Embedded,
Hash(ResourceHash),
}
impl<'de> serde::Deserialize<'de> for Key {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let raw = String::deserialize(deserializer)?;
Ok(match raw.as_str() {
"registry" => Key::Registry,
"embedded" => Key::Embedded,
_ => Key::Hash(raw.parse().map_err(serde::de::Error::custom)?),
})
}
}
struct EmbeddedResourcesVisitor {
human_readable: bool,
}
impl<'de> serde::de::Visitor<'de> for EmbeddedResourcesVisitor {
type Value = ResourceMessageHandler;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("an EmbeddedResources struct or a legacy EmbeddedResourceData map")
}
fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
let mut output = ResourceMessageHandler::default();
while let Some(key) = map.next_key::<Key>()? {
match key {
Key::Registry => output.registry = map.next_value()?,
Key::Embedded => output.embedded = map.next_value()?,
Key::Hash(hash) => {
let bytes = if self.human_readable {
let encoded: String = map.next_value()?;
BASE64.decode(&encoded).map_err(serde::de::Error::custom)?
} else {
let raw: serde_bytes::ByteBuf = map.next_value()?;
raw.into_vec()
};
let data_hash = output.embedded.store(Resource::new(bytes));
if data_hash != hash {
return Err(serde::de::Error::custom(format!("EmbeddedResource hash mismatch: expected {hash}, got {data_hash}")));
}
}
}
}
Ok(output)
}
}
let human_readable = deserializer.is_human_readable();
deserializer.deserialize_map(EmbeddedResourcesVisitor { human_readable })
}
}
@@ -0,0 +1,92 @@
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use graph_craft::application_io::resource::{Resource, ResourceHash};
use std::collections::HashMap;
use std::fmt;
#[derive(Clone, Default, Debug, PartialEq)]
pub struct EmbeddedResources {
resources: HashMap<ResourceHash, Resource>,
}
impl EmbeddedResources {
pub fn is_empty(&self) -> bool {
self.resources.is_empty()
}
pub fn store(&mut self, resource: Resource) -> ResourceHash {
let hash = ResourceHash::from(resource.as_ref());
self.resources.insert(hash, resource);
hash
}
}
impl FromIterator<(ResourceHash, Resource)> for EmbeddedResources {
fn from_iter<T: IntoIterator<Item = (ResourceHash, Resource)>>(iter: T) -> Self {
Self {
resources: iter.into_iter().collect(),
}
}
}
impl IntoIterator for EmbeddedResources {
type Item = (ResourceHash, Resource);
type IntoIter = std::collections::hash_map::IntoIter<ResourceHash, Resource>;
fn into_iter(self) -> Self::IntoIter {
self.resources.into_iter()
}
}
impl serde::Serialize for EmbeddedResources {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeMap;
let human_readable = serializer.is_human_readable();
let mut map = serializer.serialize_map(Some(self.resources.len()))?;
for (hash, resource) in &self.resources {
let bytes: &[u8] = resource.as_ref();
if human_readable {
map.serialize_entry(hash, &BASE64.encode(bytes))?;
} else {
map.serialize_entry(hash, serde_bytes::Bytes::new(bytes))?;
}
}
map.end()
}
}
impl<'de> serde::Deserialize<'de> for EmbeddedResources {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct EmbeddedResourcesVisitor {
human_readable: bool,
}
impl<'de> serde::de::Visitor<'de> for EmbeddedResourcesVisitor {
type Value = EmbeddedResources;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a map of ResourceHash to resource bytes")
}
fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
let mut resources = HashMap::with_capacity(map.size_hint().unwrap_or(0));
while let Some(hash) = map.next_key::<ResourceHash>()? {
let resource = if self.human_readable {
let encoded: String = map.next_value()?;
let bytes = BASE64.decode(&encoded).map_err(serde::de::Error::custom)?;
Resource::new(bytes)
} else {
let bytes: serde_bytes::ByteBuf = map.next_value()?;
Resource::new(bytes.into_vec())
};
resources.insert(hash, resource);
}
Ok(EmbeddedResources { resources })
}
}
let human_readable = deserializer.is_human_readable();
deserializer.deserialize_map(EmbeddedResourcesVisitor { human_readable })
}
}
@@ -16,13 +16,7 @@ pub enum EditorError {
#[error("The operation caused a document error:\n{0:?}")]
Document(String),
#[error(
"This document was created in an older version of the editor.\n\
\n\
Full backwards compatibility is not guaranteed in the current alpha release.\n\
\n\
If this document is critical, ask for support in Graphite's Discord community."
)]
#[error("Failed to deserialize document: {0}")]
DocumentDeserialization(String),
#[error("{0}")]
@@ -20,6 +20,7 @@ use crate::messages::tool::tool_messages::tool_prelude::NumberInputMode;
use deserialization::deserialize_node_persistent_metadata;
use glam::{DAffine2, DVec2, IVec2};
use graph_craft::Type;
use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork};
use graphene_std::ContextDependencies;
@@ -510,6 +511,10 @@ impl NodeNetworkInterface {
})
}
pub fn collect_used_resources(&self, target: &mut HashSet<ResourceId>) {
collect_network_resources(self.document_network(), target);
}
pub fn frontend_imports(&mut self, network_path: &[NodeId]) -> Vec<Option<FrontendGraphOutput>> {
match network_path.split_last() {
Some((node_id, encapsulating_network_path)) => {
@@ -5906,6 +5911,46 @@ impl NodeNetworkInterface {
self.create_wire(&upstream_output, &InputConnector::node(*node_id, insert_node_input_index), network_path);
}
/// Inserts the freshly-created `node_id` onto the wire feeding `input_connector`: the previous upstream becomes the
/// new node's primary (index 0) input, and the new node feeds `input_connector`.
///
/// When the wire is part of a layer's encapsulated primary chain, `set_input` chain-positions the new node
/// automatically. On an unencapsulated secondary-input branch (e.g. a 'Fill' node's fill input) chain positioning
/// doesn't apply, so the node would otherwise land at the graph origin; instead it's placed on the displaced
/// upstream node's spot and that whole branch is shifted left (in absolute graph space) to make room.
pub fn insert_node_before_input(&mut self, node_id: &NodeId, input_connector: &InputConnector, network_path: &[NodeId]) {
let feeder = self.upstream_output_connector(input_connector, network_path).and_then(|output| output.node_id());
let Some(current_input) = self.input_from_connector(input_connector, network_path).cloned() else {
log::error!("Could not get input in insert_node_before_input");
return;
};
if self.input_from_connector(&InputConnector::node(*node_id, 0), network_path).is_none() {
return;
}
self.set_input(&InputConnector::node(*node_id, 0), current_input, network_path);
self.set_input(input_connector, NodeInput::node(*node_id, 0), network_path);
// If `set_input` chain-positioned the node (it joined a layer chain), there's nothing more to do.
if !self.is_absolute(node_id, network_path) {
return;
}
// Otherwise place the node where the displaced feeder was, then shift the feeder's branch left to make room.
let Some(feeder) = feeder else { return };
let Some(node_position) = self.position(node_id, network_path) else { return };
let Some(feeder_position) = self.position(&feeder, network_path) else { return };
self.shift_node(node_id, feeder_position - node_position, network_path);
// Deduplicate, since `UpstreamFlow` can yield a shared node more than once and we must shift each node only once.
let upstream_nodes: HashSet<NodeId> = self.upstream_flow_back_from_nodes(vec![feeder], network_path, FlowType::UpstreamFlow).collect();
for upstream_node in &upstream_nodes {
self.shift_node(upstream_node, IVec2::new(-NODE_CHAIN_WIDTH, 0), network_path);
}
}
/// Moves a node to the start of a layer chain (feeding into the secondary input of the layer).
/// When `import` is true, uses lightweight wiring that skips `is_acyclic` checks and per-node cache invalidation.
pub fn move_node_to_chain_start(&mut self, node_id: &NodeId, parent: LayerNodeIdentifier, network_path: &[NodeId], import: bool) {
@@ -6769,6 +6814,21 @@ pub enum TransactionStatus {
Finished,
}
fn collect_network_resources(network: &NodeNetwork, out: &mut HashSet<ResourceId>) {
for node in network.nodes.values() {
for input in &node.inputs {
if let NodeInput::Value { tagged_value, .. } = input
&& let TaggedValue::Resource(id) = &**tagged_value
{
out.insert(*id);
}
}
if let DocumentNodeImplementation::Network(nested) = &node.implementation {
collect_network_resources(nested, out);
}
}
}
#[cfg(test)]
mod network_interface_tests {
use crate::test_utils::test_prelude::*;
@@ -94,8 +94,8 @@ impl TypeSource {
/// The type to display in the tooltip label.
pub fn resolved_type_tooltip_string(&self) -> String {
match self {
TypeSource::Compiled(compiled_type) => format!("Data Type: {}", compiled_type.nested_type()),
TypeSource::TaggedValue(value_type) => format!("Data Type: {}", value_type.nested_type()),
TypeSource::Compiled(compiled_type) => compiled_type.nested_type().to_string(),
TypeSource::TaggedValue(value_type) => value_type.nested_type().to_string(),
TypeSource::Unknown => "Unknown Data Type".to_string(),
TypeSource::Invalid => "Invalid Type Combination".to_string(),
TypeSource::Error(_) => "Error Getting Data Type".to_string(),
@@ -253,8 +253,8 @@ impl NodeNetworkInterface {
};
let number_of_inputs = self.number_of_inputs(node_id, network_path);
implementations
.iter()
.filter_map(|(node_io, _)| {
.keys()
.filter_map(|node_io| {
// Check if this NodeIOTypes implementation is valid for the other inputs
let valid_implementation = (0..number_of_inputs).filter(|iterator_index| iterator_index != input_index).all(|iterator_index| {
let input_type = self.input_type_not_invalid(&InputConnector::node(*node_id, iterator_index), network_path);
@@ -293,8 +293,8 @@ impl NodeNetworkInterface {
let valid_output_types = self.valid_output_types(&OutputConnector::node(*node_id, 0), network_path);
implementations
.iter()
.filter_map(|(node_io, _)| {
.keys()
.filter_map(|node_io| {
if !valid_output_types.iter().any(|output_type| output_type.nested_type() == node_io.return_value.nested_type()) {
return None;
}
@@ -6,6 +6,7 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeTemplate, OutputConnector};
use crate::messages::prelude::DocumentMessageHandler;
use glam::{DVec2, IVec2};
use graph_craft::application_io::resource::{DataSource, Resource, ResourceHash, ResourceId};
use graph_craft::descriptor;
use graph_craft::document::DocumentNode;
use graph_craft::document::{DocumentNodeImplementation, NodeInput, value::TaggedValue};
@@ -16,6 +17,7 @@ use graphene_std::uuid::NodeId;
use graphene_std::vector::style::{PaintOrder, StrokeAlign};
use std::collections::HashMap;
use std::f64::consts::PI;
use std::ops::Range;
const TEXT_REPLACEMENTS: &[(&str, &str)] = &[
("graphene_core::vector::vector_nodes::SamplePointsNode", "graphene_core::vector::SamplePolylineNode"),
@@ -1034,6 +1036,77 @@ pub fn document_migration_reset_node_definition(document_serialized_content: &st
false
}
pub fn document_migration_replace_resources_referenced_by_hash(document_serialized_content: String) -> (String, HashMap<ResourceHash, ResourceId>) {
fn collect_resources_referenced_by_hash(s: &str) -> HashMap<ResourceHash, Vec<Range<usize>>> {
let mut out: HashMap<ResourceHash, Vec<Range<usize>>> = HashMap::new();
let mut offset = 0;
while let Some(i) = s[offset..].find("\"Resource\":") {
let abs = offset + i + 11; // pos after `"Resource":`
offset = abs;
if let Some(j) = s[offset..].find('}') {
let chunk_start = offset;
let chunk = &s[chunk_start..chunk_start + j];
let quotes: Vec<_> = chunk.match_indices('"').collect();
if quotes.len() == 2 {
let q0 = chunk_start + quotes[0].0;
let q1 = chunk_start + quotes[1].0;
let hash = &s[q0 + 1..q1];
if hash.len() == 64
&& hash.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
&& let Ok(hash) = hash.parse::<ResourceHash>()
{
out.entry(hash).or_default().push(q0..q1 + 1);
}
}
offset = chunk_start + j + 1;
} else {
break;
}
}
out
}
let resources_by_hash = collect_resources_referenced_by_hash(&document_serialized_content);
// Require each referenced hash to also appear as an embedded resource map key (more than ranges.len() occurrences).
if resources_by_hash.is_empty()
|| !resources_by_hash
.iter()
.all(|(hash, ranges)| document_serialized_content.matches(&hash.to_string()).count() > ranges.len())
{
return (document_serialized_content, HashMap::new());
}
// Assign a new ResourceId for each hash
let mut hash_to_id: HashMap<ResourceHash, ResourceId> = HashMap::new();
for hash in resources_by_hash.keys() {
#[allow(clippy::unwrap_or_default)]
hash_to_id.entry(*hash).or_insert_with(ResourceId::new);
}
// Each range is 66 bytes (64 hex + 2 quotes) and a ResourceId serializes to at most 20 ASCII digits, so the ID always fits.
// Overwrite each hash in place with its ID and pad the leftover bytes with spaces, which JSON deserialization discards.
let mut bytes = document_serialized_content.into_bytes();
for (hash, ranges) in &resources_by_hash {
let id_str = format!("{}", hash_to_id[hash]);
let id_bytes = id_str.as_bytes();
for range in ranges {
bytes[range.start..range.start + id_bytes.len()].copy_from_slice(id_bytes);
bytes[range.start + id_bytes.len()..range.end].fill(b' ');
}
}
let out = String::from_utf8(bytes).expect("in-place hash-to-ID rewrite produced invalid UTF-8");
(out, hash_to_id)
}
pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_node_definitions_on_open: bool) {
document.network_interface.migrate_path_modify_node();
@@ -1588,12 +1661,51 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.set_input(&InputConnector::node(*node_id, 4), old_inputs[3].clone(), network_path);
}
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::image::IDENTIFIER) && inputs_count == 1 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
// Upgrade `image` nodes that stored image data as `Image<Color>`` to `image` nodes that store a reference to the image data as a resource.
// Encodes the image data as PNG and stores it in the document's embedded resources and rewires the node to reference that resource.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::image::IDENTIFIER) {
let image = node.inputs.iter().find_map(|input| match input.as_value()? {
TaggedValue::ImageData(image) => Some(image.clone()),
_ => None,
});
// Insert a new empty input for the image
document.network_interface.add_import(TaggedValue::None, false, 0, "Empty", "", &[*node_id]);
if let Some(image) = image {
let hash = document.resources.embedded.store(Resource::new(image.to_png()));
let resource_id = ResourceId::new();
document.resources.registry.push_source_back(&resource_id, DataSource::Embedded);
document.resources.registry.resolve(&resource_id, hash);
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let _ = document.network_interface.replace_inputs(node_id, network_path, &mut node_template);
document
.network_interface
.set_input(&InputConnector::node(*node_id, 0), NodeInput::value(TaggedValue::Resource(resource_id), false), network_path);
}
}
// Convert text nodes from the old `editor-api` scope + `Font` input to a single font `Resource` input.
// The chosen typeface is recorded as a `DataSource::Font` in the document's resource registry and loaded on open.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER) && inputs_count == 13 && matches!(node.inputs.first(), Some(NodeInput::Scope(_))) {
document
.network_interface
.set_input(&InputConnector::node(*node_id, 0), NodeInput::value(TaggedValue::None, false), network_path);
if let Some(TaggedValue::Font(font)) = node.inputs.get(2).and_then(|input| input.as_value()) {
let resource_id = ResourceId::new();
document.resources.registry.push_source_back(&resource_id, DataSource::Embedded);
document.resources.registry.push_source_back(
&resource_id,
DataSource::Font {
family: font.font_family.clone(),
style: Some(font.font_style.clone()),
},
);
document
.network_interface
.set_input(&InputConnector::node(*node_id, 2), NodeInput::value(TaggedValue::Resource(resource_id), false), network_path);
}
}
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) && inputs_count == 15 {
@@ -0,0 +1,5 @@
use graph_craft::application_io::resource::Resource;
use std::sync::LazyLock;
const FALLBACK_FONT_BYTES: &[u8] = include_bytes!("source-sans-pro-regular.ttf");
pub static FALLBACK_FONT_RESOURCE: LazyLock<Resource> = LazyLock::new(|| Resource::new(FALLBACK_FONT_BYTES));
@@ -0,0 +1,26 @@
use crate::messages::portfolio::fonts::utility_types::FontCatalog;
use crate::messages::prelude::*;
use graph_craft::application_io::resource::{Resource, ResourceHash};
use graphene_std::text::Font;
#[impl_message(Message, PortfolioMessage, Fonts)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum FontsMessage {
LoadCatalog,
CatalogLoaded {
catalog: FontCatalog,
},
ResourceResolved {
font: Font,
hash: ResourceHash,
},
Load {
font: Font,
response: Box<Message>,
},
Cached {
hash: ResourceHash,
#[serde(skip, default = "Resource::empty")]
resource: Resource,
},
}
@@ -0,0 +1,116 @@
use crate::messages::portfolio::fonts::FALLBACK_FONT_RESOURCE;
use crate::messages::portfolio::fonts::utility_types::FontCatalog;
use crate::messages::prelude::*;
use graph_craft::application_io::resource::{DataSource, Resource, ResourceHash, ResourceId};
use graphene_std::text::Font;
use std::sync::Arc;
#[derive(ExtractField)]
pub struct FontsMessageContext<'a> {
pub resource_storage: &'a ResourceStorageMessageHandler,
}
#[derive(Debug, Default, ExtractField)]
pub struct FontsMessageHandler {
pub font_catalog: Arc<FontCatalog>,
font_hashes: HashMap<Font, ResourceHash>,
font_data: HashMap<ResourceHash, Resource>,
}
#[message_handler_data]
impl MessageHandler<FontsMessage, FontsMessageContext<'_>> for FontsMessageHandler {
fn process_message(&mut self, message: FontsMessage, responses: &mut VecDeque<Message>, context: FontsMessageContext) {
let FontsMessageContext { resource_storage } = context;
match message {
FontsMessage::LoadCatalog => {
responses.add(NetworkMessage::request(async move |client| {
let Some(catalog) = FontCatalog::load_from_api(&client).await else {
log::error!("failed to load font catalog");
return Message::NoOp;
};
FontsMessage::CatalogLoaded { catalog }.into()
}));
}
FontsMessage::CatalogLoaded { catalog } => {
self.font_catalog = Arc::new(catalog);
responses.add(PortfolioMessage::ResolveResources);
responses.add(ToolMessage::RefreshToolOptions);
responses.add(PropertiesPanelMessage::Refresh);
}
FontsMessage::ResourceResolved { font, hash } => {
let font = self.normalize(font);
self.font_hashes.insert(font, hash);
}
FontsMessage::Load { font, response } => {
let font = self.normalize(font);
let Some(hash) = self.font_hashes.get(&font).copied() else {
log::warn!("FontsMessage::Load for {font:?} with no known hash; ignoring");
return;
};
if self.font_data.contains_key(&hash) {
responses.add(*response);
return;
}
let loader = resource_storage.resources();
responses.add(async move {
let resource = loader.load(hash).await;
match resource {
Some(resource) => Message::Batched {
messages: Box::new([FontsMessage::Cached { hash, resource }.into(), *response]),
},
None => {
log::warn!("Storage missing data for font hash {hash}");
*response
}
}
});
}
FontsMessage::Cached { hash, resource } => {
self.font_data.insert(hash, resource);
}
}
}
advertise_actions!(FontsMessageDiscriminant;);
}
impl FontsMessageHandler {
pub fn cached_hash(&self, font: &Font) -> Option<ResourceHash> {
let font = self.normalize(font.clone());
self.font_hashes.get(&font).copied()
}
pub fn get_resource_or_queue_load(&self, font: &Font, responses: &mut VecDeque<Message>) -> Resource {
let font = self.normalize(font.clone());
if let Some(hash) = self.font_hashes.get(&font) {
if let Some(resource) = self.font_data.get(hash) {
return resource.clone();
}
responses.add(FontsMessage::Load {
font: font.clone(),
response: Message::NoOp.into(),
});
}
FALLBACK_FONT_RESOURCE.clone()
}
pub fn id_font(&self, resources: &ResourceMessageHandler, resource_id: ResourceId) -> Option<Font> {
let info = resources.registry.info(&resource_id)?;
info.sources.iter().find_map(|source| match source {
DataSource::Font { family, style } => Some(match style {
Some(style) => Font::new(family.clone(), style.clone()),
None => Font::new_with_default_style(family.clone()),
}),
_ => None,
})
}
pub fn used_resources(&self) -> impl Iterator<Item = ResourceHash> + '_ {
self.font_hashes.values().copied().chain(self.font_data.keys().copied())
}
fn normalize(&self, font: Font) -> Font {
self.font_catalog.normalize(font)
}
}
@@ -0,0 +1,12 @@
mod fallback;
mod fonts_message;
mod fonts_message_handler;
pub mod utility_types;
#[doc(inline)]
pub use fallback::FALLBACK_FONT_RESOURCE;
#[doc(inline)]
pub use fonts_message::{FontsMessage, FontsMessageDiscriminant};
#[doc(inline)]
pub use fonts_message_handler::{FontsMessageContext, FontsMessageHandler};
@@ -0,0 +1,164 @@
use crate::messages::network::Client;
use graphene_std::text::Font;
use std::collections::HashMap;
const FONT_LIST_API: &str = "https://api.graphite.art/font-list";
#[derive(serde::Deserialize)]
struct FontListApiResponse {
items: Vec<FontListApiFamily>,
}
#[derive(serde::Deserialize)]
struct FontListApiFamily {
family: String,
variants: Vec<String>,
files: HashMap<String, String>,
}
impl FontCatalog {
pub async fn load_from_api(client: &Client) -> Option<Self> {
let Some(bytes) = client.fetch(FONT_LIST_API).await else {
log::error!("failed to fetch font catalog from API");
return None;
};
let response: FontListApiResponse = match serde_json::from_slice(&bytes) {
Ok(response) => response,
Err(err) => {
log::error!("failed to parse font catalog response: {err}");
return None;
}
};
let families = response
.items
.into_iter()
.map(|family| {
let styles = family
.variants
.iter()
.filter_map(|variant| {
let weight = variant.chars().take_while(|c| c.is_ascii_digit()).collect::<String>().parse::<u32>().unwrap_or(400);
let italic = variant.ends_with("italic");
let url = family.files.get(variant)?.replacen("http://", "https://", 1);
Some(FontCatalogStyle { weight, italic, url })
})
.collect();
FontCatalogFamily { name: family.family, styles }
})
.collect();
Some(Self(families))
}
}
// TODO: Should this be a BTreeMap instead?
#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FontCatalog(Vec<FontCatalogFamily>);
impl FontCatalog {
pub fn find_font_style_in_catalog(&self, font: &Font) -> Option<FontCatalogStyle> {
let family = self.0.iter().find(|family| family.name == font.font_family);
let found_style = family.map(|family| {
let FontCatalogStyle { weight, italic, .. } = FontCatalogStyle::from_named_style(&font.font_style, "");
family.closest_style(weight, italic).clone()
});
if found_style.is_none() {
log::warn!("Font not found in catalog: {:?}", font);
}
found_style
}
pub fn download_url(&self, font: &Font) -> Option<String> {
let catalog_family = self.0.iter().find(|catalog_family| catalog_family.name == font.font_family)?;
let FontCatalogStyle { weight, italic, .. } = FontCatalogStyle::from_named_style(&font.font_style, "");
Some(catalog_family.closest_style(weight, italic).url.clone())
}
pub fn normalize(&self, font: Font) -> Font {
match self.find_font_style_in_catalog(&font) {
Some(style) => Font::new(font.font_family, style.to_named_style()),
None => font,
}
}
pub fn iter(&self) -> impl Iterator<Item = &FontCatalogFamily> {
self.0.iter()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl From<Vec<FontCatalogFamily>> for FontCatalog {
fn from(value: Vec<FontCatalogFamily>) -> Self {
Self(value)
}
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FontCatalogFamily {
/// The font family name.
pub name: String,
/// The font styles (variants) available for the font family.
pub styles: Vec<FontCatalogStyle>,
}
impl FontCatalogFamily {
/// Finds the closest style to the given weight and italic setting.
/// Aims to find the nearest weight while maintaining the italic setting if possible, but italic may change if no other option is available.
pub fn closest_style(&self, weight: u32, italic: bool) -> &FontCatalogStyle {
static FALLBACK_STYLE: FontCatalogStyle = FontCatalogStyle {
weight: 400,
italic: false,
url: String::new(),
};
self.styles
.iter()
.map(|style| ((style.weight as i32 - weight as i32).unsigned_abs() + 10000 * (style.italic != italic) as u32, style))
.min_by_key(|(distance, _)| *distance)
.map(|(_, style)| style)
.unwrap_or(self.styles.first().unwrap_or(&FALLBACK_STYLE))
}
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FontCatalogStyle {
pub weight: u32,
pub italic: bool,
pub url: String,
}
impl FontCatalogStyle {
pub fn to_named_style(&self) -> String {
let weight = self.weight;
let italic = self.italic;
let named_weight = Font::named_weight(weight);
let maybe_italic = if italic { " Italic" } else { "" };
format!("{named_weight}{maybe_italic} ({weight})")
}
pub fn from_named_style(named_style: &str, url: impl Into<String>) -> FontCatalogStyle {
let weight = named_style.split_terminator(['(', ')']).next_back().and_then(|x| x.parse::<u32>().ok()).unwrap_or(400);
let italic = named_style.contains("Italic (");
FontCatalogStyle { weight, italic, url: url.into() }
}
/// Get the URL for the stylesheet for loading a font preview for this style of the given family name, subsetted to only the letters in the family name.
pub fn preview_url(&self, family: impl Into<String>) -> String {
let name = family.into().replace(' ', "+");
let italic = if self.italic { "ital," } else { "" };
let weight = self.weight;
format!("https://fonts.googleapis.com/css2?display=swap&family={name}:{italic}wght@{weight}&text={name}")
}
}
+3
View File
@@ -3,9 +3,12 @@ mod portfolio_message_handler;
pub mod document;
pub mod document_migration;
pub mod fonts;
pub mod persistent_state;
pub mod utility_types;
#[doc(inline)]
pub use fonts::{FontsMessage, FontsMessageContext, FontsMessageHandler};
#[doc(inline)]
pub use persistent_state::{PersistentStateMessage, PersistentStateMessageContext, PersistentStateMessageHandler};
#[doc(inline)]
@@ -52,3 +52,9 @@ impl MessageHandler<PersistentStateMessage, PersistentStateMessageContext> for P
advertise_actions!(PersistentStateMessageDiscriminant;);
}
impl PersistentStateMessageHandler {
pub fn loaded(&self) -> bool {
self.loaded
}
}
@@ -3,11 +3,9 @@ use super::persistent_state::PersistentStateMessage;
use super::utility_types::{DockingSplitDirection, PanelGroupId, PanelType};
use crate::messages::frontend::utility_types::{ExportBounds, FileType, PersistedState};
use crate::messages::portfolio::document::utility_types::clipboards::Clipboard;
use crate::messages::portfolio::utility_types::FontCatalog;
use crate::messages::prelude::*;
use graphene_std::Color;
use graphene_std::raster::Image;
use graphene_std::text::Font;
use std::path::PathBuf;
#[impl_message(Message, Portfolio)]
@@ -17,6 +15,8 @@ pub enum PortfolioMessage {
#[child]
Document(DocumentMessage),
#[child]
Fonts(FontsMessage),
#[child]
PersistentState(PersistentStateMessage),
// Messages
@@ -50,20 +50,11 @@ pub enum PortfolioMessage {
},
DestroyAllDocuments,
EditorPreferences,
FontCatalogLoaded {
catalog: FontCatalog,
},
LoadFontData {
font: Font,
},
FontLoaded {
font_family: String,
font_style: String,
data: Vec<u8>,
},
LoadDocumentResources {
GarbageCollectResources,
ResolveDocumentResources {
document_id: DocumentId,
},
ResolveResources,
LoadPersistedState {
state: PersistedState,
},
@@ -71,6 +62,12 @@ pub enum PortfolioMessage {
document_id: DocumentId,
document_serialized_content: String,
},
// TODO: Eventually remove this document upgrade code
ShowFailedToLoadDocumentsDialog,
// TODO: Eventually remove this document upgrade code
DiscardFailedToLoadDocuments,
// TODO: Eventually remove this document upgrade code
DownloadFailedToLoadDocuments,
MoveAllPanelTabs {
source_group: PanelGroupId,
target_group: PanelGroupId,
@@ -1,7 +1,7 @@
use super::document::utility_types::document_metadata::LayerNodeIdentifier;
use super::document::utility_types::network_interface;
use super::persistent_state::{PersistentStateMessage, PersistentStateMessageContext, PersistentStateMessageHandler};
use super::utility_types::{CachedData, PanelLayoutSubdivision, PanelType, WorkspacePanelLayout};
use super::utility_types::{PanelLayoutSubdivision, PanelType, WorkspacePanelLayout};
use crate::application::{Editor, generate_uuid};
use crate::consts::{DEFAULT_DOCUMENT_NAME, DEFAULT_STROKE_WIDTH, FILE_EXTENSION};
use crate::messages::animation::TimingInformation;
@@ -26,15 +26,16 @@ use crate::messages::tool::utility_types::{HintData, ToolType};
use crate::messages::viewport::ToPhysical;
use crate::node_graph_executor::{ExportConfig, NodeGraphExecutor};
use glam::{DAffine2, DVec2};
use graph_craft::application_io::resource::{DataSource, ResourceHash};
use graph_craft::document::NodeId;
use graphene_std::Color;
use graphene_std::raster_types::Image;
use graphene_std::renderer::Quad;
use graphene_std::subpath::BezierHandles;
use graphene_std::text::Font;
use graphene_std::vector::misc::HandleId;
use graphene_std::vector::{PointId, SegmentId, Vector, VectorModificationType};
use std::path::PathBuf;
use std::sync::Arc;
use std::vec;
#[derive(ExtractField)]
@@ -46,16 +47,27 @@ pub struct PortfolioMessageContext<'a> {
pub reset_node_definitions_on_open: bool,
pub timing_information: TimingInformation,
pub viewport: &'a ViewportMessageHandler,
pub resource_storage: &'a ResourceStorageMessageHandler,
}
#[derive(Debug, Default, ExtractField)]
pub struct PortfolioMessageHandler {
pub documents: HashMap<DocumentId, DocumentMessageHandler>,
unloaded_documents: HashMap<DocumentId, DocumentInfo>,
/// Pairs of `(info, raw serialized content)` for autosaved documents that failed to deserialize.
/// The info entries are folded back into `persisted_state_snapshot` so their on-disk autosave files survive garbage collection.
// TODO: Eventually remove this document upgrade code
failed_to_load_documents: HashMap<DocumentId, (DocumentInfo, String)>,
/// In-flight count of autosaved-document loads from the initial startup batch; the batched failure dialog fires when this hits 0.
// TODO: Eventually remove this document upgrade code
pending_initial_autosave_loads: usize,
/// Background eager loads whose trailing `SelectDocument` should be suppressed to keep focus on the user's active doc.
// TODO: Eventually remove this document upgrade code
pending_eager_loads: HashSet<DocumentId>,
document_ids: VecDeque<DocumentId>,
pub(crate) active_document_id: Option<DocumentId>,
persistent_state: PersistentStateMessageHandler,
pub cached_data: CachedData,
pub fonts: FontsMessageHandler,
copy_buffer: [Vec<CopyBufferEntry>; INTERNAL_CLIPBOARD_COUNT as usize],
pub executor: NodeGraphExecutor,
pub selection_mode: SelectionMode,
@@ -74,6 +86,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
reset_node_definitions_on_open,
timing_information,
viewport,
resource_storage,
} = context;
match message {
@@ -85,11 +98,12 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
let document_inputs = DocumentMessageContext {
document_id,
ipp,
cached_data: &self.cached_data,
fonts: &self.fonts,
executor: &mut self.executor,
current_tool,
preferences,
viewport,
resource_storage,
data_panel_open: self.workspace_panel_layout.is_panel_visible(PanelType::Data) && !self.workspace_panel_layout.focus_document,
layers_panel_open: self.workspace_panel_layout.is_panel_visible(PanelType::Layers) && !self.workspace_panel_layout.focus_document,
properties_panel_open: self.workspace_panel_layout.is_panel_visible(PanelType::Properties) && !self.workspace_panel_layout.focus_document,
@@ -103,6 +117,10 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
};
self.persistent_state.process_message(message, responses, context);
}
PortfolioMessage::Fonts(message) => {
let context = FontsMessageContext { resource_storage };
self.fonts.process_message(message, responses, context);
}
// Messages
PortfolioMessage::Init => {
@@ -154,11 +172,12 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
let document_inputs = DocumentMessageContext {
document_id,
ipp,
cached_data: &self.cached_data,
fonts: &self.fonts,
executor: &mut self.executor,
current_tool,
preferences,
viewport,
resource_storage,
data_panel_open: self.workspace_panel_layout.is_panel_visible(PanelType::Data) && !self.workspace_panel_layout.focus_document,
layers_panel_open: self.workspace_panel_layout.is_panel_visible(PanelType::Layers) && !self.workspace_panel_layout.focus_document,
properties_panel_open: self.workspace_panel_layout.is_panel_visible(PanelType::Properties) && !self.workspace_panel_layout.focus_document,
@@ -183,6 +202,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(PortfolioMessage::AutoSaveDocument { document_id: *document_id });
}
}
responses.add(PortfolioMessage::GarbageCollectResources);
}
PortfolioMessage::AutoSaveDocument { document_id } => {
let Some(document) = self.document(document_id) else { return };
@@ -190,6 +211,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document_id,
document: document.serialize_document(),
});
responses.add(PersistentStateMessage::WriteState);
}
PortfolioMessage::CloseActiveDocumentWithConfirmation => {
if let Some(document_id) = self.active_document_id {
@@ -368,86 +390,41 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(MenuBarMessage::SendLayout);
responses.add(PersistentStateMessage::WriteState);
}
PortfolioMessage::FontCatalogLoaded { catalog } => {
self.cached_data.font_catalog = catalog;
if let Some(document_id) = self.active_document_id {
responses.add(PortfolioMessage::LoadDocumentResources { document_id });
}
// Load the default font
let font = Font::new(graphene_std::consts::DEFAULT_FONT_FAMILY.into(), graphene_std::consts::DEFAULT_FONT_STYLE.into());
responses.add(PortfolioMessage::LoadFontData { font });
}
PortfolioMessage::LoadFontData { font } => {
if let Some(style) = self.cached_data.font_catalog.find_font_style_in_catalog(&font) {
let font = Font::new(font.font_family, style.to_named_style());
if !self.cached_data.font_cache.loaded_font(&font) {
responses.add(FrontendMessage::TriggerFontDataLoad { font, url: style.url });
}
}
}
PortfolioMessage::FontLoaded { font_family, font_style, data } => {
let font = Font::new(font_family, font_style);
self.cached_data.font_cache.insert(font, data);
self.executor.update_font_cache(self.cached_data.font_cache.clone());
for document_id in self.document_ids.iter() {
let node_to_inspect = self.node_to_inspect();
let Some(document) = self.documents.get_mut(document_id) else {
if self.unloaded_documents.contains_key(document_id) {
continue;
}
log::error!("Tried to render non-existent document");
continue;
};
let document_to_viewport = document
.navigation_handler
.calculate_offset_transform(viewport.center_in_viewport_space().into(), &document.document_ptz);
let pointer_position = document_to_viewport.inverse().transform_point2(ipp.mouse.position);
let scale = viewport.scale();
// Use exact physical dimensions from browser (via ResizeObserver's devicePixelContentBoxSize)
let physical_resolution = viewport.size().to_physical().into_dvec2().round().as_uvec2();
// TODO: Remove this when we do the SVG rendering with a separate library on desktop, thus avoiding a need for the hole punch.
// TODO: See #3796. There is a second instance of this todo comment and code block (be sure to remove both).
#[cfg(not(target_family = "wasm"))]
responses.add_front(FrontendMessage::UpdateViewportHolePunch {
active: document.render_mode != graphene_std::vector::style::RenderMode::SvgPreview,
});
if let Ok(message) = self
.executor
.submit_node_graph_evaluation(document, *document_id, physical_resolution, scale, timing_information, node_to_inspect, true, pointer_position)
{
responses.add_front(message);
}
}
if self.active_document_mut().is_some() {
responses.add(NodeGraphMessage::RunDocumentGraph);
}
if current_tool == &ToolType::Text {
responses.add(TextToolMessage::RefreshEditingFontData);
}
}
PortfolioMessage::EditorPreferences => self.executor.update_editor_preferences(preferences.editor_preferences()),
PortfolioMessage::LoadDocumentResources { document_id } => {
let catalog = &self.cached_data.font_catalog;
if catalog.0.is_empty() {
responses.add_front(FrontendMessage::TriggerFontCatalogLoad);
PortfolioMessage::GarbageCollectResources => {
if !self.persistent_state.loaded() {
// We don't know what can be safely garbage collected
return;
}
if let Some(document) = self.documents.get_mut(&document_id) {
document.load_layer_resources(responses);
let mut used_resources = HashSet::new();
for (id, info) in self.unloaded_documents.iter() {
if let Some(resources) = &info.resources {
used_resources.extend(resources.iter());
} else {
responses.add(PersistentStateMessage::ReadDocument { document_id: *id });
return;
}
}
for document in self.documents.values_mut() {
document.garbage_collect_resources();
used_resources.extend(document.resources.registry.resolved().filter_map(|info| info.hash.cloned()));
}
used_resources.extend(self.fonts.used_resources());
responses.add(ResourceStorageMessage::GarbageCollect {
used: Vec::from_iter(used_resources).into_boxed_slice(),
});
}
PortfolioMessage::ResolveResources => {
for document_id in self.document_ids.iter().copied().collect::<Vec<_>>() {
responses.add(PortfolioMessage::ResolveDocumentResources { document_id });
}
}
PortfolioMessage::ResolveDocumentResources { document_id } => {
responses.add(PortfolioMessage::DocumentPassMessage {
document_id,
message: DocumentMessage::Resource(ResourceMessage::ResolveAll),
});
}
PortfolioMessage::LoadPersistedState { state } => {
if let Some(layout) = state.workspace_layout {
@@ -468,11 +445,17 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
workspace_layout: _,
} = state;
// TODO: Eventually remove this document upgrade code
let mut newly_unloaded_ids = Vec::new();
for info in documents {
if !self.document_ids.contains(&info.id) {
self.document_ids.push_back(info.id);
}
if !self.documents.contains_key(&info.id) {
if !self.documents.contains_key(&info.id) && !self.unloaded_documents.contains_key(&info.id) {
// TODO: Eventually remove this document upgrade code
newly_unloaded_ids.push(info.id);
self.unloaded_documents.insert(info.id, info);
}
}
@@ -480,9 +463,27 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
let select_document_id = current_document.filter(|id| self.document_ids.contains(id)).or_else(|| self.document_ids.front().copied());
// Eagerly load every autosaved doc on startup so deserialization failures can be reported in one batched dialog at the end.
// The active doc's read is deferred to the `SelectDocument` below, but is still counted.
// TODO: Eventually remove this document upgrade code
self.pending_initial_autosave_loads = self.pending_initial_autosave_loads.saturating_add(newly_unloaded_ids.len());
// TODO: Eventually remove this document upgrade code
for document_id in &newly_unloaded_ids {
if Some(*document_id) != select_document_id {
self.pending_eager_loads.insert(*document_id);
responses.add(PersistentStateMessage::ReadDocument { document_id: *document_id });
}
}
if let Some(document_id) = select_document_id {
responses.add(PortfolioMessage::SelectDocument { document_id });
}
// TODO: Eventually remove this document upgrade code
else if self.pending_initial_autosave_loads == 0 && !self.failed_to_load_documents.is_empty() {
responses.add(PortfolioMessage::ShowFailedToLoadDocumentsDialog);
}
}
PortfolioMessage::LoadDocumentContent {
document_id,
@@ -501,7 +502,85 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document_is_saved: info.is_saved,
document_serialized_content,
});
responses.add(PortfolioMessage::SelectDocument { document_id });
// Suppress auto-select for startup eager loads to keep focus on the user's active doc
// TODO: Eventually remove this document upgrade code
// TODO: (But keep the inner logic unconditionally, just remove the condition)
if !self.pending_eager_loads.remove(&document_id) {
responses.add(PortfolioMessage::SelectDocument { document_id });
}
}
// TODO: Eventually remove this document upgrade code
PortfolioMessage::ShowFailedToLoadDocumentsDialog => {
if self.failed_to_load_documents.is_empty() {
return;
}
let failed_document_names = self.failed_to_load_documents.values().map(|(info, _)| display_name_with_fallback(info)).collect();
let dialog = simple_dialogs::FailedToLoadDocumentsDialog { failed_document_names };
dialog.send_dialog_to_frontend(responses);
}
// TODO: Eventually remove this document upgrade code
PortfolioMessage::DiscardFailedToLoadDocuments => {
let failed = std::mem::take(&mut self.failed_to_load_documents);
for document_id in failed.keys() {
self.document_ids.retain(|id| id != document_id);
responses.add(PersistentStateMessage::DeleteDocument { document_id: *document_id });
}
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(PersistentStateMessage::WriteState);
}
// TODO: Eventually remove this document upgrade code
PortfolioMessage::DownloadFailedToLoadDocuments => {
if self.failed_to_load_documents.is_empty() {
return;
}
let mut used_names: HashMap<String, u32> = HashMap::new();
let files: Vec<(String, Vec<u8>)> = self
.failed_to_load_documents
.values()
.map(|(info, content)| {
let stem = sanitize_filename_stem(&info.name).unwrap_or_else(|| format!("document-{:x}", info.id.0));
let base = format!("{stem}.{FILE_EXTENSION}");
let unique = match used_names.get(&base).copied() {
None => {
used_names.insert(base.clone(), 1);
base
}
Some(n) => {
used_names.insert(base.clone(), n + 1);
format!("{stem} ({n}).{FILE_EXTENSION}")
}
};
(unique, content.as_bytes().to_vec())
})
.collect();
const FOLDER_NAME: &str = "Graphite Recovered Documents";
if files.len() == 1 {
let (filename, content) = files.into_iter().next().expect("just checked there's one entry");
responses.add(FrontendMessage::TriggerSaveFile {
name: filename,
folder: None,
content: serde_bytes::ByteBuf::from(content),
});
} else {
match build_recovery_zip(&files) {
Ok(zip_bytes) => responses.add(FrontendMessage::TriggerSaveFile {
name: format!("{FOLDER_NAME}.zip"),
folder: None,
content: serde_bytes::ByteBuf::from(zip_bytes),
}),
Err(e) => {
log::error!("Failed to build recovery zip: {e}");
responses.add(DialogMessage::DisplayDialogError {
title: "Failed to download".to_string(),
description: format!("Could not bundle the failed documents for download.\n\n{e}"),
});
}
}
}
}
PortfolioMessage::NewDocumentWithName { name } => {
let mut new_document = DocumentMessageHandler::default();
@@ -736,6 +815,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
let reset_node_definitions_on_open = reset_node_definitions_on_open || document_migration_reset_node_definition(&document_serialized_content);
// Upgrade the document being opened with string replacements on the original JSON
let document_serialized_content = document_migration_string_preprocessing(document_serialized_content);
// Upgrade resources from being referend by hash to beeing referened by ID
let (document_serialized_content, resource_hash_to_id_migration_map) = document_migration_replace_resources_referenced_by_hash(document_serialized_content);
// Deserialize the document
let document = DocumentMessageHandler::deserialize_document(&document_serialized_content);
@@ -744,11 +825,37 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
let mut document = match document {
Ok(document) => document,
Err(e) => {
if !document_is_auto_saved {
responses.add(DialogMessage::DisplayDialogError {
title: "Failed to open document".to_string(),
description: e.to_string(),
});
log::error!("{e}");
// TODO: Eventually remove this document upgrade code
// TODO: (Only the `if` branch, the `else` branch's manual-open dialog stays)
if document_is_auto_saved {
let name = document_name.unwrap_or_default();
let info = DocumentInfo {
id: document_id,
name,
resources: None,
path: document_path,
is_saved: document_is_saved,
};
self.document_ids.retain(|id| id != &document_id);
self.failed_to_load_documents.insert(document_id, (info, document_serialized_content));
if self.active_document_id == Some(document_id) {
self.active_document_id = None;
if let Some(next_id) = self.document_ids.front().copied() {
responses.add(PortfolioMessage::SelectDocument { document_id: next_id });
}
}
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
self.tick_autosave_load_progress(responses, true);
} else {
let name = document_name
.filter(|n| !n.trim().is_empty())
.or_else(|| document_path.as_ref().and_then(|p| p.file_stem()).map(|s| s.to_string_lossy().into_owned()))
.unwrap_or_default();
let dialog = simple_dialogs::FailedToOpenDocumentDialog { document_name: name };
dialog.send_dialog_to_frontend(responses);
}
return;
@@ -758,6 +865,25 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
// Upgrade the document's nodes to be compatible with the latest version
document_migration_upgrades(&mut document, reset_node_definitions_on_open);
// Load the document's embedded resources into the resource storage
std::mem::take(&mut document.resources.embedded).into_iter().for_each(|(hash, resource)| {
let data: Arc<[u8]> = Arc::from(resource.as_ref());
if ResourceHash::from(data.as_ref()) != hash {
log::error!("Resource hash mismatch for resource with hash {hash}");
return;
}
responses.add(ResourceStorageMessage::Store { data });
// TODO: Eventually remove this document upgrade code
// Register any resources that were previously referenced by hash
if let Some(id) = resource_hash_to_id_migration_map.get(&hash)
&& !document.resources.registry.contains(id)
{
document.resources.registry.resolve(id, hash);
document.resources.registry.push_source_back(id, DataSource::Embedded);
}
});
// Ensure each node has the metadata for its inputs
for (node_id, node, path) in document.network_interface.document_network().clone().recursive_nodes() {
document.network_interface.validate_input_metadata(node_id, node, &path);
@@ -821,6 +947,11 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
self.load_document(document, document_id, responses);
responses.add(AppWindowMessage::Focus);
// TODO: Eventually remove this document upgrade code
if document_is_auto_saved {
self.tick_autosave_load_progress(responses, false);
}
}
PortfolioMessage::OpenImage { name, image } => {
// `NewDocumentWithName`'s handler routes empty/None-equivalent names through `resolve_document_name` which assigns the next available "Untitled Document {N}".
@@ -944,7 +1075,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
added_nodes = true;
}
document.load_layer_resources(responses);
let new_ids: HashMap<_, _> = entry.nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect();
let layer = LayerNodeIdentifier::new_unchecked(new_ids[&NodeId(0)]);
all_new_ids.extend(new_ids.values().cloned());
@@ -999,13 +1129,10 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
});
// Add default fill and stroke to the layer
let fill_color = Color::WHITE;
let stroke_color = Color::BLACK;
let fill = graphene_std::vector::style::Fill::solid(fill_color.to_gamma_srgb());
let fill = graphene_std::vector::style::Fill::solid(Color::WHITE);
responses.add(GraphOperationMessage::FillSet { layer, fill });
let stroke = graphene_std::vector::style::Stroke::new(Some(stroke_color.to_gamma_srgb()), DEFAULT_STROKE_WIDTH);
let stroke = graphene_std::vector::style::Stroke::new(Some(Color::BLACK), DEFAULT_STROKE_WIDTH);
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
// Create new point ids and add those into the existing Vector path
@@ -1432,7 +1559,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
};
if !document.is_loaded {
document.is_loaded = true;
responses.add(PortfolioMessage::LoadDocumentResources { document_id });
responses.add(PortfolioMessage::ResolveDocumentResources { document_id });
responses.add(PortfolioMessage::UpdateDocumentWidgets);
responses.add(PropertiesPanelMessage::Clear);
}
@@ -1478,6 +1605,13 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
return;
};
// Skip rendering while any resource is still unresolved — the preprocessor would otherwise fail with
// `ResourceNotFound`. `ResourceMessage::Resolved` queues `RunDocumentGraph` once each id resolves,
// so the render fires automatically once the registry is complete.
if document.resources.registry.unresolved().next().is_some() {
return;
}
let document_to_viewport = document
.navigation_handler
.calculate_offset_transform(viewport.center_in_viewport_space().into(), &document.document_ptz);
@@ -1733,7 +1867,13 @@ impl PortfolioMessageHandler {
}
pub fn persisted_state_snapshot(&self) -> PersistedState {
let documents = self.document_ids.iter().filter_map(|id| self.document_details(*id)).collect::<Vec<_>>();
let mut documents = self.document_ids.iter().filter_map(|id| self.document_details(*id)).collect::<Vec<_>>();
// Keep failed-to-load docs referenced in `state.documents` so their autosave files survive `garbage_collect_document_files`
// TODO: Eventually remove this document upgrade code
for (info, _) in self.failed_to_load_documents.values() {
documents.push(info.clone());
}
PersistedState {
documents,
@@ -1777,6 +1917,18 @@ impl PortfolioMessageHandler {
}
}
// TODO: Eventually remove this document upgrade code
fn tick_autosave_load_progress(&mut self, responses: &mut VecDeque<Message>, failed: bool) {
if self.pending_initial_autosave_loads > 0 {
self.pending_initial_autosave_loads -= 1;
if self.pending_initial_autosave_loads == 0 && !self.failed_to_load_documents.is_empty() {
responses.add(PortfolioMessage::ShowFailedToLoadDocumentsDialog);
}
} else if failed {
responses.add(PortfolioMessage::ShowFailedToLoadDocumentsDialog);
}
}
fn read_file(path: &PathBuf, content: Vec<u8>) -> FileContent {
let extension = path.extension().and_then(|ext| ext.to_str()).unwrap_or_default().to_lowercase();
match extension.as_str() {
@@ -1872,6 +2024,7 @@ impl PortfolioMessageHandler {
name: document.name.clone(),
path: document.path.clone(),
is_saved: document.is_saved(),
resources: Some(document.resources.registry.resolved().filter_map(|info| info.hash.cloned()).collect::<Vec<_>>().into_boxed_slice()),
})
} else {
self.unloaded_documents.get(&document_id).cloned()
@@ -1985,3 +2138,76 @@ impl PortfolioMessageHandler {
}
}
}
// TODO: Eventually remove this document upgrade code
fn display_name_with_fallback(info: &DocumentInfo) -> String {
if info.name.trim().is_empty() {
format!("Untitled Document ({:x})", info.id.0)
} else {
info.name.clone()
}
}
/// Returns `None` if the name has no safe filename characters left or matches a Windows reserved device name, so callers fall back to an ID-based stem.
// TODO: Eventually remove this document upgrade code
fn sanitize_filename_stem(name: &str) -> Option<String> {
let replaced: String = name
.chars()
.map(|c| {
if matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') || c.is_control() {
'_'
} else {
c
}
})
.collect();
// Trim dots to avoid `.` / `..` resolving against the parent directory, and to dodge Windows' trailing-dot/space quirks
let trimmed = replaced.trim().trim_matches('.').trim();
if trimmed.is_empty() {
return None;
}
// Windows rejects these regardless of extension; superscript digits are normalized equivalently by some path APIs
let first_segment = trimmed.split('.').next().unwrap_or("").to_ascii_uppercase();
if matches!(
first_segment.as_str(),
"CON"
| "PRN" | "AUX"
| "NUL" | "COM1"
| "COM2" | "COM3"
| "COM4" | "COM5"
| "COM6" | "COM7"
| "COM8" | "COM9"
| "COM¹" | "COM²"
| "COM³" | "LPT1"
| "LPT2" | "LPT3"
| "LPT4" | "LPT5"
| "LPT6" | "LPT7"
| "LPT8" | "LPT9"
| "LPT¹" | "LPT²"
| "LPT³"
) {
return None;
}
Some(trimmed.to_string())
}
// TODO: Eventually remove this document upgrade code
fn build_recovery_zip(entries: &[(String, Vec<u8>)]) -> Result<Vec<u8>, String> {
use std::io::{Cursor, Write};
use zip::write::{SimpleFileOptions, ZipWriter};
let mut buffer = Cursor::new(Vec::<u8>::new());
let mut writer = ZipWriter::new(&mut buffer);
let options: SimpleFileOptions = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored).unix_permissions(0o644);
for (filename, content) in entries {
writer.start_file(filename, options).map_err(|e| format!("start_file: {e}"))?;
writer.write_all(content).map_err(|e| format!("write_all: {e}"))?;
}
writer.finish().map_err(|e| format!("finish: {e}"))?;
Ok(buffer.into_inner())
}
+2 -84
View File
@@ -1,94 +1,12 @@
use graphene_std::Color;
use graphene_std::raster::Image;
use graphene_std::text::{Font, FontCache};
/// Proportional share (0-1) for the document panel's side when splitting adjacent to non-document panels.
const DOCUMENT_PANEL_SHARE: f64 = 0.8;
/// Proportional share for each side when neither (or both) contain the document panel.
const EQUAL_PANEL_SHARE: f64 = 0.5;
#[derive(Debug, Default)]
pub struct CachedData {
pub font_cache: FontCache,
pub font_catalog: FontCatalog,
}
// TODO: Should this be a BTreeMap instead?
#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FontCatalog(pub Vec<FontCatalogFamily>);
impl FontCatalog {
pub fn find_font_style_in_catalog(&self, font: &Font) -> Option<FontCatalogStyle> {
let family = self.0.iter().find(|family| family.name == font.font_family);
let found_style = family.map(|family| {
let FontCatalogStyle { weight, italic, .. } = FontCatalogStyle::from_named_style(&font.font_style, "");
family.closest_style(weight, italic).clone()
});
if found_style.is_none() {
log::warn!("Font not found in catalog: {:?}", font);
}
found_style
}
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FontCatalogFamily {
/// The font family name.
pub name: String,
/// The font styles (variants) available for the font family.
pub styles: Vec<FontCatalogStyle>,
}
impl FontCatalogFamily {
/// Finds the closest style to the given weight and italic setting.
/// Aims to find the nearest weight while maintaining the italic setting if possible, but italic may change if no other option is available.
pub fn closest_style(&self, weight: u32, italic: bool) -> &FontCatalogStyle {
self.styles
.iter()
.map(|style| ((style.weight as i32 - weight as i32).unsigned_abs() + 10000 * (style.italic != italic) as u32, style))
.min_by_key(|(distance, _)| *distance)
.map(|(_, style)| style)
.unwrap_or(&self.styles[0])
}
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FontCatalogStyle {
pub weight: u32,
pub italic: bool,
pub url: String,
}
impl FontCatalogStyle {
pub fn to_named_style(&self) -> String {
let weight = self.weight;
let italic = self.italic;
let named_weight = Font::named_weight(weight);
let maybe_italic = if italic { " Italic" } else { "" };
format!("{named_weight}{maybe_italic} ({weight})")
}
pub fn from_named_style(named_style: &str, url: impl Into<String>) -> FontCatalogStyle {
let weight = named_style.split_terminator(['(', ')']).next_back().and_then(|x| x.parse::<u32>().ok()).unwrap_or(400);
let italic = named_style.contains("Italic (");
FontCatalogStyle { weight, italic, url: url.into() }
}
/// Get the URL for the stylesheet for loading a font preview for this style of the given family name, subsetted to only the letters in the family name.
pub fn preview_url(&self, family: impl Into<String>) -> String {
let name = family.into().replace(' ', "+");
let italic = if self.italic { "ital," } else { "" };
let weight = self.weight;
format!("https://fonts.googleapis.com/css2?display=swap&family={name}:{italic}wght@{weight}&text={name}")
}
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub enum PanelType {
Welcome,
@@ -124,7 +42,7 @@ impl PanelType {
pub struct PanelGroupId(pub u64);
/// Which edge of a panel group to split on when docking a dragged panel.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum DockingSplitDirection {
Left,
@@ -65,7 +65,7 @@ impl Default for PreferencesMessageHandler {
viewport_zoom_wheel_rate: VIEWPORT_ZOOM_WHEEL_RATE,
ui_scale: UI_SCALE_DEFAULT,
max_render_region_size: EditorPreferences::default().max_render_region_size,
disable_ui_acceleration: false,
disable_ui_acceleration: cfg!(target_os = "linux"), // TODO: Set this back to false once we have ui acceleration working more reliably on linux
#[cfg(target_os = "macos")]
vsync: false,
}
+5
View File
@@ -16,21 +16,26 @@ pub use crate::messages::dialog::new_document_dialog::{NewDocumentDialogMessage,
pub use crate::messages::dialog::preferences_dialog::{PreferencesDialogMessage, PreferencesDialogMessageContext, PreferencesDialogMessageDiscriminant, PreferencesDialogMessageHandler};
pub use crate::messages::dialog::{DialogMessage, DialogMessageContext, DialogMessageDiscriminant, DialogMessageHandler};
pub use crate::messages::frontend::{FrontendMessage, FrontendMessageDiscriminant};
pub use crate::messages::future::{FutureMessage, FutureMessageContext, FutureMessageDiscriminant, FutureMessageHandler, MessageFuture, MessageSpawner, Wake};
pub use crate::messages::input_mapper::key_mapping::{KeyMappingMessage, KeyMappingMessageContext, KeyMappingMessageDiscriminant, KeyMappingMessageHandler};
pub use crate::messages::input_mapper::{InputMapperMessage, InputMapperMessageContext, InputMapperMessageDiscriminant, InputMapperMessageHandler};
pub use crate::messages::input_preprocessor::{InputPreprocessorMessage, InputPreprocessorMessageContext, InputPreprocessorMessageDiscriminant, InputPreprocessorMessageHandler};
pub use crate::messages::layout::{LayoutMessage, LayoutMessageDiscriminant, LayoutMessageHandler};
pub use crate::messages::menu_bar::{MenuBarMessage, MenuBarMessageDiscriminant, MenuBarMessageHandler};
pub use crate::messages::network::{NetworkMessage, NetworkMessageContext, NetworkMessageDiscriminant, NetworkMessageHandler};
pub use crate::messages::portfolio::document::data_panel::{DataPanelMessage, DataPanelMessageDiscriminant};
pub use crate::messages::portfolio::document::graph_operation::{GraphOperationMessage, GraphOperationMessageContext, GraphOperationMessageDiscriminant, GraphOperationMessageHandler};
pub use crate::messages::portfolio::document::navigation::{NavigationMessage, NavigationMessageContext, NavigationMessageDiscriminant, NavigationMessageHandler};
pub use crate::messages::portfolio::document::node_graph::{NodeGraphMessage, NodeGraphMessageDiscriminant, NodeGraphMessageHandler};
pub use crate::messages::portfolio::document::overlays::{OverlaysMessage, OverlaysMessageContext, OverlaysMessageDiscriminant, OverlaysMessageHandler};
pub use crate::messages::portfolio::document::properties_panel::{PropertiesPanelMessage, PropertiesPanelMessageDiscriminant, PropertiesPanelMessageHandler};
pub use crate::messages::portfolio::document::resource::{ResourceMessage, ResourceMessageContext, ResourceMessageDiscriminant, ResourceMessageHandler};
pub use crate::messages::portfolio::document::{DocumentMessage, DocumentMessageContext, DocumentMessageDiscriminant, DocumentMessageHandler};
pub use crate::messages::portfolio::fonts::{FontsMessage, FontsMessageContext, FontsMessageDiscriminant, FontsMessageHandler};
pub use crate::messages::portfolio::persistent_state::{PersistentStateMessage, PersistentStateMessageContext, PersistentStateMessageDiscriminant, PersistentStateMessageHandler};
pub use crate::messages::portfolio::{PortfolioMessage, PortfolioMessageContext, PortfolioMessageDiscriminant, PortfolioMessageHandler};
pub use crate::messages::preferences::{PreferencesMessage, PreferencesMessageDiscriminant, PreferencesMessageHandler};
pub use crate::messages::resource_storage::{ResourceStorageMessage, ResourceStorageMessageContext, ResourceStorageMessageDiscriminant, ResourceStorageMessageHandler};
pub use crate::messages::tool::transform_layer::{TransformLayerMessage, TransformLayerMessageDiscriminant, TransformLayerMessageHandler};
pub use crate::messages::tool::{ToolMessage, ToolMessageContext, ToolMessageDiscriminant, ToolMessageHandler};
pub use crate::messages::viewport::{ViewportMessage, ViewportMessageDiscriminant, ViewportMessageHandler};
Loaded 100 of 230 files, more files were not shown because too many files have changed in this diff. Show more