mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
37
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
953a9312f0 | ||
|
|
7a6e4f6f25 | ||
|
|
b645871dbc | ||
|
|
85ee5e41b9 | ||
|
|
d5c67eeb55 | ||
|
|
2c29d2c406 | ||
|
|
a3b62dac00 | ||
|
|
9d2071ce6a | ||
|
|
6fe1af3afe | ||
|
|
08c6d02e5b | ||
|
|
cd8ea1f554 | ||
|
|
7b9c480a8d | ||
|
|
e32ff4b7f0 | ||
|
|
78679a5ba2 | ||
|
|
51427bef5f | ||
|
|
a40e0d2887 | ||
|
|
bbbe04903f | ||
|
|
d0d9a350c7 | ||
|
|
9dccc526bb | ||
|
|
96be4ec351 | ||
|
|
62287d7893 | ||
|
|
c3b0c87cfe | ||
|
|
2770df7567 | ||
|
|
21d2994059 | ||
|
|
d5f0140f26 | ||
|
|
c4a978009a | ||
|
|
256dd26b99 | ||
|
|
06e2a049de | ||
|
|
79df7cfa87 | ||
|
|
16c7544d96 | ||
|
|
a56746c6bf | ||
|
|
456a7c868d | ||
|
|
1c9c19a697 | ||
|
|
696b625a3e | ||
|
|
4d5dce976e | ||
|
|
629a1f4b4c | ||
|
|
f6def3b911 |
No files matched your search
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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`
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -12,3 +12,4 @@ flamegraph.svg
|
||||
.idea/
|
||||
.direnv
|
||||
.DS_Store
|
||||
.nvim.lua
|
||||
+1
-1
@@ -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
|
||||
|
||||
|
||||
@@ -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 =
|
||||
|
||||
@@ -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
|
||||
|
||||
Generated
+521
-386
File diff suppressed because it is too large.
Load diff
+18
-11
@@ -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" }
|
||||
@@ -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
|
||||
|
||||
+12
-10
@@ -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(());
|
||||
}
|
||||
|
||||
@@ -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
@@ -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,
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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 }
|
||||
@@ -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())),
|
||||
}
|
||||
}
|
||||
@@ -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}"))
|
||||
}
|
||||
@@ -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}")),
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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}"))),
|
||||
}
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
}
|
||||
@@ -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, ¤t_prefix, EntryKind::File).await? {
|
||||
paths.insert(file);
|
||||
}
|
||||
for dir in list_entries(root, ¤t_prefix, EntryKind::Directory).await? {
|
||||
to_visit.push(dir);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(paths)
|
||||
}
|
||||
|
||||
fn is_not_found(error: &JsValue) -> bool {
|
||||
error.dyn_ref::<DomException>().is_some_and(|error| error.name() == "NotFoundError")
|
||||
}
|
||||
|
||||
/// OPFS raises `TypeMismatchError` when a path segment used as a directory is actually a file.
|
||||
fn is_type_mismatch(error: &JsValue) -> bool {
|
||||
error.dyn_ref::<DomException>().is_some_and(|error| error.name() == "TypeMismatchError")
|
||||
}
|
||||
|
||||
/// Map a listing error: a prefix that names a file becomes [`ContainerError::NotADirectory`], anything
|
||||
/// else passes through as a backend error.
|
||||
fn list_error(prefix: &str, error: JsValue) -> ContainerError {
|
||||
if is_type_mismatch(&error) {
|
||||
ContainerError::NotADirectory(prefix.to_string())
|
||||
} else {
|
||||
js_err(error)
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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
@@ -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 }
|
||||
@@ -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
@@ -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();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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(),
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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;
|
||||
@@ -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
|
||||
|
||||
+3
-3
@@ -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);
|
||||
|
||||
+9
-7
@@ -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::*;
|
||||
|
||||
+6
-6
@@ -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};
|
||||
File renamed without changes.
@@ -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,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())
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
mod resource_storage_message;
|
||||
mod resource_storage_message_handler;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use resource_storage_message::{ResourceStorageMessage, ResourceStorageMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use resource_storage_message_handler::{ResourceStorageMessageContext, ResourceStorageMessageHandler, ResourcesHandle};
|
||||
@@ -0,0 +1,10 @@
|
||||
use crate::messages::prelude::*;
|
||||
use graph_craft::application_io::resource::ResourceHash;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[impl_message(Message, ResourceStorage)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ResourceStorageMessage {
|
||||
Store { data: Arc<[u8]> },
|
||||
GarbageCollect { used: Box<[ResourceHash]> },
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
use crate::messages::prelude::*;
|
||||
use graph_craft::application_io::resource::{LoadResource, ResourceFuture, ResourceHash, ResourceStorage};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ResourcesHandle {
|
||||
inner: Arc<dyn ResourceStorage>,
|
||||
}
|
||||
|
||||
impl LoadResource for ResourcesHandle {
|
||||
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
|
||||
self.inner.load(hash)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct ResourceStorageMessageHandler {
|
||||
storage: Option<Arc<dyn ResourceStorage>>,
|
||||
}
|
||||
|
||||
impl ResourceStorageMessageHandler {
|
||||
pub fn new(resource_storage: Arc<dyn ResourceStorage>) -> Self {
|
||||
Self { storage: Some(resource_storage) }
|
||||
}
|
||||
|
||||
pub fn resources(&self) -> Box<dyn LoadResource> {
|
||||
Box::new(ResourcesHandle {
|
||||
inner: self.storage.clone().expect("Resource storage not initialized"),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ResourceStorageMessageHandler {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ResourceStorageMessageHandler").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ResourceStorageMessageHandler {
|
||||
#[cfg(not(test))]
|
||||
fn default() -> Self {
|
||||
Self { storage: None }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
storage: Some(Arc::new(graph_craft::application_io::resource::HashMapResourceStorage::new())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct ResourceStorageMessageContext {}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<ResourceStorageMessage, ResourceStorageMessageContext> for ResourceStorageMessageHandler {
|
||||
fn process_message(&mut self, message: ResourceStorageMessage, _responses: &mut VecDeque<Message>, _context: ResourceStorageMessageContext) {
|
||||
let Some(storage) = &self.storage else {
|
||||
log::error!("Received resource message but storage is not initialized");
|
||||
return;
|
||||
};
|
||||
|
||||
match message {
|
||||
ResourceStorageMessage::Store { data } => {
|
||||
let _hash = storage.store(data.as_ref());
|
||||
}
|
||||
ResourceStorageMessage::GarbageCollect { used } => {
|
||||
storage.garbage_collect(&used);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
advertise_actions!(ResourceStorageMessageDiscriminant;);
|
||||
}
|
||||
@@ -1,74 +1,76 @@
|
||||
use crate::consts::DEFAULT_STROKE_WIDTH;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::TransactionStatus;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::utility_types::DocumentToolData;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ToolColorType {
|
||||
Primary,
|
||||
Secondary,
|
||||
Custom,
|
||||
}
|
||||
use graphene_std::vector::style::{FillChoice, FillChoiceUI, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
|
||||
/// Color selector widgets seen in [`LayoutTarget::ToolOptions`] bar.
|
||||
pub struct ToolColorOptions {
|
||||
pub custom_color: Option<Color>,
|
||||
pub primary_working_color: Option<Color>,
|
||||
pub secondary_working_color: Option<Color>,
|
||||
pub color_type: ToolColorType,
|
||||
/// The fill/stroke value shown in the swatch. `None` = mixed across selected layers.
|
||||
pub fill_choice: Option<FillChoice>,
|
||||
/// The checkbox state. `None` = mixed across selected layers.
|
||||
pub enabled: Option<bool>,
|
||||
/// When set, `fill_choice` is a working-color fallback (vs. a layer-derived saved color) and is refreshed live by `WorkingColorChanged`.
|
||||
pub tracks_working_color: bool,
|
||||
}
|
||||
|
||||
impl Default for ToolColorOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
color_type: ToolColorType::Primary,
|
||||
custom_color: Some(Color::BLACK),
|
||||
primary_working_color: Some(Color::BLACK),
|
||||
secondary_working_color: Some(Color::WHITE),
|
||||
fill_choice: Some(FillChoice::Solid(Color::BLACK)),
|
||||
enabled: Some(true),
|
||||
tracks_working_color: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolColorOptions {
|
||||
pub fn new_primary() -> Self {
|
||||
pub fn new_enabled() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn new_secondary() -> Self {
|
||||
pub fn new_disabled() -> Self {
|
||||
Self {
|
||||
color_type: ToolColorType::Secondary,
|
||||
..Default::default()
|
||||
fill_choice: Some(FillChoice::None),
|
||||
enabled: Some(false),
|
||||
tracks_working_color: true,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_none() -> Self {
|
||||
Self {
|
||||
color_type: ToolColorType::Custom,
|
||||
custom_color: None,
|
||||
..Default::default()
|
||||
}
|
||||
/// True when the slot is actively applied, i.e. `enabled` is `Some(true)`.
|
||||
/// `None` (mixed) and `Some(false)` both count as not actively applied.
|
||||
pub fn is_active(&self) -> bool {
|
||||
self.enabled == Some(true)
|
||||
}
|
||||
|
||||
/// The active solid color, suitable for storing in a working color or downstream rendering input.
|
||||
pub fn active_color(&self) -> Option<Color> {
|
||||
match self.color_type {
|
||||
ToolColorType::Custom => self.custom_color,
|
||||
ToolColorType::Primary => self.primary_working_color,
|
||||
ToolColorType::Secondary => self.secondary_working_color,
|
||||
if !self.is_active() {
|
||||
return None;
|
||||
}
|
||||
self.fill_choice.as_ref()?.as_solid()
|
||||
}
|
||||
|
||||
pub fn apply_fill(&self, layer: LayerNodeIdentifier, responses: &mut VecDeque<Message>) {
|
||||
if let Some(color) = self.active_color() {
|
||||
let fill = graphene_std::vector::style::Fill::solid(color.to_gamma_srgb());
|
||||
if !self.is_active() {
|
||||
return;
|
||||
}
|
||||
if let Some(FillChoice::Solid(color)) = &self.fill_choice {
|
||||
let fill = graphene_std::vector::style::Fill::Solid(*color);
|
||||
responses.add(GraphOperationMessage::FillSet { layer, fill });
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_stroke(&self, weight: f64, layer: LayerNodeIdentifier, responses: &mut VecDeque<Message>) {
|
||||
if let Some(color) = self.active_color() {
|
||||
let stroke = graphene_std::vector::style::Stroke::new(Some(color.to_gamma_srgb()), weight);
|
||||
if !self.is_active() {
|
||||
return;
|
||||
}
|
||||
if let Some(FillChoice::Solid(color)) = &self.fill_choice {
|
||||
let stroke = graphene_std::vector::style::Stroke::new(Some(*color), weight);
|
||||
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
|
||||
}
|
||||
}
|
||||
@@ -76,49 +78,523 @@ impl ToolColorOptions {
|
||||
pub fn create_widgets(
|
||||
&self,
|
||||
label_text: impl Into<String>,
|
||||
color_allow_none: bool,
|
||||
reset_callback: impl Fn(&IconButton) -> Message + 'static + Send + Sync,
|
||||
radio_callback: fn(ToolColorType) -> WidgetCallback<()>,
|
||||
checkbox_callback: impl Fn(&CheckboxInput) -> Message + 'static + Send + Sync,
|
||||
color_callback: impl Fn(&ColorInput) -> Message + 'static + Send + Sync,
|
||||
) -> Vec<WidgetInstance> {
|
||||
let mut widgets = vec![TextLabel::new(label_text).widget_instance()];
|
||||
let checkbox_id = CheckboxId::new();
|
||||
// In the mixed state (`fill_choice` is `None`) the dash overlay covers the swatch, so the underlying widget value just drives the picker's initial position.
|
||||
// `FillChoice::None` gives it a neutral starting point.
|
||||
let mixed_color = self.fill_choice.is_none();
|
||||
// Convert the internal linear-light `FillChoice` to the JS-boundary `FillChoiceUI` (with `SRGBA8` colors) for the widget value.
|
||||
let widget_value = FillChoiceUI::from(self.fill_choice.as_ref().unwrap_or(&FillChoice::None));
|
||||
let mixed_enabled = self.enabled.is_none();
|
||||
// In the mixed-enabled state the underlying `checked` value is hidden behind the indeterminate dash.
|
||||
// The frontend's click handler sends `true` when the user resolves the mixed state by clicking.
|
||||
let checked = self.enabled.unwrap_or(false);
|
||||
|
||||
if !color_allow_none {
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
} else {
|
||||
let reset = IconButton::new("CloseX", 12)
|
||||
.disabled(self.custom_color.is_none() && self.color_type == ToolColorType::Custom)
|
||||
.tooltip_label("Clear Color")
|
||||
.on_update(reset_callback);
|
||||
|
||||
widgets.push(Separator::new(SeparatorStyle::Related).widget_instance());
|
||||
widgets.push(reset.widget_instance());
|
||||
widgets.push(Separator::new(SeparatorStyle::Related).widget_instance());
|
||||
};
|
||||
|
||||
let entries = vec![
|
||||
("WorkingColorsPrimary", "Primary Working Color", ToolColorType::Primary),
|
||||
("WorkingColorsSecondary", "Secondary Working Color", ToolColorType::Secondary),
|
||||
("CustomColor", "Custom Color", ToolColorType::Custom),
|
||||
vec![
|
||||
CheckboxInput::new(checked).mixed(mixed_enabled).on_update(checkbox_callback).for_label(checkbox_id).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
TextLabel::new(label_text).for_checkbox(checkbox_id).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
ColorInput::new(widget_value)
|
||||
.mixed(mixed_color)
|
||||
.min_width(48)
|
||||
.max_width(48)
|
||||
.narrow(true)
|
||||
.on_update(color_callback)
|
||||
.widget_instance(),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(icon, label, color_type)| {
|
||||
let mut entry = RadioEntryData::new(format!("{color_type:?}")).tooltip_label(label).icon(icon);
|
||||
entry.on_update = radio_callback(color_type);
|
||||
entry
|
||||
})
|
||||
.collect();
|
||||
let radio = RadioInput::new(entries).selected_index(Some(self.color_type.clone() as u32)).widget_instance();
|
||||
widgets.push(radio);
|
||||
widgets.push(Separator::new(SeparatorStyle::Related).widget_instance());
|
||||
|
||||
let fill_choice = match self.active_color() {
|
||||
Some(color) => FillChoice::Solid(color.to_gamma_srgb()),
|
||||
None => FillChoice::None,
|
||||
};
|
||||
let color_button = ColorInput::new(fill_choice).allow_none(color_allow_none).on_update(color_callback);
|
||||
widgets.push(color_button.widget_instance());
|
||||
|
||||
widgets
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared per-tool state for drawing tools that produce a stroked-and-filled shape (Shape, Pen, Freehand, Spline).
|
||||
pub struct DrawingToolState {
|
||||
/// The current stroke weight. `None` = mixed across selected layers.
|
||||
pub line_weight: Option<f64>,
|
||||
/// Persistent default weight, updated when the user edits the weight while no layer is selected.
|
||||
pub default_line_weight: f64,
|
||||
/// Stroke alignment from the selection. `None` = mixed.
|
||||
pub stroke_align: Option<StrokeAlign>,
|
||||
/// Stroke cap from the selection. `None` = mixed.
|
||||
pub stroke_cap: Option<StrokeCap>,
|
||||
/// Stroke join from the selection. `None` = mixed.
|
||||
pub stroke_join: Option<StrokeJoin>,
|
||||
/// Stroke miter limit from the selection. `None` = mixed.
|
||||
pub miter_limit: Option<f64>,
|
||||
/// Paint order from the selection. `None` = mixed.
|
||||
pub paint_order: Option<PaintOrder>,
|
||||
/// Dash lengths from the selection. `None` = mixed.
|
||||
pub dash_lengths: Option<Vec<f64>>,
|
||||
/// Dash offset from the selection. `None` = mixed.
|
||||
pub dash_offset: Option<f64>,
|
||||
/// Set of layers we last synced from, used to detect real selection changes vs. internal node toggles.
|
||||
pub last_synced_selection: Vec<LayerNodeIdentifier>,
|
||||
/// The fill swatch's color, checkbox, and mixed state.
|
||||
pub fill: ToolColorOptions,
|
||||
/// The stroke swatch's color, checkbox, and mixed state.
|
||||
pub stroke: ToolColorOptions,
|
||||
/// When false (default), fill follows the secondary working color and stroke follows the primary; when true, the routing is reversed.
|
||||
/// Persisted per-tool. The Shape tool additionally persists it for each shape mode via its options.
|
||||
pub colors_swapped: bool,
|
||||
}
|
||||
|
||||
impl DrawingToolState {
|
||||
pub fn new(fill_enabled: bool) -> Self {
|
||||
Self {
|
||||
line_weight: Some(DEFAULT_STROKE_WIDTH),
|
||||
default_line_weight: DEFAULT_STROKE_WIDTH,
|
||||
stroke_align: Some(StrokeAlign::default()),
|
||||
stroke_cap: Some(StrokeCap::default()),
|
||||
stroke_join: Some(StrokeJoin::default()),
|
||||
miter_limit: Some(4.),
|
||||
paint_order: Some(PaintOrder::default()),
|
||||
dash_lengths: Some(Vec::new()),
|
||||
dash_offset: Some(0.),
|
||||
last_synced_selection: Vec::new(),
|
||||
fill: if fill_enabled { ToolColorOptions::new_enabled() } else { ToolColorOptions::new_disabled() },
|
||||
stroke: ToolColorOptions::new_enabled(),
|
||||
colors_swapped: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The line weight to apply, falling back to the persistent default when [`Self::line_weight`] is `None` (mixed).
|
||||
pub fn effective_line_weight(&self) -> f64 {
|
||||
self.line_weight.unwrap_or(self.default_line_weight)
|
||||
}
|
||||
|
||||
/// Dash lengths to apply, falling back to empty when [`Self::dash_lengths`] is `None` (mixed).
|
||||
pub fn effective_dash_lengths(&self) -> Vec<f64> {
|
||||
self.dash_lengths.clone().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Applies a stroke to a freshly created `layer` using the tool's currently selected color, weight, and stroke options (align, cap, join, etc.).
|
||||
/// Used by the drawing tools at shape-creation time so new shapes inherit the popover's options instead of defaulting to the `Stroke` struct's defaults.
|
||||
pub fn apply_stroke_to_new_layer(&self, layer: LayerNodeIdentifier, responses: &mut VecDeque<Message>) {
|
||||
if !self.stroke.is_active() {
|
||||
return;
|
||||
}
|
||||
let Some(FillChoice::Solid(color)) = &self.stroke.fill_choice else { return };
|
||||
let stroke = graphene_std::vector::style::Stroke {
|
||||
color: Some(*color),
|
||||
weight: self.effective_line_weight(),
|
||||
align: self.stroke_align.unwrap_or_default(),
|
||||
cap: self.stroke_cap.unwrap_or_default(),
|
||||
join: self.stroke_join.unwrap_or_default(),
|
||||
join_miter_limit: self.miter_limit.unwrap_or(4.),
|
||||
paint_order: self.paint_order.unwrap_or_default(),
|
||||
dash_lengths: self.effective_dash_lengths(),
|
||||
dash_offset: self.dash_offset.unwrap_or(0.),
|
||||
transform: glam::DAffine2::IDENTITY,
|
||||
};
|
||||
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a `FillChoice::Solid` from a color.
|
||||
pub fn solid(color: Color) -> FillChoice {
|
||||
FillChoice::Solid(color)
|
||||
}
|
||||
|
||||
/// The fill working color (the source for the fill swatch when nothing is selected).
|
||||
/// Defaults to secondary, swapped to primary when the per-tool [`DrawingToolState::colors_swapped`] flag is set.
|
||||
pub fn fill_working_color(global: &DocumentToolData, colors_swapped: bool) -> Color {
|
||||
if colors_swapped { global.primary_color } else { global.secondary_color }
|
||||
}
|
||||
|
||||
/// The stroke working color (the source for the stroke swatch when nothing is selected).
|
||||
/// Defaults to primary, swapped to secondary when the per-tool [`DrawingToolState::colors_swapped`] flag is set.
|
||||
pub fn stroke_working_color(global: &DocumentToolData, colors_swapped: bool) -> Color {
|
||||
if colors_swapped { global.secondary_color } else { global.primary_color }
|
||||
}
|
||||
|
||||
/// Syncs fill and stroke from the selection (or working colors when empty). With `selection_changed = false`, preserves display values
|
||||
/// for inactive states instead of resetting them. Returns `true` if anything changed.
|
||||
pub fn sync_color_options(
|
||||
drawing: &mut DrawingToolState,
|
||||
natural_fill_enabled: bool,
|
||||
natural_stroke_enabled: bool,
|
||||
global: &DocumentToolData,
|
||||
document: &DocumentMessageHandler,
|
||||
selection_changed: bool,
|
||||
) -> bool {
|
||||
let fill_fallback = solid(fill_working_color(global, drawing.colors_swapped));
|
||||
let stroke_fallback = solid(stroke_working_color(global, drawing.colors_swapped));
|
||||
|
||||
let mut changed = false;
|
||||
|
||||
// FILL
|
||||
|
||||
let new_fill = if let Some(state) = graph_modification_utils::selected_fill_state(document) {
|
||||
let active = state.enabled == Some(true);
|
||||
let (display_choice, tracks_working) = match &state.fill_choice {
|
||||
Some(choice) if active => (Some(choice.clone()), false),
|
||||
Some(_) if selection_changed => (Some(fill_fallback.clone()), true),
|
||||
Some(_) => (drawing.fill.fill_choice.clone(), drawing.fill.tracks_working_color),
|
||||
None => (None, true),
|
||||
};
|
||||
(state.enabled, display_choice, tracks_working)
|
||||
} else {
|
||||
// On a real deselect, revert to the working color; otherwise preserve the displayed value.
|
||||
let display_choice = if selection_changed { Some(fill_fallback) } else { drawing.fill.fill_choice.clone() };
|
||||
let tracks_working = if selection_changed { true } else { drawing.fill.tracks_working_color };
|
||||
(Some(natural_fill_enabled), display_choice, tracks_working)
|
||||
};
|
||||
if drawing.fill.enabled != new_fill.0 || drawing.fill.fill_choice != new_fill.1 || drawing.fill.tracks_working_color != new_fill.2 {
|
||||
drawing.fill.enabled = new_fill.0;
|
||||
drawing.fill.fill_choice = new_fill.1;
|
||||
drawing.fill.tracks_working_color = new_fill.2;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
// STROKE
|
||||
|
||||
let new_stroke = if let Some(state) = graph_modification_utils::selected_stroke_state(document) {
|
||||
let active = state.enabled == Some(true);
|
||||
let (display_choice, tracks_working) = match state.optional_color {
|
||||
Some(color) if active => (Some(color.map_or(FillChoice::None, FillChoice::Solid)), false),
|
||||
Some(_) if selection_changed => (Some(stroke_fallback.clone()), true),
|
||||
Some(_) => (drawing.stroke.fill_choice.clone(), drawing.stroke.tracks_working_color),
|
||||
None => (None, true),
|
||||
};
|
||||
(state.enabled, display_choice, tracks_working)
|
||||
} else {
|
||||
let display_choice = if selection_changed { Some(stroke_fallback) } else { drawing.stroke.fill_choice.clone() };
|
||||
let tracks_working = if selection_changed { true } else { drawing.stroke.tracks_working_color };
|
||||
(Some(natural_stroke_enabled), display_choice, tracks_working)
|
||||
};
|
||||
if drawing.stroke.enabled != new_stroke.0 || drawing.stroke.fill_choice != new_stroke.1 || drawing.stroke.tracks_working_color != new_stroke.2 {
|
||||
drawing.stroke.enabled = new_stroke.0;
|
||||
drawing.stroke.fill_choice = new_stroke.1;
|
||||
drawing.stroke.tracks_working_color = new_stroke.2;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
changed
|
||||
}
|
||||
|
||||
/// Full SelectionChanged update for a drawing tool: syncs fill/stroke colors and the stroke weight. Returns `true` if the layout needs refreshing.
|
||||
pub fn sync_drawing_state(drawing: &mut DrawingToolState, natural_fill_enabled: bool, natural_stroke_enabled: bool, global: &DocumentToolData, document: &DocumentMessageHandler) -> bool {
|
||||
let selection_changed = selection_changed_since_last_sync(&mut drawing.last_synced_selection, document);
|
||||
let mut needs_refresh = sync_color_options(drawing, natural_fill_enabled, natural_stroke_enabled, global, document, selection_changed);
|
||||
|
||||
let new_line_weight = match compute_weight_sync(document) {
|
||||
WeightSyncOutcome::Set(weight) => Some(weight),
|
||||
WeightSyncOutcome::Mixed => None,
|
||||
// On a real selection change, revert to the default; otherwise preserve.
|
||||
WeightSyncOutcome::NoStrokes | WeightSyncOutcome::NoSelection => {
|
||||
if selection_changed {
|
||||
Some(drawing.default_line_weight)
|
||||
} else {
|
||||
drawing.line_weight
|
||||
}
|
||||
}
|
||||
};
|
||||
if drawing.line_weight != new_line_weight {
|
||||
drawing.line_weight = new_line_weight;
|
||||
needs_refresh = true;
|
||||
}
|
||||
|
||||
needs_refresh |= sync_stroke_options(drawing, document);
|
||||
|
||||
needs_refresh
|
||||
}
|
||||
|
||||
/// Reads the stroke proto-node inputs (align, cap, join, miter limit, paint order, dash lengths, dash offset) across the selection and updates
|
||||
/// the matching fields on `drawing`. Each field becomes `None` (mixed) when selected strokes disagree. With no selection, fields are left as-is.
|
||||
fn sync_stroke_options(drawing: &mut DrawingToolState, document: &DocumentMessageHandler) -> bool {
|
||||
let strokes: Vec<_> = document
|
||||
.network_interface
|
||||
.selected_nodes()
|
||||
.selected_layers_except_artboards(&document.network_interface)
|
||||
.filter_map(|layer| graph_modification_utils::get_stroke_options(layer, &document.network_interface))
|
||||
.collect();
|
||||
if strokes.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
fn unanimous<T: PartialEq + Clone>(values: impl IntoIterator<Item = T>) -> Option<T> {
|
||||
let mut iter = values.into_iter();
|
||||
let first = iter.next()?;
|
||||
iter.all(|v| v == first).then_some(first)
|
||||
}
|
||||
|
||||
let new_align = unanimous(strokes.iter().map(|s| s.align));
|
||||
let new_cap = unanimous(strokes.iter().map(|s| s.cap));
|
||||
let new_join = unanimous(strokes.iter().map(|s| s.join));
|
||||
let new_miter = unanimous(strokes.iter().map(|s| s.miter_limit));
|
||||
let new_paint_order = unanimous(strokes.iter().map(|s| s.paint_order));
|
||||
let new_dash_lengths = unanimous(strokes.iter().map(|s| &s.dash_lengths)).cloned();
|
||||
let new_dash_offset = unanimous(strokes.iter().map(|s| s.dash_offset));
|
||||
|
||||
let mut changed = false;
|
||||
|
||||
if drawing.stroke_align != new_align {
|
||||
drawing.stroke_align = new_align;
|
||||
changed = true;
|
||||
}
|
||||
if drawing.stroke_cap != new_cap {
|
||||
drawing.stroke_cap = new_cap;
|
||||
changed = true;
|
||||
}
|
||||
if drawing.stroke_join != new_join {
|
||||
drawing.stroke_join = new_join;
|
||||
changed = true;
|
||||
}
|
||||
if drawing.miter_limit != new_miter {
|
||||
drawing.miter_limit = new_miter;
|
||||
changed = true;
|
||||
}
|
||||
if drawing.paint_order != new_paint_order {
|
||||
drawing.paint_order = new_paint_order;
|
||||
changed = true;
|
||||
}
|
||||
if drawing.dash_lengths != new_dash_lengths {
|
||||
drawing.dash_lengths = new_dash_lengths;
|
||||
changed = true;
|
||||
}
|
||||
if drawing.dash_offset != new_dash_offset {
|
||||
drawing.dash_offset = new_dash_offset;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
changed
|
||||
}
|
||||
|
||||
/// Same as [`sync_color_options`] but for tools that only have a fill option (e.g., text). The fill follows the given working color when nothing is selected.
|
||||
pub fn sync_fill_only(fill: &mut ToolColorOptions, natural_fill_enabled: bool, fill_color: Color, document: &DocumentMessageHandler, selection_changed: bool) -> bool {
|
||||
let fill_fallback = solid(fill_color);
|
||||
|
||||
let new_fill = if let Some(state) = graph_modification_utils::selected_fill_state(document) {
|
||||
let active = state.enabled == Some(true);
|
||||
let (display_choice, tracks_working_color) = match &state.fill_choice {
|
||||
Some(choice) if active => (Some(choice.clone()), false),
|
||||
Some(_) if selection_changed => (Some(fill_fallback.clone()), true),
|
||||
Some(_) => (fill.fill_choice.clone(), fill.tracks_working_color),
|
||||
None => (None, true),
|
||||
};
|
||||
(state.enabled, display_choice, tracks_working_color)
|
||||
} else {
|
||||
let display_choice = if selection_changed { Some(fill_fallback) } else { fill.fill_choice.clone() };
|
||||
let tracks_working = if selection_changed { true } else { fill.tracks_working_color };
|
||||
(Some(natural_fill_enabled), display_choice, tracks_working)
|
||||
};
|
||||
|
||||
if fill.enabled != new_fill.0 || fill.fill_choice != new_fill.1 || fill.tracks_working_color != new_fill.2 {
|
||||
fill.enabled = new_fill.0;
|
||||
fill.fill_choice = new_fill.1;
|
||||
fill.tracks_working_color = new_fill.2;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// True if at least one (non-artboard) layer is currently selected.
|
||||
pub fn has_selection(document: &DocumentMessageHandler) -> bool {
|
||||
document
|
||||
.network_interface
|
||||
.selected_nodes()
|
||||
.selected_layers_except_artboards(&document.network_interface)
|
||||
.next()
|
||||
.is_some()
|
||||
}
|
||||
|
||||
/// Applies a user-picked fill (gradient or solid). With a selection, writes to the layers; with none, pushes a solid to the swap-routed working color slot.
|
||||
pub fn apply_fill_color_pick(drawing: &mut DrawingToolState, fill_choice: FillChoice, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
apply_fill_only_color_pick(&mut drawing.fill, fill_choice, drawing.colors_swapped, document, responses);
|
||||
}
|
||||
|
||||
/// Single-slot variant of [`apply_fill_color_pick`] (e.g. for text). `slot_is_primary` says which working color this slot binds to.
|
||||
pub fn apply_fill_only_color_pick(fill: &mut ToolColorOptions, fill_choice: FillChoice, slot_is_primary: bool, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
fill.fill_choice = Some(fill_choice.clone());
|
||||
fill.enabled = Some(true);
|
||||
fill.tracks_working_color = false;
|
||||
if has_selection(document) {
|
||||
if document.network_interface.transaction_status() == TransactionStatus::Finished {
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
}
|
||||
graph_modification_utils::set_fill_for_selected_layers(fill_choice, document, responses);
|
||||
} else if let FillChoice::Solid(color) = fill_choice {
|
||||
responses.add(ToolMessage::SelectWorkingColor { color, primary: slot_is_primary });
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies a user-picked stroke color. With a selection, writes to the layers; with none, pushes to the swap-routed working color slot.
|
||||
pub fn apply_stroke_color_pick(drawing: &mut DrawingToolState, color: Option<Color>, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.stroke.fill_choice = Some(color.map_or(FillChoice::None, FillChoice::Solid));
|
||||
drawing.stroke.enabled = Some(true);
|
||||
drawing.stroke.tracks_working_color = false;
|
||||
if has_selection(document) {
|
||||
if document.network_interface.transaction_status() == TransactionStatus::Finished {
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
}
|
||||
graph_modification_utils::set_stroke_color_for_selected_layers(color, drawing.effective_line_weight(), document, responses);
|
||||
} else if let Some(color) = color {
|
||||
responses.add(ToolMessage::SelectWorkingColor {
|
||||
color,
|
||||
primary: !drawing.colors_swapped,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Toggles the fill checkbox: re-applies the preserved color when enabled, removes the fill node when disabled.
|
||||
pub fn apply_fill_enabled(drawing: &mut DrawingToolState, enabled: bool, global: &DocumentToolData, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
apply_fill_only_enabled(&mut drawing.fill, enabled, fill_working_color(global, drawing.colors_swapped), document, responses);
|
||||
}
|
||||
|
||||
/// Single-slot variant of [`apply_fill_enabled`]. `working_color` is the fallback used when re-ticking or unticking from a mixed state.
|
||||
pub fn apply_fill_only_enabled(fill: &mut ToolColorOptions, enabled: bool, working_color: Color, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
fill.enabled = Some(enabled);
|
||||
if has_selection(document) {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
}
|
||||
if enabled {
|
||||
// Mixed re-tick has no per-layer color to restore; fall back to the working color and keep tracking it.
|
||||
let fill_choice = fill.fill_choice.clone().unwrap_or_else(|| {
|
||||
fill.tracks_working_color = true;
|
||||
solid(working_color)
|
||||
});
|
||||
fill.fill_choice = Some(fill_choice.clone());
|
||||
graph_modification_utils::set_fill_for_selected_layers(fill_choice, document, responses);
|
||||
} else {
|
||||
// Unticking from mixed: capture the working color as the saved value so the swatch keeps following the link.
|
||||
if fill.fill_choice.is_none() {
|
||||
fill.fill_choice = Some(solid(working_color));
|
||||
fill.tracks_working_color = true;
|
||||
}
|
||||
graph_modification_utils::remove_fill_for_selected_layers(document, responses);
|
||||
}
|
||||
}
|
||||
|
||||
/// Toggles the stroke checkbox: mirrors [`apply_fill_enabled`].
|
||||
pub fn apply_stroke_enabled(drawing: &mut DrawingToolState, enabled: bool, global: &DocumentToolData, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.stroke.enabled = Some(enabled);
|
||||
if has_selection(document) {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
}
|
||||
if enabled {
|
||||
let stroke_choice = drawing.stroke.fill_choice.clone().unwrap_or_else(|| {
|
||||
drawing.stroke.tracks_working_color = true;
|
||||
solid(stroke_working_color(global, drawing.colors_swapped))
|
||||
});
|
||||
drawing.stroke.fill_choice = Some(stroke_choice.clone());
|
||||
graph_modification_utils::set_stroke_color_for_selected_layers(stroke_choice.as_solid(), drawing.effective_line_weight(), document, responses);
|
||||
} else {
|
||||
if drawing.stroke.fill_choice.is_none() {
|
||||
drawing.stroke.fill_choice = Some(solid(stroke_working_color(global, drawing.colors_swapped)));
|
||||
drawing.stroke.tracks_working_color = true;
|
||||
}
|
||||
graph_modification_utils::remove_stroke_for_selected_layers(document, responses);
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies a user-edited stroke weight to the selection, also persisting it as the no-selection default.
|
||||
pub fn apply_line_weight(drawing: &mut DrawingToolState, line_weight: f64, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.line_weight = Some(line_weight);
|
||||
if !has_selection(document) {
|
||||
drawing.default_line_weight = line_weight;
|
||||
}
|
||||
graph_modification_utils::set_stroke_weight_for_selected_layers(line_weight, document, responses);
|
||||
}
|
||||
|
||||
/// Propagates working colors to the tool's swatches. With no selection both slots refresh; with a selection, only slots tracking the working color.
|
||||
pub fn apply_working_colors(drawing: &mut DrawingToolState, global: &DocumentToolData, document: &DocumentMessageHandler) {
|
||||
refresh_slot_working_color(&mut drawing.fill, fill_working_color(global, drawing.colors_swapped), document);
|
||||
refresh_slot_working_color(&mut drawing.stroke, stroke_working_color(global, drawing.colors_swapped), document);
|
||||
}
|
||||
|
||||
/// Refreshes a single swatch from the given working color, subject to the rules in [`apply_working_colors`].
|
||||
pub fn refresh_slot_working_color(slot: &mut ToolColorOptions, working_color: Color, document: &DocumentMessageHandler) {
|
||||
if slot.fill_choice.is_some() && (!has_selection(document) || slot.tracks_working_color) {
|
||||
slot.fill_choice = Some(solid(working_color));
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets the tool's swatches to the working colors. Called on tool deactivation and shape-mode changes.
|
||||
pub fn reset_colors_on_deactivation(drawing: &mut DrawingToolState, global: &DocumentToolData) {
|
||||
drawing.fill.fill_choice = Some(solid(fill_working_color(global, drawing.colors_swapped)));
|
||||
drawing.stroke.fill_choice = Some(solid(stroke_working_color(global, drawing.colors_swapped)));
|
||||
drawing.fill.tracks_working_color = true;
|
||||
drawing.stroke.tracks_working_color = true;
|
||||
}
|
||||
|
||||
/// Handles the "Swap Fill/Stroke" button. Stroke can only hold a solid color, so a gradient fill collapses to `None` when moved.
|
||||
pub fn swap_fill_and_stroke(drawing: &mut DrawingToolState, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.colors_swapped = !drawing.colors_swapped;
|
||||
|
||||
if has_selection(document) {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
}
|
||||
|
||||
// The new fill takes the old stroke's value as-is; the new stroke takes the old fill (with any gradient collapsed to `None`,
|
||||
// since stroke can only hold a solid color). `None` (mixed) on either side propagates as `None` to the other.
|
||||
let new_fill = drawing.stroke.fill_choice.clone();
|
||||
let new_stroke = drawing.fill.fill_choice.as_ref().map(|c| c.as_solid().map_or(FillChoice::None, FillChoice::Solid));
|
||||
let (new_fill_tracks, new_stroke_tracks) = (drawing.stroke.tracks_working_color, drawing.fill.tracks_working_color);
|
||||
|
||||
drawing.fill.fill_choice = new_fill.clone();
|
||||
drawing.stroke.fill_choice = new_stroke.clone();
|
||||
drawing.fill.tracks_working_color = new_fill_tracks;
|
||||
drawing.stroke.tracks_working_color = new_stroke_tracks;
|
||||
|
||||
if has_selection(document) {
|
||||
// Apply to layers only when we have a concrete value (`None` means mixed, no single value to broadcast).
|
||||
if drawing.fill.is_active()
|
||||
&& let Some(choice) = new_fill
|
||||
{
|
||||
graph_modification_utils::set_fill_for_selected_layers(choice, document, responses);
|
||||
}
|
||||
if drawing.stroke.is_active()
|
||||
&& let Some(choice) = new_stroke
|
||||
{
|
||||
graph_modification_utils::set_stroke_color_for_selected_layers(choice.as_solid(), drawing.effective_line_weight(), document, responses);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates the cache and returns `true` if the current selection differs from the last-synced one. Cache stays sorted to keep comparisons cheap.
|
||||
pub fn selection_changed_since_last_sync(last_synced: &mut Vec<LayerNodeIdentifier>, document: &DocumentMessageHandler) -> bool {
|
||||
let mut current: Vec<LayerNodeIdentifier> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
|
||||
|
||||
current.sort();
|
||||
|
||||
let changed = current != *last_synced;
|
||||
*last_synced = current;
|
||||
changed
|
||||
}
|
||||
|
||||
/// How the weight widget should update from inspecting selected layers' strokes.
|
||||
pub enum WeightSyncOutcome {
|
||||
/// All strokes share this weight.
|
||||
Set(f64),
|
||||
/// Stroke weights differ (or some layers lack a stroke): show the mixed dash.
|
||||
Mixed,
|
||||
/// Selection has no strokes: reset to the tool's default on a real selection change, otherwise preserve.
|
||||
NoStrokes,
|
||||
/// No selection: preserve the current value.
|
||||
NoSelection,
|
||||
}
|
||||
|
||||
/// Inspects the selection and returns how the weight widget should update.
|
||||
pub fn compute_weight_sync(document: &DocumentMessageHandler) -> WeightSyncOutcome {
|
||||
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
|
||||
|
||||
if layers.is_empty() {
|
||||
return WeightSyncOutcome::NoSelection;
|
||||
}
|
||||
|
||||
let stroke_weights: Vec<f64> = layers.iter().filter_map(|l| graph_modification_utils::get_stroke_width(*l, &document.network_interface)).collect();
|
||||
|
||||
if stroke_weights.is_empty() {
|
||||
return WeightSyncOutcome::NoStrokes;
|
||||
}
|
||||
|
||||
if stroke_weights.len() != layers.len() {
|
||||
return WeightSyncOutcome::Mixed;
|
||||
}
|
||||
|
||||
let first = stroke_weights[0];
|
||||
let all_same = stroke_weights.iter().all(|&w| (w - first).abs() < f64::EPSILON * 100.);
|
||||
if all_same { WeightSyncOutcome::Set(first) } else { WeightSyncOutcome::Mixed }
|
||||
}
|
||||
@@ -15,7 +15,7 @@ use graphene_std::raster_types::{CPU, GPU, Image, Raster};
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::misc::ManipulatorPointId;
|
||||
use graphene_std::vector::style::{Fill, Gradient};
|
||||
use graphene_std::vector::style::{Fill, FillChoice, Gradient, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::{GradientStops, PointId, SegmentId, VectorModificationType};
|
||||
use std::collections::VecDeque;
|
||||
|
||||
@@ -271,6 +271,35 @@ pub fn get_viewport_center(layer: LayerNodeIdentifier, network_interface: &NodeN
|
||||
network_interface.document_metadata().transform_to_viewport(layer).transform_point2(min + (max - min) * center)
|
||||
}
|
||||
|
||||
/// Determine the input connector where the gradient chain enters the layer.
|
||||
/// Returns Fill's fill input if the layer has a "Fill" node, otherwise returns the layer's content input.
|
||||
pub fn gradient_chain_target_input(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> InputConnector {
|
||||
if let Some(fill_node_id) = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER)) {
|
||||
InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::<Fill>::INDEX)
|
||||
} else {
|
||||
InputConnector::node(layer.to_node(), 1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to find a "Gradient Value" node that is connected to a "Fill" node, or to a layer directly.
|
||||
pub fn get_upstream_gradient_value_node_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
|
||||
network_interface
|
||||
.upstream_flow_back_from_nodes(vec![layer.to_node()], &[], FlowType::UpstreamFlow)
|
||||
.skip(1)
|
||||
.take_while(|node_id| !network_interface.is_layer(node_id, &[]))
|
||||
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_value::IDENTIFIER)))
|
||||
}
|
||||
|
||||
/// Get the node connected to Fill's fill input, if any.
|
||||
pub fn get_fill_input_node_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
|
||||
let fill_node_id = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
|
||||
let fill_node = network_interface.document_network().nodes.get(&fill_node_id)?;
|
||||
let NodeInput::Node { node_id, .. } = fill_node.inputs.get(graphene_std::vector::fill::FillInput::<Fill>::INDEX)? else {
|
||||
return None;
|
||||
};
|
||||
Some(*node_id)
|
||||
}
|
||||
|
||||
/// Get the current gradient of a layer from the closest "Fill" node.
|
||||
pub fn get_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Gradient> {
|
||||
let fill_index = 1;
|
||||
@@ -284,8 +313,8 @@ pub fn get_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkI
|
||||
|
||||
/// Get the gradient stops of a layer, if any.
|
||||
pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<GradientStops> {
|
||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_value::IDENTIFIER))?;
|
||||
let TaggedValue::Gradient(stops) = inputs.get(graphene_std::math_nodes::gradient_value::GradientInput::INDEX)?.as_value()? else {
|
||||
let gradient_value_node = network_interface.document_network().nodes.get(&get_upstream_gradient_value_node_id(layer, network_interface)?)?;
|
||||
let TaggedValue::Gradient(stops) = gradient_value_node.inputs.get(graphene_std::math_nodes::gradient_value::GradientInput::INDEX)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
Some(stops.clone())
|
||||
@@ -329,10 +358,10 @@ pub fn get_fill_color(layer: LayerNodeIdentifier, network_interface: &NodeNetwor
|
||||
let fill_index = 1;
|
||||
|
||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
|
||||
let TaggedValue::Fill(Fill::Solid(color)) = inputs.get(fill_index)?.as_value()? else {
|
||||
let &TaggedValue::Fill(Fill::Solid(color)) = inputs.get(fill_index)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
Some(color.to_linear_srgb())
|
||||
Some(color)
|
||||
}
|
||||
|
||||
/// Get the current blend mode of a layer from the closest upstream "Blend Mode" node.
|
||||
@@ -431,15 +460,21 @@ pub fn get_grid_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkIn
|
||||
NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::grid::IDENTIFIER))
|
||||
}
|
||||
|
||||
/// Gets properties from the Text node
|
||||
pub fn get_text(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<(&String, &Font, TypesettingConfig, bool)> {
|
||||
/// Gets properties from the Text node. Resolves the font selection by reading the resource id and lookup via the fonts message handler.
|
||||
pub fn get_text<'a>(
|
||||
layer: LayerNodeIdentifier,
|
||||
network_interface: &'a NodeNetworkInterface,
|
||||
fonts: &FontsMessageHandler,
|
||||
resources: &ResourceMessageHandler,
|
||||
) -> Option<(&'a String, Font, TypesettingConfig, bool)> {
|
||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER))?;
|
||||
|
||||
let Some(TaggedValue::String(text)) = &inputs[graphene_std::text::text::TextInput::INDEX].as_value() else {
|
||||
return None;
|
||||
};
|
||||
let Some(TaggedValue::Font(font)) = &inputs[graphene_std::text::text::FontInput::INDEX].as_value() else {
|
||||
return None;
|
||||
let font = match &inputs[graphene_std::text::text::FontInput::INDEX].as_value() {
|
||||
Some(TaggedValue::Resource(resource_id)) => fonts.id_font(resources, *resource_id).unwrap_or_default(),
|
||||
_ => Font::default(),
|
||||
};
|
||||
let Some(&TaggedValue::F64(font_size)) = inputs[graphene_std::text::text::SizeInput::INDEX].as_value() else {
|
||||
return None;
|
||||
@@ -493,6 +528,66 @@ pub fn get_stroke_width(layer: LayerNodeIdentifier, network_interface: &NodeNetw
|
||||
}
|
||||
}
|
||||
|
||||
/// Subset of Stroke node inputs read for the control bar's stroke options popover.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct StrokeOptionsState {
|
||||
pub align: StrokeAlign,
|
||||
pub cap: StrokeCap,
|
||||
pub join: StrokeJoin,
|
||||
pub miter_limit: f64,
|
||||
pub paint_order: PaintOrder,
|
||||
pub dash_lengths: Vec<f64>,
|
||||
pub dash_offset: f64,
|
||||
}
|
||||
|
||||
/// Reads the non-color stroke option inputs from a layer's Stroke proto node. Returns `None` when the layer has no Stroke node.
|
||||
/// Inputs that aren't a static value (e.g. wired to another node) fall back to per-field defaults so the layer still participates in the sync.
|
||||
pub fn get_stroke_options(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<StrokeOptionsState> {
|
||||
let stroke = &DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
|
||||
let layer_view = NodeGraphLayer::new(layer, network_interface);
|
||||
layer_view.upstream_node_id_from_name(stroke)?;
|
||||
let read = |index: usize| layer_view.find_input(stroke, index);
|
||||
|
||||
let align = match read(graphene_std::vector::stroke::AlignInput::INDEX) {
|
||||
Some(TaggedValue::StrokeAlign(value)) => *value,
|
||||
_ => StrokeAlign::default(),
|
||||
};
|
||||
let cap = match read(graphene_std::vector::stroke::CapInput::INDEX) {
|
||||
Some(TaggedValue::StrokeCap(value)) => *value,
|
||||
_ => StrokeCap::default(),
|
||||
};
|
||||
let join = match read(graphene_std::vector::stroke::JoinInput::INDEX) {
|
||||
Some(TaggedValue::StrokeJoin(value)) => *value,
|
||||
_ => StrokeJoin::default(),
|
||||
};
|
||||
let miter_limit = match read(graphene_std::vector::stroke::MiterLimitInput::INDEX) {
|
||||
Some(TaggedValue::F64(value)) => *value,
|
||||
_ => 4.,
|
||||
};
|
||||
let paint_order = match read(graphene_std::vector::stroke::PaintOrderInput::INDEX) {
|
||||
Some(TaggedValue::PaintOrder(value)) => *value,
|
||||
_ => PaintOrder::default(),
|
||||
};
|
||||
let dash_lengths = match read(graphene_std::vector::stroke::DashLengthsInput::<List<f64>>::INDEX) {
|
||||
Some(TaggedValue::F64Array(value)) => value.clone(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let dash_offset = match read(graphene_std::vector::stroke::DashOffsetInput::INDEX) {
|
||||
Some(TaggedValue::F64(value)) => *value,
|
||||
_ => 0.,
|
||||
};
|
||||
|
||||
Some(StrokeOptionsState {
|
||||
align,
|
||||
cap,
|
||||
join,
|
||||
miter_limit,
|
||||
paint_order,
|
||||
dash_lengths,
|
||||
dash_offset,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the node ID of a layer's upstream Stroke proto node, if one exists.
|
||||
pub fn get_stroke_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
|
||||
NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER))
|
||||
@@ -526,6 +621,176 @@ pub fn set_stroke_weight_for_selected_layers(weight: f64, document: &DocumentMes
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the `Fill` value from a layer's upstream Fill node.
|
||||
pub fn get_fill_value(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Fill> {
|
||||
let fill_index = graphene_std::vector::fill::FillInput::<Fill>::INDEX;
|
||||
let tagged = NodeGraphLayer::new(layer, network_interface).find_input(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER), fill_index)?;
|
||||
if let TaggedValue::Fill(fill) = tagged { Some(fill.clone()) } else { None }
|
||||
}
|
||||
|
||||
/// Returns the stroke color from a layer's upstream Stroke node.
|
||||
pub fn get_stroke_color(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Option<Color>> {
|
||||
let color_index = graphene_std::vector::stroke::ColorInput::INDEX;
|
||||
let tagged = NodeGraphLayer::new(layer, network_interface).find_input(&DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER), color_index)?;
|
||||
if let TaggedValue::Color(color) = tagged { Some(*color) } else { None }
|
||||
}
|
||||
|
||||
/// Aggregated fill state across all selected non-artboard layers.
|
||||
pub struct SelectedFillState {
|
||||
/// `None` means mixed values between selected layers.
|
||||
pub enabled: Option<bool>,
|
||||
/// `None` means mixed values between selected layers.
|
||||
pub fill_choice: Option<FillChoice>,
|
||||
}
|
||||
|
||||
/// Aggregated stroke state across all selected non-artboard layers.
|
||||
pub struct SelectedStrokeState {
|
||||
/// `None` means mixed values between selected layers.
|
||||
pub enabled: Option<bool>,
|
||||
/// `None` means mixed values between selected layers.
|
||||
pub optional_color: Option<Option<Color>>,
|
||||
}
|
||||
|
||||
/// Reads the fill state across all selected non-artboard layers, including whether their enabled states or colors differ.
|
||||
/// "Enabled" tracks node attachment: a layer counts as enabled whenever a Fill node is attached, even when that fill's value is [`FillChoice::None`].
|
||||
/// Unticked means there is no Fill node. Returns `None` only when no layer is selected.
|
||||
pub fn selected_fill_state(document: &DocumentMessageHandler) -> Option<SelectedFillState> {
|
||||
let selected_nodes = document.network_interface.selected_nodes();
|
||||
let mut per_layer = selected_nodes.selected_layers_except_artboards(&document.network_interface).map(|layer| {
|
||||
if get_fill_id(layer, &document.network_interface).is_none() {
|
||||
return (false, FillChoice::None);
|
||||
}
|
||||
let fill_choice = get_fill_value(layer, &document.network_interface).map_or(FillChoice::None, FillChoice::from);
|
||||
(true, fill_choice)
|
||||
});
|
||||
|
||||
let (initial_enabled, initial_choice) = per_layer.next()?;
|
||||
let mut enabled_mixed = false;
|
||||
let mut color_mixed = false;
|
||||
let mut comparison_enabled = initial_enabled;
|
||||
let mut comparison_choice = initial_choice;
|
||||
for (enabled, fill_choice) in per_layer {
|
||||
if enabled != initial_enabled {
|
||||
enabled_mixed = true;
|
||||
}
|
||||
if enabled {
|
||||
if comparison_enabled {
|
||||
if fill_choice != comparison_choice {
|
||||
color_mixed = true;
|
||||
}
|
||||
} else {
|
||||
comparison_enabled = true;
|
||||
comparison_choice = fill_choice;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(SelectedFillState {
|
||||
enabled: (!enabled_mixed).then_some(initial_enabled),
|
||||
fill_choice: (!color_mixed).then_some(comparison_choice),
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads the stroke state across all selected non-artboard layers, including whether their enabled states or colors differ.
|
||||
/// "Enabled" tracks node attachment: a layer counts as enabled whenever a Stroke node is attached, even when that stroke's color is `None`.
|
||||
/// Unticked means there is no Stroke node. Returns `None` only when no layer is selected.
|
||||
pub fn selected_stroke_state(document: &DocumentMessageHandler) -> Option<SelectedStrokeState> {
|
||||
let selected_nodes = document.network_interface.selected_nodes();
|
||||
let mut per_layer = selected_nodes.selected_layers_except_artboards(&document.network_interface).map(|layer| {
|
||||
if get_stroke_id(layer, &document.network_interface).is_none() {
|
||||
return (false, None);
|
||||
}
|
||||
let color = get_stroke_color(layer, &document.network_interface).flatten();
|
||||
(true, color)
|
||||
});
|
||||
|
||||
let (initial_enabled, initial_color) = per_layer.next()?;
|
||||
let mut enabled_mixed = false;
|
||||
let mut color_mixed = false;
|
||||
let mut comparison_enabled = initial_enabled;
|
||||
let mut comparison_color = initial_color;
|
||||
for (enabled, color) in per_layer {
|
||||
if enabled != initial_enabled {
|
||||
enabled_mixed = true;
|
||||
}
|
||||
if enabled {
|
||||
if comparison_enabled {
|
||||
if color != comparison_color {
|
||||
color_mixed = true;
|
||||
}
|
||||
} else {
|
||||
comparison_enabled = true;
|
||||
comparison_color = color;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(SelectedStrokeState {
|
||||
enabled: (!enabled_mixed).then_some(initial_enabled),
|
||||
optional_color: (!color_mixed).then_some(comparison_color),
|
||||
})
|
||||
}
|
||||
|
||||
/// Sets the fill on all selected non-artboard layers, preserving gradient transform data when the layer already has a gradient fill.
|
||||
pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
|
||||
for layer in layers {
|
||||
let existing_gradient = get_fill_value(layer, &document.network_interface).and_then(|f| match f {
|
||||
Fill::Gradient(g) => Some(g),
|
||||
_ => None,
|
||||
});
|
||||
let fill = fill_choice.clone().to_fill(existing_gradient.as_ref());
|
||||
responses.add(GraphOperationMessage::FillSet { layer, fill });
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the stroke color on all selected non-artboard layers. Layers without an existing Stroke node get one created using
|
||||
/// the provided `weight`, so picking any color (including `None`) from an unticked stroke control bar entry both attaches
|
||||
/// the Stroke node and applies the chosen color.
|
||||
pub fn set_stroke_color_for_selected_layers(color: Option<Color>, weight: f64, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
|
||||
for layer in layers {
|
||||
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
|
||||
let input_index = graphene_std::vector::stroke::ColorInput::INDEX;
|
||||
let value = TaggedValue::Color(color);
|
||||
responses.add(NodeGraphMessage::SetInputValue { node_id, input_index, value });
|
||||
} else {
|
||||
let stroke = graphene_std::vector::style::Stroke::new(color, weight);
|
||||
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the Fill node from all selected non-artboard layers.
|
||||
pub fn remove_fill_for_selected_layers(document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
|
||||
for layer in layers {
|
||||
if let Some(node_id) = get_fill_id(layer, &document.network_interface) {
|
||||
responses.add(NodeGraphMessage::DeleteNodes {
|
||||
node_ids: vec![node_id],
|
||||
delete_children: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
|
||||
/// Removes the Stroke node from all selected non-artboard layers.
|
||||
pub fn remove_stroke_for_selected_layers(document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
|
||||
for layer in layers {
|
||||
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
|
||||
responses.add(NodeGraphMessage::DeleteNodes {
|
||||
node_ids: vec![node_id],
|
||||
delete_children: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
|
||||
/// Reads a specific input from the matching proto node on the first selected non-artboard layer that has one.
|
||||
/// Used by tool control bars to mirror per-shape parameters (sides, arc type, turns, etc.) from the selection
|
||||
/// into the control bar's input widget state without each call site re-implementing the layer iteration.
|
||||
@@ -589,9 +854,10 @@ impl<'a> NodeGraphLayer<'a> {
|
||||
self.network_interface.upstream_flow_back_from_nodes(vec![self.layer_node], &[], FlowType::HorizontalFlow)
|
||||
}
|
||||
|
||||
/// Node id of a node if it exists in the layer's primary flow
|
||||
/// Node id of a node if it exists in this specific layer's primary flow, stopping at the next layer upstream so a group doesn't incorrectly match its children's nodes.
|
||||
pub fn upstream_node_id_from_name(&self, identifier: &DefinitionIdentifier) -> Option<NodeId> {
|
||||
self.horizontal_layer_flow()
|
||||
.take_while(|&node_id| node_id == self.layer_node || !self.network_interface.is_layer(&node_id, &[]))
|
||||
.find(|node_id| self.network_interface.reference(node_id, &[]).is_some_and(|reference| reference == *identifier))
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 225 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user